ELB Certificates Should Be Rotated
More Info:
Ensures that you rotate your certificate before the set configurable days.
Risk Level
Medium
Address
Security
Compliance Standards
- APRA CPS 234 (Australia)
- BSI C5 (Germany)
- Brazil LGPD
- CCPA / CPRA (California)
- CIS Critical Security Controls v8
- CMMC 2.0
- CSA Cloud Controls Matrix v4
- DPDPA
- Digital Operational Resilience Act (EU)
- Essential 8
- ISO/IEC 27017
- ISO/IEC 27018
- ISO/IEC 27701
- KSA PDPL
- MAS Technology Risk Management (Singapore)
- MITRE ATT&CK (Cloud)
- NIS2 Directive
- NIST
- NIST SP 800-171
- NYDFS 23 NYCRR 500
- SWIFT Customer Security Controls Framework
- Sarbanes-Oxley IT General Controls
- UK NCSC Cyber Assessment Framework
Triage and Remediation
- Prevention
- Cause
- Remediation
How to Prevent
Using Console
To prevent the misconfiguration of ELB (Elastic Load Balancer) certificates not being rotated in IAM (Identity and Access Management) using the AWS Management Console, follow these steps:
-
Monitor Certificate Expiration:
- Navigate to the AWS Certificate Manager (ACM) in the AWS Management Console.
- Regularly check the expiration dates of your certificates.
- Set up CloudWatch Alarms to notify you before certificates expire.
-
Automate Certificate Renewal:
- Use ACM to automatically renew certificates that are issued by ACM.
- For certificates not issued by ACM, set up a process to manually renew and upload the new certificates before the old ones expire.
-
Implement a Certificate Rotation Policy:
- Establish a policy that defines the frequency of certificate rotation (e.g., every 90 days).
- Document and enforce this policy within your organization.
-
Use AWS Config Rules:
- Enable AWS Config and create a custom rule to check the age of your certificates.
- Set the rule to trigger an alert or take action if a certificate is nearing its expiration date or has not been rotated within the defined period.
By following these steps, you can ensure that your ELB certificates are regularly rotated and remain up-to-date, thereby enhancing the security of your AWS environment.
Using CLI
To prevent the misconfiguration of ELB certificates not being rotated in IAM using AWS CLI, you can follow these steps:
-
List All Server Certificates: Regularly list all server certificates to keep track of their expiration dates and ensure they are rotated before they expire.
aws iam list-server-certificates -
Check Certificate Expiration Dates: Use the
get-server-certificatecommand to check the expiration dates of each certificate. This helps in identifying certificates that are nearing expiration.aws iam get-server-certificate --server-certificate-name <certificate-name> -
Automate Certificate Rotation: Implement a script or use AWS CLI commands to automate the rotation of certificates. This can be done by uploading a new certificate and updating the ELB to use the new certificate.
aws iam upload-server-certificate --server-certificate-name <new-certificate-name> --certificate-body file://<path-to-certificate-body> --private-key file://<path-to-private-key> --certificate-chain file://<path-to-certificate-chain> -
Update ELB with New Certificate: After uploading the new certificate, update the ELB to use the new certificate.
aws elb set-load-balancer-listener-ssl-certificate --load-balancer-name <load-balancer-name> --load-balancer-port <port> --ssl-certificate-id <new-certificate-arn>
By following these steps, you can ensure that your ELB certificates are rotated regularly, preventing any misconfigurations related to expired certificates.
Using Python
To prevent the misconfiguration of ELB (Elastic Load Balancer) certificates not being rotated in AWS IAM using Python scripts, you can follow these steps:
1. Set Up AWS SDK for Python (Boto3)
First, ensure you have the AWS SDK for Python (Boto3) installed. You can install it using pip if you haven't already:
pip install boto3
2. Create a Script to List Certificates and Check Expiry Dates
You need a script that lists all the certificates and checks their expiry dates. This will help you identify certificates that need to be rotated.
import boto3
from datetime import datetime, timedelta
# Initialize a session using Amazon IAM
session = boto3.Session(profile_name='your-profile-name')
iam_client = session.client('iam')
# Define the threshold for certificate rotation (e.g., 30 days before expiry)
rotation_threshold = timedelta(days=30)
# Get the current date
current_date = datetime.utcnow()
# List all server certificates
certificates = iam_client.list_server_certificates()
for cert in certificates['ServerCertificateMetadataList']:
cert_name = cert['ServerCertificateName']
cert_arn = cert['Arn']
cert_expiry = cert['Expiration']
# Check if the certificate is nearing expiry
if cert_expiry - current_date <= rotation_threshold:
print(f"Certificate {cert_name} (ARN: {cert_arn}) is nearing expiry and should be rotated.")
3. Automate Certificate Rotation
You can automate the rotation process by creating a new certificate and updating the ELB to use the new certificate. This example assumes you have the new certificate ready.
import boto3
# Initialize a session using Amazon IAM
session = boto3.Session(profile_name='your-profile-name')
iam_client = session.client('iam')
elb_client = session.client('elbv2')
# Function to upload a new certificate
def upload_new_certificate(cert_name, cert_body, private_key, cert_chain):
response = iam_client.upload_server_certificate(
ServerCertificateName=cert_name,
CertificateBody=cert_body,
PrivateKey=private_key,
CertificateChain=cert_chain
)
return response['ServerCertificateMetadata']['Arn']
# Function to update ELB with the new certificate
def update_elb_certificate(elb_arn, listener_arn, new_cert_arn):
response = elb_client.modify_listener(
ListenerArn=listener_arn,
Certificates=[
{
'CertificateArn': new_cert_arn
},
]
)
return response
# Example usage
new_cert_arn = upload_new_certificate('new-cert-name', 'cert-body', 'private-key', 'cert-chain')
update_elb_certificate('elb-arn', 'listener-arn', new_cert_arn)
4. Schedule the Script to Run Periodically
To ensure continuous compliance, schedule the script to run periodically using a task scheduler like cron (Linux) or Task Scheduler (Windows).
Example: Using cron (Linux)
- Open the crontab editor:
crontab -e
- Add a cron job to run the script daily:
0 0 * * * /usr/bin/python3 /path/to/your/script.py
By following these steps, you can automate the process of checking and rotating ELB certificates in AWS IAM using Python scripts, ensuring that your certificates are always up-to-date and reducing the risk of misconfigurations.
Check Cause
Using Console
- Sign in to the AWS Management Console.
- Navigate to the IAM dashboard by selecting "Services" and then "IAM" under the "Security, Identity, & Compliance" section.
- In the IAM dashboard, select "SSL/TLS certificates" from the left-hand navigation pane.
- Here, you can see all the SSL/TLS certificates associated with your account. Check the expiration dates of these certificates. If any of them are close to their expiration date or have already expired, it indicates that the ELB Certificates need to be rotated.
Using CLI
-
First, you need to install and configure AWS CLI on your local machine. You can do this by following the instructions provided by AWS. Make sure you have the necessary permissions to access the resources.
-
Once the AWS CLI is set up, you can list all the server certificates in IAM using the following command:
aws iam list-server-certificatesThis command will return a JSON object that contains all the server certificates.
-
To check the expiration date of each certificate, you can use the following command:
aws iam get-server-certificate --server-certificate-name {certificate-name}Replace
{certificate-name}with the name of the certificate you want to check. This command will return a JSON object that contains the details of the certificate, including the expiration date. -
You can then write a Python script to parse the JSON object and check if the certificate is expired or not. Here is a simple example:
import jsonimport subprocessfrom datetime import datetime# Run the AWS CLI command and get the outputoutput = subprocess.check_output(['aws', 'iam', 'get-server-certificate', '--server-certificate-name', 'your-certificate-name'])# Parse the JSON outputdata = json.loads(output)# Get the expiration dateexpiration_date = data['ServerCertificate']['ServerCertificateMetadata']['Expiration']# Convert the expiration date to a datetime objectexpiration_date = datetime.strptime(expiration_date, '%Y-%m-%dT%H:%M:%S%z')# Check if the certificate is expiredif expiration_date < datetime.now():print('The certificate is expired.')else:print('The certificate is not expired.')Replace
'your-certificate-name'with the name of your certificate. This script will print whether the certificate is expired or not.
Using Python
- Import the necessary libraries: You will need the boto3 library, which allows Python developers to write software that makes use of services like Amazon S3, Amazon EC2, etc.
import boto3
from datetime import datetime, timedelta
- Create an AWS session using boto3: You can create a session using your AWS credentials. Replace 'aws_access_key_id', 'aws_secret_access_key', and 'region_name' with your AWS credentials.
session = boto3.Session(
aws_access_key_id='YOUR_ACCESS_KEY',
aws_secret_access_key='YOUR_SECRET_KEY',
region_name='us-west-2'
)
- Connect to the IAM service: You can use the session object to connect to the IAM service.
client = session.client('iam')
- Check the certificate rotation: You can use the client object to list all the server certificates and check their rotation status. If the certificate is older than 90 days, print a warning message.
response = client.list_server_certificates()
for certificate in response['ServerCertificateMetadataList']:
if (datetime.now() - certificate['UploadDate']).days > 90:
print(f"Warning: The certificate {certificate['ServerCertificateName']} should be rotated.")
This script will print a warning message for all the server certificates that are older than 90 days.
Remediation
Using Console
To remediate the ELB Certificates Should Be Rotated misconfiguration in AWS using the AWS Console, follow these steps:
- Open the AWS Management Console and navigate to the EC2 dashboard.
- Click on the "Load Balancers" option in the left-hand menu.
- Select the load balancer that has the outdated certificate.
- Click on the "Listeners" tab.
- Click the pencil icon next to the listener that has the outdated certificate.
- In the "Edit Listener" dialog box, click on the "Change" button next to the SSL certificate.
- Select the new certificate from the list of available certificates or upload a new one.
- Click on the "Save" button to save the changes.
- Repeat steps 5-8 for all listeners that have outdated certificates.
- After updating the certificates, verify that the load balancer is functioning properly by testing it.
Note: It is recommended that you rotate your SSL/TLS certificates at least once a year to ensure that they are up-to-date and secure.
Using CLI
To remediate the ELB certificate rotation misconfiguration in AWS, you can follow these steps using AWS CLI:
- Identify the ELB that needs certificate rotation by running the following command:
aws elb describe-load-balancers
This will list all the ELBs in your AWS account.
- Once you have identified the ELB that needs certificate rotation, run the following command to retrieve the current certificate details:
aws elb describe-load-balancer-attributes --load-balancer-name <ELB-Name> --query 'LoadBalancerAttributes.SSLServerCertificate'
Replace <ELB-Name> with the name of the ELB that needs certificate rotation.
-
Verify the certificate expiry date and ensure that it is within the recommended time frame for rotation. If it is expired or about to expire, you need to request a new certificate from your certificate authority.
-
Once you have obtained the new certificate, upload it to AWS IAM by running the following command:
aws iam upload-server-certificate --server-certificate-name <Certificate-Name> --certificate-body file://<Certificate-File-Path> --private-key file://<Private-Key-File-Path>
Replace <Certificate-Name> with a name for the new certificate, <Certificate-File-Path> with the path to the new certificate file, and <Private-Key-File-Path> with the path to the private key file for the new certificate.
- After uploading the new certificate, update the ELB with the new certificate by running the following command:
aws elb set-load-balancer-listener-ssl-certificate --load-balancer-name <ELB-Name> --load-balancer-port <Port> --ssl-certificate-id <Certificate-ID>
Replace <ELB-Name> with the name of the ELB that needs certificate rotation, <Port> with the port number for which the certificate is being updated, and <Certificate-ID> with the ID of the new certificate that was uploaded to AWS IAM.
- Verify that the new certificate is being used by running the following command:
aws elb describe-load-balancer-attributes --load-balancer-name <ELB-Name> --query 'LoadBalancerAttributes.SSLServerCertificate'
This will display the details of the new certificate being used by the ELB.
- Finally, ensure that the certificate rotation process is automated to avoid future misconfigurations. You can use AWS Certificate Manager (ACM) to automate the process of certificate issuance, deployment, and renewal.
Using Python
To remediate the ELB certificate rotation misconfiguration in AWS using Python, follow these steps:
- Import the necessary AWS SDKs and libraries, such as boto3 and datetime.
import boto3
from datetime import datetime
- Initialize the AWS client with the appropriate credentials and region.
elb_client = boto3.client('elbv2', region_name='us-east-1')
- Get a list of all the load balancers in your AWS account.
elbs = elb_client.describe_load_balancers()['LoadBalancers']
- For each load balancer, check the expiration date of its SSL certificate.
for elb in elbs:
certs = elb_client.describe_certificates(LoadBalancerArn=elb['LoadBalancerArn'])['Certificates']
for cert in certs:
if cert['Type'] == 'acm':
cert_expiration = cert['NotAfter']
if cert_expiration < datetime.now(cert_expiration.tzinfo):
# certificate has expired, rotate it
else:
# certificate is still valid, no action needed
- If the certificate has expired, use the AWS SDK to request a new certificate.
acm_client = boto3.client('acm', region_name='us-east-1')
new_cert = acm_client.request_certificate(
DomainName='example.com',
ValidationMethod='DNS',
SubjectAlternativeNames=[
'*.example.com',
]
)
- After the new certificate is issued, update the load balancer with the new certificate.
elb_client.modify_listener(
ListenerArn='listener-arn',
Certificates=[
{
'CertificateArn': new_cert['CertificateArn']
}
]
)
- Repeat this process for all load balancers in your AWS account.
Note: This is just a basic outline of the steps involved in remediating the ELB certificate rotation misconfiguration in AWS using Python. The specific implementation may vary depending on your specific configuration and requirements.
Using Terraform
# Upload the new IAM server certificate (equivalent to aws iam upload-server-certificate)
resource "aws_iam_server_certificate" "new_lb_cert" {
name = "NEW_CERTIFICATE_NAME" # replace with your new certificate name
certificate_body = file("PATH/TO/certificate.pem") # replace with your cert path
private_key = file("PATH/TO/private-key.pem") # replace with your key path
certificate_chain = file("PATH/TO/chain.pem") # optional; remove if unused
# Optional: tag so you can find it later
tags = {
Name = "NEW_CERTIFICATE_NAME"
}
}
# CLASSIC LOAD BALANCER: point its listener at the new certificate
# (equivalent to aws elb set-load-balancer-listener-ssl-certificate)
resource "aws_elb" "example_classic_lb" {
name = "CLASSIC_LB_NAME" # replace with your ELB name
availability_zones = ["us-east-1a"] # replace as appropriate
listener {
instance_port = 80
instance_protocol = "HTTP"
lb_port = 443 # <LISTENER_PORT>
lb_protocol = "HTTPS"
ssl_certificate_id = aws_iam_server_certificate.new_lb_cert.arn
}
# ...other arguments...
}
# APPLICATION / NETWORK LOAD BALANCER: point its listener at the new certificate
# (equivalent to aws elbv2 modify-listener --certificates CertificateArn=<NEW_CERTIFICATE_ARN>)
resource "aws_lb" "example_alb" {
name = "ALB_NAME" # replace with your ALB/NLB name
load_balancer_type = "application"
subnets = ["SUBNET_ID_1", "SUBNET_ID_2"] # replace with your subnet IDs
# ...other arguments...
}
resource "aws_lb_target_group" "example_tg" {
name = "EXAMPLE_TG"
port = 80
protocol = "HTTP"
vpc_id = "VPC_ID" # replace with your VPC ID
}
resource "aws_lb_listener" "https_listener" {
load_balancer_arn = aws_lb.example_alb.arn
port = 443 # <LISTENER_PORT>
protocol = "HTTPS"
ssl_policy = "ELBSecurityPolicy-2016-08"
certificate_arn = aws_iam_server_certificate.new_lb_cert.arn
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.example_tg.arn
}
}
Notes:
- This Terraform uploads a new IAM server certificate and updates Classic ELB (
aws_elb.listener.ssl_certificate_id) and ALB/NLB (aws_lb_listener.certificate_arn) listeners to use it, matching the CLI remediation. - Deleting the old IAM server certificate is only done by Terraform if that certificate is also managed as an
aws_iam_server_certificateresource and you remove it from configuration; otherwise delete it manually in the IAM console or viaaws iam delete-server-certificateafter verifying all listeners have switched and traffic is healthy. - Updating listeners to point at the new certificate is an in-place change and does not replace the load balancers.
terraform planshould show:+creation ofaws_iam_server_certificate.new_lb_cert~in-place updates to the affectedaws_elband/oraws_lb_listenerresources to reference the new certificate ARN- (Optional)
-destruction of the oldaws_iam_server_certificateif you remove it from Terraform.