Securing AWS CI/CD with Zero Trust: A Step-by-Step Approach

am
AWSome Diary
7 min readMar 9, 2024

--

source: Google

Zero Trust Architecture (ZTA) is an approach to cybersecurity that operates under the principle "never trust, always verify." Instead of assuming everything behind the corporate firewall is safe, the Zero Trust model assumes breach and verifies each request as though it originates from an open network. This is particularly relevant in today's digital environment where cloud services, such as those offered by Amazon Web Services (AWS), are extensively used for continuous integration and continuous deployment (CI/CD) processes. In this article, I will write about how Zero Trust Architecture can be implemented in an AWS CI/CD environment, including the use of AWS services and tools to enforce advanced ZTA principles, supported by examples and use cases.

Understanding AWS CI/CD in the Context of Zero Trust

Continuous Integration (CI) and Continuous Deployment (CD) form the backbone of modern software development practices, enabling developers to frequently merge code changes into a central repository, where automated builds and tests are run. AWS provides a suite of services to support CI/CD, such as AWS CodeCommit, AWS CodeBuild, AWS CodeDeploy, and AWS CodePipeline.

Implementing ZTA in this environment requires a shift in how security controls are applied. Traditionally, perimeter-based security models would focus on securing the network boundary. However, with ZTA, the focus is on securing the individual access requests and transactions based on their context and conforming to the least privilege access principle.

Key Principles of Zero Trust in AWS CI/CD

  1. Identity Verification: Every user and device must be authenticated and authorized before accessing resources. AWS Identity and Access Management (IAM) can enforce granular access controls, ensuring that only authenticated entities with the necessary permissions can access CI/CD resources.
  2. Least Privilege Access: Entities should only have access to the resources necessary for their role. IAM roles and policies can be used to limit access to AWS resources strictly to what's needed for a task, reducing the potential impact of a compromised account or role.
  3. Microsegmentation: Splitting the network into secure zones allows for more granular control of traffic and reduces the lateral movement of attackers. AWS Virtual Private Cloud (VPC) can be configured to create private cloud environments, while security groups and network ACLs can enforce traffic rules at the instance and subnet level, respectively.
  4. Monitoring and Analytics: Continuous monitoring of all activities with real-time analytics allows for the detection of suspicious activities and potential threats. AWS CloudTrail, Amazon CloudWatch, and AWS Security Hub provide extensive monitoring, logging, and alerting capabilities.
  5. Automation and Orchestration: Automating responses to security incidents reduces the time and scope of breaches. AWS Lambda can be used to automate responses to security alerts, such as revoking access or isolating compromised instances.

Implementing Zero Trust in AWS CI/CD: A Use Case

Consider a scenario where a development team uses AWS for their CI/CD pipeline. The team uses GitHub for source control, AWS CodeBuild for building the application, AWS CodeDeploy for deployment, and Amazon EC2 instances to host the application.

  1. Source Control Access: Developers use personal access tokens (PATs) to pull and push code to GitHub repositories. AWS CodeBuild is configured to use these tokens for accessing the repository, ensuring that the build process is initiated by verified users.
  2. Build Process: AWS CodeBuild projects are set up with specific IAM roles that have the least privilege access to resources needed for the build process, such as Amazon S3 buckets for storing artifacts and AWS Key Management Service (KMS) for managing encryption keys.
  3. Deployment: AWS CodeDeploy uses IAM roles with permissions limited to deploying artifacts on EC2 instances or AWS Lambda functions. Network access to these resources is tightly controlled through security groups, allowing traffic only from AWS CodeDeploy and blocking all other sources.
  4. Runtime Environment: EC2 instances hosting the application are placed in a private subnet within a VPC. Access to these instances is restricted to necessary personnel through IAM roles, and SSH access is disabled to prevent unauthorized access. Application communication to external services is routed through AWS PrivateLink to minimize exposure to the public internet.

Advanced Tools for ZTA in AWS

  • Amazon GuardDuty: Offers threat detection to identify unauthorized and malicious activity across your AWS infrastructure.
  • AWS Network Firewall: Provides fine-grained network protections, including stateful firewall, intrusion detection, and web filtering within your VPC.
  • Amazon Inspector: Automatically assesses applications for vulnerabilities or deviations from best practices, including at runtime.
  • AWS WAF (Web Application Firewall): Protects web applications from common web exploits.

Sample Code for Implementing Least Privilege IAM Policy

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::your-ci-cd-artifact-bucket/*"
}
]
}

This IAM policy snippet allows an IAM role to only read and write objects within a specific S3 bucket, demonstrating the principle of least privilege.

Enhanced Identity Verification with AWS IAM and MFA

To strengthen identity verification, Multi-Factor Authentication (MFA) should be enforced for all users accessing the AWS Management Console or using AWS CLI. Below is an example of how to enforce MFA for a specific IAM role that needs to access AWS CodeCommit repositories.

  1. Create IAM Policy for MFA Enforcement:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowPullPushOnlyWithMFA",
"Effect": "Allow",
"Action": [
"codecommit:GitPull",
"codecommit:GitPush"
],
"Resource": "arn:aws:codecommit:region:account-id:repository-name",
"Condition": {"Bool": {"aws:MultiFactorAuthPresent": "true"}}
}
]
}
  1. Attach Policy to IAM Role/User:

Using AWS CLI, attach the created policy to the necessary IAM role or user.

aws iam put-role-policy --role-name YourIAMRoleName --policy-name EnforceMFAForCodeCommit --policy-document file://path_to_your_policy_file.json

This ensures that Git operations against the CodeCommit repository can only be performed when the user has authenticated with MFA.

Securing AWS CodeBuild Projects

When configuring AWS CodeBuild for your CI process, it’s essential to limit the permissions of the build projects to access only necessary AWS resources. Here’s an example IAM policy that restricts a CodeBuild project’s access to a specific S3 bucket for storing build artifacts and to ECR for pushing Docker images:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::your-build-artifacts-bucket/*"
},
{
"Effect": "Allow",
"Action": [
"ecr:GetAuthorizationToken",
"ecr:BatchCheckLayerAvailability",
"ecr:InitiateLayerUpload",
"ecr:UploadLayerPart",
"ecr:CompleteLayerUpload",
"ecr:PutImage"
],
"Resource": "arn:aws:ecr:region:account-id:repository/repository-name"
}
]
}

Implementing Microsegmentation in AWS VPC

Microsegmentation can be achieved by properly configuring VPC subnets, security groups, and network ACLs. Below is a high-level outline of steps to create a secure VPC environment for your CI/CD pipeline:

  1. Create a VPC with Private and Public Subnets:

Use the AWS Management Console or AWS CLI to set up a VPC. Place your CI/CD resources such as CodeBuild and CodeDeploy in private subnets to restrict direct access from the internet.

2. Configure Security Groups:

Create security groups for your AWS resources that strictly define inbound and outbound traffic rules. For instance, a security group for your EC2 instances hosting the application might only allow inbound traffic on port 80 and 443 from the internet and no outbound traffic to the internet.

3. Set Network ACLs:

Network ACLs can provide an additional layer of security, acting as a firewall for associated subnets, controlling both inbound and outbound traffic. Ensure that your NACLs are configured to allow only necessary traffic and deny all others by default.

Continuous Monitoring and Alerts with Amazon CloudWatch and AWS Lambda

Automate the response to security incidents using Amazon CloudWatch to monitor logs and metrics, with AWS Lambda functions to execute specific security responses. For example, you could set up an alert for unauthorized access attempts and trigger a Lambda function to automatically revoke access or notify security teams.

  1. Create CloudWatch Alarm:
aws cloudwatch put-metric-alarm --alarm-name UnauthorizedAccessAttempts --metric-name NumberOfUnauthorizedAccessAttempts --namespace "AWS/Logs" --statistic Sum --period 300 --threshold 1 --comparison-operator GreaterThanOrEqualToThreshold --evaluation-periods 2 --alarm-actions arn:aws:sns:region:account-id:alarm-topic

2. Lambda Function for Incident Response:

Deploy a Lambda function that, upon invocation by CloudWatch Alarm, performs actions such as revoking IAM user permissions temporarily or sending notifications to security administrators.

This sample Lambda function demonstrates how you could approach this:

  1. Prerequisites: Ensure your Lambda function has the necessary IAM permissions to modify IAM user policies and to publish messages to an SNS topic for notifications.
  2. IAM Policy for Lambda:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iam:PutUserPolicy",
"iam:DeleteUserPolicy",
"sns:Publish"
],
"Resource": "*"
}
]
}

Lambda Function Code:

This Python code snippet for a Lambda function uses Boto3 to revoke an IAM user’s permissions by attaching a policy that denies all actions except the ability to log in to the AWS Management Console. It also sends a notification to a specified SNS to

import boto3
import json

def lambda_handler(event, context):
# Initialize Boto3 clients
iam_client = boto3.client('iam')
sns_client = boto3.client('sns')

# Specify the IAM user and SNS topic ARN
user_name = 'your-iam-user-name'
sns_topic_arn = 'your-sns-topic-arn'
policy_name = 'TemporaryDenyAllPolicy'

# Policy document that denies all actions
deny_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Deny",
"Action": "*",
"Resource": "*"
}
]
}

try:
# Attach the deny policy to the specified IAM user
iam_client.put_user_policy(
UserName=user_name,
PolicyName=policy_name,
PolicyDocument=json.dumps(deny_policy_document)
)

# Notify administrators via SNS
message = f"Temporary deny all policy applied to IAM user: {user_name}"
sns_client.publish(TopicArn=sns_topic_arn, Message=message)

return {
'statusCode': 200,
'body': json.dumps('Success: Deny policy applied and notification sent.')
}
except Exception as e:
return {
'statusCode': 500,
'body': json.dumps(f'Error: {str(e)}')
}

Replace 'your-iam-user-name' with the actual IAM user name and 'your-sns-topic-arn' with the SNS topic ARN where you want to send the notification.

Deployment:

  • Create a new Lambda function in the AWS Management Console or via AWS CLI, and paste this code.
  • Ensure the execution role assigned to the Lambda function includes the policy specified above.
  • Configure CloudWatch Alarms to trigger this Lambda function in response to specific events or metrics that you’ve deemed indicative of a security issue.

Implementing Zero Trust Architecture in an AWS CI/CD environment enhances security by applying strict access controls, identity verification, and continuous monitoring throughout the development lifecycle. By leveraging AWS’s comprehensive suite of services and following the principles of Zero Trust, organizations can significantly reduce their security risks and protect their infrastructure and data from unauthorized access and potential breaches. As the digital landscape evolves, adopting a Zero Trust approach in cloud environments will become increasingly critical for maintaining robust security postures.

--

--

am
AWSome Diary

Unapologetically Nerdy. Privacy | Encryption | Digital Rights | FOSS | Video Tech | Security | GNU/Linux. Check out https://git.aloke.tech