Voiced by Amazon Polly |
Introduction
When you visit a website, your browser gets web page content and HTTP headers from the server. Headers like cache-control control caching duration, while content-type specifies media type. This post explains adding security headers for privacy and security. Learn to integrate them using Lambda@Edge and Amazon CloudFront. If your app setup can’t be changed, like an Amazon S3-hosted site, we can still explore how to add security response headers.
What are security headers?
Pioneers in Cloud Consulting & Migration Services
- Reduced infrastructural costs
- Accelerated application deployment
Lambda@Edge Overview
Lambda@Edge lets you run AWS Lambda functions at Amazon CloudFront Edge Locations, optimizing HTTP request processing near your users. Submit your Node.js code and link it to Amazon CloudFront behavior. You can use Lambda@Edge to respond to four Amazon CloudFront events; we’ll focus on the Origin Response event for this blog.
Origin Response – This event occurs when the origin delivers a response to a request. It can access the answer from the origin.
The graphic below shows the potential triggers for Amazon CloudFront distribution. We’re concentrating on number six:
Solution overview
The solution involves a simple single-page website on an Amazon S3 bucket, delivered via Amazon CloudFront. Learn to create a new Lambda@Edge function, link it to your Amazon CloudFront distribution, and monitor it with Amazon CloudWatch Logs. We will use the origin response trigger for our Lambda@Edge function. Amazon CloudFront caches the response after adding security headers, reducing the need for function calls ensuring security headers on subsequent ‘Hits.’
Assuming you’ve set up an Amazon S3 bucket for your website and Amazon CloudFront distribution. In my sample, I used an Amazon S3 bucket as the origin of the distribution and uploaded a basic index.html page with “Hello World!” Do you have the security headers yet?
The sequence of events that trigger our Lambda@Edge function is shown in the diagram below:
This is how the procedure operates:
- The viewer requests the “www.example.com” webpage.
- Should the object already be cached, Amazon CloudFront proceeds to step 3; if not, it returns the object to the viewer from the cache.
- An Amazon S3 bucket originates from which Amazon CloudFront requests the object.
- When Amazon S3 returns the object, Amazon CloudFront initiates the origin response event.
- When our Add Security Headers AWS Lambda function runs, Amazon CloudFront caches and serves the output.
Step-by-step Guide
We will make a new AWS Lambda function and link it to Amazon CloudFront distribution. Before proceeding, ensure you have Amazon CloudFront distribution.
First, head to the AWS Lambda Console and confirm if you are in the ap-south-1 (Mumbai) region. Then, click “Create Function” to start a new AWS Lambda function.
We select the Author from scratch for this solution because we will be utilizing the code supplied here.
As we set up the new AWS Lambda function trigger, we can select Amazon CloudFront from the dotted grey box. Then, we choose the distribution ID generated earlier, which serves content from my Amazon S3 bucket.
For cache behavior, we can opt for ‘*’, which applies to all requests as the default setting. This choice would apply only if no other behaviors match if multiple are configured.
Selecting Amazon CloudFront Event, we opt for Origin Response, occurring after the origin returns the item but before caching.
Enabling the trigger and selecting “Replicate,” Amazon CloudFront triggers the AWS Lambda function. This option automatically replicates the AWS Lambda function across multiple regions when created.
After clicking “Next,” we are taken to the Configure Function page. In this case, we can select a meaningful name and description. Node is required as the runtime for Lambda@Edge.JS 6.10.
We can use the following code to retrieve the content of the response, set new headers, and return the updated response with the additional security headers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
'use strict'; exports.handler = (event, context, callback) => { //Get contents of response const response = event.Records[0].cf.response; const headers = response.headers; //Set new headers headers['strict-transport-security'] = [{key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubdomains; preload'}]; headers['content-security-policy'] = [{key: 'Content-Security-Policy', value: "default-src 'none'; img-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'"}]; headers['x-content-type-options'] = [{key: 'X-Content-Type-Options', value: 'nosniff'}]; headers['x-frame-options'] = [{key: 'X-Frame-Options', value: 'DENY'}]; headers['x-xss-protection'] = [{key: 'X-XSS-Protection', value: '1; mode=block'}]; headers['referrer-policy'] = [{key: 'Referrer-Policy', value: 'same-origin'}]; //Return modified response callback(null, response); }; |
We can copy the code into my function, leave the handler set to index.handler by default, and choose “Create a new role from template(s).” To enable function execution, we can choose “Basic Edge Lambda permissions” from the Policy Templates drop-down menu. This establishes a role for me when creating the AWS Lambda function.
In the Advanced Settings tab, allocate 128 MB of RAM and set the timeout to 3 seconds (the maximum for Lambda@Edge). Click “Next,” review the details, and choose “Create Function.”
Note: The maximum timeout would be one second for Viewer Request or Viewer Response triggers.
This process constructs the function, links the trigger with the distribution, and initiates global replicating of the function. During replication (typically 5 to 8 minutes), the distribution status changes to “In Progress.”
Once the status reverts to “Deployed,” I access the root of my distribution and observe the index.html file.
To confirm header insertion, open a browser’s Web Developer toolbar, select the Network tab, and reload the page. In the GET request for index.html, Amazon CloudFront’s response contains the additional security headers. Highlight the ones added by my function.
Conclusion
In this blog, we have learned how to use Lambda@Edge to bolster website security by adding security headers via the origin response trigger in Amazon CloudFront distribution behavior. Also, a detailed creation of a Lambda@Edge function, linking it to Amazon CloudFront trigger, and verifying and monitoring the outcomes.
Drop a query if you have any questions regarding Lambda@Edge and we will get back to you quickly.
Empowering organizations to become ‘data driven’ enterprises with our Cloud experts.
- Reduced infrastructure costs
- Timely data-driven decisions
About CloudThat
CloudThat is a leading provider of Cloud Training and Consulting services with a global presence in India, the USA, Asia, Europe, and Africa. Specializing in AWS, Microsoft Azure, GCP, VMware, Databricks, and more, the company serves mid-market and enterprise clients, offering comprehensive expertise in Cloud Migration, Data Platforms, DevOps, IoT, AI/ML, and more.
CloudThat is recognized as a top-tier partner with AWS and Microsoft, including the prestigious ‘Think Big’ partner award from AWS and the Microsoft Superstars FY 2023 award in Asia & India. Having trained 650k+ professionals in 500+ cloud certifications and completed 300+ consulting projects globally, CloudThat is an official AWS Advanced Consulting Partner, Microsoft Gold Partner, AWS Training Partner, AWS Migration Partner, AWS Data and Analytics Partner, AWS DevOps Competency Partner, Amazon QuickSight Service Delivery Partner, Amazon EKS Service Delivery Partner, AWS Microsoft Workload Partners, Amazon EC2 Service Delivery Partner, and many more.
To get started, go through our Consultancy page and Managed Services Package, CloudThat’s offerings.
FAQs
1. How does Lambda@Edge enhance website security by adding HTTP security headers?
ANS: – Lambda@Edge allows for the dynamic insertion of HTTP security headers in CloudFront distributions, bolstering website security by mitigating various attacks such as XSS, clickjacking, and content sniffing.
2. What are the main procedures for configuring Lambda@Edge to use Amazon CloudFront to add security headers?
ANS: – Key steps include creating a Lambda@Edge function, associating it with Amazon CloudFront distribution trigger (such as Origin Response), and deploying the function globally through Amazon CloudFront’s replication.
![](https://content.cloudthat.com/resources/wp-content/uploads/2022/12/Ayush_Agarwal-150x150.jpg)
WRITTEN BY Ayush Agarwal
Ayush Agarwal works as a Research Associate at CloudThat. He has excellent analytical thinking and carries an optimistic approach toward his life. He is having sound Knowledge of AWS Cloud Services, Infra setup, Security, WAR, and Migration. He is always keen to learn and adopt new technologies.
Comments