hoangquochung1110 / public-notes

0 stars 0 forks source link

Configure AWS ALB with custom domain and https enabled #18

Open hoangquochung1110 opened 2 months ago

hoangquochung1110 commented 2 months ago

We have:

Step-by-Step Implementation

1. Configure Cloudflare DNS

  1. Log in to your Cloudflare account

  2. Select your domain (ssan.me)

  3. Add an A record: • Type: A • Name: Choose a subdomain (e.g., app) or use @ for root domain • IPv4 address: Point to one of your ALB's DNS name • Proxy status: Proxied (Orange cloud enabled) • TTL: Auto

  4. Add a second CNAME (or A) record for the other ALB DNS name/IP address (for redundancy)

2. Configure Cloudflare SSL/TLS Settings

  1. Go to SSL/TLS section in your Cloudflare dashboard

  2. Set SSL/TLS encryption mode: • Choose "Full (strict)" - This requires a valid certificate on your ALB • This setting ensures encrypted connections between: • Users and Cloudflare • Cloudflare and your ALB

  3. Edge Certificates: • Ensure "Always Use HTTPS" is enabled • Enable "Automatic HTTPS Rewrites"

3. Keep Your Current Certificate on the ALB

Your current setup is actually correct: • You have a Cloudflare Origin Certificate installed on your ALB • This certificate is specifically designed for securing the Cloudflare-to- origin connection • The certificate is for *.ssan.me and ssan.me, which is correct

4. Update Security Group (If Needed)

Ensure your ALB security group allows traffic from Cloudflare's IP ranges:

# Get Cloudflare's IP ranges
curl -s https://api.cloudflare.com/client/v4/ips | jq -r '.result.ipv4_cidrs[]'

# Add these to your ALB security group for ports 443 and 80

5. Configure HTTP to HTTPS Redirection

  1. In Cloudflare: • SSL/TLS → Edge Certificates → Always Use HTTPS: ON

  2. On your ALB (optional but recommended): • Create a listener rule on port 80 that redirects to HTTPS

bash aws elbv2 create-listener --load-balancer-arn arn:aws:elasticloadbalancing:ap-southeast-1:838835070561:loadbalancer/app/FCJ-Management-LB/32c4949eb748b54c \ --protocol HTTP --port 80 \ --default-actions Type=redirect,RedirectConfig="{Protocol=HTTPS,Port=443,Host='#{host}',Path='/#{path}',Query='#{query}',StatusCode=HTTP_301}" \ --region ap-southeast-1

6. Test Your Configuration

  1. DNS Propagation: • Wait for DNS changes to propagate (usually quick with Cloudflare) • Check with: dig app.ssan.me or whatever subdomain you chose

  2. Connection Test: • Try accessing your site through the Cloudflare domain (https://app.ssan.me) • Verify the connection is secure (lock icon in browser)

  3. Origin Connection: • Cloudflare provides a tool to test your origin connection in the SSL/TLS section

Troubleshooting Common Issues

  1. Certificate Issues: • If you see certificate errors, ensure your Cloudflare Origin Certificate is properly installed on the ALB • Verify the certificate covers the domain you're using

  2. Connection Refused: • Check that your ALB security group allows traffic from Cloudflare IPs • Verify your ALB is healthy and has healthy targets

  3. Cloudflare Bypassed: • Ensure the DNS record is proxied (orange cloud) • Check that you're not accessing the ALB directly via its DNS name

  4. Mixed Content Warnings: • Enable "Automatic HTTPS Rewrites" in Cloudflare • Check your application for hardcoded HTTP URLs

hoangquochung1110 commented 2 months ago

let's design a solution to enable HTTPS traffic going into an Application Load Balancer. Relate to other services in AWS to make it work

Designing an HTTPS Solution with Application Load Balancer

Based on your infrastructure plan, I'll design a solution to enable HTTPS traffic to an Application Load Balancer (ALB) that integrates with your existing S3, CloudTrail, and Athena setup.

HTTPS Solution Components

1. SSL/TLS Certificate

AWS Certificate Manager (ACM) • Request a public certificate for your domain(s) • Alternatively, import an existing certificate • ACM handles certificate renewal automatically • Zero cost for certificates used with AWS services

2. Application Load Balancer Configuration

Listeners: • HTTPS listener on port 443 • Optional HTTP listener on port 80 with redirect to HTTPS • Associate the ACM certificate with the HTTPS listener

Security Groups: • Inbound: Allow HTTPS (443) from public internet • Inbound: Allow HTTP (80) if using redirect • Outbound: Allow traffic to target groups

Target Groups: • Configure health checks • Register EC2 instances, containers, or IP addresses

3. DNS Configuration

Amazon Route 53: • Create A/AAAA record pointing to the ALB • Alternatively, update existing DNS provider records

Integration with Your Existing Infrastructure

Security Integration

KMS Integration: • Use your existing KMS key (alias/s3-encryption-key) for any sensitive data in transit • Configure TLS policies on the ALB to enforce strong encryption

CloudTrail Monitoring: • Your existing s3-data-activity-trail will capture ALB API activities • Add CloudWatch metrics for ALB monitoring

IAM Considerations

Service Role: • ALB will need permissions to write access logs to S3 • Extend your S3DataProcessingRole or create a new role

Security Policies: • Update security groups to allow ALB to communicate with backend services

Logging and Analysis

ALB Access Logs: • Store in your existing -cloudtrail-logs bucket • Enable encryption using your KMS key

Athena Integration: • Create additional tables in your cloudtrail_logs database for ALB logs • Develop queries to analyze traffic patterns and security events

Implementation Steps

  1. Request/Import SSL Certificate in ACM

bash aws acm request-certificate --domain-name example.com --validation-method DNS

  1. Create the Application Load Balancer

bash aws elbv2 create-load-balancer \ --name secure-application-lb \ --subnets subnet-12345 subnet-67890 \ --security-groups sg-12345 \ --scheme internet-facing \ --type application

  1. Create Target Group

bash aws elbv2 create-target-group \ --name app-target-group \ --protocol HTTP \ --port 80 \ --vpc-id vpc-12345 \ --health-check-protocol HTTP \ --health-check-path /health

  1. Add HTTPS Listener with Certificate

bash aws elbv2 create-listener \ --load-balancer-arn arn:aws:elasticloadbalancing:region:account-id:loadbalancer/app/secure-application-lb/1234567890 \ --protocol HTTPS \ --port 443 \ --certificates CertificateArn=arn:aws:acm:region:account-id:certificate/12345678-1234-1234-1234-123456789012 \ --ssl-policy ELBSecurityPolicy-TLS-1-2-2017-01 \ --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:region:account-id:targetgroup/app-target-group/1234567890

  1. Configure HTTP to HTTPS Redirect (Optional)

bash aws elbv2 create-listener \ --load-balancer-arn arn:aws:elasticloadbalancing:region:account-id:loadbalancer/app/secure-application-lb/1234567890 \ --protocol HTTP \ --port 80 \ --default-actions "Type=redirect,RedirectConfig={Protocol=HTTPS,Port=443,StatusCode=HTTP_301}"

  1. Enable Access Logging to S3

bash aws elbv2 modify-load-balancer-attributes \ --load-balancer-arn arn:aws:elasticloadbalancing:region:account-id:loadbalancer/app/secure-application-lb/1234567890 \ --attributes Key=access_logs.s3.enabled,Value=true Key=access_logs.s3.bucket,Value=-cloudtrail-logs Key=access_logs.s3.prefix,Value=alb-logs

Security Best Practices

  1. TLS Configuration • Use ELBSecurityPolicy-FS-1-2-Res-2020-10 or newer policy • Disable older TLS versions (TLS 1.0/1.1)

  2. Security Headers • Configure response headers using Lambda@Edge or on your application: • Strict-Transport-Security (HSTS) • Content-Security-Policy • X-Content-Type-Options

  3. WAF Integration • Attach AWS WAF to the ALB for additional protection: • SQL injection prevention • Cross-site scripting (XSS) protection • Rate limiting

  4. CloudWatch Alarms • Set up alarms for: • Rejected connections • HTTP 4xx/5xx error rates • Latency thresholds

This solution provides secure HTTPS traffic to your application while integrating with your existing S3 encryption, CloudTrail logging, and Athena analysis infrastructure.

hoangquochung1110 commented 2 months ago

AWS CLI Implementation Steps

Here's how to implement this using AWS CLI:

bash

Step 1: Create Cognito User Pool

aws cognito-idp create-user-pool \ --pool-name "MyAppUserPool" \ --auto-verify-attributes email \ --schema Name=email,Required=true,Mutable=true

Step 2: Create App Client

aws cognito-idp create-user-pool-client \ --user-pool-id YOUR_USER_POOL_ID \ --client-name "MyALBClient" \ --generate-secret \ --allowed-o-auth-flows "code" \ --allowed-o-auth-scopes "openid" "email" "profile" \ --callback-urls "https://your-alb-domain.com/oauth2/idpresponse" \ --supported-identity-providers "COGNITO"

Step 3: Configure Cognito Domain

aws cognito-idp create-user-pool-domain \ --domain "myapp-auth" \ --user-pool-id YOUR_USER_POOL_ID

Step 4: Configure ALB Rule with Cognito Authentication

aws elbv2 create-rule \ --listener-arn YOUR_LISTENER_ARN \ --priority 10 \ --conditions Field=path-pattern,Values='/*' \ --actions Type=authenticate-cognito,AuthenticateCognitoConfig='{UserPoolArn=YOUR_USER_POOL_ARN,UserPoolClientId=YOUR_CLIENT_ID,UserPoolDomain=YOUR_COGNITO_DOMAIN,SessionCookieName=AWSELBAuthSessionCookie,Scope=openid,SessionTimeout=3600,OnUnauthenticatedRequest=authenticate}' Type=forward,TargetGroupArn=YOUR_TARGET_GROUP_ARN

Testing and Validation

  1. Access your ALB URL
  2. You should be redirected to the Cognito login page
  3. After successful login, you'll be redirected back to your application
  4. Your application should receive user information in HTTP headers

Security Considerations

• Configure appropriate token expiration times • Use HTTPS for all communications • Implement proper logout mechanisms • Consider implementing refresh token handling for long-lived sessions • Restrict the scopes to only what's necessary

This implementation provides a secure authentication layer at the ALB level, offloading authentication concerns from your application while still allowing your application to know who the user is through the passed headers.

Do I need to provide any additional endpoints in my application as I see you m ention callback urls

You're right to ask about callback URLs. When implementing authentication with AWS Cognito and ALB, your application itself doesn't need to implement any additional endpoints specifically for authentication. This is one of the key benefits of using ALB with Cognito integration.

Here's why:

  1. ALB handles the OAuth flow: The ALB itself manages the entire authentication process with Cognito, including the callback handling.

  2. Callback URL: The callback URL you configure ( https://your-alb-domain.com/oauth2/idpresponse) is a special path that the ALB reserves for handling OAuth responses from Cognito. This path is managed by the ALB, not your application.

  3. How it works: • When a user tries to access your application, the ALB redirects them to Cognito • After authentication, Cognito redirects back to the ALB at the callback URL • The ALB processes the authentication response, creates a session cookie • The ALB then forwards the original request to your application with user information in HTTP headers

  4. Application integration: Your application only needs to: • Read the user information from HTTP headers (like x-amzn-oidc-data) • Use this information for authorization decisions • No special endpoints or OAuth handling code is required in your application

This is a significant advantage of this architecture - the authentication complexity is handled at the infrastructure level (ALB), keeping your application code focused on business logic rather than authentication flows.

If you're planning to implement features like logout or token refresh, those would typically be handled through the ALB as well, not through custom endpoints in your application.

hoangquochung1110 commented 2 months ago

Requisites

Implementation Plan

  1. Create an User Pool: an user directory
  2. Create an User Pool Domain: authentication backend that implements the standard OpenID Connect (OIDC) endpoints like authorize, userInfo, and token as We use Cognito's built-in login, registration, and account recovery pages.
  3. Add a CNAME record of your domain pointing to ALB's DNS Name
  4. Configure listeners for ALB
    • One listener to redirect HTTP to HTTPS
    • One listener to route other regular HTTP requests
      • One rule to redirect traffic to AWS Cognito if request path is "/"
      • One rule to redirect traffic to Web Application if request path is not "/"

Implementation Details

1. Create an User Pool: an user directory