Enforce HTTPS Redirection across AWS ALB

Enforcing HTTPS redirection on AWS ALB ensures all HTTP traffic is redirected to HTTPS, enhancing data security. This is achieved by modifying the ALB's listener rules, ensuring encrypted and secure data transit.

  1. 1

    This task identifies and lists AWS ALB listeners that are not configured to redirect HTTP traffic to HTTPS, potentially exposing unencrypted data in transit.

    import boto3 from botocore.exceptions import ClientError creds = _get_creds(cred_label)['creds'] access_key = creds['username'] secret_key = creds['password'] # target_region = 'us-east-1' # Set this to your desired region or None for all regions # Initialize the EC2 client to get a list of all regions ec2_client = boto3.client('ec2',aws_access_key_id=access_key,aws_secret_access_key=secret_key,region_name='us-east-1') # If target_region is not defined or None, fetch all regions, otherwise use the provided region regions = [region['RegionName'] for region in ec2_client.describe_regions()['Regions']] if not locals().get('target_region') else [target_region] # Iterate through the selected regions to check ALB listeners for region in regions: elbv2_client = boto3.client('elbv2',aws_access_key_id=access_key,aws_secret_access_key=secret_key, region_name=region) listeners_without_redirect = [] total_listeners = 0 # Counter to keep track of total listeners print(f"\nChecking ALB listeners in region {region}...") try: alb_response = elbv2_client.describe_load_balancers() except ClientError as e: print(f"Error fetching ALB list in region {region}: {e}") continue # Skip to the next region if there's an error fetching ALBs for this one for lb in alb_response.get('LoadBalancers', []): try: listener_response = elbv2_client.describe_listeners(LoadBalancerArn=lb['LoadBalancerArn']) total_listeners += len(listener_response['Listeners']) except ClientError as e: print(f"Error fetching listeners for ALB {lb['LoadBalancerName']} in region {region}: {e}") continue # Skip to the next ALB if there's an error fetching listeners for this one for listener in listener_response['Listeners']: if listener['Protocol'] == 'HTTP': redirect_actions = [action for action in listener['DefaultActions'] if action['Type'] == 'redirect'] if not redirect_actions: listeners_without_redirect.append({ 'Region': region, 'ALBName': lb['LoadBalancerName'], 'ListenerArn': listener['ListenerArn'] }) # Summary for the region if total_listeners == 0: print(f"No listeners found in region {region}.") elif listeners_without_redirect: print(listeners_without_redirect) print(f"In region {region}, found {len(listeners_without_redirect)} listener(s) without HTTPS redirection:") for listener_info in listeners_without_redirect: print(f"Region: {listener_info['Region']}, ALB: {listener_info['ALBName']}, Listener ARN: {listener_info['ListenerArn']}") else: print(f"All listeners in region {region} have HTTPS redirection configured.") context.skip_sub_tasks=True
    copied
    1
  2. 2

    This procedure adjusts AWS ALB listeners to ensure that all HTTP traffic is automatically redirected to HTTPS, enhancing the security of data transmission by using encryption.

    import boto3 from botocore.exceptions import ClientError creds = _get_creds(cred_label)['creds'] access_key = creds['username'] secret_key = creds['password'] ''' # Example structure, list passed down from upstream task listeners_without_redirect = [ {'Region': 'us-east-1', 'ALBName': 'alb-blahblah', 'ListenerArn': 'arn:aws:elasticloadbalancing:us-east-1:355237452254:listener/app/alb-blahblah/599c713a19a4afce/56d57ff44837d30f'}, {'Region': 'us-east-1', 'ALBName': 'alb-blahblah', 'ListenerArn': 'arn:aws:elasticloadbalancing:us-east-1:355237452254:listener/app/alb-blahblah/599c713a19a4afce/6a54c2e7d3c08fee'} ] ''' # Check if there are any listeners to process if not listeners_without_redirect: print("No listeners provided to modify. Exiting task.") else: print(f"Attempting to modify {len(listeners_without_redirect)} listener(s) to enforce HTTP redirection...") for listener_info in listeners_without_redirect: region = listener_info['Region'] listener_arn = listener_info['ListenerArn'] elbv2_client = boto3.client('elbv2', aws_access_key_id=access_key,aws_secret_access_key=secret_key,region_name=region) try: elbv2_client.modify_listener( ListenerArn=listener_arn, DefaultActions=[ { 'Type': 'redirect', 'Order': 1, 'RedirectConfig': { 'Protocol': 'HTTPS', 'Port': '443', 'Host': '#{host}', 'Path': '/#{path}', 'Query': '#{query}', 'StatusCode': 'HTTP_301' } } ] ) print(f"Modified listener {listener_arn} in ALB {listener_info['ALBName']} to enforce HTTP redirection.") except ClientError as e: print(f"Error modifying listener {listener_arn} in ALB {listener_info['ALBName']} in region {region}: {e}") print("Modification task completed.")
    copied
    2