From d483b007dd30d142522ac7e6396524caaa294857 Mon Sep 17 00:00:00 2001 From: ajinkyajawalkar Date: Fri, 12 Jul 2024 15:04:15 +0530 Subject: [PATCH 1/2] Added prevention for apigateway --- .../rules/acm_certificate_expired.mdx | 152 ++++++++++++ .../acm_certificate_expired_remediation.mdx | 151 +++++++++++ .../rules/acm_certificates_min_rsa_length.mdx | 147 +++++++++++ ...ertificates_min_rsa_length_remediation.mdx | 146 +++++++++++ .../acm_certificates_renewal_30_days.mdx | 133 ++++++++++ ...rtificates_renewal_30_days_remediation.mdx | 132 ++++++++++ .../acm_certificates_renewal_45_days.mdx | 126 ++++++++++ ...rtificates_renewal_45_days_remediation.mdx | 125 ++++++++++ .../rules/acm_certificates_renewal_7_days.mdx | 155 ++++++++++++ ...ertificates_renewal_7_days_remediation.mdx | 154 ++++++++++++ .../rules/acm_certificates_validity.mdx | 149 +++++++++++ .../acm_certificates_validity_remediation.mdx | 148 +++++++++++ ...acm_certificates_wildcard_domain_names.mdx | 141 +++++++++++ ...ates_wildcard_domain_names_remediation.mdx | 140 +++++++++++ .../rules/api_gateway_xray_enabled.mdx | 151 +++++++++++ .../api_gateway_xray_enabled_remediation.mdx | 150 +++++++++++ ...api_gwv2_authorization_type_configured.mdx | 112 +++++++++ ...horization_type_configured_remediation.mdx | 111 +++++++++ .../rules/apigateway_client_certificate.mdx | 124 ++++++++++ ...gateway_client_certificate_remediation.mdx | 123 +++++++++ .../rules/apigateway_cloudwatch_logs.mdx | 118 +++++++++ ...apigateway_cloudwatch_logs_remediation.mdx | 117 +++++++++ .../rules/apigateway_content_encoding.mdx | 110 ++++++++ ...pigateway_content_encoding_remediation.mdx | 109 ++++++++ ...way_default_execution_endpoint_enabled.mdx | 132 ++++++++++ ...execution_endpoint_enabled_remediation.mdx | 131 ++++++++++ ...apigateway_detailed_cloudwatch_metrics.mdx | 118 +++++++++ ...etailed_cloudwatch_metrics_remediation.mdx | 117 +++++++++ .../rules/apigateway_enable_api_cache.mdx | 170 +++++++++++++ ...pigateway_enable_api_cache_remediation.mdx | 169 +++++++++++++ ...apigateway_enable_encryption_api_cache.mdx | 178 +++++++++++++ ...nable_encryption_api_cache_remediation.mdx | 177 +++++++++++++ .../rules/apigateway_integrated_waf.mdx | 129 ++++++++++ .../apigateway_integrated_waf_remediation.mdx | 128 ++++++++++ .../rules/apigateway_private_endpoint.mdx | 234 ++++++++++++++++++ ...pigateway_private_endpoint_remediation.mdx | 233 +++++++++++++++++ .../apigateway_rotate_ssl_certificates.mdx | 152 ++++++++++++ ...ay_rotate_ssl_certificates_remediation.mdx | 151 +++++++++++ .../apigateway_stages_logging_enabled.mdx | 132 ++++++++++ ...way_stages_logging_enabled_remediation.mdx | 131 ++++++++++ .../rules/apigateway_tracing_enabled.mdx | 116 +++++++++ ...apigateway_tracing_enabled_remediation.mdx | 115 +++++++++ .../rules/efs_encryption_enabled.mdx | 182 ++++++++++++++ .../efs_encryption_enabled_remediation.mdx | 181 ++++++++++++++ .../rules/efs_kms_customer_master_keys.mdx | 191 ++++++++++++++ ...s_kms_customer_master_keys_remediation.mdx | 190 ++++++++++++++ 46 files changed, 6681 insertions(+) diff --git a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificate_expired.mdx b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificate_expired.mdx index 2ac53529..bf02e610 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificate_expired.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificate_expired.mdx @@ -24,6 +24,158 @@ NIST ### Triage and Remediation + + +### How to Prevent + + +To prevent ACM (AWS Certificate Manager) Certificate Expired issues in API Gateway using the AWS Console, follow these steps: + +1. **Automate Certificate Renewal:** + - Navigate to the AWS Certificate Manager (ACM) in the AWS Management Console. + - Ensure that you are using ACM-provided certificates, which are automatically renewed by AWS. If you are using imported certificates, consider switching to ACM-provided certificates for automatic renewal. + +2. **Set Up Expiration Notifications:** + - In the ACM console, select the certificate you want to monitor. + - Configure Amazon CloudWatch Alarms to notify you before the certificate expires. Set up an alarm to trigger a notification (via SNS) when the certificate is nearing its expiration date. + +3. **Regularly Review Certificates:** + - Periodically review the list of certificates in the ACM console to ensure none are nearing expiration. + - Create a routine check (e.g., monthly) to manually verify the status of all certificates. + +4. **Update API Gateway with New Certificates:** + - When a certificate is renewed, ensure that the API Gateway is updated with the new certificate. + - Navigate to the API Gateway console, select your API, and update the Custom Domain Name settings with the new certificate ARN. + +By following these steps, you can proactively manage and prevent ACM Certificate Expired issues in API Gateway using the AWS Console. + + + +To prevent ACM (AWS Certificate Manager) certificate expiration in API Gateway using AWS CLI, you can follow these steps: + +1. **List Certificates and Check Expiration Dates:** + Regularly list your ACM certificates and check their expiration dates to ensure they are renewed before they expire. + + ```sh + aws acm list-certificates --query "CertificateSummaryList[*].{CertificateArn:CertificateArn,DomainName:DomainName,NotAfter:NotAfter}" + ``` + +2. **Request a New Certificate:** + If a certificate is nearing its expiration date, request a new certificate. Make sure to specify the domain name(s) for which you need the certificate. + + ```sh + aws acm request-certificate --domain-name example.com --validation-method DNS + ``` + +3. **Validate the New Certificate:** + Follow the validation process to ensure the new certificate is issued. This typically involves creating DNS records or using email validation. + + ```sh + aws acm describe-certificate --certificate-arn + ``` + +4. **Update API Gateway with the New Certificate:** + Once the new certificate is issued, update your API Gateway to use the new certificate ARN. + + ```sh + aws apigateway update-domain-name --domain-name example.com --patch-operations op=replace,path=/certificateArn,value= + ``` + +By following these steps, you can ensure that your ACM certificates are always up-to-date and prevent any disruptions due to expired certificates in your API Gateway. + + + +To prevent ACM (AWS Certificate Manager) certificate expiration in API Gateway using Python scripts, you can follow these steps: + +1. **Monitor Certificate Expiration Dates:** + Use a Python script to regularly check the expiration dates of your ACM certificates. You can use the `boto3` library to interact with AWS services. + + ```python + import boto3 + from datetime import datetime, timezone + + def check_certificate_expiration(): + client = boto3.client('acm') + response = client.list_certificates() + certificates = response['CertificateSummaryList'] + + for cert in certificates: + cert_arn = cert['CertificateArn'] + cert_details = client.describe_certificate(CertificateArn=cert_arn) + expiration_date = cert_details['Certificate']['NotAfter'] + days_to_expire = (expiration_date - datetime.now(timezone.utc)).days + + if days_to_expire < 30: # Notify if the certificate will expire in less than 30 days + print(f"Certificate {cert_arn} is expiring in {days_to_expire} days.") + + check_certificate_expiration() + ``` + +2. **Automate Certificate Renewal:** + Automate the renewal process for ACM certificates. ACM automatically renews eligible certificates, but you can ensure this by scripting the renewal process. + + ```python + def renew_certificate(cert_arn): + client = boto3.client('acm') + client.renew_certificate(CertificateArn=cert_arn) + print(f"Renewal initiated for certificate {cert_arn}") + + # Example usage + cert_arn = 'arn:aws:acm:region:account-id:certificate/certificate-id' + renew_certificate(cert_arn) + ``` + +3. **Update API Gateway with New Certificate:** + After renewing the certificate, update the API Gateway to use the new certificate. + + ```python + def update_api_gateway(api_id, domain_name, cert_arn): + client = boto3.client('apigateway') + response = client.update_domain_name( + domainName=domain_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/certificateArn', + 'value': cert_arn + } + ] + ) + print(f"API Gateway {api_id} updated with new certificate {cert_arn}") + + # Example usage + api_id = 'your-api-id' + domain_name = 'your-domain-name' + cert_arn = 'arn:aws:acm:region:account-id:certificate/certificate-id' + update_api_gateway(api_id, domain_name, cert_arn) + ``` + +4. **Set Up Notifications:** + Set up notifications to alert you when a certificate is nearing expiration. You can use AWS SNS (Simple Notification Service) to send alerts. + + ```python + import boto3 + + def send_notification(message): + client = boto3.client('sns') + response = client.publish( + TopicArn='arn:aws:sns:region:account-id:topic-name', + Message=message, + Subject='ACM Certificate Expiration Alert' + ) + print("Notification sent") + + # Example usage + message = "Your ACM certificate is expiring soon. Please take action to renew it." + send_notification(message) + ``` + +By implementing these steps, you can proactively prevent ACM certificate expiration in API Gateway using Python scripts. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificate_expired_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificate_expired_remediation.mdx index 91a4e929..8f6ac634 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificate_expired_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificate_expired_remediation.mdx @@ -2,6 +2,157 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent ACM (AWS Certificate Manager) Certificate Expired issues in API Gateway using the AWS Console, follow these steps: + +1. **Automate Certificate Renewal:** + - Navigate to the AWS Certificate Manager (ACM) in the AWS Management Console. + - Ensure that you are using ACM-provided certificates, which are automatically renewed by AWS. If you are using imported certificates, consider switching to ACM-provided certificates for automatic renewal. + +2. **Set Up Expiration Notifications:** + - In the ACM console, select the certificate you want to monitor. + - Configure Amazon CloudWatch Alarms to notify you before the certificate expires. Set up an alarm to trigger a notification (via SNS) when the certificate is nearing its expiration date. + +3. **Regularly Review Certificates:** + - Periodically review the list of certificates in the ACM console to ensure none are nearing expiration. + - Create a routine check (e.g., monthly) to manually verify the status of all certificates. + +4. **Update API Gateway with New Certificates:** + - When a certificate is renewed, ensure that the API Gateway is updated with the new certificate. + - Navigate to the API Gateway console, select your API, and update the Custom Domain Name settings with the new certificate ARN. + +By following these steps, you can proactively manage and prevent ACM Certificate Expired issues in API Gateway using the AWS Console. + + + +To prevent ACM (AWS Certificate Manager) certificate expiration in API Gateway using AWS CLI, you can follow these steps: + +1. **List Certificates and Check Expiration Dates:** + Regularly list your ACM certificates and check their expiration dates to ensure they are renewed before they expire. + + ```sh + aws acm list-certificates --query "CertificateSummaryList[*].{CertificateArn:CertificateArn,DomainName:DomainName,NotAfter:NotAfter}" + ``` + +2. **Request a New Certificate:** + If a certificate is nearing its expiration date, request a new certificate. Make sure to specify the domain name(s) for which you need the certificate. + + ```sh + aws acm request-certificate --domain-name example.com --validation-method DNS + ``` + +3. **Validate the New Certificate:** + Follow the validation process to ensure the new certificate is issued. This typically involves creating DNS records or using email validation. + + ```sh + aws acm describe-certificate --certificate-arn + ``` + +4. **Update API Gateway with the New Certificate:** + Once the new certificate is issued, update your API Gateway to use the new certificate ARN. + + ```sh + aws apigateway update-domain-name --domain-name example.com --patch-operations op=replace,path=/certificateArn,value= + ``` + +By following these steps, you can ensure that your ACM certificates are always up-to-date and prevent any disruptions due to expired certificates in your API Gateway. + + + +To prevent ACM (AWS Certificate Manager) certificate expiration in API Gateway using Python scripts, you can follow these steps: + +1. **Monitor Certificate Expiration Dates:** + Use a Python script to regularly check the expiration dates of your ACM certificates. You can use the `boto3` library to interact with AWS services. + + ```python + import boto3 + from datetime import datetime, timezone + + def check_certificate_expiration(): + client = boto3.client('acm') + response = client.list_certificates() + certificates = response['CertificateSummaryList'] + + for cert in certificates: + cert_arn = cert['CertificateArn'] + cert_details = client.describe_certificate(CertificateArn=cert_arn) + expiration_date = cert_details['Certificate']['NotAfter'] + days_to_expire = (expiration_date - datetime.now(timezone.utc)).days + + if days_to_expire < 30: # Notify if the certificate will expire in less than 30 days + print(f"Certificate {cert_arn} is expiring in {days_to_expire} days.") + + check_certificate_expiration() + ``` + +2. **Automate Certificate Renewal:** + Automate the renewal process for ACM certificates. ACM automatically renews eligible certificates, but you can ensure this by scripting the renewal process. + + ```python + def renew_certificate(cert_arn): + client = boto3.client('acm') + client.renew_certificate(CertificateArn=cert_arn) + print(f"Renewal initiated for certificate {cert_arn}") + + # Example usage + cert_arn = 'arn:aws:acm:region:account-id:certificate/certificate-id' + renew_certificate(cert_arn) + ``` + +3. **Update API Gateway with New Certificate:** + After renewing the certificate, update the API Gateway to use the new certificate. + + ```python + def update_api_gateway(api_id, domain_name, cert_arn): + client = boto3.client('apigateway') + response = client.update_domain_name( + domainName=domain_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/certificateArn', + 'value': cert_arn + } + ] + ) + print(f"API Gateway {api_id} updated with new certificate {cert_arn}") + + # Example usage + api_id = 'your-api-id' + domain_name = 'your-domain-name' + cert_arn = 'arn:aws:acm:region:account-id:certificate/certificate-id' + update_api_gateway(api_id, domain_name, cert_arn) + ``` + +4. **Set Up Notifications:** + Set up notifications to alert you when a certificate is nearing expiration. You can use AWS SNS (Simple Notification Service) to send alerts. + + ```python + import boto3 + + def send_notification(message): + client = boto3.client('sns') + response = client.publish( + TopicArn='arn:aws:sns:region:account-id:topic-name', + Message=message, + Subject='ACM Certificate Expiration Alert' + ) + print("Notification sent") + + # Example usage + message = "Your ACM certificate is expiring soon. Please take action to renew it." + send_notification(message) + ``` + +By implementing these steps, you can proactively prevent ACM certificate expiration in API Gateway using Python scripts. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_min_rsa_length.mdx b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_min_rsa_length.mdx index 636ea018..1fbf8ceb 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_min_rsa_length.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_min_rsa_length.mdx @@ -24,6 +24,153 @@ CBP ### Triage and Remediation + + +### How to Prevent + + +To prevent ACM Certificates from having a minimum RSA length in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to ACM (AWS Certificate Manager):** + - Open the AWS Management Console. + - In the search bar, type "Certificate Manager" and select it from the dropdown. + +2. **Request a New Certificate:** + - Click on the "Request a certificate" button. + - Choose "Request a public certificate" or "Request a private certificate" based on your needs, then click "Next." + +3. **Configure Certificate Options:** + - Enter the domain names for your certificate. + - Under "Additional names (SANs)," add any additional domain names if needed. + - Click "Next." + +4. **Select Key Algorithm and RSA Key Length:** + - In the "Select validation method" step, choose your preferred validation method and click "Next." + - In the "Add tags" step, add any tags if necessary and click "Next." + - In the "Review" step, ensure that the "Key algorithm" is set to "RSA" and the "RSA key length" is set to at least 2048 bits. + - Click "Confirm and request" to complete the process. + +By following these steps, you ensure that your ACM certificates meet the minimum RSA length requirement, thereby preventing misconfigurations in API Gateway. + + + +To prevent the misconfiguration of ACM Certificates having a minimum RSA length in API Gateway using AWS CLI, follow these steps: + +1. **Create a Certificate with the Required RSA Length:** + Ensure that when you request a new ACM certificate, you specify the required RSA key length. AWS ACM supports RSA key lengths of 2048, 3072, and 4096 bits. + + ```sh + aws acm request-certificate \ + --domain-name example.com \ + --validation-method DNS \ + --options CertificateTransparencyLoggingPreference=ENABLED \ + --key-algorithm RSA_2048 + ``` + +2. **List Certificates to Verify RSA Length:** + List your ACM certificates and check their details to ensure they meet the required RSA length. + + ```sh + aws acm list-certificates + ``` + + To get detailed information about a specific certificate, including the key algorithm: + + ```sh + aws acm describe-certificate --certificate-arn + ``` + +3. **Associate the Certificate with API Gateway:** + When creating or updating an API Gateway custom domain name, ensure you associate it with the ACM certificate that has the required RSA length. + + ```sh + aws apigateway create-domain-name \ + --domain-name api.example.com \ + --certificate-arn + ``` + +4. **Verify Domain Name Configuration:** + After associating the certificate, verify the domain name configuration to ensure it is correctly set up with the required certificate. + + ```sh + aws apigateway get-domain-name --domain-name api.example.com + ``` + +By following these steps, you can ensure that your ACM certificates used in API Gateway have the minimum required RSA length, thereby preventing misconfigurations. + + + +To prevent ACM Certificates from having a minimum RSA length in API Gateway using Python scripts, you can use the AWS SDK for Python (Boto3). Below are the steps to ensure that ACM certificates have a minimum RSA length of 2048 bits: + +### Step 1: Install Boto3 +Ensure you have Boto3 installed in your Python environment. You can install it using pip if you haven't already: +```bash +pip install boto3 +``` + +### Step 2: Initialize Boto3 Client +Initialize the Boto3 client for ACM (AWS Certificate Manager) and API Gateway. + +```python +import boto3 + +acm_client = boto3.client('acm') +apigateway_client = boto3.client('apigateway') +``` + +### Step 3: List ACM Certificates +Fetch the list of ACM certificates and their details. + +```python +def list_acm_certificates(): + response = acm_client.list_certificates() + return response['CertificateSummaryList'] + +certificates = list_acm_certificates() +``` + +### Step 4: Validate RSA Key Length and Update API Gateway +Check the RSA key length of each certificate and ensure it meets the minimum requirement. If it does, associate it with the API Gateway. + +```python +def get_certificate_details(certificate_arn): + response = acm_client.describe_certificate(CertificateArn=certificate_arn) + return response['Certificate'] + +def validate_and_associate_certificates(certificates): + for cert in certificates: + cert_details = get_certificate_details(cert['CertificateArn']) + key_algorithm = cert_details['KeyAlgorithm'] + key_size = cert_details['KeySize'] + + if key_algorithm == 'RSA' and key_size >= 2048: + # Assuming you have the API Gateway ID and Domain Name + api_gateway_id = 'your_api_gateway_id' + domain_name = 'your_domain_name' + + apigateway_client.create_domain_name( + domainName=domain_name, + certificateArn=cert['CertificateArn'] + ) + print(f"Certificate {cert['CertificateArn']} with RSA {key_size} bits associated with API Gateway.") + else: + print(f"Certificate {cert['CertificateArn']} does not meet the RSA 2048 bits requirement.") + +validate_and_associate_certificates(certificates) +``` + +### Summary +1. **Install Boto3**: Ensure Boto3 is installed in your Python environment. +2. **Initialize Boto3 Client**: Initialize the ACM and API Gateway clients. +3. **List ACM Certificates**: Fetch the list of ACM certificates. +4. **Validate RSA Key Length and Update API Gateway**: Check the RSA key length and associate the certificate with API Gateway if it meets the minimum requirement. + +This script ensures that only ACM certificates with a minimum RSA length of 2048 bits are associated with your API Gateway, thereby preventing misconfigurations. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_min_rsa_length_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_min_rsa_length_remediation.mdx index 36ce441c..ce848830 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_min_rsa_length_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_min_rsa_length_remediation.mdx @@ -2,6 +2,152 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent ACM Certificates from having a minimum RSA length in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to ACM (AWS Certificate Manager):** + - Open the AWS Management Console. + - In the search bar, type "Certificate Manager" and select it from the dropdown. + +2. **Request a New Certificate:** + - Click on the "Request a certificate" button. + - Choose "Request a public certificate" or "Request a private certificate" based on your needs, then click "Next." + +3. **Configure Certificate Options:** + - Enter the domain names for your certificate. + - Under "Additional names (SANs)," add any additional domain names if needed. + - Click "Next." + +4. **Select Key Algorithm and RSA Key Length:** + - In the "Select validation method" step, choose your preferred validation method and click "Next." + - In the "Add tags" step, add any tags if necessary and click "Next." + - In the "Review" step, ensure that the "Key algorithm" is set to "RSA" and the "RSA key length" is set to at least 2048 bits. + - Click "Confirm and request" to complete the process. + +By following these steps, you ensure that your ACM certificates meet the minimum RSA length requirement, thereby preventing misconfigurations in API Gateway. + + + +To prevent the misconfiguration of ACM Certificates having a minimum RSA length in API Gateway using AWS CLI, follow these steps: + +1. **Create a Certificate with the Required RSA Length:** + Ensure that when you request a new ACM certificate, you specify the required RSA key length. AWS ACM supports RSA key lengths of 2048, 3072, and 4096 bits. + + ```sh + aws acm request-certificate \ + --domain-name example.com \ + --validation-method DNS \ + --options CertificateTransparencyLoggingPreference=ENABLED \ + --key-algorithm RSA_2048 + ``` + +2. **List Certificates to Verify RSA Length:** + List your ACM certificates and check their details to ensure they meet the required RSA length. + + ```sh + aws acm list-certificates + ``` + + To get detailed information about a specific certificate, including the key algorithm: + + ```sh + aws acm describe-certificate --certificate-arn + ``` + +3. **Associate the Certificate with API Gateway:** + When creating or updating an API Gateway custom domain name, ensure you associate it with the ACM certificate that has the required RSA length. + + ```sh + aws apigateway create-domain-name \ + --domain-name api.example.com \ + --certificate-arn + ``` + +4. **Verify Domain Name Configuration:** + After associating the certificate, verify the domain name configuration to ensure it is correctly set up with the required certificate. + + ```sh + aws apigateway get-domain-name --domain-name api.example.com + ``` + +By following these steps, you can ensure that your ACM certificates used in API Gateway have the minimum required RSA length, thereby preventing misconfigurations. + + + +To prevent ACM Certificates from having a minimum RSA length in API Gateway using Python scripts, you can use the AWS SDK for Python (Boto3). Below are the steps to ensure that ACM certificates have a minimum RSA length of 2048 bits: + +### Step 1: Install Boto3 +Ensure you have Boto3 installed in your Python environment. You can install it using pip if you haven't already: +```bash +pip install boto3 +``` + +### Step 2: Initialize Boto3 Client +Initialize the Boto3 client for ACM (AWS Certificate Manager) and API Gateway. + +```python +import boto3 + +acm_client = boto3.client('acm') +apigateway_client = boto3.client('apigateway') +``` + +### Step 3: List ACM Certificates +Fetch the list of ACM certificates and their details. + +```python +def list_acm_certificates(): + response = acm_client.list_certificates() + return response['CertificateSummaryList'] + +certificates = list_acm_certificates() +``` + +### Step 4: Validate RSA Key Length and Update API Gateway +Check the RSA key length of each certificate and ensure it meets the minimum requirement. If it does, associate it with the API Gateway. + +```python +def get_certificate_details(certificate_arn): + response = acm_client.describe_certificate(CertificateArn=certificate_arn) + return response['Certificate'] + +def validate_and_associate_certificates(certificates): + for cert in certificates: + cert_details = get_certificate_details(cert['CertificateArn']) + key_algorithm = cert_details['KeyAlgorithm'] + key_size = cert_details['KeySize'] + + if key_algorithm == 'RSA' and key_size >= 2048: + # Assuming you have the API Gateway ID and Domain Name + api_gateway_id = 'your_api_gateway_id' + domain_name = 'your_domain_name' + + apigateway_client.create_domain_name( + domainName=domain_name, + certificateArn=cert['CertificateArn'] + ) + print(f"Certificate {cert['CertificateArn']} with RSA {key_size} bits associated with API Gateway.") + else: + print(f"Certificate {cert['CertificateArn']} does not meet the RSA 2048 bits requirement.") + +validate_and_associate_certificates(certificates) +``` + +### Summary +1. **Install Boto3**: Ensure Boto3 is installed in your Python environment. +2. **Initialize Boto3 Client**: Initialize the ACM and API Gateway clients. +3. **List ACM Certificates**: Fetch the list of ACM certificates. +4. **Validate RSA Key Length and Update API Gateway**: Check the RSA key length and associate the certificate with API Gateway if it meets the minimum requirement. + +This script ensures that only ACM certificates with a minimum RSA length of 2048 bits are associated with your API Gateway, thereby preventing misconfigurations. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_30_days.mdx b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_30_days.mdx index dde25f1a..c5984e95 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_30_days.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_30_days.mdx @@ -24,6 +24,139 @@ NIST ### Triage and Remediation + + +### How to Prevent + + +To prevent AWS ACM Certificates from being renewed under 30 days in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to manage the ACM certificate. + - Click on the API name to open its configuration. + +3. **Check Custom Domain Names:** + - In the left-hand navigation pane, select "Custom domain names." + - Review the list of custom domain names associated with your API. + +4. **Review and Update ACM Certificates:** + - For each custom domain name, check the associated ACM certificate. + - Ensure that the certificate is not set to renew within 30 days by verifying the expiration date and renewal settings. + - If necessary, update the certificate to one with a longer validity period or adjust the renewal settings to avoid renewal under 30 days. + +By following these steps, you can ensure that your ACM certificates associated with API Gateway are managed properly and do not renew under 30 days. + + + +To prevent AWS ACM Certificates from being renewed under 30 days in API Gateway using AWS CLI, you can follow these steps: + +1. **List Existing Certificates:** + First, identify the ACM certificates that are currently in use by your API Gateway. This will help you understand which certificates need to be monitored for renewal. + + ```sh + aws acm list-certificates --query "CertificateSummaryList[*].{CertificateArn:CertificateArn,DomainName:DomainName}" + ``` + +2. **Describe Certificate Details:** + For each certificate, get detailed information to check the expiration date. This will help you determine if any certificates are nearing the 30-day renewal window. + + ```sh + aws acm describe-certificate --certificate-arn + ``` + +3. **Monitor Certificate Expiration:** + Implement a monitoring mechanism to regularly check the expiration dates of your certificates. You can use AWS CloudWatch or a custom script to alert you when a certificate is within the 30-day renewal window. + + ```sh + aws acm describe-certificate --certificate-arn --query "Certificate.NotAfter" + ``` + +4. **Update API Gateway with New Certificate:** + If a certificate is nearing the 30-day renewal window, manually update the API Gateway with a new certificate to avoid automatic renewal. This can be done by creating a new certificate and associating it with your API Gateway. + + ```sh + aws apigateway update-domain-name --domain-name --patch-operations op=replace,path=/certificateArn,value= + ``` + +By following these steps, you can prevent AWS ACM Certificates from being renewed under 30 days in API Gateway using AWS CLI. + + + +To prevent AWS ACM Certificates from being renewed under 30 days in API Gateway using Python scripts, you can follow these steps: + +1. **Set Up AWS SDK for Python (Boto3):** + - Ensure you have Boto3 installed and configured with the necessary permissions to interact with ACM and API Gateway. + + ```bash + pip install boto3 + ``` + +2. **List ACM Certificates:** + - Use Boto3 to list all ACM certificates and filter out those that are due for renewal within the next 30 days. + + ```python + import boto3 + from datetime import datetime, timedelta + + acm_client = boto3.client('acm') + + def list_certificates_due_for_renewal(): + response = acm_client.list_certificates() + certificates = response['CertificateSummaryList'] + due_for_renewal = [] + for cert in certificates: + cert_details = acm_client.describe_certificate(CertificateArn=cert['CertificateArn']) + not_after = cert_details['Certificate']['NotAfter'] + if not_after < datetime.now() + timedelta(days=30): + due_for_renewal.append(cert) + return due_for_renewal + ``` + +3. **Check API Gateway Custom Domain Names:** + - Use Boto3 to list all custom domain names in API Gateway and check if they are associated with any of the certificates due for renewal. + + ```python + apigateway_client = boto3.client('apigateway') + + def list_custom_domain_names(): + response = apigateway_client.get_domain_names() + return response['items'] + + def check_certificates_in_api_gateway(certificates): + domain_names = list_custom_domain_names() + for domain in domain_names: + if 'certificateArn' in domain: + for cert in certificates: + if domain['certificateArn'] == cert['CertificateArn']: + print(f"Domain {domain['domainName']} is using a certificate due for renewal: {cert['CertificateArn']}") + ``` + +4. **Prevent Renewal Under 30 Days:** + - Implement logic to prevent the renewal of certificates under 30 days by either notifying the responsible team or taking automated actions. + + ```python + def prevent_renewal_under_30_days(): + certificates_due_for_renewal = list_certificates_due_for_renewal() + if certificates_due_for_renewal: + check_certificates_in_api_gateway(certificates_due_for_renewal) + # Add logic to notify or take automated actions + # For example, send an email or log the details + print("Action required: Some certificates are due for renewal under 30 days.") + + if __name__ == "__main__": + prevent_renewal_under_30_days() + ``` + +By following these steps, you can identify and prevent AWS ACM certificates from being renewed under 30 days in API Gateway using Python scripts. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_30_days_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_30_days_remediation.mdx index 319be691..d93e5e8f 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_30_days_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_30_days_remediation.mdx @@ -2,6 +2,138 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent AWS ACM Certificates from being renewed under 30 days in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to manage the ACM certificate. + - Click on the API name to open its configuration. + +3. **Check Custom Domain Names:** + - In the left-hand navigation pane, select "Custom domain names." + - Review the list of custom domain names associated with your API. + +4. **Review and Update ACM Certificates:** + - For each custom domain name, check the associated ACM certificate. + - Ensure that the certificate is not set to renew within 30 days by verifying the expiration date and renewal settings. + - If necessary, update the certificate to one with a longer validity period or adjust the renewal settings to avoid renewal under 30 days. + +By following these steps, you can ensure that your ACM certificates associated with API Gateway are managed properly and do not renew under 30 days. + + + +To prevent AWS ACM Certificates from being renewed under 30 days in API Gateway using AWS CLI, you can follow these steps: + +1. **List Existing Certificates:** + First, identify the ACM certificates that are currently in use by your API Gateway. This will help you understand which certificates need to be monitored for renewal. + + ```sh + aws acm list-certificates --query "CertificateSummaryList[*].{CertificateArn:CertificateArn,DomainName:DomainName}" + ``` + +2. **Describe Certificate Details:** + For each certificate, get detailed information to check the expiration date. This will help you determine if any certificates are nearing the 30-day renewal window. + + ```sh + aws acm describe-certificate --certificate-arn + ``` + +3. **Monitor Certificate Expiration:** + Implement a monitoring mechanism to regularly check the expiration dates of your certificates. You can use AWS CloudWatch or a custom script to alert you when a certificate is within the 30-day renewal window. + + ```sh + aws acm describe-certificate --certificate-arn --query "Certificate.NotAfter" + ``` + +4. **Update API Gateway with New Certificate:** + If a certificate is nearing the 30-day renewal window, manually update the API Gateway with a new certificate to avoid automatic renewal. This can be done by creating a new certificate and associating it with your API Gateway. + + ```sh + aws apigateway update-domain-name --domain-name --patch-operations op=replace,path=/certificateArn,value= + ``` + +By following these steps, you can prevent AWS ACM Certificates from being renewed under 30 days in API Gateway using AWS CLI. + + + +To prevent AWS ACM Certificates from being renewed under 30 days in API Gateway using Python scripts, you can follow these steps: + +1. **Set Up AWS SDK for Python (Boto3):** + - Ensure you have Boto3 installed and configured with the necessary permissions to interact with ACM and API Gateway. + + ```bash + pip install boto3 + ``` + +2. **List ACM Certificates:** + - Use Boto3 to list all ACM certificates and filter out those that are due for renewal within the next 30 days. + + ```python + import boto3 + from datetime import datetime, timedelta + + acm_client = boto3.client('acm') + + def list_certificates_due_for_renewal(): + response = acm_client.list_certificates() + certificates = response['CertificateSummaryList'] + due_for_renewal = [] + for cert in certificates: + cert_details = acm_client.describe_certificate(CertificateArn=cert['CertificateArn']) + not_after = cert_details['Certificate']['NotAfter'] + if not_after < datetime.now() + timedelta(days=30): + due_for_renewal.append(cert) + return due_for_renewal + ``` + +3. **Check API Gateway Custom Domain Names:** + - Use Boto3 to list all custom domain names in API Gateway and check if they are associated with any of the certificates due for renewal. + + ```python + apigateway_client = boto3.client('apigateway') + + def list_custom_domain_names(): + response = apigateway_client.get_domain_names() + return response['items'] + + def check_certificates_in_api_gateway(certificates): + domain_names = list_custom_domain_names() + for domain in domain_names: + if 'certificateArn' in domain: + for cert in certificates: + if domain['certificateArn'] == cert['CertificateArn']: + print(f"Domain {domain['domainName']} is using a certificate due for renewal: {cert['CertificateArn']}") + ``` + +4. **Prevent Renewal Under 30 Days:** + - Implement logic to prevent the renewal of certificates under 30 days by either notifying the responsible team or taking automated actions. + + ```python + def prevent_renewal_under_30_days(): + certificates_due_for_renewal = list_certificates_due_for_renewal() + if certificates_due_for_renewal: + check_certificates_in_api_gateway(certificates_due_for_renewal) + # Add logic to notify or take automated actions + # For example, send an email or log the details + print("Action required: Some certificates are due for renewal under 30 days.") + + if __name__ == "__main__": + prevent_renewal_under_30_days() + ``` + +By following these steps, you can identify and prevent AWS ACM certificates from being renewed under 30 days in API Gateway using Python scripts. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_45_days.mdx b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_45_days.mdx index 9140524e..f9261391 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_45_days.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_45_days.mdx @@ -24,6 +24,132 @@ NIST ### Triage and Remediation + + +### How to Prevent + + +To prevent AWS ACM Certificates from being renewed under 45 days in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to ACM Console:** + - Open the AWS Management Console. + - In the search bar, type "ACM" and select "Certificate Manager" from the dropdown. + +2. **Review Certificate Expiration Dates:** + - In the ACM console, review the list of certificates. + - Check the expiration dates to ensure they are not set to renew within 45 days. + +3. **Update Certificate Renewal Settings:** + - Select the certificate that is set to renew under 45 days. + - Click on the "Actions" dropdown and choose "Edit renewal settings." + - Adjust the renewal settings to ensure the certificate is renewed at least 45 days before expiration. + +4. **Monitor Certificates:** + - Set up CloudWatch Alarms or AWS Config Rules to monitor certificate expiration dates. + - Ensure you receive notifications well in advance if a certificate is approaching the 45-day renewal window. + +By following these steps, you can ensure that your ACM certificates in API Gateway are not renewed under 45 days, thereby maintaining proper security and compliance. + + + +To prevent AWS ACM Certificates from being under 45 days of renewal in API Gateway using AWS CLI, you can follow these steps: + +1. **List All Certificates:** + Use the AWS CLI to list all the ACM certificates in your account. This will help you identify which certificates are nearing their expiration date. + + ```sh + aws acm list-certificates + ``` + +2. **Describe Certificate Details:** + For each certificate, get detailed information including the expiration date. This will help you determine if any certificates are within the 45-day renewal window. + + ```sh + aws acm describe-certificate --certificate-arn + ``` + +3. **Monitor Certificate Expiration:** + Set up a monitoring mechanism to regularly check the expiration dates of your certificates. You can use AWS CloudWatch Events to trigger a Lambda function that runs the above commands and checks for certificates nearing expiration. + + ```sh + aws events put-rule --name "CheckCertificateExpiration" --schedule-expression "rate(1 day)" + ``` + +4. **Automate Renewal Process:** + If a certificate is found to be within the 45-day renewal window, automate the renewal process using AWS CLI. This can be done by creating a script that renews the certificate and updates the API Gateway with the new certificate ARN. + + ```sh + aws acm renew-certificate --certificate-arn + aws apigateway update-domain-name --domain-name --patch-operations op=replace,path=/certificateArn,value= + ``` + +By following these steps, you can ensure that your ACM certificates are renewed well before they fall under the 45-day renewal window, thereby preventing any potential disruptions in your API Gateway services. + + + +To prevent AWS ACM Certificates from being renewed under 45 days in API Gateway using Python scripts, you can follow these steps: + +1. **Set Up AWS SDK for Python (Boto3):** + - Ensure you have Boto3 installed and configured with the necessary permissions to interact with ACM and API Gateway. + + ```bash + pip install boto3 + ``` + +2. **List ACM Certificates:** + - Use Boto3 to list all ACM certificates and filter out those that are associated with API Gateway. + + ```python + import boto3 + + acm_client = boto3.client('acm') + response = acm_client.list_certificates() + + certificates = response['CertificateSummaryList'] + ``` + +3. **Check Certificate Expiry Dates:** + - Iterate through the certificates and check their expiry dates. If the expiry date is within 45 days, log a warning or take appropriate action. + + ```python + from datetime import datetime, timedelta + + for cert in certificates: + cert_details = acm_client.describe_certificate(CertificateArn=cert['CertificateArn']) + expiry_date = cert_details['Certificate']['NotAfter'] + days_to_expiry = (expiry_date - datetime.now()).days + + if days_to_expiry < 45: + print(f"Warning: Certificate {cert['CertificateArn']} is expiring in {days_to_expiry} days.") + ``` + +4. **Automate the Monitoring:** + - Set up a scheduled Lambda function or a cron job to run this script periodically to ensure continuous monitoring and prevention of certificates being renewed under 45 days. + + ```python + import boto3 + from datetime import datetime, timedelta + + def lambda_handler(event, context): + acm_client = boto3.client('acm') + response = acm_client.list_certificates() + certificates = response['CertificateSummaryList'] + + for cert in certificates: + cert_details = acm_client.describe_certificate(CertificateArn=cert['CertificateArn']) + expiry_date = cert_details['Certificate']['NotAfter'] + days_to_expiry = (expiry_date - datetime.now()).days + + if days_to_expiry < 45: + print(f"Warning: Certificate {cert['CertificateArn']} is expiring in {days_to_expiry} days.") + ``` + +By following these steps, you can effectively monitor and prevent ACM certificates from being renewed under 45 days in API Gateway using Python scripts. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_45_days_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_45_days_remediation.mdx index 705ba316..f16f30f0 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_45_days_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_45_days_remediation.mdx @@ -2,6 +2,131 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent AWS ACM Certificates from being renewed under 45 days in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to ACM Console:** + - Open the AWS Management Console. + - In the search bar, type "ACM" and select "Certificate Manager" from the dropdown. + +2. **Review Certificate Expiration Dates:** + - In the ACM console, review the list of certificates. + - Check the expiration dates to ensure they are not set to renew within 45 days. + +3. **Update Certificate Renewal Settings:** + - Select the certificate that is set to renew under 45 days. + - Click on the "Actions" dropdown and choose "Edit renewal settings." + - Adjust the renewal settings to ensure the certificate is renewed at least 45 days before expiration. + +4. **Monitor Certificates:** + - Set up CloudWatch Alarms or AWS Config Rules to monitor certificate expiration dates. + - Ensure you receive notifications well in advance if a certificate is approaching the 45-day renewal window. + +By following these steps, you can ensure that your ACM certificates in API Gateway are not renewed under 45 days, thereby maintaining proper security and compliance. + + + +To prevent AWS ACM Certificates from being under 45 days of renewal in API Gateway using AWS CLI, you can follow these steps: + +1. **List All Certificates:** + Use the AWS CLI to list all the ACM certificates in your account. This will help you identify which certificates are nearing their expiration date. + + ```sh + aws acm list-certificates + ``` + +2. **Describe Certificate Details:** + For each certificate, get detailed information including the expiration date. This will help you determine if any certificates are within the 45-day renewal window. + + ```sh + aws acm describe-certificate --certificate-arn + ``` + +3. **Monitor Certificate Expiration:** + Set up a monitoring mechanism to regularly check the expiration dates of your certificates. You can use AWS CloudWatch Events to trigger a Lambda function that runs the above commands and checks for certificates nearing expiration. + + ```sh + aws events put-rule --name "CheckCertificateExpiration" --schedule-expression "rate(1 day)" + ``` + +4. **Automate Renewal Process:** + If a certificate is found to be within the 45-day renewal window, automate the renewal process using AWS CLI. This can be done by creating a script that renews the certificate and updates the API Gateway with the new certificate ARN. + + ```sh + aws acm renew-certificate --certificate-arn + aws apigateway update-domain-name --domain-name --patch-operations op=replace,path=/certificateArn,value= + ``` + +By following these steps, you can ensure that your ACM certificates are renewed well before they fall under the 45-day renewal window, thereby preventing any potential disruptions in your API Gateway services. + + + +To prevent AWS ACM Certificates from being renewed under 45 days in API Gateway using Python scripts, you can follow these steps: + +1. **Set Up AWS SDK for Python (Boto3):** + - Ensure you have Boto3 installed and configured with the necessary permissions to interact with ACM and API Gateway. + + ```bash + pip install boto3 + ``` + +2. **List ACM Certificates:** + - Use Boto3 to list all ACM certificates and filter out those that are associated with API Gateway. + + ```python + import boto3 + + acm_client = boto3.client('acm') + response = acm_client.list_certificates() + + certificates = response['CertificateSummaryList'] + ``` + +3. **Check Certificate Expiry Dates:** + - Iterate through the certificates and check their expiry dates. If the expiry date is within 45 days, log a warning or take appropriate action. + + ```python + from datetime import datetime, timedelta + + for cert in certificates: + cert_details = acm_client.describe_certificate(CertificateArn=cert['CertificateArn']) + expiry_date = cert_details['Certificate']['NotAfter'] + days_to_expiry = (expiry_date - datetime.now()).days + + if days_to_expiry < 45: + print(f"Warning: Certificate {cert['CertificateArn']} is expiring in {days_to_expiry} days.") + ``` + +4. **Automate the Monitoring:** + - Set up a scheduled Lambda function or a cron job to run this script periodically to ensure continuous monitoring and prevention of certificates being renewed under 45 days. + + ```python + import boto3 + from datetime import datetime, timedelta + + def lambda_handler(event, context): + acm_client = boto3.client('acm') + response = acm_client.list_certificates() + certificates = response['CertificateSummaryList'] + + for cert in certificates: + cert_details = acm_client.describe_certificate(CertificateArn=cert['CertificateArn']) + expiry_date = cert_details['Certificate']['NotAfter'] + days_to_expiry = (expiry_date - datetime.now()).days + + if days_to_expiry < 45: + print(f"Warning: Certificate {cert['CertificateArn']} is expiring in {days_to_expiry} days.") + ``` + +By following these steps, you can effectively monitor and prevent ACM certificates from being renewed under 45 days in API Gateway using Python scripts. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_7_days.mdx b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_7_days.mdx index 229fc96e..070b0bbb 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_7_days.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_7_days.mdx @@ -24,6 +24,161 @@ NIST ### Triage and Remediation + + +### How to Prevent + + +To prevent AWS ACM Certificates from being within 7 days of expiration in API Gateway using the AWS Management Console, follow these steps: + +1. **Monitor Certificate Expiration:** + - Navigate to the **AWS Certificate Manager (ACM)** in the AWS Management Console. + - Check the expiration dates of your certificates regularly. You can set up a CloudWatch alarm to notify you when a certificate is approaching its expiration date. + +2. **Enable Automatic Renewal:** + - Ensure that your ACM certificates are set to automatically renew. ACM automatically renews certificates that are in use with other AWS services, such as API Gateway, as long as the domain validation is still valid. + +3. **Update API Gateway with New Certificates:** + - Go to the **API Gateway** service in the AWS Management Console. + - Select the API that uses the ACM certificate. + - Under the **Custom Domain Names** section, ensure that the domain name is associated with the correct, automatically renewing ACM certificate. + +4. **Set Up Notifications:** + - Use **Amazon CloudWatch** to set up alarms and notifications for certificate expiration. + - Create a CloudWatch alarm that triggers an Amazon SNS notification when a certificate is within a certain number of days from expiration (e.g., 30 days). This will give you ample time to address any issues before the 7-day mark. + +By following these steps, you can ensure that your ACM certificates are renewed well before they are within 7 days of expiration, thus preventing any potential disruptions in your API Gateway services. + + + +To prevent AWS ACM Certificates from being within 7 days of expiration in API Gateway using AWS CLI, you can follow these steps: + +1. **List All Certificates:** + Use the AWS CLI to list all ACM certificates and their expiration dates. This helps you identify certificates that are nearing expiration. + ```sh + aws acm list-certificates --query "CertificateSummaryList[*].{CertificateArn:CertificateArn,DomainName:DomainName,NotAfter:NotAfter}" + ``` + +2. **Describe Certificate Details:** + For each certificate, get detailed information including the expiration date. + ```sh + aws acm describe-certificate --certificate-arn + ``` + +3. **Monitor Expiration Dates:** + Implement a monitoring script or use AWS CloudWatch to set up an alarm for certificates that are within 30 days of expiration. This can be done using a combination of AWS CLI and CloudWatch. + ```sh + aws cloudwatch put-metric-alarm --alarm-name "ACM-Certificate-Expiration" --metric-name "DaysToExpiry" --namespace "AWS/ACM" --statistic "Minimum" --period 86400 --threshold 30 --comparison-operator "LessThanThreshold" --dimensions Name=CertificateArn,Value= --evaluation-periods 1 --alarm-actions + ``` + +4. **Automate Certificate Renewal:** + Use AWS CLI to request a new certificate and update the API Gateway with the new certificate ARN before the old one expires. + ```sh + aws acm request-certificate --domain-name --validation-method DNS + aws apigateway update-domain-name --domain-name --patch-operations op=replace,path=/certificateArn,value= + ``` + +By following these steps, you can ensure that your ACM certificates are renewed well before they are within 7 days of expiration, thus preventing any potential disruptions in your API Gateway services. + + + +To prevent AWS ACM Certificates from being within 7 days of expiration in API Gateway using Python scripts, you can follow these steps: + +### 1. **Set Up AWS SDK for Python (Boto3)** +Ensure you have Boto3 installed and configured with the necessary permissions to access ACM and API Gateway. + +```bash +pip install boto3 +``` + +### 2. **List ACM Certificates** +Create a Python script to list all ACM certificates and check their expiration dates. + +```python +import boto3 +from datetime import datetime, timedelta + +# Initialize a session using Amazon ACM +acm_client = boto3.client('acm') + +# Get the current date +current_date = datetime.utcnow() + +# List all ACM certificates +certificates = acm_client.list_certificates() + +# Check each certificate's expiration date +for cert in certificates['CertificateSummaryList']: + cert_details = acm_client.describe_certificate(CertificateArn=cert['CertificateArn']) + expiration_date = cert_details['Certificate']['NotAfter'] + + # Calculate the difference in days + days_to_expire = (expiration_date - current_date).days + + if days_to_expire < 7: + print(f"Certificate {cert['CertificateArn']} is expiring in {days_to_expire} days.") +``` + +### 3. **Automate Certificate Renewal** +If a certificate is found to be expiring within 7 days, automate the renewal process. + +```python +# Function to renew a certificate +def renew_certificate(cert_arn): + response = acm_client.renew_certificate(CertificateArn=cert_arn) + return response + +# Renew certificates that are expiring within 7 days +for cert in certificates['CertificateSummaryList']: + cert_details = acm_client.describe_certificate(CertificateArn=cert['CertificateArn']) + expiration_date = cert_details['Certificate']['NotAfter'] + days_to_expire = (expiration_date - current_date).days + + if days_to_expire < 7: + renew_response = renew_certificate(cert['CertificateArn']) + print(f"Renewed certificate {cert['CertificateArn']}: {renew_response}") +``` + +### 4. **Update API Gateway with New Certificate** +After renewing the certificate, update the API Gateway to use the new certificate. + +```python +# Initialize a session using Amazon API Gateway +apigateway_client = boto3.client('apigateway') + +# Function to update API Gateway with new certificate +def update_api_gateway(domain_name, new_cert_arn): + response = apigateway_client.update_domain_name( + domainName=domain_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/certificateArn', + 'value': new_cert_arn + } + ] + ) + return response + +# Example: Update API Gateway with the new certificate +domain_name = 'example.com' # Replace with your domain name +new_cert_arn = 'arn:aws:acm:region:account-id:certificate/new-certificate-id' # Replace with your new certificate ARN +update_response = update_api_gateway(domain_name, new_cert_arn) +print(f"Updated API Gateway for domain {domain_name} with new certificate: {update_response}") +``` + +### Summary +1. **Set Up AWS SDK for Python (Boto3)**: Install and configure Boto3. +2. **List ACM Certificates**: Create a script to list and check expiration dates. +3. **Automate Certificate Renewal**: Renew certificates expiring within 7 days. +4. **Update API Gateway with New Certificate**: Update API Gateway to use the renewed certificate. + +By following these steps, you can automate the process of preventing ACM certificates from expiring within 7 days in API Gateway using Python scripts. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_7_days_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_7_days_remediation.mdx index 86b89fd6..2bfc523b 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_7_days_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_renewal_7_days_remediation.mdx @@ -2,6 +2,160 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent AWS ACM Certificates from being within 7 days of expiration in API Gateway using the AWS Management Console, follow these steps: + +1. **Monitor Certificate Expiration:** + - Navigate to the **AWS Certificate Manager (ACM)** in the AWS Management Console. + - Check the expiration dates of your certificates regularly. You can set up a CloudWatch alarm to notify you when a certificate is approaching its expiration date. + +2. **Enable Automatic Renewal:** + - Ensure that your ACM certificates are set to automatically renew. ACM automatically renews certificates that are in use with other AWS services, such as API Gateway, as long as the domain validation is still valid. + +3. **Update API Gateway with New Certificates:** + - Go to the **API Gateway** service in the AWS Management Console. + - Select the API that uses the ACM certificate. + - Under the **Custom Domain Names** section, ensure that the domain name is associated with the correct, automatically renewing ACM certificate. + +4. **Set Up Notifications:** + - Use **Amazon CloudWatch** to set up alarms and notifications for certificate expiration. + - Create a CloudWatch alarm that triggers an Amazon SNS notification when a certificate is within a certain number of days from expiration (e.g., 30 days). This will give you ample time to address any issues before the 7-day mark. + +By following these steps, you can ensure that your ACM certificates are renewed well before they are within 7 days of expiration, thus preventing any potential disruptions in your API Gateway services. + + + +To prevent AWS ACM Certificates from being within 7 days of expiration in API Gateway using AWS CLI, you can follow these steps: + +1. **List All Certificates:** + Use the AWS CLI to list all ACM certificates and their expiration dates. This helps you identify certificates that are nearing expiration. + ```sh + aws acm list-certificates --query "CertificateSummaryList[*].{CertificateArn:CertificateArn,DomainName:DomainName,NotAfter:NotAfter}" + ``` + +2. **Describe Certificate Details:** + For each certificate, get detailed information including the expiration date. + ```sh + aws acm describe-certificate --certificate-arn + ``` + +3. **Monitor Expiration Dates:** + Implement a monitoring script or use AWS CloudWatch to set up an alarm for certificates that are within 30 days of expiration. This can be done using a combination of AWS CLI and CloudWatch. + ```sh + aws cloudwatch put-metric-alarm --alarm-name "ACM-Certificate-Expiration" --metric-name "DaysToExpiry" --namespace "AWS/ACM" --statistic "Minimum" --period 86400 --threshold 30 --comparison-operator "LessThanThreshold" --dimensions Name=CertificateArn,Value= --evaluation-periods 1 --alarm-actions + ``` + +4. **Automate Certificate Renewal:** + Use AWS CLI to request a new certificate and update the API Gateway with the new certificate ARN before the old one expires. + ```sh + aws acm request-certificate --domain-name --validation-method DNS + aws apigateway update-domain-name --domain-name --patch-operations op=replace,path=/certificateArn,value= + ``` + +By following these steps, you can ensure that your ACM certificates are renewed well before they are within 7 days of expiration, thus preventing any potential disruptions in your API Gateway services. + + + +To prevent AWS ACM Certificates from being within 7 days of expiration in API Gateway using Python scripts, you can follow these steps: + +### 1. **Set Up AWS SDK for Python (Boto3)** +Ensure you have Boto3 installed and configured with the necessary permissions to access ACM and API Gateway. + +```bash +pip install boto3 +``` + +### 2. **List ACM Certificates** +Create a Python script to list all ACM certificates and check their expiration dates. + +```python +import boto3 +from datetime import datetime, timedelta + +# Initialize a session using Amazon ACM +acm_client = boto3.client('acm') + +# Get the current date +current_date = datetime.utcnow() + +# List all ACM certificates +certificates = acm_client.list_certificates() + +# Check each certificate's expiration date +for cert in certificates['CertificateSummaryList']: + cert_details = acm_client.describe_certificate(CertificateArn=cert['CertificateArn']) + expiration_date = cert_details['Certificate']['NotAfter'] + + # Calculate the difference in days + days_to_expire = (expiration_date - current_date).days + + if days_to_expire < 7: + print(f"Certificate {cert['CertificateArn']} is expiring in {days_to_expire} days.") +``` + +### 3. **Automate Certificate Renewal** +If a certificate is found to be expiring within 7 days, automate the renewal process. + +```python +# Function to renew a certificate +def renew_certificate(cert_arn): + response = acm_client.renew_certificate(CertificateArn=cert_arn) + return response + +# Renew certificates that are expiring within 7 days +for cert in certificates['CertificateSummaryList']: + cert_details = acm_client.describe_certificate(CertificateArn=cert['CertificateArn']) + expiration_date = cert_details['Certificate']['NotAfter'] + days_to_expire = (expiration_date - current_date).days + + if days_to_expire < 7: + renew_response = renew_certificate(cert['CertificateArn']) + print(f"Renewed certificate {cert['CertificateArn']}: {renew_response}") +``` + +### 4. **Update API Gateway with New Certificate** +After renewing the certificate, update the API Gateway to use the new certificate. + +```python +# Initialize a session using Amazon API Gateway +apigateway_client = boto3.client('apigateway') + +# Function to update API Gateway with new certificate +def update_api_gateway(domain_name, new_cert_arn): + response = apigateway_client.update_domain_name( + domainName=domain_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/certificateArn', + 'value': new_cert_arn + } + ] + ) + return response + +# Example: Update API Gateway with the new certificate +domain_name = 'example.com' # Replace with your domain name +new_cert_arn = 'arn:aws:acm:region:account-id:certificate/new-certificate-id' # Replace with your new certificate ARN +update_response = update_api_gateway(domain_name, new_cert_arn) +print(f"Updated API Gateway for domain {domain_name} with new certificate: {update_response}") +``` + +### Summary +1. **Set Up AWS SDK for Python (Boto3)**: Install and configure Boto3. +2. **List ACM Certificates**: Create a script to list and check expiration dates. +3. **Automate Certificate Renewal**: Renew certificates expiring within 7 days. +4. **Update API Gateway with New Certificate**: Update API Gateway to use the renewed certificate. + +By following these steps, you can automate the process of preventing ACM certificates from expiring within 7 days in API Gateway using Python scripts. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_validity.mdx b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_validity.mdx index 6ad68f97..342080ba 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_validity.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_validity.mdx @@ -24,6 +24,155 @@ NIST ### Triage and Remediation + + +### How to Prevent + + +To prevent AWS ACM Certificates from not being valid in API Gateway using the AWS Management Console, follow these steps: + +1. **Request a Valid ACM Certificate:** + - Navigate to the **AWS Certificate Manager (ACM)** in the AWS Management Console. + - Click on **Request a certificate**. + - Choose **Request a public certificate** and click **Next**. + - Enter the domain names for the certificate and click **Next**. + - Choose a validation method (DNS or Email) and follow the instructions to validate the domain. + - Once validated, the certificate will be issued and available for use. + +2. **Ensure Certificate is in the Same Region:** + - Make sure the ACM certificate is requested and issued in the same AWS region where your API Gateway is deployed. + - ACM certificates are region-specific and must match the region of the API Gateway. + +3. **Associate the ACM Certificate with API Gateway:** + - Navigate to the **API Gateway** service in the AWS Management Console. + - Select the API you want to configure. + - Go to the **Custom Domain Names** section and click on **Create**. + - Enter the domain name and select the ACM certificate from the dropdown list. + - Click **Save** to associate the certificate with the custom domain. + +4. **Verify Domain Name Configuration:** + - Ensure that the custom domain name is correctly configured in your DNS provider to point to the API Gateway. + - Create a CNAME record in your DNS provider that maps your custom domain name to the API Gateway domain name provided in the API Gateway console. + +By following these steps, you can prevent issues related to invalid ACM certificates in AWS API Gateway using the AWS Management Console. + + + +To prevent AWS ACM Certificates from not being valid in API Gateway using AWS CLI, follow these steps: + +1. **Request a Valid ACM Certificate:** + Ensure you request a valid ACM certificate for your domain. Use the following command to request a certificate: + ```sh + aws acm request-certificate --domain-name yourdomain.com --validation-method DNS + ``` + +2. **Validate the ACM Certificate:** + After requesting the certificate, validate it using DNS or email validation. For DNS validation, you will need to add a CNAME record to your DNS configuration. Use the following command to describe the certificate and get the validation details: + ```sh + aws acm describe-certificate --certificate-arn arn:aws:acm:region:account-id:certificate/certificate-id + ``` + +3. **Associate the ACM Certificate with API Gateway:** + Once the certificate is validated, associate it with your API Gateway custom domain name. Use the following command to create or update the custom domain name with the ACM certificate: + ```sh + aws apigateway create-domain-name --domain-name yourdomain.com --certificate-arn arn:aws:acm:region:account-id:certificate/certificate-id + ``` + +4. **Deploy API Gateway with the Custom Domain:** + Finally, deploy your API Gateway stages to use the custom domain name. Use the following command to create a base path mapping: + ```sh + aws apigateway create-base-path-mapping --domain-name yourdomain.com --rest-api-id your-rest-api-id --stage your-stage + ``` + +By following these steps, you ensure that your ACM certificates are valid and properly associated with your API Gateway, preventing any misconfigurations. + + + +To prevent AWS ACM Certificates from not being valid in API Gateway using Python scripts, you can follow these steps: + +1. **Ensure ACM Certificate is Issued and Valid:** + - Use the `boto3` library to check the status of the ACM certificate and ensure it is issued and valid before associating it with API Gateway. + + ```python + import boto3 + + acm_client = boto3.client('acm') + + def is_certificate_valid(certificate_arn): + response = acm_client.describe_certificate(CertificateArn=certificate_arn) + status = response['Certificate']['Status'] + return status == 'ISSUED' + + certificate_arn = 'arn:aws:acm:region:account-id:certificate/certificate-id' + if is_certificate_valid(certificate_arn): + print("Certificate is valid and issued.") + else: + print("Certificate is not valid or not issued.") + ``` + +2. **Associate Valid ACM Certificate with API Gateway Custom Domain:** + - Ensure that the valid ACM certificate is associated with the API Gateway custom domain name. + + ```python + apigateway_client = boto3.client('apigateway') + + def create_custom_domain(domain_name, certificate_arn): + response = apigateway_client.create_domain_name( + domainName=domain_name, + certificateArn=certificate_arn + ) + return response + + domain_name = 'example.com' + if is_certificate_valid(certificate_arn): + create_custom_domain(domain_name, certificate_arn) + print(f"Custom domain {domain_name} created with valid certificate.") + else: + print("Cannot create custom domain with invalid certificate.") + ``` + +3. **Verify Domain Ownership:** + - Ensure that the domain ownership verification is completed for the ACM certificate. + + ```python + def is_domain_verified(certificate_arn): + response = acm_client.describe_certificate(CertificateArn=certificate_arn) + options = response['Certificate']['DomainValidationOptions'] + for option in options: + if option['ValidationStatus'] != 'SUCCESS': + return False + return True + + if is_domain_verified(certificate_arn): + print("Domain ownership is verified.") + else: + print("Domain ownership is not verified.") + ``` + +4. **Automate Renewal and Validation:** + - Set up automation to renew and validate the ACM certificate periodically to ensure it remains valid. + + ```python + import time + + def renew_certificate(certificate_arn): + # ACM automatically renews certificates, but you can trigger validation if needed + response = acm_client.renew_certificate(CertificateArn=certificate_arn) + return response + + while True: + if not is_certificate_valid(certificate_arn): + renew_certificate(certificate_arn) + print("Certificate renewed.") + time.sleep(86400) # Check every 24 hours + ``` + +By following these steps, you can ensure that your ACM certificates remain valid and properly associated with your API Gateway custom domains, preventing misconfigurations. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_validity_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_validity_remediation.mdx index e518d354..77dc6141 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_validity_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_validity_remediation.mdx @@ -2,6 +2,154 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent AWS ACM Certificates from not being valid in API Gateway using the AWS Management Console, follow these steps: + +1. **Request a Valid ACM Certificate:** + - Navigate to the **AWS Certificate Manager (ACM)** in the AWS Management Console. + - Click on **Request a certificate**. + - Choose **Request a public certificate** and click **Next**. + - Enter the domain names for the certificate and click **Next**. + - Choose a validation method (DNS or Email) and follow the instructions to validate the domain. + - Once validated, the certificate will be issued and available for use. + +2. **Ensure Certificate is in the Same Region:** + - Make sure the ACM certificate is requested and issued in the same AWS region where your API Gateway is deployed. + - ACM certificates are region-specific and must match the region of the API Gateway. + +3. **Associate the ACM Certificate with API Gateway:** + - Navigate to the **API Gateway** service in the AWS Management Console. + - Select the API you want to configure. + - Go to the **Custom Domain Names** section and click on **Create**. + - Enter the domain name and select the ACM certificate from the dropdown list. + - Click **Save** to associate the certificate with the custom domain. + +4. **Verify Domain Name Configuration:** + - Ensure that the custom domain name is correctly configured in your DNS provider to point to the API Gateway. + - Create a CNAME record in your DNS provider that maps your custom domain name to the API Gateway domain name provided in the API Gateway console. + +By following these steps, you can prevent issues related to invalid ACM certificates in AWS API Gateway using the AWS Management Console. + + + +To prevent AWS ACM Certificates from not being valid in API Gateway using AWS CLI, follow these steps: + +1. **Request a Valid ACM Certificate:** + Ensure you request a valid ACM certificate for your domain. Use the following command to request a certificate: + ```sh + aws acm request-certificate --domain-name yourdomain.com --validation-method DNS + ``` + +2. **Validate the ACM Certificate:** + After requesting the certificate, validate it using DNS or email validation. For DNS validation, you will need to add a CNAME record to your DNS configuration. Use the following command to describe the certificate and get the validation details: + ```sh + aws acm describe-certificate --certificate-arn arn:aws:acm:region:account-id:certificate/certificate-id + ``` + +3. **Associate the ACM Certificate with API Gateway:** + Once the certificate is validated, associate it with your API Gateway custom domain name. Use the following command to create or update the custom domain name with the ACM certificate: + ```sh + aws apigateway create-domain-name --domain-name yourdomain.com --certificate-arn arn:aws:acm:region:account-id:certificate/certificate-id + ``` + +4. **Deploy API Gateway with the Custom Domain:** + Finally, deploy your API Gateway stages to use the custom domain name. Use the following command to create a base path mapping: + ```sh + aws apigateway create-base-path-mapping --domain-name yourdomain.com --rest-api-id your-rest-api-id --stage your-stage + ``` + +By following these steps, you ensure that your ACM certificates are valid and properly associated with your API Gateway, preventing any misconfigurations. + + + +To prevent AWS ACM Certificates from not being valid in API Gateway using Python scripts, you can follow these steps: + +1. **Ensure ACM Certificate is Issued and Valid:** + - Use the `boto3` library to check the status of the ACM certificate and ensure it is issued and valid before associating it with API Gateway. + + ```python + import boto3 + + acm_client = boto3.client('acm') + + def is_certificate_valid(certificate_arn): + response = acm_client.describe_certificate(CertificateArn=certificate_arn) + status = response['Certificate']['Status'] + return status == 'ISSUED' + + certificate_arn = 'arn:aws:acm:region:account-id:certificate/certificate-id' + if is_certificate_valid(certificate_arn): + print("Certificate is valid and issued.") + else: + print("Certificate is not valid or not issued.") + ``` + +2. **Associate Valid ACM Certificate with API Gateway Custom Domain:** + - Ensure that the valid ACM certificate is associated with the API Gateway custom domain name. + + ```python + apigateway_client = boto3.client('apigateway') + + def create_custom_domain(domain_name, certificate_arn): + response = apigateway_client.create_domain_name( + domainName=domain_name, + certificateArn=certificate_arn + ) + return response + + domain_name = 'example.com' + if is_certificate_valid(certificate_arn): + create_custom_domain(domain_name, certificate_arn) + print(f"Custom domain {domain_name} created with valid certificate.") + else: + print("Cannot create custom domain with invalid certificate.") + ``` + +3. **Verify Domain Ownership:** + - Ensure that the domain ownership verification is completed for the ACM certificate. + + ```python + def is_domain_verified(certificate_arn): + response = acm_client.describe_certificate(CertificateArn=certificate_arn) + options = response['Certificate']['DomainValidationOptions'] + for option in options: + if option['ValidationStatus'] != 'SUCCESS': + return False + return True + + if is_domain_verified(certificate_arn): + print("Domain ownership is verified.") + else: + print("Domain ownership is not verified.") + ``` + +4. **Automate Renewal and Validation:** + - Set up automation to renew and validate the ACM certificate periodically to ensure it remains valid. + + ```python + import time + + def renew_certificate(certificate_arn): + # ACM automatically renews certificates, but you can trigger validation if needed + response = acm_client.renew_certificate(CertificateArn=certificate_arn) + return response + + while True: + if not is_certificate_valid(certificate_arn): + renew_certificate(certificate_arn) + print("Certificate renewed.") + time.sleep(86400) # Check every 24 hours + ``` + +By following these steps, you can ensure that your ACM certificates remain valid and properly associated with your API Gateway custom domains, preventing misconfigurations. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_wildcard_domain_names.mdx b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_wildcard_domain_names.mdx index 9b223a3b..5c1c3c37 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_wildcard_domain_names.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_wildcard_domain_names.mdx @@ -24,6 +24,147 @@ NIST ### Triage and Remediation + + +### How to Prevent + + +To prevent the use of AWS ACM Certificates with wildcard domain names in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to configure the custom domain name. + +3. **Configure Custom Domain Name:** + - In the left-hand navigation pane, click on "Custom domain names." + - Click on "Create Custom Domain Name" or select an existing custom domain name to edit. + +4. **Specify Certificate:** + - In the "Create Custom Domain Name" or "Edit Custom Domain Name" page, ensure that you select an ACM certificate that does not use a wildcard domain name. Instead, use a specific domain name certificate. + - Save the changes by clicking on the "Save" or "Create" button. + +By following these steps, you can ensure that only specific domain name certificates are used in API Gateway, thereby preventing the use of wildcard domain names. + + + +To prevent the use of AWS ACM Certificates with wildcard domain names in API Gateway using AWS CLI, you can follow these steps: + +1. **List Existing Certificates**: + First, identify all the ACM certificates in your account to check for any wildcard certificates. + ```sh + aws acm list-certificates --query "CertificateSummaryList[?DomainName=='*.example.com']" + ``` + +2. **Describe Certificate**: + If you find any wildcard certificates, describe them to get more details and ensure they are not used in API Gateway. + ```sh + aws acm describe-certificate --certificate-arn + ``` + +3. **List API Gateway Custom Domain Names**: + List all custom domain names in API Gateway to check if any of them are using wildcard certificates. + ```sh + aws apigateway get-domain-names + ``` + +4. **Update API Gateway Custom Domain Name**: + If you find any custom domain names using wildcard certificates, update them to use a specific domain certificate instead. + ```sh + aws apigateway update-domain-name --domain-name --patch-operations op=replace,path=/certificateArn,value= + ``` + +By following these steps, you can ensure that wildcard domain names are not used in API Gateway, thereby preventing potential misconfigurations. + + + +To prevent the use of AWS ACM Certificates with wildcard domain names in API Gateway using Python scripts, you can follow these steps: + +1. **Set Up AWS SDK for Python (Boto3):** + Ensure you have Boto3 installed and configured with the necessary permissions to interact with AWS ACM and API Gateway. + + ```bash + pip install boto3 + ``` + +2. **List ACM Certificates:** + Use Boto3 to list all ACM certificates and filter out those with wildcard domain names. + + ```python + import boto3 + + acm_client = boto3.client('acm') + + def list_wildcard_certificates(): + paginator = acm_client.get_paginator('list_certificates') + for page in paginator.paginate(): + for cert in page['CertificateSummaryList']: + cert_details = acm_client.describe_certificate(CertificateArn=cert['CertificateArn']) + domain_name = cert_details['Certificate']['DomainName'] + if domain_name.startswith('*.'): + yield cert['CertificateArn'] + + wildcard_certs = list(list_wildcard_certificates()) + ``` + +3. **Check API Gateway Custom Domain Names:** + Use Boto3 to list all custom domain names in API Gateway and check if any of them are using the wildcard certificates identified in the previous step. + + ```python + apigateway_client = boto3.client('apigateway') + + def list_custom_domain_names(): + paginator = apigateway_client.get_paginator('get_domain_names') + for page in paginator.paginate(): + for domain in page['items']: + yield domain + + def check_wildcard_cert_usage(): + for domain in list_custom_domain_names(): + if 'certificateArn' in domain and domain['certificateArn'] in wildcard_certs: + print(f"Custom domain {domain['domainName']} is using a wildcard certificate: {domain['certificateArn']}") + + check_wildcard_cert_usage() + ``` + +4. **Prevent Future Use of Wildcard Certificates:** + Implement a policy or automation to prevent the association of wildcard certificates with API Gateway custom domain names. This can be done by creating a Lambda function that triggers on certificate creation or domain name association events and checks for wildcard certificates. + + ```python + import json + + def lambda_handler(event, context): + for record in event['Records']: + if record['eventName'] == 'CreateCertificate': + cert_arn = record['responseElements']['certificateArn'] + cert_details = acm_client.describe_certificate(CertificateArn=cert_arn) + domain_name = cert_details['Certificate']['DomainName'] + if domain_name.startswith('*.'): + raise Exception(f"Wildcard certificates are not allowed: {cert_arn}") + + # Example event structure for testing + test_event = { + "Records": [ + { + "eventName": "CreateCertificate", + "responseElements": { + "certificateArn": "arn:aws:acm:region:account-id:certificate/certificate-id" + } + } + ] + } + + lambda_handler(test_event, None) + ``` + +By following these steps, you can prevent the use of wildcard domain names in AWS ACM certificates for API Gateway custom domain names using Python scripts. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_wildcard_domain_names_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_wildcard_domain_names_remediation.mdx index ecca0ce7..85cb514a 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_wildcard_domain_names_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/acm_certificates_wildcard_domain_names_remediation.mdx @@ -2,6 +2,146 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent the use of AWS ACM Certificates with wildcard domain names in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to configure the custom domain name. + +3. **Configure Custom Domain Name:** + - In the left-hand navigation pane, click on "Custom domain names." + - Click on "Create Custom Domain Name" or select an existing custom domain name to edit. + +4. **Specify Certificate:** + - In the "Create Custom Domain Name" or "Edit Custom Domain Name" page, ensure that you select an ACM certificate that does not use a wildcard domain name. Instead, use a specific domain name certificate. + - Save the changes by clicking on the "Save" or "Create" button. + +By following these steps, you can ensure that only specific domain name certificates are used in API Gateway, thereby preventing the use of wildcard domain names. + + + +To prevent the use of AWS ACM Certificates with wildcard domain names in API Gateway using AWS CLI, you can follow these steps: + +1. **List Existing Certificates**: + First, identify all the ACM certificates in your account to check for any wildcard certificates. + ```sh + aws acm list-certificates --query "CertificateSummaryList[?DomainName=='*.example.com']" + ``` + +2. **Describe Certificate**: + If you find any wildcard certificates, describe them to get more details and ensure they are not used in API Gateway. + ```sh + aws acm describe-certificate --certificate-arn + ``` + +3. **List API Gateway Custom Domain Names**: + List all custom domain names in API Gateway to check if any of them are using wildcard certificates. + ```sh + aws apigateway get-domain-names + ``` + +4. **Update API Gateway Custom Domain Name**: + If you find any custom domain names using wildcard certificates, update them to use a specific domain certificate instead. + ```sh + aws apigateway update-domain-name --domain-name --patch-operations op=replace,path=/certificateArn,value= + ``` + +By following these steps, you can ensure that wildcard domain names are not used in API Gateway, thereby preventing potential misconfigurations. + + + +To prevent the use of AWS ACM Certificates with wildcard domain names in API Gateway using Python scripts, you can follow these steps: + +1. **Set Up AWS SDK for Python (Boto3):** + Ensure you have Boto3 installed and configured with the necessary permissions to interact with AWS ACM and API Gateway. + + ```bash + pip install boto3 + ``` + +2. **List ACM Certificates:** + Use Boto3 to list all ACM certificates and filter out those with wildcard domain names. + + ```python + import boto3 + + acm_client = boto3.client('acm') + + def list_wildcard_certificates(): + paginator = acm_client.get_paginator('list_certificates') + for page in paginator.paginate(): + for cert in page['CertificateSummaryList']: + cert_details = acm_client.describe_certificate(CertificateArn=cert['CertificateArn']) + domain_name = cert_details['Certificate']['DomainName'] + if domain_name.startswith('*.'): + yield cert['CertificateArn'] + + wildcard_certs = list(list_wildcard_certificates()) + ``` + +3. **Check API Gateway Custom Domain Names:** + Use Boto3 to list all custom domain names in API Gateway and check if any of them are using the wildcard certificates identified in the previous step. + + ```python + apigateway_client = boto3.client('apigateway') + + def list_custom_domain_names(): + paginator = apigateway_client.get_paginator('get_domain_names') + for page in paginator.paginate(): + for domain in page['items']: + yield domain + + def check_wildcard_cert_usage(): + for domain in list_custom_domain_names(): + if 'certificateArn' in domain and domain['certificateArn'] in wildcard_certs: + print(f"Custom domain {domain['domainName']} is using a wildcard certificate: {domain['certificateArn']}") + + check_wildcard_cert_usage() + ``` + +4. **Prevent Future Use of Wildcard Certificates:** + Implement a policy or automation to prevent the association of wildcard certificates with API Gateway custom domain names. This can be done by creating a Lambda function that triggers on certificate creation or domain name association events and checks for wildcard certificates. + + ```python + import json + + def lambda_handler(event, context): + for record in event['Records']: + if record['eventName'] == 'CreateCertificate': + cert_arn = record['responseElements']['certificateArn'] + cert_details = acm_client.describe_certificate(CertificateArn=cert_arn) + domain_name = cert_details['Certificate']['DomainName'] + if domain_name.startswith('*.'): + raise Exception(f"Wildcard certificates are not allowed: {cert_arn}") + + # Example event structure for testing + test_event = { + "Records": [ + { + "eventName": "CreateCertificate", + "responseElements": { + "certificateArn": "arn:aws:acm:region:account-id:certificate/certificate-id" + } + } + ] + } + + lambda_handler(test_event, None) + ``` + +By following these steps, you can prevent the use of wildcard domain names in AWS ACM certificates for API Gateway custom domain names using Python scripts. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/api_gateway_xray_enabled.mdx b/docs/aws/audit/apigatewaymonitoring/rules/api_gateway_xray_enabled.mdx index 465e5fcf..ff17d370 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/api_gateway_xray_enabled.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/api_gateway_xray_enabled.mdx @@ -24,6 +24,157 @@ CBP ### Triage and Remediation + + +### How to Prevent + + +To prevent the misconfiguration of "API Gateway X-Ray Should Be Enabled" in AWS API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to enable X-Ray tracing. + +3. **Enable X-Ray Tracing:** + - In the left-hand navigation pane, select "Stages." + - Choose the stage you want to configure (e.g., "prod" or "dev"). + - In the "Stage Editor" pane, scroll down to the "Tracing" section. + - Check the box labeled "Enable X-Ray Tracing." + +4. **Deploy the Changes:** + - After enabling X-Ray tracing, click the "Save Changes" button at the top of the Stage Editor pane. + - If necessary, redeploy the API to ensure the changes take effect. + +By following these steps, you can ensure that X-Ray tracing is enabled for your API Gateway, which helps in monitoring and debugging your API calls. + + + +To prevent the misconfiguration of not having AWS X-Ray enabled in API Gateway using AWS CLI, follow these steps: + +1. **Create or Update API Gateway Stage with X-Ray Tracing Enabled:** + Ensure that the stage of your API Gateway has X-Ray tracing enabled. You can do this by creating a new stage or updating an existing one. + + ```sh + aws apigateway create-stage --rest-api-id --stage-name --tracing-enabled + ``` + + Or, if you are updating an existing stage: + + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/tracingEnabled,value=true + ``` + +2. **Verify X-Ray Tracing is Enabled:** + After enabling X-Ray tracing, verify that it is correctly set up by describing the stage. + + ```sh + aws apigateway get-stage --rest-api-id --stage-name + ``` + + Look for the `tracingEnabled` field in the output to ensure it is set to `true`. + +3. **Enable X-Ray Tracing for All Stages (Optional):** + If you want to ensure that X-Ray tracing is enabled for all stages of a specific API Gateway, you can loop through all stages and enable tracing. + + ```sh + stages=$(aws apigateway get-stages --rest-api-id --query 'item[*].stageName' --output text) + for stage in $stages; do + aws apigateway update-stage --rest-api-id --stage-name $stage --patch-operations op=replace,path=/tracingEnabled,value=true + done + ``` + +4. **Automate the Process with a Script (Optional):** + To ensure that X-Ray tracing is always enabled, you can create a script that checks and enables X-Ray tracing for all stages periodically. + + ```sh + #!/bin/bash + rest_api_id= + stages=$(aws apigateway get-stages --rest-api-id $rest_api_id --query 'item[*].stageName' --output text) + for stage in $stages; do + tracing_enabled=$(aws apigateway get-stage --rest-api-id $rest_api_id --stage-name $stage --query 'tracingEnabled' --output text) + if [ "$tracing_enabled" != "true" ]; then + aws apigateway update-stage --rest-api-id $rest_api_id --stage-name $stage --patch-operations op=replace,path=/tracingEnabled,value=true + fi + done + ``` + +By following these steps, you can ensure that X-Ray tracing is enabled for your API Gateway stages, helping you to prevent the misconfiguration. + + + +To prevent the misconfiguration of API Gateway X-Ray not being enabled in AWS API Gateway using Python scripts, you can follow these steps: + +1. **Install Boto3 Library**: + Ensure you have the Boto3 library installed, which is the AWS SDK for Python. You can install it using pip if you haven't already. + + ```bash + pip install boto3 + ``` + +2. **Set Up AWS Credentials**: + Make sure your AWS credentials are configured. You can set them up using the AWS CLI or by setting environment variables. + + ```bash + aws configure + ``` + + Alternatively, you can set the environment variables directly in your script: + + ```python + import os + + os.environ['AWS_ACCESS_KEY_ID'] = 'your_access_key_id' + os.environ['AWS_SECRET_ACCESS_KEY'] = 'your_secret_access_key' + os.environ['AWS_DEFAULT_REGION'] = 'your_default_region' + ``` + +3. **Enable X-Ray Tracing for API Gateway**: + Use the Boto3 library to enable X-Ray tracing for your API Gateway. Below is a Python script to enable X-Ray tracing for a specific API Gateway stage. + + ```python + import boto3 + + # Initialize the API Gateway client + client = boto3.client('apigateway') + + # Define the API ID and stage name + api_id = 'your_api_id' + stage_name = 'your_stage_name' + + # Update the stage to enable X-Ray tracing + response = client.update_stage( + restApiId=api_id, + stageName=stage_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/tracingEnabled', + 'value': 'true' + } + ] + ) + + print(f"X-Ray tracing enabled for API Gateway stage {stage_name}: {response}") + ``` + +4. **Verify the Configuration**: + After running the script, you can verify that X-Ray tracing is enabled by checking the API Gateway stage settings in the AWS Management Console or by using the AWS CLI. + + ```bash + aws apigateway get-stage --rest-api-id your_api_id --stage-name your_stage_name + ``` + + Look for the `tracingEnabled` attribute in the output to ensure it is set to `true`. + +By following these steps, you can programmatically ensure that X-Ray tracing is enabled for your API Gateway stages, helping to prevent the misconfiguration. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/api_gateway_xray_enabled_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/api_gateway_xray_enabled_remediation.mdx index c38419ba..e5e1d1b7 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/api_gateway_xray_enabled_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/api_gateway_xray_enabled_remediation.mdx @@ -2,6 +2,156 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent the misconfiguration of "API Gateway X-Ray Should Be Enabled" in AWS API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to enable X-Ray tracing. + +3. **Enable X-Ray Tracing:** + - In the left-hand navigation pane, select "Stages." + - Choose the stage you want to configure (e.g., "prod" or "dev"). + - In the "Stage Editor" pane, scroll down to the "Tracing" section. + - Check the box labeled "Enable X-Ray Tracing." + +4. **Deploy the Changes:** + - After enabling X-Ray tracing, click the "Save Changes" button at the top of the Stage Editor pane. + - If necessary, redeploy the API to ensure the changes take effect. + +By following these steps, you can ensure that X-Ray tracing is enabled for your API Gateway, which helps in monitoring and debugging your API calls. + + + +To prevent the misconfiguration of not having AWS X-Ray enabled in API Gateway using AWS CLI, follow these steps: + +1. **Create or Update API Gateway Stage with X-Ray Tracing Enabled:** + Ensure that the stage of your API Gateway has X-Ray tracing enabled. You can do this by creating a new stage or updating an existing one. + + ```sh + aws apigateway create-stage --rest-api-id --stage-name --tracing-enabled + ``` + + Or, if you are updating an existing stage: + + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/tracingEnabled,value=true + ``` + +2. **Verify X-Ray Tracing is Enabled:** + After enabling X-Ray tracing, verify that it is correctly set up by describing the stage. + + ```sh + aws apigateway get-stage --rest-api-id --stage-name + ``` + + Look for the `tracingEnabled` field in the output to ensure it is set to `true`. + +3. **Enable X-Ray Tracing for All Stages (Optional):** + If you want to ensure that X-Ray tracing is enabled for all stages of a specific API Gateway, you can loop through all stages and enable tracing. + + ```sh + stages=$(aws apigateway get-stages --rest-api-id --query 'item[*].stageName' --output text) + for stage in $stages; do + aws apigateway update-stage --rest-api-id --stage-name $stage --patch-operations op=replace,path=/tracingEnabled,value=true + done + ``` + +4. **Automate the Process with a Script (Optional):** + To ensure that X-Ray tracing is always enabled, you can create a script that checks and enables X-Ray tracing for all stages periodically. + + ```sh + #!/bin/bash + rest_api_id= + stages=$(aws apigateway get-stages --rest-api-id $rest_api_id --query 'item[*].stageName' --output text) + for stage in $stages; do + tracing_enabled=$(aws apigateway get-stage --rest-api-id $rest_api_id --stage-name $stage --query 'tracingEnabled' --output text) + if [ "$tracing_enabled" != "true" ]; then + aws apigateway update-stage --rest-api-id $rest_api_id --stage-name $stage --patch-operations op=replace,path=/tracingEnabled,value=true + fi + done + ``` + +By following these steps, you can ensure that X-Ray tracing is enabled for your API Gateway stages, helping you to prevent the misconfiguration. + + + +To prevent the misconfiguration of API Gateway X-Ray not being enabled in AWS API Gateway using Python scripts, you can follow these steps: + +1. **Install Boto3 Library**: + Ensure you have the Boto3 library installed, which is the AWS SDK for Python. You can install it using pip if you haven't already. + + ```bash + pip install boto3 + ``` + +2. **Set Up AWS Credentials**: + Make sure your AWS credentials are configured. You can set them up using the AWS CLI or by setting environment variables. + + ```bash + aws configure + ``` + + Alternatively, you can set the environment variables directly in your script: + + ```python + import os + + os.environ['AWS_ACCESS_KEY_ID'] = 'your_access_key_id' + os.environ['AWS_SECRET_ACCESS_KEY'] = 'your_secret_access_key' + os.environ['AWS_DEFAULT_REGION'] = 'your_default_region' + ``` + +3. **Enable X-Ray Tracing for API Gateway**: + Use the Boto3 library to enable X-Ray tracing for your API Gateway. Below is a Python script to enable X-Ray tracing for a specific API Gateway stage. + + ```python + import boto3 + + # Initialize the API Gateway client + client = boto3.client('apigateway') + + # Define the API ID and stage name + api_id = 'your_api_id' + stage_name = 'your_stage_name' + + # Update the stage to enable X-Ray tracing + response = client.update_stage( + restApiId=api_id, + stageName=stage_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/tracingEnabled', + 'value': 'true' + } + ] + ) + + print(f"X-Ray tracing enabled for API Gateway stage {stage_name}: {response}") + ``` + +4. **Verify the Configuration**: + After running the script, you can verify that X-Ray tracing is enabled by checking the API Gateway stage settings in the AWS Management Console or by using the AWS CLI. + + ```bash + aws apigateway get-stage --rest-api-id your_api_id --stage-name your_stage_name + ``` + + Look for the `tracingEnabled` attribute in the output to ensure it is set to `true`. + +By following these steps, you can programmatically ensure that X-Ray tracing is enabled for your API Gateway stages, helping to prevent the misconfiguration. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/api_gwv2_authorization_type_configured.mdx b/docs/aws/audit/apigatewaymonitoring/rules/api_gwv2_authorization_type_configured.mdx index 843f877d..fbd7f17b 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/api_gwv2_authorization_type_configured.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/api_gwv2_authorization_type_configured.mdx @@ -24,6 +24,118 @@ CBP,SEBI ### Triage and Remediation + + +### How to Prevent + + +To prevent the misconfiguration of API Gateway V2 lacking an authorization type configuration in AWS using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select the API:** + - In the API Gateway console, select the API you want to configure from the list of APIs. + +3. **Configure Authorization:** + - Go to the "Routes" section under your selected API. + - Select the specific route you want to secure. + - In the "Route Request" pane, find the "Authorization" section. + - Choose an appropriate authorization type (e.g., AWS_IAM, COGNITO_USER_POOLS, JWT, etc.) from the dropdown menu. + +4. **Save Changes:** + - After selecting the authorization type, click the "Save" button to apply the changes. + +By following these steps, you ensure that your API Gateway V2 routes have the necessary authorization type configured, enhancing the security of your API. + + + +To prevent the misconfiguration of API Gateway V2 by ensuring it has an authorization type configuration using AWS CLI, follow these steps: + +1. **Create an IAM Role for API Gateway:** + Ensure you have an IAM role with the necessary permissions for API Gateway to use for authorization. + + ```sh + aws iam create-role --role-name APIGatewayAuthRole --assume-role-policy-document file://trust-policy.json + ``` + +2. **Attach Policy to IAM Role:** + Attach a policy to the IAM role that grants the necessary permissions. + + ```sh + aws iam attach-role-policy --role-name APIGatewayAuthRole --policy-arn arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayInvokeFullAccess + ``` + +3. **Create an Authorizer:** + Create an authorizer for your API Gateway. This example uses a Lambda authorizer. + + ```sh + aws apigatewayv2 create-authorizer --api-id --name MyAuthorizer --authorizer-type REQUEST --identity-source "$request.header.Authorization" --authorizer-uri arn:aws:apigateway::lambda:path/2015-03-31/functions//invocations --authorizer-result-ttl-in-seconds 300 + ``` + +4. **Update API Gateway Route to Use Authorizer:** + Update the route to use the created authorizer. + + ```sh + aws apigatewayv2 update-route --api-id --route-id --authorization-type CUSTOM --authorizer-id + ``` + +Replace ``, ``, ``, and `` with your specific API Gateway, region, Lambda function ARN, and route ID respectively. This ensures that your API Gateway V2 has an authorization type configuration, preventing unauthorized access. + + + +To prevent the misconfiguration of API Gateway V2 lacking an authorization type configuration in AWS using Python scripts, you can follow these steps: + +1. **Install AWS SDK for Python (Boto3):** + Ensure you have Boto3 installed in your environment. If not, you can install it using pip: + ```bash + pip install boto3 + ``` + +2. **Set Up AWS Credentials:** + Make sure your AWS credentials are configured. You can set them up using the AWS CLI or by directly configuring the `~/.aws/credentials` file. + +3. **Create a Python Script to Configure Authorization:** + Use the following Python script to create or update an API Gateway V2 route with an authorization type. This example assumes you are using a JWT authorizer. + + ```python + import boto3 + + # Initialize the API Gateway V2 client + client = boto3.client('apigatewayv2') + + # Define the API ID and the route key + api_id = 'your_api_id' + route_key = 'GET /yourroute' + + # Define the authorizer ID (you should have created an authorizer beforehand) + authorizer_id = 'your_authorizer_id' + + # Update the route with the authorization type + response = client.update_route( + ApiId=api_id, + RouteKey=route_key, + AuthorizationType='JWT', + AuthorizerId=authorizer_id + ) + + print("Route updated with authorization type:", response) + ``` + +4. **Run the Script:** + Execute the script in your Python environment to apply the authorization configuration to your API Gateway V2 route. + + ```bash + python configure_api_gateway_authorization.py + ``` + +By following these steps, you ensure that your API Gateway V2 routes have the necessary authorization type configured, thereby preventing unauthorized access. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/api_gwv2_authorization_type_configured_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/api_gwv2_authorization_type_configured_remediation.mdx index 75d93308..e4c944cd 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/api_gwv2_authorization_type_configured_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/api_gwv2_authorization_type_configured_remediation.mdx @@ -2,6 +2,117 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent the misconfiguration of API Gateway V2 lacking an authorization type configuration in AWS using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select the API:** + - In the API Gateway console, select the API you want to configure from the list of APIs. + +3. **Configure Authorization:** + - Go to the "Routes" section under your selected API. + - Select the specific route you want to secure. + - In the "Route Request" pane, find the "Authorization" section. + - Choose an appropriate authorization type (e.g., AWS_IAM, COGNITO_USER_POOLS, JWT, etc.) from the dropdown menu. + +4. **Save Changes:** + - After selecting the authorization type, click the "Save" button to apply the changes. + +By following these steps, you ensure that your API Gateway V2 routes have the necessary authorization type configured, enhancing the security of your API. + + + +To prevent the misconfiguration of API Gateway V2 by ensuring it has an authorization type configuration using AWS CLI, follow these steps: + +1. **Create an IAM Role for API Gateway:** + Ensure you have an IAM role with the necessary permissions for API Gateway to use for authorization. + + ```sh + aws iam create-role --role-name APIGatewayAuthRole --assume-role-policy-document file://trust-policy.json + ``` + +2. **Attach Policy to IAM Role:** + Attach a policy to the IAM role that grants the necessary permissions. + + ```sh + aws iam attach-role-policy --role-name APIGatewayAuthRole --policy-arn arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayInvokeFullAccess + ``` + +3. **Create an Authorizer:** + Create an authorizer for your API Gateway. This example uses a Lambda authorizer. + + ```sh + aws apigatewayv2 create-authorizer --api-id --name MyAuthorizer --authorizer-type REQUEST --identity-source "$request.header.Authorization" --authorizer-uri arn:aws:apigateway::lambda:path/2015-03-31/functions//invocations --authorizer-result-ttl-in-seconds 300 + ``` + +4. **Update API Gateway Route to Use Authorizer:** + Update the route to use the created authorizer. + + ```sh + aws apigatewayv2 update-route --api-id --route-id --authorization-type CUSTOM --authorizer-id + ``` + +Replace ``, ``, ``, and `` with your specific API Gateway, region, Lambda function ARN, and route ID respectively. This ensures that your API Gateway V2 has an authorization type configuration, preventing unauthorized access. + + + +To prevent the misconfiguration of API Gateway V2 lacking an authorization type configuration in AWS using Python scripts, you can follow these steps: + +1. **Install AWS SDK for Python (Boto3):** + Ensure you have Boto3 installed in your environment. If not, you can install it using pip: + ```bash + pip install boto3 + ``` + +2. **Set Up AWS Credentials:** + Make sure your AWS credentials are configured. You can set them up using the AWS CLI or by directly configuring the `~/.aws/credentials` file. + +3. **Create a Python Script to Configure Authorization:** + Use the following Python script to create or update an API Gateway V2 route with an authorization type. This example assumes you are using a JWT authorizer. + + ```python + import boto3 + + # Initialize the API Gateway V2 client + client = boto3.client('apigatewayv2') + + # Define the API ID and the route key + api_id = 'your_api_id' + route_key = 'GET /yourroute' + + # Define the authorizer ID (you should have created an authorizer beforehand) + authorizer_id = 'your_authorizer_id' + + # Update the route with the authorization type + response = client.update_route( + ApiId=api_id, + RouteKey=route_key, + AuthorizationType='JWT', + AuthorizerId=authorizer_id + ) + + print("Route updated with authorization type:", response) + ``` + +4. **Run the Script:** + Execute the script in your Python environment to apply the authorization configuration to your API Gateway V2 route. + + ```bash + python configure_api_gateway_authorization.py + ``` + +By following these steps, you ensure that your API Gateway V2 routes have the necessary authorization type configured, thereby preventing unauthorized access. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_client_certificate.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_client_certificate.mdx index ac76baf0..07fc962a 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_client_certificate.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_client_certificate.mdx @@ -24,6 +24,130 @@ NIST ### Triage and Remediation + + +### How to Prevent + + +To prevent API Gateway APIs from not using SSL certificates in AWS using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API you want to configure from the list of APIs. + +3. **Configure Custom Domain Names:** + - In the left-hand navigation pane, select "Custom domain names." + - Click on "Create Custom Domain Name." + - Enter the domain name and choose the appropriate endpoint configuration (Regional or Edge-Optimized). + - Upload your SSL/TLS certificate by selecting "Choose File" for the certificate body, private key, and certificate chain. + +4. **Associate API with Custom Domain:** + - After creating the custom domain name, go back to the "Custom domain names" section. + - Select the custom domain name you created. + - Click on "Add Mapping" to map the custom domain name to your API stage. + - Select the API and the stage (e.g., prod) you want to associate with the custom domain name. + +By following these steps, you ensure that your API Gateway APIs are using SSL certificates, thereby securing the communication between clients and your API. + + + +To ensure that API Gateway APIs use SSL certificates in AWS, you can follow these steps using the AWS CLI: + +1. **Create a Custom Domain Name with an SSL Certificate:** + - First, you need to create a custom domain name and associate it with an SSL certificate. This ensures that your API Gateway uses HTTPS. + ```sh + aws apigateway create-domain-name --domain-name --certificate-arn + ``` + +2. **Create or Update an API Gateway Stage to Use the Custom Domain:** + - Associate your API Gateway stage with the custom domain name you created. + ```sh + aws apigateway create-base-path-mapping --domain-name --rest-api-id --stage + ``` + +3. **Enable Endpoint Configuration to Use EDGE or REGIONAL:** + - Ensure that your API Gateway endpoint configuration is set to `EDGE` or `REGIONAL`, which supports SSL by default. + ```sh + aws apigateway update-rest-api --rest-api-id --patch-operations op=replace,path=/endpointConfiguration/types,value=REGIONAL + ``` + +4. **Verify the Custom Domain Name Configuration:** + - Verify that the custom domain name is correctly configured and associated with your API Gateway. + ```sh + aws apigateway get-domain-name --domain-name + ``` + +By following these steps, you can ensure that your API Gateway APIs are configured to use SSL certificates, thereby enforcing secure communication over HTTPS. + + + +To ensure that API Gateway APIs use SSL certificates in AWS, you can use the Boto3 library in Python. Below are the steps to prevent misconfigurations related to SSL certificates in API Gateway: + +### Step 1: Install Boto3 +First, ensure you have Boto3 installed. If not, you can install it using pip: +```bash +pip install boto3 +``` + +### Step 2: Create a Boto3 Client +Create a Boto3 client to interact with the API Gateway service. +```python +import boto3 + +client = boto3.client('apigateway') +``` + +### Step 3: Create or Update API Gateway with SSL Certificate +When creating or updating an API Gateway, ensure that you specify the `endpointConfiguration` to use `REGIONAL` or `EDGE` endpoint types, which support SSL by default. + +#### Example: Create a New API with SSL +```python +response = client.create_rest_api( + name='MySecureAPI', + description='API with SSL', + endpointConfiguration={ + 'types': ['REGIONAL'] # or 'EDGE' + } +) +print(response) +``` + +#### Example: Update an Existing API to Use SSL +```python +api_id = 'your_api_id_here' + +response = client.update_rest_api( + restApiId=api_id, + patchOperations=[ + { + 'op': 'replace', + 'path': '/endpointConfiguration/types', + 'value': 'REGIONAL' # or 'EDGE' + } + ] +) +print(response) +``` + +### Step 4: Verify SSL Configuration +After creating or updating the API, you can verify that the endpoint configuration is set correctly. +```python +response = client.get_rest_api( + restApiId='your_api_id_here' +) + +print(response['endpointConfiguration']) +``` + +By following these steps, you can ensure that your API Gateway APIs are configured to use SSL certificates, thereby preventing misconfigurations related to insecure endpoints. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_client_certificate_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_client_certificate_remediation.mdx index e64acdf4..fffe8ea1 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_client_certificate_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_client_certificate_remediation.mdx @@ -2,6 +2,129 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent API Gateway APIs from not using SSL certificates in AWS using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API you want to configure from the list of APIs. + +3. **Configure Custom Domain Names:** + - In the left-hand navigation pane, select "Custom domain names." + - Click on "Create Custom Domain Name." + - Enter the domain name and choose the appropriate endpoint configuration (Regional or Edge-Optimized). + - Upload your SSL/TLS certificate by selecting "Choose File" for the certificate body, private key, and certificate chain. + +4. **Associate API with Custom Domain:** + - After creating the custom domain name, go back to the "Custom domain names" section. + - Select the custom domain name you created. + - Click on "Add Mapping" to map the custom domain name to your API stage. + - Select the API and the stage (e.g., prod) you want to associate with the custom domain name. + +By following these steps, you ensure that your API Gateway APIs are using SSL certificates, thereby securing the communication between clients and your API. + + + +To ensure that API Gateway APIs use SSL certificates in AWS, you can follow these steps using the AWS CLI: + +1. **Create a Custom Domain Name with an SSL Certificate:** + - First, you need to create a custom domain name and associate it with an SSL certificate. This ensures that your API Gateway uses HTTPS. + ```sh + aws apigateway create-domain-name --domain-name --certificate-arn + ``` + +2. **Create or Update an API Gateway Stage to Use the Custom Domain:** + - Associate your API Gateway stage with the custom domain name you created. + ```sh + aws apigateway create-base-path-mapping --domain-name --rest-api-id --stage + ``` + +3. **Enable Endpoint Configuration to Use EDGE or REGIONAL:** + - Ensure that your API Gateway endpoint configuration is set to `EDGE` or `REGIONAL`, which supports SSL by default. + ```sh + aws apigateway update-rest-api --rest-api-id --patch-operations op=replace,path=/endpointConfiguration/types,value=REGIONAL + ``` + +4. **Verify the Custom Domain Name Configuration:** + - Verify that the custom domain name is correctly configured and associated with your API Gateway. + ```sh + aws apigateway get-domain-name --domain-name + ``` + +By following these steps, you can ensure that your API Gateway APIs are configured to use SSL certificates, thereby enforcing secure communication over HTTPS. + + + +To ensure that API Gateway APIs use SSL certificates in AWS, you can use the Boto3 library in Python. Below are the steps to prevent misconfigurations related to SSL certificates in API Gateway: + +### Step 1: Install Boto3 +First, ensure you have Boto3 installed. If not, you can install it using pip: +```bash +pip install boto3 +``` + +### Step 2: Create a Boto3 Client +Create a Boto3 client to interact with the API Gateway service. +```python +import boto3 + +client = boto3.client('apigateway') +``` + +### Step 3: Create or Update API Gateway with SSL Certificate +When creating or updating an API Gateway, ensure that you specify the `endpointConfiguration` to use `REGIONAL` or `EDGE` endpoint types, which support SSL by default. + +#### Example: Create a New API with SSL +```python +response = client.create_rest_api( + name='MySecureAPI', + description='API with SSL', + endpointConfiguration={ + 'types': ['REGIONAL'] # or 'EDGE' + } +) +print(response) +``` + +#### Example: Update an Existing API to Use SSL +```python +api_id = 'your_api_id_here' + +response = client.update_rest_api( + restApiId=api_id, + patchOperations=[ + { + 'op': 'replace', + 'path': '/endpointConfiguration/types', + 'value': 'REGIONAL' # or 'EDGE' + } + ] +) +print(response) +``` + +### Step 4: Verify SSL Configuration +After creating or updating the API, you can verify that the endpoint configuration is set correctly. +```python +response = client.get_rest_api( + restApiId='your_api_id_here' +) + +print(response['endpointConfiguration']) +``` + +By following these steps, you can ensure that your API Gateway APIs are configured to use SSL certificates, thereby preventing misconfigurations related to insecure endpoints. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_cloudwatch_logs.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_cloudwatch_logs.mdx index 196bbde3..42780b28 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_cloudwatch_logs.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_cloudwatch_logs.mdx @@ -24,6 +24,124 @@ HIPAA, SOC2, HITRUST, NISTCSF, PCIDSS ### Triage and Remediation + + +### How to Prevent + + +To ensure that CloudWatch Logs are enabled for all APIs in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to enable CloudWatch Logs. + +3. **Enable CloudWatch Logs:** + - In the left-hand navigation pane, select "Stages." + - Choose the stage (e.g., "prod" or "dev") for which you want to enable logging. + - In the Stage Editor, select the "Logs/Tracing" tab. + - Check the box for "Enable CloudWatch Logs" and set the desired log level (e.g., INFO, ERROR). + +4. **Set Log Group and Role ARN:** + - Specify a CloudWatch Log Group name where the logs will be stored. + - Provide the ARN of an IAM role that has the necessary permissions to write logs to CloudWatch. This role should have the `AmazonAPIGatewayPushToCloudWatchLogs` managed policy attached. + +By following these steps, you can ensure that CloudWatch Logs are enabled for all APIs in API Gateway using the AWS Management Console. + + + +To ensure that CloudWatch Logs are enabled for all APIs in API Gateway using AWS CLI, follow these steps: + +1. **List All API Gateways**: + First, list all the API Gateways in your account to identify the ones you need to configure. + ```sh + aws apigateway get-rest-apis + ``` + +2. **Get Stages for Each API**: + For each API Gateway, list all the stages to identify where you need to enable logging. + ```sh + aws apigateway get-stages --rest-api-id + ``` + +3. **Enable CloudWatch Logs for a Stage**: + Enable CloudWatch Logs for a specific stage of an API Gateway. Replace `` and `` with the appropriate values. + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/accessLogSettings/destinationArn,value=arn:aws:logs:::log-group: + ``` + +4. **Set Log Format**: + Define the format of the log entries. This step ensures that the logs are structured and contain the necessary information. + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/accessLogSettings/format,value='{"requestId":"$context.requestId","ip":"$context.identity.sourceIp","caller":"$context.identity.caller","user":"$context.identity.user","requestTime":"$context.requestTime","httpMethod":"$context.httpMethod","resourcePath":"$context.resourcePath","status":"$context.status","protocol":"$context.protocol","responseLength":"$context.responseLength"}' + ``` + +By following these steps, you can ensure that CloudWatch Logs are enabled for all APIs in API Gateway using AWS CLI. + + + +To ensure that CloudWatch Logs are enabled for all APIs in API Gateway using Python scripts, you can use the AWS SDK for Python (Boto3). Below are the steps to achieve this: + +1. **Install Boto3**: + Ensure you have Boto3 installed in your Python environment. If not, you can install it using pip: + ```bash + pip install boto3 + ``` + +2. **Initialize Boto3 Client**: + Initialize the Boto3 client for API Gateway and CloudWatch Logs. + ```python + import boto3 + + api_gateway_client = boto3.client('apigateway') + ``` + +3. **List All API Gateways**: + Retrieve a list of all API Gateway Rest APIs. + ```python + def list_apis(): + response = api_gateway_client.get_rest_apis() + return response['items'] + + apis = list_apis() + ``` + +4. **Enable CloudWatch Logs for Each API**: + Iterate through each API and ensure that CloudWatch Logs are enabled by setting the appropriate stage settings. + ```python + def enable_cloudwatch_logs(api_id, stage_name): + response = api_gateway_client.update_stage( + restApiId=api_id, + stageName=stage_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/*/*/logging/loglevel', + 'value': 'INFO' + }, + { + 'op': 'replace', + 'path': '/*/*/logging/dataTrace', + 'value': 'true' + } + ] + ) + return response + + for api in apis: + stages = api_gateway_client.get_stages(restApiId=api['id'])['item'] + for stage in stages: + enable_cloudwatch_logs(api['id'], stage['stageName']) + ``` + +This script will ensure that CloudWatch Logs are enabled for all stages of all APIs in your API Gateway. Make sure you have the necessary permissions to perform these actions. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_cloudwatch_logs_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_cloudwatch_logs_remediation.mdx index e6d015d6..3831adfb 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_cloudwatch_logs_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_cloudwatch_logs_remediation.mdx @@ -2,6 +2,123 @@ ### Triage and Remediation + + +### How to Prevent + + +To ensure that CloudWatch Logs are enabled for all APIs in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to enable CloudWatch Logs. + +3. **Enable CloudWatch Logs:** + - In the left-hand navigation pane, select "Stages." + - Choose the stage (e.g., "prod" or "dev") for which you want to enable logging. + - In the Stage Editor, select the "Logs/Tracing" tab. + - Check the box for "Enable CloudWatch Logs" and set the desired log level (e.g., INFO, ERROR). + +4. **Set Log Group and Role ARN:** + - Specify a CloudWatch Log Group name where the logs will be stored. + - Provide the ARN of an IAM role that has the necessary permissions to write logs to CloudWatch. This role should have the `AmazonAPIGatewayPushToCloudWatchLogs` managed policy attached. + +By following these steps, you can ensure that CloudWatch Logs are enabled for all APIs in API Gateway using the AWS Management Console. + + + +To ensure that CloudWatch Logs are enabled for all APIs in API Gateway using AWS CLI, follow these steps: + +1. **List All API Gateways**: + First, list all the API Gateways in your account to identify the ones you need to configure. + ```sh + aws apigateway get-rest-apis + ``` + +2. **Get Stages for Each API**: + For each API Gateway, list all the stages to identify where you need to enable logging. + ```sh + aws apigateway get-stages --rest-api-id + ``` + +3. **Enable CloudWatch Logs for a Stage**: + Enable CloudWatch Logs for a specific stage of an API Gateway. Replace `` and `` with the appropriate values. + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/accessLogSettings/destinationArn,value=arn:aws:logs:::log-group: + ``` + +4. **Set Log Format**: + Define the format of the log entries. This step ensures that the logs are structured and contain the necessary information. + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/accessLogSettings/format,value='{"requestId":"$context.requestId","ip":"$context.identity.sourceIp","caller":"$context.identity.caller","user":"$context.identity.user","requestTime":"$context.requestTime","httpMethod":"$context.httpMethod","resourcePath":"$context.resourcePath","status":"$context.status","protocol":"$context.protocol","responseLength":"$context.responseLength"}' + ``` + +By following these steps, you can ensure that CloudWatch Logs are enabled for all APIs in API Gateway using AWS CLI. + + + +To ensure that CloudWatch Logs are enabled for all APIs in API Gateway using Python scripts, you can use the AWS SDK for Python (Boto3). Below are the steps to achieve this: + +1. **Install Boto3**: + Ensure you have Boto3 installed in your Python environment. If not, you can install it using pip: + ```bash + pip install boto3 + ``` + +2. **Initialize Boto3 Client**: + Initialize the Boto3 client for API Gateway and CloudWatch Logs. + ```python + import boto3 + + api_gateway_client = boto3.client('apigateway') + ``` + +3. **List All API Gateways**: + Retrieve a list of all API Gateway Rest APIs. + ```python + def list_apis(): + response = api_gateway_client.get_rest_apis() + return response['items'] + + apis = list_apis() + ``` + +4. **Enable CloudWatch Logs for Each API**: + Iterate through each API and ensure that CloudWatch Logs are enabled by setting the appropriate stage settings. + ```python + def enable_cloudwatch_logs(api_id, stage_name): + response = api_gateway_client.update_stage( + restApiId=api_id, + stageName=stage_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/*/*/logging/loglevel', + 'value': 'INFO' + }, + { + 'op': 'replace', + 'path': '/*/*/logging/dataTrace', + 'value': 'true' + } + ] + ) + return response + + for api in apis: + stages = api_gateway_client.get_stages(restApiId=api['id'])['item'] + for stage in stages: + enable_cloudwatch_logs(api['id'], stage['stageName']) + ``` + +This script will ensure that CloudWatch Logs are enabled for all stages of all APIs in your API Gateway. Make sure you have the necessary permissions to perform these actions. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_content_encoding.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_content_encoding.mdx index 32e170ed..7ae10efe 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_content_encoding.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_content_encoding.mdx @@ -24,6 +24,116 @@ CBP ### Triage and Remediation + + +### How to Prevent + + +To prevent the misconfiguration "Content Encoding Should Be Enabled For APIs" in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to enable content encoding. + +3. **Enable Content Encoding:** + - In the API details page, go to the "Settings" tab. + - Look for the "Content Encoding" section. + - Check the box to enable content encoding for the API. + +4. **Save Changes:** + - After enabling content encoding, make sure to save the changes by clicking the "Save" button at the bottom of the settings page. + +By following these steps, you can ensure that content encoding is enabled for your APIs in API Gateway using the AWS Management Console. + + + +To prevent the misconfiguration "Content Encoding Should Be Enabled For APIs" in API Gateway using AWS CLI, follow these steps: + +1. **Create or Update API Gateway Deployment:** + Ensure you have an API Gateway deployment. If you don't have one, create it using the following command: + ```sh + aws apigateway create-deployment --rest-api-id --stage-name + ``` + +2. **Enable Content Encoding:** + Update the API Gateway stage settings to enable content encoding. Use the following command to update the stage settings: + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/contentHandling,value=CONVERT_TO_BINARY + ``` + +3. **Verify Stage Settings:** + Verify that the content encoding settings have been applied correctly by describing the stage: + ```sh + aws apigateway get-stage --rest-api-id --stage-name + ``` + +4. **Test the API:** + Test the API to ensure that content encoding is working as expected. You can use `curl` or any HTTP client to make a request to your API endpoint and check the response headers for content encoding. + +By following these steps, you can ensure that content encoding is enabled for your APIs in API Gateway using AWS CLI. + + + +To prevent the misconfiguration of "Content Encoding Should Be Enabled For APIs" in API Gateway using Python scripts, you can use the AWS SDK for Python (Boto3). Here are the steps to ensure that content encoding is enabled for your APIs: + +1. **Install Boto3**: + Ensure you have Boto3 installed in your Python environment. You can install it using pip if you haven't already: + ```bash + pip install boto3 + ``` + +2. **Initialize Boto3 Client**: + Initialize the Boto3 client for API Gateway. This will allow you to interact with the API Gateway service. + ```python + import boto3 + + client = boto3.client('apigateway') + ``` + +3. **Retrieve API Gateway Stages**: + Retrieve the stages for your API Gateway to identify which stages need content encoding enabled. + ```python + def get_api_stages(api_id): + response = client.get_stages( + restApiId=api_id + ) + return response['item'] + + api_id = 'your_api_id' # Replace with your API ID + stages = get_api_stages(api_id) + ``` + +4. **Enable Content Encoding**: + Update the settings for each stage to enable content encoding. + ```python + def enable_content_encoding(api_id, stage_name): + response = client.update_stage( + restApiId=api_id, + stageName=stage_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/methodSettings/*/*/contentHandling', + 'value': 'CONVERT_TO_BINARY' + } + ] + ) + return response + + for stage in stages: + stage_name = stage['stageName'] + enable_content_encoding(api_id, stage_name) + ``` + +This script will ensure that content encoding is enabled for all stages of your API Gateway. Make sure to replace `'your_api_id'` with the actual API ID of your API Gateway. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_content_encoding_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_content_encoding_remediation.mdx index 4385aa0e..3d414b7e 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_content_encoding_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_content_encoding_remediation.mdx @@ -2,6 +2,115 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent the misconfiguration "Content Encoding Should Be Enabled For APIs" in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to enable content encoding. + +3. **Enable Content Encoding:** + - In the API details page, go to the "Settings" tab. + - Look for the "Content Encoding" section. + - Check the box to enable content encoding for the API. + +4. **Save Changes:** + - After enabling content encoding, make sure to save the changes by clicking the "Save" button at the bottom of the settings page. + +By following these steps, you can ensure that content encoding is enabled for your APIs in API Gateway using the AWS Management Console. + + + +To prevent the misconfiguration "Content Encoding Should Be Enabled For APIs" in API Gateway using AWS CLI, follow these steps: + +1. **Create or Update API Gateway Deployment:** + Ensure you have an API Gateway deployment. If you don't have one, create it using the following command: + ```sh + aws apigateway create-deployment --rest-api-id --stage-name + ``` + +2. **Enable Content Encoding:** + Update the API Gateway stage settings to enable content encoding. Use the following command to update the stage settings: + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/contentHandling,value=CONVERT_TO_BINARY + ``` + +3. **Verify Stage Settings:** + Verify that the content encoding settings have been applied correctly by describing the stage: + ```sh + aws apigateway get-stage --rest-api-id --stage-name + ``` + +4. **Test the API:** + Test the API to ensure that content encoding is working as expected. You can use `curl` or any HTTP client to make a request to your API endpoint and check the response headers for content encoding. + +By following these steps, you can ensure that content encoding is enabled for your APIs in API Gateway using AWS CLI. + + + +To prevent the misconfiguration of "Content Encoding Should Be Enabled For APIs" in API Gateway using Python scripts, you can use the AWS SDK for Python (Boto3). Here are the steps to ensure that content encoding is enabled for your APIs: + +1. **Install Boto3**: + Ensure you have Boto3 installed in your Python environment. You can install it using pip if you haven't already: + ```bash + pip install boto3 + ``` + +2. **Initialize Boto3 Client**: + Initialize the Boto3 client for API Gateway. This will allow you to interact with the API Gateway service. + ```python + import boto3 + + client = boto3.client('apigateway') + ``` + +3. **Retrieve API Gateway Stages**: + Retrieve the stages for your API Gateway to identify which stages need content encoding enabled. + ```python + def get_api_stages(api_id): + response = client.get_stages( + restApiId=api_id + ) + return response['item'] + + api_id = 'your_api_id' # Replace with your API ID + stages = get_api_stages(api_id) + ``` + +4. **Enable Content Encoding**: + Update the settings for each stage to enable content encoding. + ```python + def enable_content_encoding(api_id, stage_name): + response = client.update_stage( + restApiId=api_id, + stageName=stage_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/methodSettings/*/*/contentHandling', + 'value': 'CONVERT_TO_BINARY' + } + ] + ) + return response + + for stage in stages: + stage_name = stage['stageName'] + enable_content_encoding(api_id, stage_name) + ``` + +This script will ensure that content encoding is enabled for all stages of your API Gateway. Make sure to replace `'your_api_id'` with the actual API ID of your API Gateway. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_default_execution_endpoint_enabled.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_default_execution_endpoint_enabled.mdx index dd805cac..059e26dd 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_default_execution_endpoint_enabled.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_default_execution_endpoint_enabled.mdx @@ -24,6 +24,138 @@ CBP ### Triage and Remediation + + +### How to Prevent + + +To prevent the "Default Execution Endpoint Should Not Be Enabled" in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to disable the default execution endpoint. + +3. **Disable Default Endpoint:** + - Go to the "Settings" tab for the selected API. + - Locate the "Default Endpoint" setting and uncheck the box to disable it. + +4. **Save Changes:** + - Click the "Save" button to apply the changes. + +By following these steps, you can ensure that the default execution endpoint is not enabled, thereby enhancing the security of your API Gateway. + + + +To prevent the default execution endpoint from being enabled in API Gateway using AWS CLI, follow these steps: + +1. **Create a Custom Domain Name:** + - First, create a custom domain name for your API Gateway. + ```sh + aws apigateway create-domain-name --domain-name --certificate-arn + ``` + +2. **Create a Base Path Mapping:** + - Map the custom domain name to your API stage. + ```sh + aws apigateway create-base-path-mapping --domain-name --rest-api-id --stage + ``` + +3. **Update API Gateway Stage:** + - Ensure that the stage is correctly configured to use the custom domain. + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/customDomainName,value= + ``` + +4. **Disable Default Endpoint:** + - Update the API Gateway settings to disable the default endpoint. + ```sh + aws apigateway update-rest-api --rest-api-id --patch-operations op=replace,path=/disableExecuteApiEndpoint,value=true + ``` + +By following these steps, you can ensure that the default execution endpoint is not enabled, thereby enhancing the security of your API Gateway. + + + +To prevent the "Default Execution Endpoint Should Not Be Enabled" misconfiguration in API Gateway using Python scripts, you can use the AWS SDK for Python (Boto3). Here are the steps to achieve this: + +1. **Install Boto3**: + Ensure you have Boto3 installed in your Python environment. You can install it using pip if you haven't already: + ```bash + pip install boto3 + ``` + +2. **Create a Boto3 Client**: + Initialize a Boto3 client for API Gateway. This client will be used to interact with the API Gateway service. + ```python + import boto3 + + client = boto3.client('apigateway') + ``` + +3. **List All API Gateways**: + Retrieve a list of all API Gateways in your account. This will help you identify which APIs have the default execution endpoint enabled. + ```python + response = client.get_rest_apis() + apis = response['items'] + ``` + +4. **Disable Default Execution Endpoint**: + Iterate through the list of APIs and disable the default execution endpoint for each one. This can be done by updating the API Gateway settings. + ```python + for api in apis: + api_id = api['id'] + # Update the API to disable the default execution endpoint + client.update_rest_api( + restApiId=api_id, + patchOperations=[ + { + 'op': 'replace', + 'path': '/disableExecuteApiEndpoint', + 'value': 'true' + } + ] + ) + print(f"Disabled default execution endpoint for API: {api_id}") + ``` + +Here is the complete script: + +```python +import boto3 + +# Initialize the Boto3 client for API Gateway +client = boto3.client('apigateway') + +# Retrieve a list of all API Gateways +response = client.get_rest_apis() +apis = response['items'] + +# Iterate through the list of APIs and disable the default execution endpoint +for api in apis: + api_id = api['id'] + # Update the API to disable the default execution endpoint + client.update_rest_api( + restApiId=api_id, + patchOperations=[ + { + 'op': 'replace', + 'path': '/disableExecuteApiEndpoint', + 'value': 'true' + } + ] + ) + print(f"Disabled default execution endpoint for API: {api_id}") +``` + +This script will ensure that the default execution endpoint is disabled for all API Gateways in your AWS account, thereby preventing the misconfiguration. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_default_execution_endpoint_enabled_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_default_execution_endpoint_enabled_remediation.mdx index 5a10f0d7..3b569682 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_default_execution_endpoint_enabled_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_default_execution_endpoint_enabled_remediation.mdx @@ -2,6 +2,137 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent the "Default Execution Endpoint Should Not Be Enabled" in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to disable the default execution endpoint. + +3. **Disable Default Endpoint:** + - Go to the "Settings" tab for the selected API. + - Locate the "Default Endpoint" setting and uncheck the box to disable it. + +4. **Save Changes:** + - Click the "Save" button to apply the changes. + +By following these steps, you can ensure that the default execution endpoint is not enabled, thereby enhancing the security of your API Gateway. + + + +To prevent the default execution endpoint from being enabled in API Gateway using AWS CLI, follow these steps: + +1. **Create a Custom Domain Name:** + - First, create a custom domain name for your API Gateway. + ```sh + aws apigateway create-domain-name --domain-name --certificate-arn + ``` + +2. **Create a Base Path Mapping:** + - Map the custom domain name to your API stage. + ```sh + aws apigateway create-base-path-mapping --domain-name --rest-api-id --stage + ``` + +3. **Update API Gateway Stage:** + - Ensure that the stage is correctly configured to use the custom domain. + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/customDomainName,value= + ``` + +4. **Disable Default Endpoint:** + - Update the API Gateway settings to disable the default endpoint. + ```sh + aws apigateway update-rest-api --rest-api-id --patch-operations op=replace,path=/disableExecuteApiEndpoint,value=true + ``` + +By following these steps, you can ensure that the default execution endpoint is not enabled, thereby enhancing the security of your API Gateway. + + + +To prevent the "Default Execution Endpoint Should Not Be Enabled" misconfiguration in API Gateway using Python scripts, you can use the AWS SDK for Python (Boto3). Here are the steps to achieve this: + +1. **Install Boto3**: + Ensure you have Boto3 installed in your Python environment. You can install it using pip if you haven't already: + ```bash + pip install boto3 + ``` + +2. **Create a Boto3 Client**: + Initialize a Boto3 client for API Gateway. This client will be used to interact with the API Gateway service. + ```python + import boto3 + + client = boto3.client('apigateway') + ``` + +3. **List All API Gateways**: + Retrieve a list of all API Gateways in your account. This will help you identify which APIs have the default execution endpoint enabled. + ```python + response = client.get_rest_apis() + apis = response['items'] + ``` + +4. **Disable Default Execution Endpoint**: + Iterate through the list of APIs and disable the default execution endpoint for each one. This can be done by updating the API Gateway settings. + ```python + for api in apis: + api_id = api['id'] + # Update the API to disable the default execution endpoint + client.update_rest_api( + restApiId=api_id, + patchOperations=[ + { + 'op': 'replace', + 'path': '/disableExecuteApiEndpoint', + 'value': 'true' + } + ] + ) + print(f"Disabled default execution endpoint for API: {api_id}") + ``` + +Here is the complete script: + +```python +import boto3 + +# Initialize the Boto3 client for API Gateway +client = boto3.client('apigateway') + +# Retrieve a list of all API Gateways +response = client.get_rest_apis() +apis = response['items'] + +# Iterate through the list of APIs and disable the default execution endpoint +for api in apis: + api_id = api['id'] + # Update the API to disable the default execution endpoint + client.update_rest_api( + restApiId=api_id, + patchOperations=[ + { + 'op': 'replace', + 'path': '/disableExecuteApiEndpoint', + 'value': 'true' + } + ] + ) + print(f"Disabled default execution endpoint for API: {api_id}") +``` + +This script will ensure that the default execution endpoint is disabled for all API Gateways in your AWS account, thereby preventing the misconfiguration. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_detailed_cloudwatch_metrics.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_detailed_cloudwatch_metrics.mdx index fb23299c..d45807db 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_detailed_cloudwatch_metrics.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_detailed_cloudwatch_metrics.mdx @@ -24,6 +24,124 @@ HIPAA, SOC2, HITRUST, NISTCSF, PCIDSS ### Triage and Remediation + + +### How to Prevent + + +To prevent the misconfiguration of "CloudWatch Metrics Must Be Enabled For All APIs in API Gateway" using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to enable CloudWatch metrics. + - Click on the API name to open its configuration. + +3. **Enable CloudWatch Metrics:** + - In the left-hand navigation pane, select "Stages." + - Choose the stage (e.g., `prod`, `dev`) for which you want to enable CloudWatch metrics. + - In the Stage Editor, under the "Logs/Tracing" tab, check the box for "Enable CloudWatch Metrics." + +4. **Save Changes:** + - Click the "Save Changes" button at the bottom of the page to apply the configuration. + +By following these steps, you ensure that CloudWatch metrics are enabled for all APIs in API Gateway, which helps in monitoring and managing your API performance and usage effectively. + + + +To ensure that CloudWatch Metrics are enabled for all APIs in API Gateway using AWS CLI, follow these steps: + +1. **List All API Gateway Rest APIs:** + First, you need to list all the Rest APIs in your account to identify which APIs need CloudWatch Metrics enabled. + ```sh + aws apigateway get-rest-apis + ``` + +2. **Get Stages for Each API:** + For each API, list all the stages to identify where to enable CloudWatch Metrics. + ```sh + aws apigateway get-stages --rest-api-id + ``` + +3. **Enable CloudWatch Metrics for Each Stage:** + For each stage of each API, enable CloudWatch Metrics by updating the stage settings. + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/metrics/enabled,value=true + ``` + +4. **Verify the Configuration:** + Finally, verify that CloudWatch Metrics are enabled for the stages. + ```sh + aws apigateway get-stage --rest-api-id --stage-name + ``` + +By following these steps, you can ensure that CloudWatch Metrics are enabled for all APIs in API Gateway using AWS CLI. + + + +To ensure that CloudWatch Metrics are enabled for all APIs in API Gateway using Python scripts, you can use the AWS SDK for Python (Boto3). Below are the steps to achieve this: + +1. **Install Boto3**: + Ensure you have Boto3 installed in your Python environment. If not, you can install it using pip: + ```bash + pip install boto3 + ``` + +2. **Initialize Boto3 Client**: + Initialize the Boto3 client for API Gateway. + ```python + import boto3 + + client = boto3.client('apigateway') + ``` + +3. **List All APIs**: + Retrieve a list of all APIs in your account. + ```python + def list_apis(): + response = client.get_rest_apis() + return response['items'] + + apis = list_apis() + ``` + +4. **Enable CloudWatch Metrics for Each API**: + Iterate through each API and enable CloudWatch Metrics. + ```python + def enable_cloudwatch_metrics(api_id): + stages = client.get_stages(restApiId=api_id) + for stage in stages['item']: + client.update_stage( + restApiId=api_id, + stageName=stage['stageName'], + patchOperations=[ + { + 'op': 'replace', + 'path': '/*/*/metrics/enabled', + 'value': 'true' + } + ] + ) + + for api in apis: + enable_cloudwatch_metrics(api['id']) + ``` + +This script will ensure that CloudWatch Metrics are enabled for all stages of all APIs in your API Gateway. Here’s a summary of the steps: + +1. **Install Boto3**: Ensure Boto3 is installed. +2. **Initialize Boto3 Client**: Set up the Boto3 client for API Gateway. +3. **List All APIs**: Retrieve all APIs in your account. +4. **Enable CloudWatch Metrics for Each API**: Iterate through each API and enable CloudWatch Metrics for all stages. + +By following these steps, you can programmatically ensure that CloudWatch Metrics are enabled for all APIs in your API Gateway. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_detailed_cloudwatch_metrics_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_detailed_cloudwatch_metrics_remediation.mdx index f693613e..92fba391 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_detailed_cloudwatch_metrics_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_detailed_cloudwatch_metrics_remediation.mdx @@ -2,6 +2,123 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent the misconfiguration of "CloudWatch Metrics Must Be Enabled For All APIs in API Gateway" using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to enable CloudWatch metrics. + - Click on the API name to open its configuration. + +3. **Enable CloudWatch Metrics:** + - In the left-hand navigation pane, select "Stages." + - Choose the stage (e.g., `prod`, `dev`) for which you want to enable CloudWatch metrics. + - In the Stage Editor, under the "Logs/Tracing" tab, check the box for "Enable CloudWatch Metrics." + +4. **Save Changes:** + - Click the "Save Changes" button at the bottom of the page to apply the configuration. + +By following these steps, you ensure that CloudWatch metrics are enabled for all APIs in API Gateway, which helps in monitoring and managing your API performance and usage effectively. + + + +To ensure that CloudWatch Metrics are enabled for all APIs in API Gateway using AWS CLI, follow these steps: + +1. **List All API Gateway Rest APIs:** + First, you need to list all the Rest APIs in your account to identify which APIs need CloudWatch Metrics enabled. + ```sh + aws apigateway get-rest-apis + ``` + +2. **Get Stages for Each API:** + For each API, list all the stages to identify where to enable CloudWatch Metrics. + ```sh + aws apigateway get-stages --rest-api-id + ``` + +3. **Enable CloudWatch Metrics for Each Stage:** + For each stage of each API, enable CloudWatch Metrics by updating the stage settings. + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/metrics/enabled,value=true + ``` + +4. **Verify the Configuration:** + Finally, verify that CloudWatch Metrics are enabled for the stages. + ```sh + aws apigateway get-stage --rest-api-id --stage-name + ``` + +By following these steps, you can ensure that CloudWatch Metrics are enabled for all APIs in API Gateway using AWS CLI. + + + +To ensure that CloudWatch Metrics are enabled for all APIs in API Gateway using Python scripts, you can use the AWS SDK for Python (Boto3). Below are the steps to achieve this: + +1. **Install Boto3**: + Ensure you have Boto3 installed in your Python environment. If not, you can install it using pip: + ```bash + pip install boto3 + ``` + +2. **Initialize Boto3 Client**: + Initialize the Boto3 client for API Gateway. + ```python + import boto3 + + client = boto3.client('apigateway') + ``` + +3. **List All APIs**: + Retrieve a list of all APIs in your account. + ```python + def list_apis(): + response = client.get_rest_apis() + return response['items'] + + apis = list_apis() + ``` + +4. **Enable CloudWatch Metrics for Each API**: + Iterate through each API and enable CloudWatch Metrics. + ```python + def enable_cloudwatch_metrics(api_id): + stages = client.get_stages(restApiId=api_id) + for stage in stages['item']: + client.update_stage( + restApiId=api_id, + stageName=stage['stageName'], + patchOperations=[ + { + 'op': 'replace', + 'path': '/*/*/metrics/enabled', + 'value': 'true' + } + ] + ) + + for api in apis: + enable_cloudwatch_metrics(api['id']) + ``` + +This script will ensure that CloudWatch Metrics are enabled for all stages of all APIs in your API Gateway. Here’s a summary of the steps: + +1. **Install Boto3**: Ensure Boto3 is installed. +2. **Initialize Boto3 Client**: Set up the Boto3 client for API Gateway. +3. **List All APIs**: Retrieve all APIs in your account. +4. **Enable CloudWatch Metrics for Each API**: Iterate through each API and enable CloudWatch Metrics for all stages. + +By following these steps, you can programmatically ensure that CloudWatch Metrics are enabled for all APIs in your API Gateway. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_enable_api_cache.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_enable_api_cache.mdx index eaf77cbf..0f475102 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_enable_api_cache.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_enable_api_cache.mdx @@ -24,6 +24,176 @@ CBP ### Triage and Remediation + + +### How to Prevent + + +To prevent enabling API Cache in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to prevent enabling the cache. + +3. **Access Stage Settings:** + - Click on the "Stages" option in the left-hand navigation pane. + - Select the stage you want to configure (e.g., "prod" or "dev"). + +4. **Disable Cache:** + - In the "Stage Editor" pane, scroll down to the "Cache Settings" section. + - Ensure that the "Enable API Cache" option is unchecked. + +By following these steps, you can prevent the API cache from being enabled in API Gateway using the AWS Management Console. + + + +To prevent the misconfiguration of not enabling API Cache in API Gateway using AWS CLI, you can follow these steps: + +1. **Create or Update API Gateway Stage with Caching Enabled:** + Ensure that the stage of your API Gateway has caching enabled. You can do this by creating or updating the stage with the `--cache-cluster-enabled` parameter set to `true`. + + ```sh + aws apigateway create-stage --rest-api-id --stage-name --deployment-id --cache-cluster-enabled true + ``` + + Or, if you are updating an existing stage: + + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/cacheClusterEnabled,value=true + ``` + +2. **Specify Cache Cluster Size:** + Define the size of the cache cluster to ensure it is appropriately configured. This can be done during the creation or update of the stage. + + ```sh + aws apigateway create-stage --rest-api-id --stage-name --deployment-id --cache-cluster-size + ``` + + Or, if you are updating an existing stage: + + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/cacheClusterSize,value= + ``` + +3. **Enable Caching for Specific Methods:** + Ensure that caching is enabled for specific methods within your API Gateway. This can be done by updating the method settings. + + ```sh + aws apigateway update-method --rest-api-id --resource-id --http-method --patch-operations op=replace,path=/methodSettings/*/*/cachingEnabled,value=true + ``` + +4. **Set Cache TTL (Time to Live):** + Define the TTL for the cache to control how long responses are cached. + + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/methodSettings/*/*/cacheTtlInSeconds,value= + ``` + +Replace ``, ``, ``, ``, ``, ``, and `` with your specific API Gateway details. + + + +To prevent the misconfiguration of not enabling API Cache in API Gateway using Python scripts, you can follow these steps: + +1. **Install Required Libraries**: + Ensure you have the necessary libraries installed. You will need `boto3` for AWS, `azure-mgmt-apimanagement` for Azure, and `google-api-python-client` for GCP. + + ```bash + pip install boto3 azure-mgmt-apimanagement google-api-python-client + ``` + +2. **AWS: Enable API Cache in API Gateway**: + Use `boto3` to enable caching for your API Gateway in AWS. + + ```python + import boto3 + + client = boto3.client('apigateway') + + def enable_api_cache(rest_api_id, stage_name): + response = client.update_stage( + restApiId=rest_api_id, + stageName=stage_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/cacheClusterEnabled', + 'value': 'true' + }, + { + 'op': 'replace', + 'path': '/cacheClusterSize', + 'value': '0.5' # Example size, adjust as needed + } + ] + ) + print(response) + + # Example usage + enable_api_cache('your_rest_api_id', 'your_stage_name') + ``` + +3. **Azure: Enable API Cache in API Management**: + Use `azure-mgmt-apimanagement` to enable caching for your API Management in Azure. + + ```python + from azure.identity import DefaultAzureCredential + from azure.mgmt.apimanagement import ApiManagementClient + + credential = DefaultAzureCredential() + client = ApiManagementClient(credential, 'your_subscription_id') + + def enable_api_cache(resource_group_name, service_name, api_id): + api = client.api.get(resource_group_name, service_name, api_id) + api.cache = { + 'description': 'Cache description', + 'duration': '300', # Cache duration in seconds + 'useDynamicCompression': True + } + client.api.create_or_update(resource_group_name, service_name, api_id, api) + + # Example usage + enable_api_cache('your_resource_group_name', 'your_service_name', 'your_api_id') + ``` + +4. **GCP: Enable API Cache in API Gateway**: + Use `google-api-python-client` to enable caching for your API Gateway in GCP. + + ```python + from googleapiclient.discovery import build + from google.oauth2 import service_account + + credentials = service_account.Credentials.from_service_account_file('path_to_your_service_account.json') + service = build('apigateway', 'v1', credentials=credentials) + + def enable_api_cache(api_name, config_id): + config = service.projects().locations().apis().configs().get( + name=f'projects/your_project_id/locations/global/apis/{api_name}/configs/{config_id}' + ).execute() + + config['gatewayConfig']['backendConfig']['cacheConfig'] = { + 'enabled': True, + 'ttl': '300s' # Cache TTL in seconds + } + + service.projects().locations().apis().configs().patch( + name=f'projects/your_project_id/locations/global/apis/{api_name}/configs/{config_id}', + body=config + ).execute() + + # Example usage + enable_api_cache('your_api_name', 'your_config_id') + ``` + +These scripts will help you enable API caching in AWS, Azure, and GCP, thereby preventing the misconfiguration of not having API caching enabled. Adjust the parameters as needed for your specific environment. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_enable_api_cache_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_enable_api_cache_remediation.mdx index 3123e5c2..00f3d89d 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_enable_api_cache_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_enable_api_cache_remediation.mdx @@ -2,6 +2,175 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent enabling API Cache in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to prevent enabling the cache. + +3. **Access Stage Settings:** + - Click on the "Stages" option in the left-hand navigation pane. + - Select the stage you want to configure (e.g., "prod" or "dev"). + +4. **Disable Cache:** + - In the "Stage Editor" pane, scroll down to the "Cache Settings" section. + - Ensure that the "Enable API Cache" option is unchecked. + +By following these steps, you can prevent the API cache from being enabled in API Gateway using the AWS Management Console. + + + +To prevent the misconfiguration of not enabling API Cache in API Gateway using AWS CLI, you can follow these steps: + +1. **Create or Update API Gateway Stage with Caching Enabled:** + Ensure that the stage of your API Gateway has caching enabled. You can do this by creating or updating the stage with the `--cache-cluster-enabled` parameter set to `true`. + + ```sh + aws apigateway create-stage --rest-api-id --stage-name --deployment-id --cache-cluster-enabled true + ``` + + Or, if you are updating an existing stage: + + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/cacheClusterEnabled,value=true + ``` + +2. **Specify Cache Cluster Size:** + Define the size of the cache cluster to ensure it is appropriately configured. This can be done during the creation or update of the stage. + + ```sh + aws apigateway create-stage --rest-api-id --stage-name --deployment-id --cache-cluster-size + ``` + + Or, if you are updating an existing stage: + + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/cacheClusterSize,value= + ``` + +3. **Enable Caching for Specific Methods:** + Ensure that caching is enabled for specific methods within your API Gateway. This can be done by updating the method settings. + + ```sh + aws apigateway update-method --rest-api-id --resource-id --http-method --patch-operations op=replace,path=/methodSettings/*/*/cachingEnabled,value=true + ``` + +4. **Set Cache TTL (Time to Live):** + Define the TTL for the cache to control how long responses are cached. + + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/methodSettings/*/*/cacheTtlInSeconds,value= + ``` + +Replace ``, ``, ``, ``, ``, ``, and `` with your specific API Gateway details. + + + +To prevent the misconfiguration of not enabling API Cache in API Gateway using Python scripts, you can follow these steps: + +1. **Install Required Libraries**: + Ensure you have the necessary libraries installed. You will need `boto3` for AWS, `azure-mgmt-apimanagement` for Azure, and `google-api-python-client` for GCP. + + ```bash + pip install boto3 azure-mgmt-apimanagement google-api-python-client + ``` + +2. **AWS: Enable API Cache in API Gateway**: + Use `boto3` to enable caching for your API Gateway in AWS. + + ```python + import boto3 + + client = boto3.client('apigateway') + + def enable_api_cache(rest_api_id, stage_name): + response = client.update_stage( + restApiId=rest_api_id, + stageName=stage_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/cacheClusterEnabled', + 'value': 'true' + }, + { + 'op': 'replace', + 'path': '/cacheClusterSize', + 'value': '0.5' # Example size, adjust as needed + } + ] + ) + print(response) + + # Example usage + enable_api_cache('your_rest_api_id', 'your_stage_name') + ``` + +3. **Azure: Enable API Cache in API Management**: + Use `azure-mgmt-apimanagement` to enable caching for your API Management in Azure. + + ```python + from azure.identity import DefaultAzureCredential + from azure.mgmt.apimanagement import ApiManagementClient + + credential = DefaultAzureCredential() + client = ApiManagementClient(credential, 'your_subscription_id') + + def enable_api_cache(resource_group_name, service_name, api_id): + api = client.api.get(resource_group_name, service_name, api_id) + api.cache = { + 'description': 'Cache description', + 'duration': '300', # Cache duration in seconds + 'useDynamicCompression': True + } + client.api.create_or_update(resource_group_name, service_name, api_id, api) + + # Example usage + enable_api_cache('your_resource_group_name', 'your_service_name', 'your_api_id') + ``` + +4. **GCP: Enable API Cache in API Gateway**: + Use `google-api-python-client` to enable caching for your API Gateway in GCP. + + ```python + from googleapiclient.discovery import build + from google.oauth2 import service_account + + credentials = service_account.Credentials.from_service_account_file('path_to_your_service_account.json') + service = build('apigateway', 'v1', credentials=credentials) + + def enable_api_cache(api_name, config_id): + config = service.projects().locations().apis().configs().get( + name=f'projects/your_project_id/locations/global/apis/{api_name}/configs/{config_id}' + ).execute() + + config['gatewayConfig']['backendConfig']['cacheConfig'] = { + 'enabled': True, + 'ttl': '300s' # Cache TTL in seconds + } + + service.projects().locations().apis().configs().patch( + name=f'projects/your_project_id/locations/global/apis/{api_name}/configs/{config_id}', + body=config + ).execute() + + # Example usage + enable_api_cache('your_api_name', 'your_config_id') + ``` + +These scripts will help you enable API caching in AWS, Azure, and GCP, thereby preventing the misconfiguration of not having API caching enabled. Adjust the parameters as needed for your specific environment. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_enable_encryption_api_cache.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_enable_encryption_api_cache.mdx index 26d10976..4b418c4f 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_enable_encryption_api_cache.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_enable_encryption_api_cache.mdx @@ -25,6 +25,184 @@ HITRUST, SOC2, NISTCSF, PCIDSS ### Triage and Remediation + + +### How to Prevent + + +To prevent the misconfiguration of not enabling encryption for API Cache in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to enable cache encryption. + - Click on the API name to open its configuration. + +3. **Enable Cache Encryption:** + - In the left-hand navigation pane, select "Stages." + - Choose the stage you want to configure (e.g., "prod" or "dev"). + - Scroll down to the "Cache Settings" section. + - Ensure that the "Enable Cache Encryption" checkbox is checked. + +4. **Save Changes:** + - After enabling the cache encryption, click the "Save Changes" button to apply the configuration. + +By following these steps, you can ensure that the API cache is encrypted, enhancing the security of your API Gateway. + + + +To prevent the misconfiguration of not enabling encryption for API Cache in API Gateway using AWS CLI, follow these steps: + +1. **Ensure AWS CLI is Installed and Configured:** + Make sure you have the AWS CLI installed and configured with the necessary permissions to modify API Gateway settings. + + ```sh + aws configure + ``` + +2. **Retrieve the Current API Gateway Settings:** + Identify the API Gateway for which you want to enable cache encryption. You can list your API Gateways to find the correct one. + + ```sh + aws apigateway get-rest-apis + ``` + +3. **Update the Stage Settings to Enable Cache Encryption:** + Use the `update-stage` command to enable cache encryption for a specific stage of your API Gateway. Replace `rest-api-id`, `stage-name`, and `true` with your specific values. + + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/cacheClusterEnabled,value=true + ``` + +4. **Verify the Configuration:** + Confirm that the cache encryption is enabled by describing the stage settings. + + ```sh + aws apigateway get-stage --rest-api-id --stage-name + ``` + +By following these steps, you can ensure that the API Cache in API Gateway is encrypted, thereby preventing the misconfiguration. + + + +To prevent the misconfiguration of not enabling encryption for API Cache in API Gateway 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: + +```bash +pip install boto3 +``` + +### 2. **Initialize Boto3 Client** +Initialize the Boto3 client for API Gateway: + +```python +import boto3 + +client = boto3.client('apigateway') +``` + +### 3. **Retrieve API Gateway Stage Configuration** +Retrieve the configuration of the API Gateway stage where you want to enable cache encryption: + +```python +rest_api_id = 'your_rest_api_id' # Replace with your API Gateway ID +stage_name = 'your_stage_name' # Replace with your stage name + +response = client.get_stage( + restApiId=rest_api_id, + stageName=stage_name +) +``` + +### 4. **Update Stage to Enable Cache Encryption** +Update the stage configuration to enable cache encryption: + +```python +client.update_stage( + restApiId=rest_api_id, + stageName=stage_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/cacheClusterEnabled', + 'value': 'true' + }, + { + 'op': 'replace', + 'path': '/cacheClusterSize', + 'value': '0.5' # Example size, adjust as needed + }, + { + 'op': 'replace', + 'path': '/methodSettings/*/*/caching/dataEncrypted', + 'value': 'true' + } + ] +) +``` + +### Full Script Example + +Here is the full script combining all the steps: + +```python +import boto3 + +# Initialize Boto3 client +client = boto3.client('apigateway') + +# Define your API Gateway ID and Stage Name +rest_api_id = 'your_rest_api_id' # Replace with your API Gateway ID +stage_name = 'your_stage_name' # Replace with your stage name + +# Retrieve the current stage configuration +response = client.get_stage( + restApiId=rest_api_id, + stageName=stage_name +) + +# Update the stage to enable cache encryption +client.update_stage( + restApiId=rest_api_id, + stageName=stage_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/cacheClusterEnabled', + 'value': 'true' + }, + { + 'op': 'replace', + 'path': '/cacheClusterSize', + 'value': '0.5' # Example size, adjust as needed + }, + { + 'op': 'replace', + 'path': '/methodSettings/*/*/caching/dataEncrypted', + 'value': 'true' + } + ] +) + +print("Cache encryption enabled for API Gateway stage.") +``` + +### Summary +1. Install and set up Boto3. +2. Initialize the Boto3 client for API Gateway. +3. Retrieve the current stage configuration. +4. Update the stage to enable cache encryption. + +By following these steps, you can ensure that the API cache in API Gateway is encrypted, thereby preventing the misconfiguration. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_enable_encryption_api_cache_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_enable_encryption_api_cache_remediation.mdx index aa64bcde..997f6a82 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_enable_encryption_api_cache_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_enable_encryption_api_cache_remediation.mdx @@ -2,6 +2,183 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent the misconfiguration of not enabling encryption for API Cache in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to enable cache encryption. + - Click on the API name to open its configuration. + +3. **Enable Cache Encryption:** + - In the left-hand navigation pane, select "Stages." + - Choose the stage you want to configure (e.g., "prod" or "dev"). + - Scroll down to the "Cache Settings" section. + - Ensure that the "Enable Cache Encryption" checkbox is checked. + +4. **Save Changes:** + - After enabling the cache encryption, click the "Save Changes" button to apply the configuration. + +By following these steps, you can ensure that the API cache is encrypted, enhancing the security of your API Gateway. + + + +To prevent the misconfiguration of not enabling encryption for API Cache in API Gateway using AWS CLI, follow these steps: + +1. **Ensure AWS CLI is Installed and Configured:** + Make sure you have the AWS CLI installed and configured with the necessary permissions to modify API Gateway settings. + + ```sh + aws configure + ``` + +2. **Retrieve the Current API Gateway Settings:** + Identify the API Gateway for which you want to enable cache encryption. You can list your API Gateways to find the correct one. + + ```sh + aws apigateway get-rest-apis + ``` + +3. **Update the Stage Settings to Enable Cache Encryption:** + Use the `update-stage` command to enable cache encryption for a specific stage of your API Gateway. Replace `rest-api-id`, `stage-name`, and `true` with your specific values. + + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/cacheClusterEnabled,value=true + ``` + +4. **Verify the Configuration:** + Confirm that the cache encryption is enabled by describing the stage settings. + + ```sh + aws apigateway get-stage --rest-api-id --stage-name + ``` + +By following these steps, you can ensure that the API Cache in API Gateway is encrypted, thereby preventing the misconfiguration. + + + +To prevent the misconfiguration of not enabling encryption for API Cache in API Gateway 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: + +```bash +pip install boto3 +``` + +### 2. **Initialize Boto3 Client** +Initialize the Boto3 client for API Gateway: + +```python +import boto3 + +client = boto3.client('apigateway') +``` + +### 3. **Retrieve API Gateway Stage Configuration** +Retrieve the configuration of the API Gateway stage where you want to enable cache encryption: + +```python +rest_api_id = 'your_rest_api_id' # Replace with your API Gateway ID +stage_name = 'your_stage_name' # Replace with your stage name + +response = client.get_stage( + restApiId=rest_api_id, + stageName=stage_name +) +``` + +### 4. **Update Stage to Enable Cache Encryption** +Update the stage configuration to enable cache encryption: + +```python +client.update_stage( + restApiId=rest_api_id, + stageName=stage_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/cacheClusterEnabled', + 'value': 'true' + }, + { + 'op': 'replace', + 'path': '/cacheClusterSize', + 'value': '0.5' # Example size, adjust as needed + }, + { + 'op': 'replace', + 'path': '/methodSettings/*/*/caching/dataEncrypted', + 'value': 'true' + } + ] +) +``` + +### Full Script Example + +Here is the full script combining all the steps: + +```python +import boto3 + +# Initialize Boto3 client +client = boto3.client('apigateway') + +# Define your API Gateway ID and Stage Name +rest_api_id = 'your_rest_api_id' # Replace with your API Gateway ID +stage_name = 'your_stage_name' # Replace with your stage name + +# Retrieve the current stage configuration +response = client.get_stage( + restApiId=rest_api_id, + stageName=stage_name +) + +# Update the stage to enable cache encryption +client.update_stage( + restApiId=rest_api_id, + stageName=stage_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/cacheClusterEnabled', + 'value': 'true' + }, + { + 'op': 'replace', + 'path': '/cacheClusterSize', + 'value': '0.5' # Example size, adjust as needed + }, + { + 'op': 'replace', + 'path': '/methodSettings/*/*/caching/dataEncrypted', + 'value': 'true' + } + ] +) + +print("Cache encryption enabled for API Gateway stage.") +``` + +### Summary +1. Install and set up Boto3. +2. Initialize the Boto3 client for API Gateway. +3. Retrieve the current stage configuration. +4. Update the stage to enable cache encryption. + +By following these steps, you can ensure that the API cache in API Gateway is encrypted, thereby preventing the misconfiguration. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_integrated_waf.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_integrated_waf.mdx index b7e1adcf..368b6b59 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_integrated_waf.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_integrated_waf.mdx @@ -24,6 +24,135 @@ HITRUST, SOC2, NISTCSF, PCIDSS ### Triage and Remediation + + +### How to Prevent + + +To prevent the misconfiguration where an API Gateway should be integrated with a Web Application Firewall (WAF) in AWS using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API you want to integrate with WAF from the list of APIs. + +3. **Enable WAF Integration:** + - In the API details page, look for the "Resource Policy" or "Settings" section. + - Find the option to enable WAF integration. This might be labeled as "AWS WAF WebACL" or similar. + - Click on "Edit" or "Add" to configure the WAF settings. + +4. **Associate a WebACL:** + - In the WAF integration settings, select an existing WebACL (Web Access Control List) or create a new one. + - Ensure the WebACL is properly configured with the necessary rules to protect your API. + - Save the changes to associate the WebACL with your API Gateway. + +By following these steps, you can ensure that your API Gateway is integrated with AWS WAF, providing an additional layer of security to protect against common web exploits and vulnerabilities. + + + +To prevent the misconfiguration where an API Gateway should be integrated with a Web Application Firewall (WAF) in AWS using the AWS CLI, follow these steps: + +1. **Create a Web ACL (Web Access Control List) in WAF:** + First, you need to create a Web ACL in AWS WAF. This Web ACL will be used to protect your API Gateway. + + ```sh + aws wafv2 create-web-acl --name --scope REGIONAL --default-action Allow={} --visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName= --region + ``` + +2. **Create WAF Rules:** + Define the rules that you want to include in your Web ACL. This step is optional but recommended to specify the security rules. + + ```sh + aws wafv2 create-rule-group --name --scope REGIONAL --capacity --visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName= --rules --region + ``` + +3. **Associate the Web ACL with the API Gateway:** + Once the Web ACL is created, you need to associate it with your API Gateway. + + ```sh + aws wafv2 associate-web-acl --web-acl-arn --resource-arn --region + ``` + +4. **Verify the Association:** + Ensure that the Web ACL is correctly associated with your API Gateway by describing the Web ACL associations. + + ```sh + aws wafv2 list-resources-for-web-acl --web-acl-arn --region + ``` + +Replace ``, ``, ``, ``, ``, ``, ``, and `` with your specific values. This will ensure that your API Gateway is protected by a WAF, preventing the misconfiguration. + + + +To prevent the misconfiguration where an API Gateway should be integrated with a Web Application Firewall (WAF) in AWS using Python scripts, you can follow these steps: + +1. **Install AWS SDK for Python (Boto3):** + Ensure you have Boto3 installed in your environment. If not, you can install it using pip: + ```bash + pip install boto3 + ``` + +2. **Create a WAF WebACL:** + First, create a WebACL in AWS WAF. This WebACL will be associated with your API Gateway. Below is a sample script to create a WebACL: + ```python + import boto3 + + waf_client = boto3.client('wafv2', region_name='us-east-1') + + response = waf_client.create_web_acl( + Name='MyWebACL', + Scope='REGIONAL', + DefaultAction={'Allow': {}}, + VisibilityConfig={ + 'SampledRequestsEnabled': True, + 'CloudWatchMetricsEnabled': True, + 'MetricName': 'MyWebACL' + }, + Rules=[] + ) + + web_acl_arn = response['Summary']['ARN'] + print(f"Created WebACL with ARN: {web_acl_arn}") + ``` + +3. **Retrieve the API Gateway ID:** + Retrieve the ID of the API Gateway that you want to integrate with the WAF. Below is a sample script to list API Gateways and get their IDs: + ```python + apigateway_client = boto3.client('apigateway', region_name='us-east-1') + + response = apigateway_client.get_rest_apis() + api_gateway_id = None + + for item in response['items']: + if item['name'] == 'MyApiGateway': + api_gateway_id = item['id'] + break + + if api_gateway_id: + print(f"API Gateway ID: {api_gateway_id}") + else: + print("API Gateway not found.") + ``` + +4. **Associate the WebACL with the API Gateway:** + Finally, associate the created WebACL with the API Gateway. Below is a sample script to perform this association: + ```python + waf_client.associate_web_acl( + WebACLArn=web_acl_arn, + ResourceArn=f'arn:aws:apigateway:us-east-1::/restapis/{api_gateway_id}/stages/prod' + ) + + print(f"Associated WebACL {web_acl_arn} with API Gateway {api_gateway_id}") + ``` + +By following these steps, you can ensure that your API Gateway is integrated with a WAF, thereby preventing the misconfiguration. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_integrated_waf_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_integrated_waf_remediation.mdx index 2cb5fae0..939a0c65 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_integrated_waf_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_integrated_waf_remediation.mdx @@ -2,6 +2,134 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent the misconfiguration where an API Gateway should be integrated with a Web Application Firewall (WAF) in AWS using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API you want to integrate with WAF from the list of APIs. + +3. **Enable WAF Integration:** + - In the API details page, look for the "Resource Policy" or "Settings" section. + - Find the option to enable WAF integration. This might be labeled as "AWS WAF WebACL" or similar. + - Click on "Edit" or "Add" to configure the WAF settings. + +4. **Associate a WebACL:** + - In the WAF integration settings, select an existing WebACL (Web Access Control List) or create a new one. + - Ensure the WebACL is properly configured with the necessary rules to protect your API. + - Save the changes to associate the WebACL with your API Gateway. + +By following these steps, you can ensure that your API Gateway is integrated with AWS WAF, providing an additional layer of security to protect against common web exploits and vulnerabilities. + + + +To prevent the misconfiguration where an API Gateway should be integrated with a Web Application Firewall (WAF) in AWS using the AWS CLI, follow these steps: + +1. **Create a Web ACL (Web Access Control List) in WAF:** + First, you need to create a Web ACL in AWS WAF. This Web ACL will be used to protect your API Gateway. + + ```sh + aws wafv2 create-web-acl --name --scope REGIONAL --default-action Allow={} --visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName= --region + ``` + +2. **Create WAF Rules:** + Define the rules that you want to include in your Web ACL. This step is optional but recommended to specify the security rules. + + ```sh + aws wafv2 create-rule-group --name --scope REGIONAL --capacity --visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName= --rules --region + ``` + +3. **Associate the Web ACL with the API Gateway:** + Once the Web ACL is created, you need to associate it with your API Gateway. + + ```sh + aws wafv2 associate-web-acl --web-acl-arn --resource-arn --region + ``` + +4. **Verify the Association:** + Ensure that the Web ACL is correctly associated with your API Gateway by describing the Web ACL associations. + + ```sh + aws wafv2 list-resources-for-web-acl --web-acl-arn --region + ``` + +Replace ``, ``, ``, ``, ``, ``, ``, and `` with your specific values. This will ensure that your API Gateway is protected by a WAF, preventing the misconfiguration. + + + +To prevent the misconfiguration where an API Gateway should be integrated with a Web Application Firewall (WAF) in AWS using Python scripts, you can follow these steps: + +1. **Install AWS SDK for Python (Boto3):** + Ensure you have Boto3 installed in your environment. If not, you can install it using pip: + ```bash + pip install boto3 + ``` + +2. **Create a WAF WebACL:** + First, create a WebACL in AWS WAF. This WebACL will be associated with your API Gateway. Below is a sample script to create a WebACL: + ```python + import boto3 + + waf_client = boto3.client('wafv2', region_name='us-east-1') + + response = waf_client.create_web_acl( + Name='MyWebACL', + Scope='REGIONAL', + DefaultAction={'Allow': {}}, + VisibilityConfig={ + 'SampledRequestsEnabled': True, + 'CloudWatchMetricsEnabled': True, + 'MetricName': 'MyWebACL' + }, + Rules=[] + ) + + web_acl_arn = response['Summary']['ARN'] + print(f"Created WebACL with ARN: {web_acl_arn}") + ``` + +3. **Retrieve the API Gateway ID:** + Retrieve the ID of the API Gateway that you want to integrate with the WAF. Below is a sample script to list API Gateways and get their IDs: + ```python + apigateway_client = boto3.client('apigateway', region_name='us-east-1') + + response = apigateway_client.get_rest_apis() + api_gateway_id = None + + for item in response['items']: + if item['name'] == 'MyApiGateway': + api_gateway_id = item['id'] + break + + if api_gateway_id: + print(f"API Gateway ID: {api_gateway_id}") + else: + print("API Gateway not found.") + ``` + +4. **Associate the WebACL with the API Gateway:** + Finally, associate the created WebACL with the API Gateway. Below is a sample script to perform this association: + ```python + waf_client.associate_web_acl( + WebACLArn=web_acl_arn, + ResourceArn=f'arn:aws:apigateway:us-east-1::/restapis/{api_gateway_id}/stages/prod' + ) + + print(f"Associated WebACL {web_acl_arn} with API Gateway {api_gateway_id}") + ``` + +By following these steps, you can ensure that your API Gateway is integrated with a WAF, thereby preventing the misconfiguration. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_private_endpoint.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_private_endpoint.mdx index 6b1b809e..4a9a4cea 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_private_endpoint.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_private_endpoint.mdx @@ -24,6 +24,240 @@ SOC2, NISTCSF, PCIDSS ### Triage and Remediation + + +### How to Prevent + + +To prevent only private endpoints from accessing APIs in API Gateway using the AWS Management Console, follow these steps: + +1. **Create a VPC Endpoint for API Gateway:** + - Navigate to the VPC Dashboard. + - Select "Endpoints" from the left-hand menu. + - Click on "Create Endpoint." + - Choose the service name for API Gateway (com.amazonaws..execute-api). + - Select the VPC and subnets where you want the endpoint to be accessible. + - Configure the security group to control access to the endpoint. + - Click "Create Endpoint." + +2. **Configure API Gateway to Use the VPC Endpoint:** + - Navigate to the API Gateway Console. + - Select the API you want to configure. + - Go to the "Stages" section and select the stage you want to configure. + - In the "Settings" tab, set the "Endpoint Type" to "Private." + - Specify the VPC Endpoint ID created in the previous step. + +3. **Update Resource Policies:** + - In the API Gateway Console, select the API. + - Go to the "Resource Policy" section. + - Add a policy that allows access only from the VPC Endpoint. + - Example policy: + ```json + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": "*", + "Action": "execute-api:Invoke", + "Resource": "arn:aws:execute-api:::/*", + "Condition": { + "StringEquals": { + "aws:SourceVpce": "" + } + } + } + ] + } + ``` + - Save the policy. + +4. **Test the Configuration:** + - Ensure that the API is only accessible through the VPC Endpoint. + - Attempt to access the API from outside the VPC to confirm that it is not accessible. + +By following these steps, you can ensure that only private endpoints within your VPC can access your API Gateway, enhancing the security of your APIs. + + + +To prevent only private endpoints from accessing APIs in API Gateway using AWS CLI, you can follow these steps: + +1. **Create a VPC Endpoint for API Gateway:** + Ensure you have a VPC endpoint for API Gateway in your VPC. This allows your API Gateway to be accessed only within your VPC. + + ```sh + aws ec2 create-vpc-endpoint --vpc-id --service-name com.amazonaws..execute-api --vpc-endpoint-type Interface + ``` + +2. **Update API Gateway to Use VPC Endpoint:** + Configure your API Gateway to use the VPC endpoint by associating it with the VPC link. + + ```sh + aws apigateway create-vpc-link --name --target-arns + ``` + +3. **Restrict API Gateway Access to VPC:** + Update the API Gateway resource policy to restrict access to the VPC endpoint. + + ```sh + aws apigateway update-rest-api --rest-api-id --patch-operations op=add,path=/policy,value='{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Principal": "*", + "Action": "execute-api:Invoke", + "Resource": "arn:aws:execute-api:::/*", + "Condition": { + "StringNotEquals": { + "aws:SourceVpce": "" + } + } + } + ] + }' + ``` + +4. **Verify the Configuration:** + Ensure that the API Gateway is correctly configured to only allow access from the specified VPC endpoint. + + ```sh + aws apigateway get-rest-api --rest-api-id + ``` + +By following these steps, you can ensure that only private endpoints within your VPC can access your API Gateway, thereby preventing public access. + + + +To prevent public access to APIs in API Gateway and ensure that only private endpoints can access them, you can use Python scripts to configure the necessary settings in AWS, Azure, and GCP. Below are the steps for each cloud provider: + +### AWS (Amazon Web Services) + +1. **Create a VPC Endpoint for API Gateway:** + ```python + import boto3 + + ec2_client = boto3.client('ec2') + + response = ec2_client.create_vpc_endpoint( + VpcEndpointType='Interface', + VpcId='vpc-xxxxxxxx', + ServiceName='com.amazonaws..execute-api', + SubnetIds=['subnet-xxxxxxxx'], + SecurityGroupIds=['sg-xxxxxxxx'] + ) + print(response) + ``` + +2. **Update API Gateway to Use the VPC Endpoint:** + ```python + import boto3 + + apigateway_client = boto3.client('apigateway') + + response = apigateway_client.update_rest_api( + restApiId='api-id', + patchOperations=[ + { + 'op': 'replace', + 'path': '/endpointConfiguration/types', + 'value': 'PRIVATE' + } + ] + ) + print(response) + ``` + +### Azure (Microsoft Azure) + +1. **Create a Private Endpoint for API Management:** + ```python + from azure.identity import DefaultAzureCredential + from azure.mgmt.network import NetworkManagementClient + + credential = DefaultAzureCredential() + network_client = NetworkManagementClient(credential, 'subscription-id') + + response = network_client.private_endpoints.begin_create_or_update( + 'resource-group-name', + 'private-endpoint-name', + { + 'location': 'eastus', + 'private_link_service_connections': [{ + 'name': 'connection-name', + 'private_link_service_id': '/subscriptions/subscription-id/resourceGroups/resource-group-name/providers/Microsoft.ApiManagement/service/apim-service-name', + 'group_ids': ['gateway'] + }], + 'subnet': { + 'id': '/subscriptions/subscription-id/resourceGroups/resource-group-name/providers/Microsoft.Network/virtualNetworks/vnet-name/subnets/subnet-name' + } + } + ).result() + print(response) + ``` + +2. **Configure API Management to Use the Private Endpoint:** + ```python + from azure.identity import DefaultAzureCredential + from azure.mgmt.apimanagement import ApiManagementClient + + credential = DefaultAzureCredential() + apim_client = ApiManagementClient(credential, 'subscription-id') + + response = apim_client.api_management_service.update( + 'resource-group-name', + 'apim-service-name', + { + 'public_network_access': 'Disabled' + } + ) + print(response) + ``` + +### GCP (Google Cloud Platform) + +1. **Create a Private Service Connect Endpoint:** + ```python + from google.cloud import compute_v1 + + client = compute_v1.GlobalForwardingRulesClient() + + forwarding_rule = compute_v1.ForwardingRule( + name='private-endpoint', + load_balancing_scheme='INTERNAL', + network='projects/project-id/global/networks/network-name', + target='projects/project-id/global/targetHttpProxies/target-proxy-name' + ) + + operation = client.insert( + project='project-id', + forwarding_rule_resource=forwarding_rule + ) + print(operation) + ``` + +2. **Restrict API Gateway to Use the Private Endpoint:** + ```python + from google.cloud import apigateway_v1 + + client = apigateway_v1.ApiGatewayServiceClient() + + api = client.get_api(name='projects/project-id/locations/global/apis/api-id') + + api.gateway_config = { + 'endpoint_type': 'PRIVATE' + } + + operation = client.update_api(api=api) + print(operation) + ``` + +These scripts will help you configure your API Gateways to ensure that only private endpoints can access them, thereby preventing public access. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_private_endpoint_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_private_endpoint_remediation.mdx index db4a4147..61885ade 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_private_endpoint_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_private_endpoint_remediation.mdx @@ -2,6 +2,239 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent only private endpoints from accessing APIs in API Gateway using the AWS Management Console, follow these steps: + +1. **Create a VPC Endpoint for API Gateway:** + - Navigate to the VPC Dashboard. + - Select "Endpoints" from the left-hand menu. + - Click on "Create Endpoint." + - Choose the service name for API Gateway (com.amazonaws..execute-api). + - Select the VPC and subnets where you want the endpoint to be accessible. + - Configure the security group to control access to the endpoint. + - Click "Create Endpoint." + +2. **Configure API Gateway to Use the VPC Endpoint:** + - Navigate to the API Gateway Console. + - Select the API you want to configure. + - Go to the "Stages" section and select the stage you want to configure. + - In the "Settings" tab, set the "Endpoint Type" to "Private." + - Specify the VPC Endpoint ID created in the previous step. + +3. **Update Resource Policies:** + - In the API Gateway Console, select the API. + - Go to the "Resource Policy" section. + - Add a policy that allows access only from the VPC Endpoint. + - Example policy: + ```json + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": "*", + "Action": "execute-api:Invoke", + "Resource": "arn:aws:execute-api:::/*", + "Condition": { + "StringEquals": { + "aws:SourceVpce": "" + } + } + } + ] + } + ``` + - Save the policy. + +4. **Test the Configuration:** + - Ensure that the API is only accessible through the VPC Endpoint. + - Attempt to access the API from outside the VPC to confirm that it is not accessible. + +By following these steps, you can ensure that only private endpoints within your VPC can access your API Gateway, enhancing the security of your APIs. + + + +To prevent only private endpoints from accessing APIs in API Gateway using AWS CLI, you can follow these steps: + +1. **Create a VPC Endpoint for API Gateway:** + Ensure you have a VPC endpoint for API Gateway in your VPC. This allows your API Gateway to be accessed only within your VPC. + + ```sh + aws ec2 create-vpc-endpoint --vpc-id --service-name com.amazonaws..execute-api --vpc-endpoint-type Interface + ``` + +2. **Update API Gateway to Use VPC Endpoint:** + Configure your API Gateway to use the VPC endpoint by associating it with the VPC link. + + ```sh + aws apigateway create-vpc-link --name --target-arns + ``` + +3. **Restrict API Gateway Access to VPC:** + Update the API Gateway resource policy to restrict access to the VPC endpoint. + + ```sh + aws apigateway update-rest-api --rest-api-id --patch-operations op=add,path=/policy,value='{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Principal": "*", + "Action": "execute-api:Invoke", + "Resource": "arn:aws:execute-api:::/*", + "Condition": { + "StringNotEquals": { + "aws:SourceVpce": "" + } + } + } + ] + }' + ``` + +4. **Verify the Configuration:** + Ensure that the API Gateway is correctly configured to only allow access from the specified VPC endpoint. + + ```sh + aws apigateway get-rest-api --rest-api-id + ``` + +By following these steps, you can ensure that only private endpoints within your VPC can access your API Gateway, thereby preventing public access. + + + +To prevent public access to APIs in API Gateway and ensure that only private endpoints can access them, you can use Python scripts to configure the necessary settings in AWS, Azure, and GCP. Below are the steps for each cloud provider: + +### AWS (Amazon Web Services) + +1. **Create a VPC Endpoint for API Gateway:** + ```python + import boto3 + + ec2_client = boto3.client('ec2') + + response = ec2_client.create_vpc_endpoint( + VpcEndpointType='Interface', + VpcId='vpc-xxxxxxxx', + ServiceName='com.amazonaws..execute-api', + SubnetIds=['subnet-xxxxxxxx'], + SecurityGroupIds=['sg-xxxxxxxx'] + ) + print(response) + ``` + +2. **Update API Gateway to Use the VPC Endpoint:** + ```python + import boto3 + + apigateway_client = boto3.client('apigateway') + + response = apigateway_client.update_rest_api( + restApiId='api-id', + patchOperations=[ + { + 'op': 'replace', + 'path': '/endpointConfiguration/types', + 'value': 'PRIVATE' + } + ] + ) + print(response) + ``` + +### Azure (Microsoft Azure) + +1. **Create a Private Endpoint for API Management:** + ```python + from azure.identity import DefaultAzureCredential + from azure.mgmt.network import NetworkManagementClient + + credential = DefaultAzureCredential() + network_client = NetworkManagementClient(credential, 'subscription-id') + + response = network_client.private_endpoints.begin_create_or_update( + 'resource-group-name', + 'private-endpoint-name', + { + 'location': 'eastus', + 'private_link_service_connections': [{ + 'name': 'connection-name', + 'private_link_service_id': '/subscriptions/subscription-id/resourceGroups/resource-group-name/providers/Microsoft.ApiManagement/service/apim-service-name', + 'group_ids': ['gateway'] + }], + 'subnet': { + 'id': '/subscriptions/subscription-id/resourceGroups/resource-group-name/providers/Microsoft.Network/virtualNetworks/vnet-name/subnets/subnet-name' + } + } + ).result() + print(response) + ``` + +2. **Configure API Management to Use the Private Endpoint:** + ```python + from azure.identity import DefaultAzureCredential + from azure.mgmt.apimanagement import ApiManagementClient + + credential = DefaultAzureCredential() + apim_client = ApiManagementClient(credential, 'subscription-id') + + response = apim_client.api_management_service.update( + 'resource-group-name', + 'apim-service-name', + { + 'public_network_access': 'Disabled' + } + ) + print(response) + ``` + +### GCP (Google Cloud Platform) + +1. **Create a Private Service Connect Endpoint:** + ```python + from google.cloud import compute_v1 + + client = compute_v1.GlobalForwardingRulesClient() + + forwarding_rule = compute_v1.ForwardingRule( + name='private-endpoint', + load_balancing_scheme='INTERNAL', + network='projects/project-id/global/networks/network-name', + target='projects/project-id/global/targetHttpProxies/target-proxy-name' + ) + + operation = client.insert( + project='project-id', + forwarding_rule_resource=forwarding_rule + ) + print(operation) + ``` + +2. **Restrict API Gateway to Use the Private Endpoint:** + ```python + from google.cloud import apigateway_v1 + + client = apigateway_v1.ApiGatewayServiceClient() + + api = client.get_api(name='projects/project-id/locations/global/apis/api-id') + + api.gateway_config = { + 'endpoint_type': 'PRIVATE' + } + + operation = client.update_api(api=api) + print(operation) + ``` + +These scripts will help you configure your API Gateways to ensure that only private endpoints can access them, thereby preventing public access. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_rotate_ssl_certificates.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_rotate_ssl_certificates.mdx index d138447e..b6dbdfa4 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_rotate_ssl_certificates.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_rotate_ssl_certificates.mdx @@ -24,6 +24,158 @@ GDPR ### Triage and Remediation + + +### How to Prevent + + +To prevent expiring SSL client certificates in AWS API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to manage SSL client certificates. + - Click on the API name to open its configuration. + +3. **Manage Client Certificates:** + - In the left-hand navigation pane, select "Client Certificates." + - Here, you can view the list of existing client certificates and their expiration dates. + +4. **Rotate Certificates:** + - To rotate a certificate, click on the certificate that is nearing expiration. + - Choose "Generate Client Certificate" to create a new certificate. + - Update your API configurations to use the new certificate and ensure that the old certificate is removed or deactivated once the new one is in place. + +By following these steps, you can ensure that your SSL client certificates are rotated before they expire, maintaining the security and integrity of your API Gateway. + + + +To prevent expiring SSL client certificates in AWS API Gateway using AWS CLI, you can follow these steps: + +1. **List Existing Client Certificates:** + - First, identify the client certificates that are currently in use and their expiration dates. + - Command: + ```sh + aws apigateway get-client-certificates + ``` + +2. **Create a New Client Certificate:** + - Generate a new client certificate to replace the expiring one. + - Command: + ```sh + aws apigateway create-client-certificate --description "New client certificate for API Gateway" + ``` + +3. **Update API Gateway to Use the New Certificate:** + - Update the API Gateway to use the newly created client certificate. + - Command: + ```sh + aws apigateway update-rest-api --rest-api-id --patch-operations op=replace,path=/clientCertificateId,value= + ``` + +4. **Delete the Old Client Certificate:** + - Once the new certificate is in place and verified, delete the old, expiring client certificate to avoid confusion and potential security risks. + - Command: + ```sh + aws apigateway delete-client-certificate --client-certificate-id + ``` + +By following these steps, you can ensure that your SSL client certificates in AWS API Gateway are rotated before they expire, maintaining the security and integrity of your API communications. + + + +To prevent expiring SSL client certificates in API Gateway using Python scripts, you can automate the process of checking and rotating the certificates. Below are the steps to achieve this: + +### 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: + +```bash +pip install boto3 +``` + +### 2. **Check Expiry Date of SSL Certificates** +Create a Python script to check the expiry date of the SSL certificates associated with your API Gateway. This script will list all the certificates and their expiration dates. + +```python +import boto3 +from datetime import datetime, timezone + +# Initialize a session using Amazon API Gateway +client = boto3.client('apigateway') + +# List all client certificates +response = client.get_client_certificates() + +# Check the expiration date of each certificate +for cert in response['items']: + cert_id = cert['clientCertificateId'] + expiration_date = cert['expirationDate'] + expiration_date = datetime.strptime(expiration_date, '%Y-%m-%dT%H:%M:%S.%fZ') + expiration_date = expiration_date.replace(tzinfo=timezone.utc) + + # Print certificate details + print(f"Certificate ID: {cert_id}") + print(f"Expiration Date: {expiration_date}") + + # Check if the certificate is expiring within 30 days + if expiration_date < datetime.now(timezone.utc) + timedelta(days=30): + print(f"Certificate {cert_id} is expiring soon.") +``` + +### 3. **Automate Certificate Rotation** +If a certificate is found to be expiring soon, you can automate the rotation process by creating a new certificate and associating it with the API Gateway. + +```python +from datetime import timedelta + +# Function to create a new client certificate +def create_new_certificate(): + response = client.generate_client_certificate( + description='New client certificate' + ) + return response['clientCertificateId'] + +# Function to update API Gateway with the new certificate +def update_api_gateway(api_id, new_cert_id): + client.update_rest_api( + restApiId=api_id, + patchOperations=[ + { + 'op': 'replace', + 'path': '/clientCertificateId', + 'value': new_cert_id + } + ] + ) + +# Example usage +api_id = 'your_api_id_here' +new_cert_id = create_new_certificate() +update_api_gateway(api_id, new_cert_id) +print(f"Updated API Gateway {api_id} with new certificate {new_cert_id}") +``` + +### 4. **Schedule the Script** +To ensure continuous monitoring and rotation, schedule the script to run periodically using a task scheduler like cron (Linux) or Task Scheduler (Windows). + +#### Example: Using cron (Linux) +1. Open the crontab editor: + ```bash + crontab -e + ``` +2. Add a cron job to run the script daily: + ```bash + 0 0 * * * /usr/bin/python3 /path/to/your_script.py + ``` + +By following these steps, you can automate the process of checking and rotating expiring SSL client certificates in API Gateway using Python scripts. This will help prevent any disruptions due to expired certificates. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_rotate_ssl_certificates_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_rotate_ssl_certificates_remediation.mdx index 21c1ea2b..569f82d3 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_rotate_ssl_certificates_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_rotate_ssl_certificates_remediation.mdx @@ -2,6 +2,157 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent expiring SSL client certificates in AWS API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to manage SSL client certificates. + - Click on the API name to open its configuration. + +3. **Manage Client Certificates:** + - In the left-hand navigation pane, select "Client Certificates." + - Here, you can view the list of existing client certificates and their expiration dates. + +4. **Rotate Certificates:** + - To rotate a certificate, click on the certificate that is nearing expiration. + - Choose "Generate Client Certificate" to create a new certificate. + - Update your API configurations to use the new certificate and ensure that the old certificate is removed or deactivated once the new one is in place. + +By following these steps, you can ensure that your SSL client certificates are rotated before they expire, maintaining the security and integrity of your API Gateway. + + + +To prevent expiring SSL client certificates in AWS API Gateway using AWS CLI, you can follow these steps: + +1. **List Existing Client Certificates:** + - First, identify the client certificates that are currently in use and their expiration dates. + - Command: + ```sh + aws apigateway get-client-certificates + ``` + +2. **Create a New Client Certificate:** + - Generate a new client certificate to replace the expiring one. + - Command: + ```sh + aws apigateway create-client-certificate --description "New client certificate for API Gateway" + ``` + +3. **Update API Gateway to Use the New Certificate:** + - Update the API Gateway to use the newly created client certificate. + - Command: + ```sh + aws apigateway update-rest-api --rest-api-id --patch-operations op=replace,path=/clientCertificateId,value= + ``` + +4. **Delete the Old Client Certificate:** + - Once the new certificate is in place and verified, delete the old, expiring client certificate to avoid confusion and potential security risks. + - Command: + ```sh + aws apigateway delete-client-certificate --client-certificate-id + ``` + +By following these steps, you can ensure that your SSL client certificates in AWS API Gateway are rotated before they expire, maintaining the security and integrity of your API communications. + + + +To prevent expiring SSL client certificates in API Gateway using Python scripts, you can automate the process of checking and rotating the certificates. Below are the steps to achieve this: + +### 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: + +```bash +pip install boto3 +``` + +### 2. **Check Expiry Date of SSL Certificates** +Create a Python script to check the expiry date of the SSL certificates associated with your API Gateway. This script will list all the certificates and their expiration dates. + +```python +import boto3 +from datetime import datetime, timezone + +# Initialize a session using Amazon API Gateway +client = boto3.client('apigateway') + +# List all client certificates +response = client.get_client_certificates() + +# Check the expiration date of each certificate +for cert in response['items']: + cert_id = cert['clientCertificateId'] + expiration_date = cert['expirationDate'] + expiration_date = datetime.strptime(expiration_date, '%Y-%m-%dT%H:%M:%S.%fZ') + expiration_date = expiration_date.replace(tzinfo=timezone.utc) + + # Print certificate details + print(f"Certificate ID: {cert_id}") + print(f"Expiration Date: {expiration_date}") + + # Check if the certificate is expiring within 30 days + if expiration_date < datetime.now(timezone.utc) + timedelta(days=30): + print(f"Certificate {cert_id} is expiring soon.") +``` + +### 3. **Automate Certificate Rotation** +If a certificate is found to be expiring soon, you can automate the rotation process by creating a new certificate and associating it with the API Gateway. + +```python +from datetime import timedelta + +# Function to create a new client certificate +def create_new_certificate(): + response = client.generate_client_certificate( + description='New client certificate' + ) + return response['clientCertificateId'] + +# Function to update API Gateway with the new certificate +def update_api_gateway(api_id, new_cert_id): + client.update_rest_api( + restApiId=api_id, + patchOperations=[ + { + 'op': 'replace', + 'path': '/clientCertificateId', + 'value': new_cert_id + } + ] + ) + +# Example usage +api_id = 'your_api_id_here' +new_cert_id = create_new_certificate() +update_api_gateway(api_id, new_cert_id) +print(f"Updated API Gateway {api_id} with new certificate {new_cert_id}") +``` + +### 4. **Schedule the Script** +To ensure continuous monitoring and rotation, schedule the script to run periodically using a task scheduler like cron (Linux) or Task Scheduler (Windows). + +#### Example: Using cron (Linux) +1. Open the crontab editor: + ```bash + crontab -e + ``` +2. Add a cron job to run the script daily: + ```bash + 0 0 * * * /usr/bin/python3 /path/to/your_script.py + ``` + +By following these steps, you can automate the process of checking and rotating expiring SSL client certificates in API Gateway using Python scripts. This will help prevent any disruptions due to expired certificates. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_stages_logging_enabled.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_stages_logging_enabled.mdx index e0518e04..9bca25cc 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_stages_logging_enabled.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_stages_logging_enabled.mdx @@ -24,6 +24,138 @@ CBP,GDPR,HIPAA,ISO27001,SEBI,RBI_MD_ITF,RBI_UCB ### Triage and Remediation + + +### How to Prevent + + +To prevent the misconfiguration of "API Gateway Execution Logging Should Be Enabled" in AWS API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to enable execution logging. + +3. **Enable CloudWatch Logs:** + - In the left-hand navigation pane, select "Stages." + - Choose the stage you want to configure (e.g., "prod" or "dev"). + - In the "Stage Editor" pane, expand the "Logs/Tracing" section. + - Check the box for "Enable CloudWatch Logs." + - Set the "Log level" to the desired level (e.g., INFO, ERROR). + +4. **Save Changes:** + - Click the "Save Changes" button at the bottom of the "Logs/Tracing" section to apply the configuration. + +By following these steps, you ensure that execution logging is enabled for your API Gateway, which helps in monitoring and troubleshooting API calls. + + + +To prevent the misconfiguration of API Gateway Execution Logging not being enabled in AWS using the AWS CLI, follow these steps: + +1. **Create or Update a Log Group:** + Ensure you have a CloudWatch Log Group where the API Gateway logs will be stored. If you don't have one, create it using the following command: + ```sh + aws logs create-log-group --log-group-name + ``` + +2. **Enable Logging for the API Gateway Stage:** + Use the `update-stage` command to enable logging for a specific stage of your API Gateway. Replace ``, ``, and `` with your actual values. + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/accessLogSettings/destinationArn,value=arn:aws:logs:::log-group: + ``` + +3. **Set the Log Format:** + Define the format of the logs that will be sent to CloudWatch. This can be done using the `update-stage` command as well. Replace `` with your desired log format. + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/accessLogSettings/format,value='' + ``` + +4. **Verify the Configuration:** + Ensure that the logging settings have been applied correctly by describing the stage configuration. + ```sh + aws apigateway get-stage --rest-api-id --stage-name + ``` + +By following these steps, you can ensure that API Gateway Execution Logging is enabled, which helps in monitoring and troubleshooting API calls effectively. + + + +To prevent the misconfiguration of API Gateway Execution Logging not being enabled in AWS API Gateway using Python scripts, you can follow these steps: + +1. **Install Boto3 Library**: + Ensure you have the Boto3 library installed, which is the AWS SDK for Python. You can install it using pip if you haven't already. + + ```bash + pip install boto3 + ``` + +2. **Set Up AWS Credentials**: + Make sure your AWS credentials are configured. You can set them up using the AWS CLI or by setting environment variables. + + ```bash + aws configure + ``` + +3. **Enable Execution Logging for API Gateway**: + Use the following Python script to enable execution logging for a specific API Gateway stage. This script assumes you have an existing API Gateway and stage. + + ```python + import boto3 + + # Initialize a session using Amazon API Gateway + client = boto3.client('apigateway') + + # Replace these variables with your API Gateway ID and Stage Name + rest_api_id = 'your_rest_api_id' + stage_name = 'your_stage_name' + cloudwatch_log_group_arn = 'arn:aws:logs:region:account-id:log-group:your-log-group' + + # Enable execution logging + response = client.update_stage( + restApiId=rest_api_id, + stageName=stage_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/*/*/logging/loglevel', + 'value': 'INFO' + }, + { + 'op': 'replace', + 'path': '/*/*/logging/dataTrace', + 'value': 'true' + }, + { + 'op': 'replace', + 'path': '/*/*/metrics/enabled', + 'value': 'true' + }, + { + 'op': 'replace', + 'path': '/*/*/logging/loggroup', + 'value': cloudwatch_log_group_arn + } + ] + ) + + print("Execution logging enabled:", response) + ``` + +4. **Verify Execution Logging**: + After running the script, you can verify that execution logging is enabled by checking the API Gateway stage settings in the AWS Management Console or by using the AWS CLI. + + ```bash + aws apigateway get-stage --rest-api-id your_rest_api_id --stage-name your_stage_name + ``` + +By following these steps, you can ensure that execution logging is enabled for your API Gateway stages, helping you to monitor and troubleshoot your API Gateway effectively. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_stages_logging_enabled_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_stages_logging_enabled_remediation.mdx index f3968618..dbbe0166 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_stages_logging_enabled_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_stages_logging_enabled_remediation.mdx @@ -2,6 +2,137 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent the misconfiguration of "API Gateway Execution Logging Should Be Enabled" in AWS API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API for which you want to enable execution logging. + +3. **Enable CloudWatch Logs:** + - In the left-hand navigation pane, select "Stages." + - Choose the stage you want to configure (e.g., "prod" or "dev"). + - In the "Stage Editor" pane, expand the "Logs/Tracing" section. + - Check the box for "Enable CloudWatch Logs." + - Set the "Log level" to the desired level (e.g., INFO, ERROR). + +4. **Save Changes:** + - Click the "Save Changes" button at the bottom of the "Logs/Tracing" section to apply the configuration. + +By following these steps, you ensure that execution logging is enabled for your API Gateway, which helps in monitoring and troubleshooting API calls. + + + +To prevent the misconfiguration of API Gateway Execution Logging not being enabled in AWS using the AWS CLI, follow these steps: + +1. **Create or Update a Log Group:** + Ensure you have a CloudWatch Log Group where the API Gateway logs will be stored. If you don't have one, create it using the following command: + ```sh + aws logs create-log-group --log-group-name + ``` + +2. **Enable Logging for the API Gateway Stage:** + Use the `update-stage` command to enable logging for a specific stage of your API Gateway. Replace ``, ``, and `` with your actual values. + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/accessLogSettings/destinationArn,value=arn:aws:logs:::log-group: + ``` + +3. **Set the Log Format:** + Define the format of the logs that will be sent to CloudWatch. This can be done using the `update-stage` command as well. Replace `` with your desired log format. + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/accessLogSettings/format,value='' + ``` + +4. **Verify the Configuration:** + Ensure that the logging settings have been applied correctly by describing the stage configuration. + ```sh + aws apigateway get-stage --rest-api-id --stage-name + ``` + +By following these steps, you can ensure that API Gateway Execution Logging is enabled, which helps in monitoring and troubleshooting API calls effectively. + + + +To prevent the misconfiguration of API Gateway Execution Logging not being enabled in AWS API Gateway using Python scripts, you can follow these steps: + +1. **Install Boto3 Library**: + Ensure you have the Boto3 library installed, which is the AWS SDK for Python. You can install it using pip if you haven't already. + + ```bash + pip install boto3 + ``` + +2. **Set Up AWS Credentials**: + Make sure your AWS credentials are configured. You can set them up using the AWS CLI or by setting environment variables. + + ```bash + aws configure + ``` + +3. **Enable Execution Logging for API Gateway**: + Use the following Python script to enable execution logging for a specific API Gateway stage. This script assumes you have an existing API Gateway and stage. + + ```python + import boto3 + + # Initialize a session using Amazon API Gateway + client = boto3.client('apigateway') + + # Replace these variables with your API Gateway ID and Stage Name + rest_api_id = 'your_rest_api_id' + stage_name = 'your_stage_name' + cloudwatch_log_group_arn = 'arn:aws:logs:region:account-id:log-group:your-log-group' + + # Enable execution logging + response = client.update_stage( + restApiId=rest_api_id, + stageName=stage_name, + patchOperations=[ + { + 'op': 'replace', + 'path': '/*/*/logging/loglevel', + 'value': 'INFO' + }, + { + 'op': 'replace', + 'path': '/*/*/logging/dataTrace', + 'value': 'true' + }, + { + 'op': 'replace', + 'path': '/*/*/metrics/enabled', + 'value': 'true' + }, + { + 'op': 'replace', + 'path': '/*/*/logging/loggroup', + 'value': cloudwatch_log_group_arn + } + ] + ) + + print("Execution logging enabled:", response) + ``` + +4. **Verify Execution Logging**: + After running the script, you can verify that execution logging is enabled by checking the API Gateway stage settings in the AWS Management Console or by using the AWS CLI. + + ```bash + aws apigateway get-stage --rest-api-id your_rest_api_id --stage-name your_stage_name + ``` + +By following these steps, you can ensure that execution logging is enabled for your API Gateway stages, helping you to monitor and troubleshoot your API Gateway effectively. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_tracing_enabled.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_tracing_enabled.mdx index 51facd7a..f99aaada 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_tracing_enabled.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_tracing_enabled.mdx @@ -24,6 +24,122 @@ CBP ### Triage and Remediation + + +### How to Prevent + + +To prevent the misconfiguration of "Active Tracing Should Be Enabled For API Gateway Stages" in AWS API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select the API:** + - In the API Gateway console, select the API for which you want to enable active tracing. + - Click on the API name to open its details. + +3. **Access Stages:** + - In the left-hand navigation pane, click on "Stages." + - Select the stage (e.g., "dev," "prod") for which you want to enable active tracing. + +4. **Enable Active Tracing:** + - In the Stage Editor, scroll down to the "Tracing" section. + - Check the box labeled "Enable X-Ray Tracing." + - Click the "Save Changes" button to apply the configuration. + +By following these steps, you ensure that active tracing is enabled for the specified API Gateway stage, which helps in monitoring and debugging API requests using AWS X-Ray. + + + +To prevent the misconfiguration of "Active Tracing Should Be Enabled For API Gateway Stages" in AWS API Gateway using AWS CLI, follow these steps: + +1. **Install and Configure AWS CLI:** + Ensure that the AWS CLI is installed and configured with the necessary permissions to manage API Gateway resources. + ```sh + aws configure + ``` + +2. **List API Gateway Stages:** + Identify the API Gateway stages for which you need to enable active tracing. + ```sh + aws apigateway get-rest-apis + aws apigateway get-stages --rest-api-id + ``` + +3. **Enable Active Tracing for a Specific Stage:** + Use the `update-stage` command to enable active tracing for a specific stage. + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/tracingEnabled,value=true + ``` + +4. **Verify the Configuration:** + Confirm that active tracing has been enabled for the specified stage. + ```sh + aws apigateway get-stage --rest-api-id --stage-name + ``` + +By following these steps, you can ensure that active tracing is enabled for your API Gateway stages, helping you to monitor and troubleshoot your API more effectively. + + + +To prevent the misconfiguration of "Active Tracing Should Be Enabled For API Gateway Stages" in AWS API Gateway using Python scripts, you can use the AWS SDK for Python (Boto3). Here are the steps to ensure that active tracing is enabled for your API Gateway stages: + +1. **Install Boto3**: + Ensure you have Boto3 installed in your Python environment. If not, you can install it using pip: + ```bash + pip install boto3 + ``` + +2. **Initialize Boto3 Client**: + Initialize the Boto3 client for API Gateway. + ```python + import boto3 + + client = boto3.client('apigateway') + ``` + +3. **List All API Gateway Stages**: + Retrieve all the stages for a given API Gateway to check their current tracing settings. + ```python + def list_stages(api_id): + response = client.get_stages( + restApiId=api_id + ) + return response['item'] + ``` + +4. **Enable Active Tracing for Each Stage**: + Iterate through each stage and enable active tracing if it is not already enabled. + ```python + def enable_active_tracing(api_id): + stages = list_stages(api_id) + for stage in stages: + if not stage.get('tracingEnabled', False): + client.update_stage( + restApiId=api_id, + stageName=stage['stageName'], + patchOperations=[ + { + 'op': 'replace', + 'path': '/tracingEnabled', + 'value': 'true' + } + ] + ) + print(f"Enabled active tracing for stage: {stage['stageName']}") + + # Example usage + api_id = 'your_api_id_here' + enable_active_tracing(api_id) + ``` + +This script will ensure that active tracing is enabled for all stages of a specified API Gateway. Make sure to replace `'your_api_id_here'` with the actual API ID of your API Gateway. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_tracing_enabled_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_tracing_enabled_remediation.mdx index 91e7d35b..1b8c7d55 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_tracing_enabled_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_tracing_enabled_remediation.mdx @@ -2,6 +2,121 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent the misconfiguration of "Active Tracing Should Be Enabled For API Gateway Stages" in AWS API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select the API:** + - In the API Gateway console, select the API for which you want to enable active tracing. + - Click on the API name to open its details. + +3. **Access Stages:** + - In the left-hand navigation pane, click on "Stages." + - Select the stage (e.g., "dev," "prod") for which you want to enable active tracing. + +4. **Enable Active Tracing:** + - In the Stage Editor, scroll down to the "Tracing" section. + - Check the box labeled "Enable X-Ray Tracing." + - Click the "Save Changes" button to apply the configuration. + +By following these steps, you ensure that active tracing is enabled for the specified API Gateway stage, which helps in monitoring and debugging API requests using AWS X-Ray. + + + +To prevent the misconfiguration of "Active Tracing Should Be Enabled For API Gateway Stages" in AWS API Gateway using AWS CLI, follow these steps: + +1. **Install and Configure AWS CLI:** + Ensure that the AWS CLI is installed and configured with the necessary permissions to manage API Gateway resources. + ```sh + aws configure + ``` + +2. **List API Gateway Stages:** + Identify the API Gateway stages for which you need to enable active tracing. + ```sh + aws apigateway get-rest-apis + aws apigateway get-stages --rest-api-id + ``` + +3. **Enable Active Tracing for a Specific Stage:** + Use the `update-stage` command to enable active tracing for a specific stage. + ```sh + aws apigateway update-stage --rest-api-id --stage-name --patch-operations op=replace,path=/tracingEnabled,value=true + ``` + +4. **Verify the Configuration:** + Confirm that active tracing has been enabled for the specified stage. + ```sh + aws apigateway get-stage --rest-api-id --stage-name + ``` + +By following these steps, you can ensure that active tracing is enabled for your API Gateway stages, helping you to monitor and troubleshoot your API more effectively. + + + +To prevent the misconfiguration of "Active Tracing Should Be Enabled For API Gateway Stages" in AWS API Gateway using Python scripts, you can use the AWS SDK for Python (Boto3). Here are the steps to ensure that active tracing is enabled for your API Gateway stages: + +1. **Install Boto3**: + Ensure you have Boto3 installed in your Python environment. If not, you can install it using pip: + ```bash + pip install boto3 + ``` + +2. **Initialize Boto3 Client**: + Initialize the Boto3 client for API Gateway. + ```python + import boto3 + + client = boto3.client('apigateway') + ``` + +3. **List All API Gateway Stages**: + Retrieve all the stages for a given API Gateway to check their current tracing settings. + ```python + def list_stages(api_id): + response = client.get_stages( + restApiId=api_id + ) + return response['item'] + ``` + +4. **Enable Active Tracing for Each Stage**: + Iterate through each stage and enable active tracing if it is not already enabled. + ```python + def enable_active_tracing(api_id): + stages = list_stages(api_id) + for stage in stages: + if not stage.get('tracingEnabled', False): + client.update_stage( + restApiId=api_id, + stageName=stage['stageName'], + patchOperations=[ + { + 'op': 'replace', + 'path': '/tracingEnabled', + 'value': 'true' + } + ] + ) + print(f"Enabled active tracing for stage: {stage['stageName']}") + + # Example usage + api_id = 'your_api_id_here' + enable_active_tracing(api_id) + ``` + +This script will ensure that active tracing is enabled for all stages of a specified API Gateway. Make sure to replace `'your_api_id_here'` with the actual API ID of your API Gateway. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/efs_encryption_enabled.mdx b/docs/aws/audit/apigatewaymonitoring/rules/efs_encryption_enabled.mdx index 418eb59c..af6b06d9 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/efs_encryption_enabled.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/efs_encryption_enabled.mdx @@ -24,6 +24,188 @@ HIPAA, GDPR, CISAWS, CBP, NIST ### Triage and Remediation + + +### How to Prevent + + +To prevent EFS (Elastic File System) Encryption from being disabled in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API you want to configure from the list of available APIs. + +3. **Enable Encryption:** + - Go to the "Settings" tab for your selected API. + - Look for the "Encryption" settings. Ensure that the "Enable Encryption" option is checked or turned on. + +4. **Save Changes:** + - After enabling encryption, make sure to save your changes by clicking the "Save" button at the bottom of the settings page. + +By following these steps, you can ensure that EFS encryption is enabled for your API Gateway, enhancing the security of your data. + + + +To prevent misconfigurations related to EFS (Elastic File System) encryption in AWS API Gateway using AWS CLI, you can follow these steps: + +1. **Create an EFS File System with Encryption Enabled:** + Ensure that any new EFS file system you create has encryption enabled by default. + + ```sh + aws efs create-file-system --creation-token --encrypted + ``` + +2. **Verify Encryption Status of Existing EFS File Systems:** + Regularly check the encryption status of your existing EFS file systems to ensure they are encrypted. + + ```sh + aws efs describe-file-systems --query "FileSystems[*].{ID:FileSystemId,Encrypted:Encrypted}" + ``` + +3. **Update API Gateway to Use Encrypted EFS:** + When configuring API Gateway to use EFS, ensure that it references an encrypted EFS file system. This step is more about ensuring the correct setup rather than a direct CLI command, but you can verify the EFS ID used in your API Gateway configuration. + + ```sh + aws apigateway get-rest-apis --query "items[*].{ID:id,name:name}" + ``` + +4. **Automate Compliance Checks:** + Use AWS Config to set up a rule that checks whether your EFS file systems are encrypted. This will help in maintaining compliance and preventing misconfigurations. + + ```sh + aws configservice put-config-rule --config-rule file://efs-encryption-enabled-rule.json + ``` + + Example `efs-encryption-enabled-rule.json`: + ```json + { + "ConfigRuleName": "efs-encryption-enabled", + "Description": "Checks whether EFS file systems are encrypted.", + "Scope": { + "ComplianceResourceTypes": [ + "AWS::EFS::FileSystem" + ] + }, + "Source": { + "Owner": "AWS", + "SourceIdentifier": "EFS_ENCRYPTION_ENABLED" + } + } + ``` + +By following these steps, you can ensure that your EFS file systems used with API Gateway are encrypted, thereby preventing misconfigurations related to EFS encryption. + + + +To prevent misconfigurations related to EFS (Elastic File System) encryption in AWS API Gateway using Python scripts, you can follow these steps: + +1. **Set Up AWS SDK for Python (Boto3):** + - Ensure you have Boto3 installed and configured with the necessary permissions to interact with AWS services. + + ```bash + pip install boto3 + ``` + +2. **Create a Python Script to Check EFS Encryption:** + - Write a Python script that checks if the EFS is encrypted. If not, it should enable encryption. + + ```python + import boto3 + + def check_and_enable_efs_encryption(efs_id): + client = boto3.client('efs') + response = client.describe_file_systems( + FileSystemId=efs_id + ) + file_system = response['FileSystems'][0] + if not file_system['Encrypted']: + print(f"EFS {efs_id} is not encrypted. Enabling encryption...") + # Note: EFS encryption at rest can only be enabled at creation time. + # You would need to create a new EFS with encryption enabled and migrate data. + # This is a placeholder for the actual logic. + # client.create_file_system(Encrypted=True, ...) + else: + print(f"EFS {efs_id} is already encrypted.") + + if __name__ == "__main__": + efs_id = 'your-efs-id' # Replace with your EFS ID + check_and_enable_efs_encryption(efs_id) + ``` + +3. **Automate the Script Execution:** + - Use AWS Lambda or a scheduled task to run the script periodically to ensure compliance. + + ```python + import boto3 + import json + + def lambda_handler(event, context): + efs_id = event['efs_id'] + check_and_enable_efs_encryption(efs_id) + + def check_and_enable_efs_encryption(efs_id): + client = boto3.client('efs') + response = client.describe_file_systems( + FileSystemId=efs_id + ) + file_system = response['FileSystems'][0] + if not file_system['Encrypted']: + print(f"EFS {efs_id} is not encrypted. Enabling encryption...") + # Note: EFS encryption at rest can only be enabled at creation time. + # You would need to create a new EFS with encryption enabled and migrate data. + # This is a placeholder for the actual logic. + # client.create_file_system(Encrypted=True, ...) + else: + print(f"EFS {efs_id} is already encrypted.") + + if __name__ == "__main__": + efs_id = 'your-efs-id' # Replace with your EFS ID + check_and_enable_efs_encryption(efs_id) + ``` + +4. **Integrate with CI/CD Pipeline:** + - Integrate the script into your CI/CD pipeline to ensure that any new EFS created is checked for encryption. + + ```yaml + # Example GitHub Actions workflow + name: Check EFS Encryption + + on: + push: + branches: + - main + + jobs: + check-efs-encryption: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.x' + - name: Install dependencies + run: | + pip install boto3 + - name: Run script + run: | + python check_efs_encryption.py + env: + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: 'us-west-2' + ``` + +By following these steps, you can ensure that your EFS is always encrypted, thereby preventing misconfigurations related to EFS encryption in AWS API Gateway. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/efs_encryption_enabled_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/efs_encryption_enabled_remediation.mdx index c26e76c6..520fe6ca 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/efs_encryption_enabled_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/efs_encryption_enabled_remediation.mdx @@ -2,6 +2,187 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent EFS (Elastic File System) Encryption from being disabled in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to API Gateway:** + - Open the AWS Management Console. + - In the Services menu, select "API Gateway" under the "Networking & Content Delivery" section. + +2. **Select Your API:** + - In the API Gateway console, select the API you want to configure from the list of available APIs. + +3. **Enable Encryption:** + - Go to the "Settings" tab for your selected API. + - Look for the "Encryption" settings. Ensure that the "Enable Encryption" option is checked or turned on. + +4. **Save Changes:** + - After enabling encryption, make sure to save your changes by clicking the "Save" button at the bottom of the settings page. + +By following these steps, you can ensure that EFS encryption is enabled for your API Gateway, enhancing the security of your data. + + + +To prevent misconfigurations related to EFS (Elastic File System) encryption in AWS API Gateway using AWS CLI, you can follow these steps: + +1. **Create an EFS File System with Encryption Enabled:** + Ensure that any new EFS file system you create has encryption enabled by default. + + ```sh + aws efs create-file-system --creation-token --encrypted + ``` + +2. **Verify Encryption Status of Existing EFS File Systems:** + Regularly check the encryption status of your existing EFS file systems to ensure they are encrypted. + + ```sh + aws efs describe-file-systems --query "FileSystems[*].{ID:FileSystemId,Encrypted:Encrypted}" + ``` + +3. **Update API Gateway to Use Encrypted EFS:** + When configuring API Gateway to use EFS, ensure that it references an encrypted EFS file system. This step is more about ensuring the correct setup rather than a direct CLI command, but you can verify the EFS ID used in your API Gateway configuration. + + ```sh + aws apigateway get-rest-apis --query "items[*].{ID:id,name:name}" + ``` + +4. **Automate Compliance Checks:** + Use AWS Config to set up a rule that checks whether your EFS file systems are encrypted. This will help in maintaining compliance and preventing misconfigurations. + + ```sh + aws configservice put-config-rule --config-rule file://efs-encryption-enabled-rule.json + ``` + + Example `efs-encryption-enabled-rule.json`: + ```json + { + "ConfigRuleName": "efs-encryption-enabled", + "Description": "Checks whether EFS file systems are encrypted.", + "Scope": { + "ComplianceResourceTypes": [ + "AWS::EFS::FileSystem" + ] + }, + "Source": { + "Owner": "AWS", + "SourceIdentifier": "EFS_ENCRYPTION_ENABLED" + } + } + ``` + +By following these steps, you can ensure that your EFS file systems used with API Gateway are encrypted, thereby preventing misconfigurations related to EFS encryption. + + + +To prevent misconfigurations related to EFS (Elastic File System) encryption in AWS API Gateway using Python scripts, you can follow these steps: + +1. **Set Up AWS SDK for Python (Boto3):** + - Ensure you have Boto3 installed and configured with the necessary permissions to interact with AWS services. + + ```bash + pip install boto3 + ``` + +2. **Create a Python Script to Check EFS Encryption:** + - Write a Python script that checks if the EFS is encrypted. If not, it should enable encryption. + + ```python + import boto3 + + def check_and_enable_efs_encryption(efs_id): + client = boto3.client('efs') + response = client.describe_file_systems( + FileSystemId=efs_id + ) + file_system = response['FileSystems'][0] + if not file_system['Encrypted']: + print(f"EFS {efs_id} is not encrypted. Enabling encryption...") + # Note: EFS encryption at rest can only be enabled at creation time. + # You would need to create a new EFS with encryption enabled and migrate data. + # This is a placeholder for the actual logic. + # client.create_file_system(Encrypted=True, ...) + else: + print(f"EFS {efs_id} is already encrypted.") + + if __name__ == "__main__": + efs_id = 'your-efs-id' # Replace with your EFS ID + check_and_enable_efs_encryption(efs_id) + ``` + +3. **Automate the Script Execution:** + - Use AWS Lambda or a scheduled task to run the script periodically to ensure compliance. + + ```python + import boto3 + import json + + def lambda_handler(event, context): + efs_id = event['efs_id'] + check_and_enable_efs_encryption(efs_id) + + def check_and_enable_efs_encryption(efs_id): + client = boto3.client('efs') + response = client.describe_file_systems( + FileSystemId=efs_id + ) + file_system = response['FileSystems'][0] + if not file_system['Encrypted']: + print(f"EFS {efs_id} is not encrypted. Enabling encryption...") + # Note: EFS encryption at rest can only be enabled at creation time. + # You would need to create a new EFS with encryption enabled and migrate data. + # This is a placeholder for the actual logic. + # client.create_file_system(Encrypted=True, ...) + else: + print(f"EFS {efs_id} is already encrypted.") + + if __name__ == "__main__": + efs_id = 'your-efs-id' # Replace with your EFS ID + check_and_enable_efs_encryption(efs_id) + ``` + +4. **Integrate with CI/CD Pipeline:** + - Integrate the script into your CI/CD pipeline to ensure that any new EFS created is checked for encryption. + + ```yaml + # Example GitHub Actions workflow + name: Check EFS Encryption + + on: + push: + branches: + - main + + jobs: + check-efs-encryption: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.x' + - name: Install dependencies + run: | + pip install boto3 + - name: Run script + run: | + python check_efs_encryption.py + env: + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: 'us-west-2' + ``` + +By following these steps, you can ensure that your EFS is always encrypted, thereby preventing misconfigurations related to EFS encryption in AWS API Gateway. + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/efs_kms_customer_master_keys.mdx b/docs/aws/audit/apigatewaymonitoring/rules/efs_kms_customer_master_keys.mdx index 989e7a7c..f8c4e099 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/efs_kms_customer_master_keys.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/efs_kms_customer_master_keys.mdx @@ -24,6 +24,197 @@ ISO27001, HIPAA ### Triage and Remediation + + +### How to Prevent + + +To prevent AWS KMS Customer Master Keys (CMKs) for EFS encryption in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to the API Gateway Console:** + - Open the AWS Management Console. + - In the search bar, type "API Gateway" and select it from the list of services. + +2. **Select Your API:** + - In the API Gateway console, select the API you want to configure from the list of available APIs. + +3. **Configure Encryption Settings:** + - Go to the "Settings" section of your API. + - Look for the "Encryption" settings or similar options related to data protection and encryption. + +4. **Specify KMS Key:** + - Ensure that the encryption settings are configured to use the appropriate AWS KMS Customer Master Key (CMK) for EFS encryption. + - If necessary, create a new CMK in the AWS KMS console and specify it in the API Gateway settings. + +By following these steps, you can ensure that your API Gateway is properly configured to use AWS KMS CMKs for EFS encryption, enhancing the security of your data. + + + +To prevent the use of AWS KMS Customer Master Keys (CMKs) for EFS encryption in API Gateway using AWS CLI, you can follow these steps: + +1. **Create a Key Policy to Restrict Usage:** + Ensure that the key policy for your CMK restricts its usage to only the intended services and principals. This can be done by specifying the allowed actions and principals in the key policy. + + ```sh + aws kms put-key-policy --key-id --policy-name default --policy file://key-policy.json + ``` + + Example `key-policy.json`: + ```json + { + "Version": "2012-10-17", + "Id": "key-default-1", + "Statement": [ + { + "Sid": "Allow administration of the key", + "Effect": "Allow", + "Principal": { + "AWS": "arn:aws:iam::111122223333:role/Admin" + }, + "Action": [ + "kms:*" + ], + "Resource": "*" + }, + { + "Sid": "Allow use of the key", + "Effect": "Allow", + "Principal": { + "AWS": "arn:aws:iam::111122223333:role/EFSRole" + }, + "Action": [ + "kms:Encrypt", + "kms:Decrypt", + "kms:ReEncrypt*", + "kms:GenerateDataKey*", + "kms:DescribeKey" + ], + "Resource": "*" + } + ] + } + ``` + +2. **Disable Key Rotation:** + Disable automatic key rotation for the CMK to ensure that the key is not automatically rotated, which might affect its usage. + + ```sh + aws kms disable-key-rotation --key-id + ``` + +3. **Tagging the Key for Identification:** + Tag the CMK to identify it easily and ensure it is not used for unintended purposes. + + ```sh + aws kms tag-resource --key-id --tags TagKey=Purpose,TagValue=EFS-Only + ``` + +4. **Audit Key Usage:** + Regularly audit the usage of the CMK to ensure it is only being used for the intended purpose. You can use AWS CloudTrail to monitor the usage of the key. + + ```sh + aws cloudtrail lookup-events --lookup-attributes AttributeKey=ResourceName,AttributeValue= + ``` + +By following these steps, you can prevent the misuse of AWS KMS Customer Master Keys for EFS encryption in API Gateway using AWS CLI. + + + +To prevent AWS KMS Customer Master Keys (CMKs) for EFS (Elastic File System) encryption in API Gateway using Python scripts, you can follow these steps: + +### Step 1: Install Boto3 +Ensure you have the Boto3 library installed, which is the AWS SDK for Python. + +```bash +pip install boto3 +``` + +### Step 2: Create a Boto3 Session +Create a Boto3 session to interact with AWS services. + +```python +import boto3 + +# Create a session using your AWS credentials +session = boto3.Session( + aws_access_key_id='YOUR_AWS_ACCESS_KEY_ID', + aws_secret_access_key='YOUR_AWS_SECRET_ACCESS_KEY', + region_name='YOUR_AWS_REGION' +) +``` + +### Step 3: Define the KMS Key Policy +Define a key policy that restricts the use of the CMK to specific AWS services and principals. This policy will ensure that only authorized entities can use the CMK for EFS encryption. + +```python +key_policy = { + "Version": "2012-10-17", + "Id": "key-default-1", + "Statement": [ + { + "Sid": "Allow administration of the key", + "Effect": "Allow", + "Principal": { + "AWS": "arn:aws:iam::YOUR_ACCOUNT_ID:root" + }, + "Action": "kms:*", + "Resource": "*" + }, + { + "Sid": "Allow use of the key", + "Effect": "Allow", + "Principal": { + "AWS": [ + "arn:aws:iam::YOUR_ACCOUNT_ID:role/YOUR_ROLE", + "arn:aws:iam::YOUR_ACCOUNT_ID:user/YOUR_USER" + ] + }, + "Action": [ + "kms:Encrypt", + "kms:Decrypt", + "kms:ReEncrypt*", + "kms:GenerateDataKey*", + "kms:DescribeKey" + ], + "Resource": "*" + } + ] +} +``` + +### Step 4: Create the KMS Key with the Defined Policy +Use the Boto3 KMS client to create a new CMK with the defined key policy. + +```python +# Create a KMS client +kms_client = session.client('kms') + +# Create a new CMK with the defined key policy +response = kms_client.create_key( + Policy=json.dumps(key_policy), + Description='CMK for EFS encryption', + KeyUsage='ENCRYPT_DECRYPT', + Origin='AWS_KMS' +) + +# Get the Key ID of the newly created CMK +key_id = response['KeyMetadata']['KeyId'] + +print(f"Created CMK with Key ID: {key_id}") +``` + +### Summary +1. **Install Boto3**: Ensure the Boto3 library is installed. +2. **Create a Boto3 Session**: Set up a session with your AWS credentials. +3. **Define the KMS Key Policy**: Create a policy that restricts the use of the CMK. +4. **Create the KMS Key**: Use the Boto3 KMS client to create the CMK with the defined policy. + +By following these steps, you can ensure that your AWS KMS Customer Master Keys are properly configured for EFS encryption, preventing unauthorized use in API Gateway. + + + + + ### Check Cause diff --git a/docs/aws/audit/apigatewaymonitoring/rules/efs_kms_customer_master_keys_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/efs_kms_customer_master_keys_remediation.mdx index ddaba39c..7b72ce29 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/efs_kms_customer_master_keys_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/efs_kms_customer_master_keys_remediation.mdx @@ -2,6 +2,196 @@ ### Triage and Remediation + + +### How to Prevent + + +To prevent AWS KMS Customer Master Keys (CMKs) for EFS encryption in API Gateway using the AWS Management Console, follow these steps: + +1. **Navigate to the API Gateway Console:** + - Open the AWS Management Console. + - In the search bar, type "API Gateway" and select it from the list of services. + +2. **Select Your API:** + - In the API Gateway console, select the API you want to configure from the list of available APIs. + +3. **Configure Encryption Settings:** + - Go to the "Settings" section of your API. + - Look for the "Encryption" settings or similar options related to data protection and encryption. + +4. **Specify KMS Key:** + - Ensure that the encryption settings are configured to use the appropriate AWS KMS Customer Master Key (CMK) for EFS encryption. + - If necessary, create a new CMK in the AWS KMS console and specify it in the API Gateway settings. + +By following these steps, you can ensure that your API Gateway is properly configured to use AWS KMS CMKs for EFS encryption, enhancing the security of your data. + + + +To prevent the use of AWS KMS Customer Master Keys (CMKs) for EFS encryption in API Gateway using AWS CLI, you can follow these steps: + +1. **Create a Key Policy to Restrict Usage:** + Ensure that the key policy for your CMK restricts its usage to only the intended services and principals. This can be done by specifying the allowed actions and principals in the key policy. + + ```sh + aws kms put-key-policy --key-id --policy-name default --policy file://key-policy.json + ``` + + Example `key-policy.json`: + ```json + { + "Version": "2012-10-17", + "Id": "key-default-1", + "Statement": [ + { + "Sid": "Allow administration of the key", + "Effect": "Allow", + "Principal": { + "AWS": "arn:aws:iam::111122223333:role/Admin" + }, + "Action": [ + "kms:*" + ], + "Resource": "*" + }, + { + "Sid": "Allow use of the key", + "Effect": "Allow", + "Principal": { + "AWS": "arn:aws:iam::111122223333:role/EFSRole" + }, + "Action": [ + "kms:Encrypt", + "kms:Decrypt", + "kms:ReEncrypt*", + "kms:GenerateDataKey*", + "kms:DescribeKey" + ], + "Resource": "*" + } + ] + } + ``` + +2. **Disable Key Rotation:** + Disable automatic key rotation for the CMK to ensure that the key is not automatically rotated, which might affect its usage. + + ```sh + aws kms disable-key-rotation --key-id + ``` + +3. **Tagging the Key for Identification:** + Tag the CMK to identify it easily and ensure it is not used for unintended purposes. + + ```sh + aws kms tag-resource --key-id --tags TagKey=Purpose,TagValue=EFS-Only + ``` + +4. **Audit Key Usage:** + Regularly audit the usage of the CMK to ensure it is only being used for the intended purpose. You can use AWS CloudTrail to monitor the usage of the key. + + ```sh + aws cloudtrail lookup-events --lookup-attributes AttributeKey=ResourceName,AttributeValue= + ``` + +By following these steps, you can prevent the misuse of AWS KMS Customer Master Keys for EFS encryption in API Gateway using AWS CLI. + + + +To prevent AWS KMS Customer Master Keys (CMKs) for EFS (Elastic File System) encryption in API Gateway using Python scripts, you can follow these steps: + +### Step 1: Install Boto3 +Ensure you have the Boto3 library installed, which is the AWS SDK for Python. + +```bash +pip install boto3 +``` + +### Step 2: Create a Boto3 Session +Create a Boto3 session to interact with AWS services. + +```python +import boto3 + +# Create a session using your AWS credentials +session = boto3.Session( + aws_access_key_id='YOUR_AWS_ACCESS_KEY_ID', + aws_secret_access_key='YOUR_AWS_SECRET_ACCESS_KEY', + region_name='YOUR_AWS_REGION' +) +``` + +### Step 3: Define the KMS Key Policy +Define a key policy that restricts the use of the CMK to specific AWS services and principals. This policy will ensure that only authorized entities can use the CMK for EFS encryption. + +```python +key_policy = { + "Version": "2012-10-17", + "Id": "key-default-1", + "Statement": [ + { + "Sid": "Allow administration of the key", + "Effect": "Allow", + "Principal": { + "AWS": "arn:aws:iam::YOUR_ACCOUNT_ID:root" + }, + "Action": "kms:*", + "Resource": "*" + }, + { + "Sid": "Allow use of the key", + "Effect": "Allow", + "Principal": { + "AWS": [ + "arn:aws:iam::YOUR_ACCOUNT_ID:role/YOUR_ROLE", + "arn:aws:iam::YOUR_ACCOUNT_ID:user/YOUR_USER" + ] + }, + "Action": [ + "kms:Encrypt", + "kms:Decrypt", + "kms:ReEncrypt*", + "kms:GenerateDataKey*", + "kms:DescribeKey" + ], + "Resource": "*" + } + ] +} +``` + +### Step 4: Create the KMS Key with the Defined Policy +Use the Boto3 KMS client to create a new CMK with the defined key policy. + +```python +# Create a KMS client +kms_client = session.client('kms') + +# Create a new CMK with the defined key policy +response = kms_client.create_key( + Policy=json.dumps(key_policy), + Description='CMK for EFS encryption', + KeyUsage='ENCRYPT_DECRYPT', + Origin='AWS_KMS' +) + +# Get the Key ID of the newly created CMK +key_id = response['KeyMetadata']['KeyId'] + +print(f"Created CMK with Key ID: {key_id}") +``` + +### Summary +1. **Install Boto3**: Ensure the Boto3 library is installed. +2. **Create a Boto3 Session**: Set up a session with your AWS credentials. +3. **Define the KMS Key Policy**: Create a policy that restricts the use of the CMK. +4. **Create the KMS Key**: Use the Boto3 KMS client to create the CMK with the defined policy. + +By following these steps, you can ensure that your AWS KMS Customer Master Keys are properly configured for EFS encryption, preventing unauthorized use in API Gateway. + + + + ### Check Cause From ba82b451d8ad63f6c18ae7ba96863c82afb45f8e Mon Sep 17 00:00:00 2001 From: ajinkyajawalkar Date: Fri, 12 Jul 2024 15:08:50 +0530 Subject: [PATCH 2/2] Added prevention for apigateway --- ...pigateway_default_execution_endpoint_enabled_remediation.mdx | 2 +- .../apigatewaymonitoring/rules/apigateway_private_endpoint.mdx | 2 +- .../rules/apigateway_private_endpoint_remediation.mdx | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_default_execution_endpoint_enabled_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_default_execution_endpoint_enabled_remediation.mdx index 3b569682..77531fed 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_default_execution_endpoint_enabled_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_default_execution_endpoint_enabled_remediation.mdx @@ -145,7 +145,7 @@ This script will ensure that the default execution endpoint is disabled for all 4. In the API details pane, choose 'Stages'. -5. In the Stages pane, select the stage you want to check. If the 'Invoke URL' ends with '/{proxy+}', the Default Execution Endpoint is enabled. +5. In the Stages pane, select the stage you want to check. If the 'Invoke URL' ends with `/{proxy+}`, the Default Execution Endpoint is enabled. diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_private_endpoint.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_private_endpoint.mdx index 4a9a4cea..ea343b6a 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_private_endpoint.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_private_endpoint.mdx @@ -35,7 +35,7 @@ To prevent only private endpoints from accessing APIs in API Gateway using the A - Navigate to the VPC Dashboard. - Select "Endpoints" from the left-hand menu. - Click on "Create Endpoint." - - Choose the service name for API Gateway (com.amazonaws..execute-api). + - Choose the service name for API Gateway `(com.amazonaws..execute-api)`. - Select the VPC and subnets where you want the endpoint to be accessible. - Configure the security group to control access to the endpoint. - Click "Create Endpoint." diff --git a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_private_endpoint_remediation.mdx b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_private_endpoint_remediation.mdx index 61885ade..50314e43 100644 --- a/docs/aws/audit/apigatewaymonitoring/rules/apigateway_private_endpoint_remediation.mdx +++ b/docs/aws/audit/apigatewaymonitoring/rules/apigateway_private_endpoint_remediation.mdx @@ -13,7 +13,7 @@ To prevent only private endpoints from accessing APIs in API Gateway using the A - Navigate to the VPC Dashboard. - Select "Endpoints" from the left-hand menu. - Click on "Create Endpoint." - - Choose the service name for API Gateway (com.amazonaws..execute-api). + - Choose the service name for API Gateway `(com.amazonaws..execute-api)`. - Select the VPC and subnets where you want the endpoint to be accessible. - Configure the security group to control access to the endpoint. - Click "Create Endpoint."