AWS, Cloud Computing

5 Mins Read

Adding HTTP Security Headers Using AWS Lambda@Edge and Amazon CloudFront

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?

Security headers are a set of headers in a server’s HTTP response that instruct your browser on how to handle the content of your website. For instance, when it detects cross-site scripting (XSS) attacks, Internet Explorer and Chrome employ the header X-XSS-Protection to stop pages from loading.

Pioneers in Cloud Consulting & Migration Services

  • Reduced infrastructural costs
  • Accelerated application deployment
Get Started

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:

lambda1

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:

lambda2

This is how the procedure operates:

  1. The viewer requests the “www.example.com” webpage.
  2. Should the object already be cached, Amazon CloudFront proceeds to step 3; if not, it returns the object to the viewer from the cache.
  3. An Amazon S3 bucket originates from which Amazon CloudFront requests the object.
  4. When Amazon S3 returns the object, Amazon CloudFront initiates the origin response event.
  5. 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.

lambda3

We select the Author from scratch for this solution because we will be utilizing the code supplied here.

lambda4

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.

lambda5

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.

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.

lambda6

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.

lambda7

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.

lambda8

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.

lambda9

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
Get Started

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 PartnerAWS Migration PartnerAWS Data and Analytics PartnerAWS DevOps Competency PartnerAmazon QuickSight Service Delivery PartnerAmazon EKS Service Delivery PartnerAWS Microsoft Workload PartnersAmazon EC2 Service Delivery Partner, and many more.

To get started, go through our Consultancy page and Managed Services PackageCloudThat’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.

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.

Share

Comments

    Click to Comment

Get The Most Out Of Us

Our support doesn't end here. We have monthly newsletters, study guides, practice questions, and more to assist you in upgrading your cloud career. Subscribe to get them all!