AWS Security ChangesHomeSearch

AWS code-library high security documentation change

Service: code-library · 2026-05-01 · Security-related high

File: code-library/latest/ug/ec2_example_ec2_GettingStarted_015_section.md

Summary

Updated VPC peering script with security enhancements including input validation, command injection prevention, secure logging, AWS CLI validation, CIDR validation, and improved error handling.

Security assessment

The changes include concrete security improvements: 1) Added input sanitization to prevent command injection via variables, 2) Implemented suspicious command pattern detection in logging, 3) Set strict file permissions (umask 0077 and chmod 0600) for log files, 4) Added AWS account validation to prevent misconfiguration, 5) Implemented CIDR validation to prevent network misconfigurations, 6) Added security-focused error messages. These changes directly address security vulnerabilities like command injection and insecure configurations.

Diff

diff --git a/code-library/latest/ug/ec2_example_ec2_GettingStarted_015_section.md b/code-library/latest/ug/ec2_example_ec2_GettingStarted_015_section.md
index 044b48c09..9002f5966 100644
--- a//code-library/latest/ug/ec2_example_ec2_GettingStarted_015_section.md
+++ b//code-library/latest/ug/ec2_example_ec2_GettingStarted_015_section.md
@@ -39 +39 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-    # VPC Peering Connection Script - Version 4 (Fixed)
+    # VPC Peering Connection Script - Version 6 (Security Enhanced)
@@ -44,3 +44 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-    # Initialize log file
-    LOG_FILE="vpc-peering-script-v4.log"
-    echo "Starting VPC Peering script at $(date)" > $LOG_FILE
+    set -euo pipefail
@@ -48 +46,38 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-    # Function to log commands and their output
+    # Security: Set strict umask
+    umask 0077
+    
+    # Initialize log file with restricted permissions
+    LOG_FILE="./vpc-peering-script-v6.log"
+    touch "$LOG_FILE"
+    chmod 0600 "$LOG_FILE"
+    echo "Starting VPC Peering script at $(date)" > "$LOG_FILE"
+    
+    # Configuration
+    declare -r AWS_REGION="${AWS_REGION:-us-east-1}"
+    declare -r MAX_RETRIES=3
+    declare -r RETRY_DELAY=5
+    
+    # Validate script is run from secure location
+    if [[ "$LOG_FILE" != /* ]] && [[ "$LOG_FILE" != ./* ]]; then
+        echo "ERROR: Log file path must be absolute or relative starting with ./" >&2
+        exit 1
+    fi
+    
+    # Function to sanitize variable for safe command execution
+    sanitize_var() {
+        local var="$1"
+        if [[ ! "$var" =~ ^[a-zA-Z0-9_/.-]+$ ]]; then
+            echo "ERROR: Invalid characters in variable: $var" | tee -a "$LOG_FILE"
+            return 1
+        fi
+        echo "$var"
+        return 0
+    }
+    
+    # Function to escape string for safe use in commands
+    escape_string() {
+        local string="$1"
+        printf '%s\n' "$string" | sed -e 's/[\/&]/\\&/g'
+    }
+    
+    # Function to log commands and their output securely
@@ -50,3 +85,11 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-        echo "$(date): COMMAND: $1" >> $LOG_FILE
-        eval "$1" 2>&1 | tee -a $LOG_FILE
-        return ${PIPESTATUS[0]}
+        local cmd="$1"
+        
+        # Validate command doesn't contain suspicious patterns
+        if [[ "$cmd" =~ (\$\(|\`|;.*rm|;.*mv|;.*cp) ]]; then
+            echo "ERROR: Suspicious command pattern detected" | tee -a "$LOG_FILE"
+            return 1
+        fi
+        
+        echo "$(date): COMMAND: $cmd" >> "$LOG_FILE"
+        eval "$cmd" 2>&1 | tee -a "$LOG_FILE"
+        return "${PIPESTATUS[0]}"
@@ -57,2 +100,4 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-        if [ $1 -ne 0 ]; then
-            echo "ERROR: Command failed with exit code $1" | tee -a $LOG_FILE
+        local exit_code="$1"
+        local error_msg="${2:-Command failed}"
+        if [ "$exit_code" -ne 0 ]; then
+            echo "ERROR: $error_msg (exit code: $exit_code)" | tee -a "$LOG_FILE"
@@ -61 +106,9 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-            exit $1
+            exit "$exit_code"
+        fi
+    }
+    
+    # Function to validate AWS CLI is available and configured
+    validate_aws_cli() {
+        if ! command -v aws &> /dev/null; then
+            echo "ERROR: AWS CLI is not installed" | tee -a "$LOG_FILE"
+            exit 1
@@ -62,0 +116,47 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
+        
+        # Check AWS CLI version
+        local aws_version
+        aws_version=$(aws --version 2>&1 | cut -d' ' -f1 | cut -d'/' -f2)
+        echo "AWS CLI version: $aws_version" >> "$LOG_FILE"
+        
+        if ! aws sts get-caller-identity --region "$AWS_REGION" &>/dev/null; then
+            echo "ERROR: AWS CLI is not properly configured or credentials are invalid" | tee -a "$LOG_FILE"
+            exit 1
+        fi
+        
+        # Validate caller identity
+        local account_id
+        account_id=$(aws sts get-caller-identity --query 'Account' --output text 2>/dev/null)
+        if [[ ! "$account_id" =~ ^[0-9]{12}$ ]]; then
+            echo "ERROR: Invalid AWS account ID" | tee -a "$LOG_FILE"
+            exit 1
+        fi
+        echo "Authenticated as AWS Account: $account_id" | tee -a "$LOG_FILE"
+    }
+    
+    # Function to validate CIDR blocks
+    validate_cidr() {
+        local cidr="$1"
+        if ! [[ "$cidr" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]{1,2}$ ]]; then
+            echo "ERROR: Invalid CIDR block format: $cidr" | tee -a "$LOG_FILE"
+            return 1
+        fi
+        
+        # Additional validation for IP octets
+        local ip_part="${cidr%/*}"
+        local mask_part="${cidr#*/}"
+        
+        IFS='.' read -r -a octets <<< "$ip_part"
+        for octet in "${octets[@]}"; do
+            if (( octet > 255 )); then
+                echo "ERROR: Invalid octet value in CIDR: $cidr" | tee -a "$LOG_FILE"
+                return 1
+            fi
+        done
+        
+        if (( mask_part > 32 || mask_part < 0 )); then
+            echo "ERROR: Invalid CIDR mask value: $mask_part" | tee -a "$LOG_FILE"
+            return 1
+        fi
+        
+        return 0
@@ -67 +167 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-        echo "Error encountered. Attempting to clean up resources..." | tee -a $LOG_FILE
+        echo "Error encountered. Attempting to clean up resources..." | tee -a "$LOG_FILE"
@@ -70,3 +170,3 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-        echo "Resources created:" | tee -a $LOG_FILE
-        for resource in "${CREATED_RESOURCES[@]}"; do
-            echo "- $resource" | tee -a $LOG_FILE
+        echo "Resources created:" | tee -a "$LOG_FILE"
+        for resource in "${CREATED_RESOURCES[@]:-}"; do
+            echo "- $resource" | tee -a "$LOG_FILE"
@@ -75 +175 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-        # Clean up in reverse order
+        # Clean up in reverse order with retry logic
@@ -77,2 +177,13 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-            echo "Executing cleanup: ${CLEANUP_COMMANDS[$i]}" >> $LOG_FILE
-            eval "${CLEANUP_COMMANDS[$i]}" 2>&1 >> $LOG_FILE
+            echo "Executing cleanup: ${CLEANUP_COMMANDS[$i]}" >> "$LOG_FILE"
+            local retry_count=0
+            while [ $retry_count -lt $MAX_RETRIES ]; do
+                if eval "${CLEANUP_COMMANDS[$i]}" 2>&1 >> "$LOG_FILE"; then
+                    break
+                else
+                    retry_count=$((retry_count + 1))
+                    if [ $retry_count -lt $MAX_RETRIES ]; then
+                        echo "Cleanup command failed, retrying in ${RETRY_DELAY}s..." >> "$LOG_FILE"
+                        sleep "$RETRY_DELAY"
+                    fi
+                fi
+            done
@@ -83,2 +194,2 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-    declare -a CREATED_RESOURCES
-    declare -a CLEANUP_COMMANDS
+    declare -a CREATED_RESOURCES=()
+    declare -a CLEANUP_COMMANDS=()
@@ -86 +197,2 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-    echo "Setting up VPC peering connection..."
+    # Trap errors and cleanup
+    trap cleanup_on_error EXIT
@@ -88,3 +200 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-    # Check for existing VPCs
-    echo "Checking for existing VPCs..."
-    EXISTING_VPCS=$(aws ec2 describe-vpcs --query 'Vpcs[?State==`available`].[VpcId,CidrBlock]' --output text 2>/dev/null)
+    echo "Setting up VPC peering connection..."
@@ -92,27 +202,16 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-    if [ -z "$EXISTING_VPCS" ]; then
-        echo "No existing VPCs found. Creating new VPCs..."
-        CREATE_VPCS=true
-    else
-        echo "Found existing VPCs:"
-        echo "$EXISTING_VPCS"
-        echo ""
-        echo "Do you want to use existing VPCs (e) or create new ones (n)? [e/n]: "
-        read -r VPC_CHOICE
-        
-        if [[ "${VPC_CHOICE,,}" == "e" ]]; then
-            CREATE_VPCS=false
-            # Get the first two available VPCs
-            VPC1_INFO=$(echo "$EXISTING_VPCS" | head -n 1)
-            VPC2_INFO=$(echo "$EXISTING_VPCS" | head -n 2 | tail -n 1)
-            
-            if [ -z "$VPC2_INFO" ]; then
-                echo "Only one VPC found. Creating a second VPC..."
-                VPC1_ID=$(echo $VPC1_INFO | awk '{print $1}')
-                VPC1_CIDR=$(echo $VPC1_INFO | awk '{print $2}')
-                CREATE_VPC2_ONLY=true
-            else
-                VPC1_ID=$(echo $VPC1_INFO | awk '{print $1}')