AWS Security ChangesHomeSearch

AWS code-library medium security documentation change

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

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

Summary

Enhanced IoT Device Defender implementation script with improved security validations, error handling, and resource management

Security assessment

The changes introduce JSON validation for all IAM policies and configuration documents, preventing misconfigurations that could lead to over-permissive access. Added security features include: 1) Validation of trust policies before role creation (lines 131-135), 2) Validation of custom logging/mitigation policies (lines 192-196, 238-243), 3) Input sanitization through jq parsing, 4) Security hardening through 'set -euo pipefail' at script start. These changes directly mitigate risks of policy misconfiguration and privilege escalation.

Diff

diff --git a/code-library/latest/ug/bash_2_iot_code_examples.md b/code-library/latest/ug/bash_2_iot_code_examples.md
index ff95810c6..65bc5f2ba 100644
--- a//code-library/latest/ug/bash_2_iot_code_examples.md
+++ b//code-library/latest/ug/bash_2_iot_code_examples.md
@@ -60,0 +61,2 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
+    set -euo pipefail
+    
@@ -73 +75 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-        if echo "$1" | grep -i "An error occurred\|Exception\|Failed\|usage: aws" > /dev/null; then
+        if echo "$1" | grep -iE "An error occurred|Exception|Failed|usage: aws" > /dev/null; then
@@ -81 +83,39 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-    # Function to create IAM roles
+    # Function to safely extract JSON values using jq
+    extract_json_value() {
+        local json="$1"
+        local key="$2"
+        echo "$json" | jq -r ".${key} // empty" 2>/dev/null || echo ""
+    }
+    
+    # Function to validate JSON
+    validate_json() {
+        local json="$1"
+        echo "$json" | jq empty 2>/dev/null
+    }
+    
+    # Function to check AWS CLI availability
+    check_aws_cli() {
+        if ! command -v aws &> /dev/null; then
+            echo "ERROR: AWS CLI is not installed or not in PATH"
+            return 1
+        fi
+        if ! command -v jq &> /dev/null; then
+            echo "ERROR: jq is not installed or not in PATH"
+            return 1
+        fi
+        return 0
+    }
+    
+    # Function to get AWS account ID
+    get_account_id() {
+        local account_id
+        account_id=$(aws sts get-caller-identity --query 'Account' --output text 2>/dev/null) || true
+        if [ -z "$account_id" ]; then
+            echo "ERROR: Could not retrieve AWS account ID"
+            return 1
+        fi
+        echo "$account_id"
+        return 0
+    }
+    
+    # Function to create IAM roles with retry logic
@@ -85,0 +126,2 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
+        local RETRY_COUNT=0
+        local MAX_RETRIES=3
@@ -88,0 +131,6 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
+        # Validate trust policy JSON
+        if ! validate_json "$TRUST_POLICY"; then
+            echo "ERROR: Invalid trust policy JSON for role $ROLE_NAME"
+            return 1
+        fi
+        
@@ -90 +138,10 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-        ROLE_EXISTS=$(aws iam get-role --role-name "$ROLE_NAME" 2>&1 || echo "NOT_EXISTS")
+        if aws iam get-role --role-name "$ROLE_NAME" >/dev/null 2>&1; then
+            echo "Role $ROLE_NAME already exists, skipping creation"
+            ROLE_ARN=$(aws iam get-role --role-name "$ROLE_NAME" --query 'Role.Arn' --output text 2>/dev/null) || true
+            if [ -z "$ROLE_ARN" ]; then
+                echo "ERROR: Could not retrieve ARN for existing role $ROLE_NAME"
+                return 1
+            fi
+            echo "Role ARN: $ROLE_ARN"
+            return 0
+        fi
@@ -92,2 +149,2 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-        if echo "$ROLE_EXISTS" | grep -i "NoSuchEntity" > /dev/null; then
-            # Create the role with trust policy
+        # Create the role with trust policy and retry logic
+        while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
@@ -96 +153,12 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-                --assume-role-policy-document "$TRUST_POLICY" 2>&1)
+                --assume-role-policy-document "$TRUST_POLICY" 2>&1) || true
+            
+            if check_error "$ROLE_RESULT"; then
+                break
+            fi
+            
+            RETRY_COUNT=$((RETRY_COUNT + 1))
+            if [ $RETRY_COUNT -lt $MAX_RETRIES ]; then
+                echo "Retrying role creation (attempt $((RETRY_COUNT + 1))/$MAX_RETRIES)..."
+                sleep $((RETRY_COUNT * 2))
+            fi
+        done
@@ -99 +167 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-                echo "Failed to create role $ROLE_NAME"
+            echo "Failed to create role $ROLE_NAME after $MAX_RETRIES attempts"
@@ -105 +173,3 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-                LOGGING_POLICY='{
+            local LOGGING_POLICY
+            LOGGING_POLICY=$(cat <<'EOF'
+    {
@@ -119,3 +189 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-                            "Resource": [
-                                "arn:aws:logs:*:*:*"
-                            ]
+                "Resource": "arn:aws:logs:*:*:*"
@@ -124 +192,8 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-                }'
+    }
+    EOF
+    )
+            
+            if ! validate_json "$LOGGING_POLICY"; then
+                echo "ERROR: Invalid logging policy JSON"
+                return 1
+            fi
@@ -129 +204 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-                    --policy-document "$LOGGING_POLICY" 2>&1)
+                --policy-document "$LOGGING_POLICY" 2>&1) || true
@@ -136 +211,3 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-                MITIGATION_POLICY='{
+            local MITIGATION_POLICY
+            MITIGATION_POLICY=$(cat <<'EOF'
+    {
@@ -146,2 +223 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-                                "iot:AddThingToThingGroup",
-                                "iot:PublishToTopic"
+                    "iot:AddThingToThingGroup"
@@ -149 +225 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-                            "Resource": "*"
+                "Resource": "arn:aws:iot:*:*:*"
@@ -162 +238,8 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-                }'
+    }
+    EOF
+    )
+            
+            if ! validate_json "$MITIGATION_POLICY"; then
+                echo "ERROR: Invalid mitigation policy JSON"
+                return 1
+            fi
@@ -167 +250 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-                    --policy-document "$MITIGATION_POLICY" 2>&1)
+                --policy-document "$MITIGATION_POLICY" 2>&1) || true
@@ -178 +261 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-                        --policy-arn "$MANAGED_POLICY" 2>&1)
+                    --policy-arn "$MANAGED_POLICY" 2>&1) || true
@@ -188,3 +270,0 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-        else
-            echo "Role $ROLE_NAME already exists, skipping creation"
-        fi
@@ -192,2 +272,6 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-        # Get the role ARN
-        ROLE_ARN=$(aws iam get-role --role-name "$ROLE_NAME" --query 'Role.Arn' --output text)
+        # Get the role ARN with error handling
+        ROLE_ARN=$(aws iam get-role --role-name "$ROLE_NAME" --query 'Role.Arn' --output text 2>/dev/null) || true
+        if [ -z "$ROLE_ARN" ]; then
+            echo "ERROR: Could not retrieve ARN for newly created role $ROLE_NAME"
+            return 1
+        fi
@@ -200,0 +285,11 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
+    # Validate prerequisites
+    echo "Validating prerequisites..."
+    if ! check_aws_cli; then
+        echo "ERROR: Prerequisites not met"
+        exit 1
+    fi
+    
+    ACCOUNT_ID=$(get_account_id) || exit 1
+    echo "AWS Account ID: $ACCOUNT_ID"
+    echo ""
+    
@@ -207 +302,2 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-    IOT_DEFENDER_AUDIT_TRUST_POLICY='{
+    IOT_DEFENDER_AUDIT_TRUST_POLICY=$(cat <<'EOF'
+    {
@@ -218 +314,3 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-    }'
+    }
+    EOF
+    )
@@ -220 +318,4 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-    create_iam_role "AWSIoTDeviceDefenderAuditRole" "$IOT_DEFENDER_AUDIT_TRUST_POLICY" "arn:aws:iam::aws:policy/service-role/AWSIoTDeviceDefenderAudit"
+    if ! create_iam_role "AWSIoTDeviceDefenderAuditRole" "$IOT_DEFENDER_AUDIT_TRUST_POLICY" "arn:aws:iam::aws:policy/service-role/AWSIoTDeviceDefenderAudit"; then
+        echo "ERROR: Failed to create audit role"
+        exit 1
+    fi
@@ -225 +326,2 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-    IOT_LOGGING_TRUST_POLICY='{
+    IOT_LOGGING_TRUST_POLICY=$(cat <<'EOF'
+    {
@@ -236 +338,3 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-    }'
+    }
+    EOF
+    )
@@ -238 +342,4 @@ There's more on GitHub. Find the complete example and learn how to set up and ru
-    create_iam_role "AWSIoTLoggingRole" "$IOT_LOGGING_TRUST_POLICY" ""
+    if ! create_iam_role "AWSIoTLoggingRole" "$IOT_LOGGING_TRUST_POLICY" ""; then
+        echo "ERROR: Failed to create logging role"
+        exit 1