EDIT: This has a similar answer here:
For those that come along now, you can use Lambda@Edge to add HSTS headers as well as other "frame-buster" headers like x-frame-options
and referrer-policy
.
This is quite cheap, working out to about 30 cents per million requests.
This link from the AWS networking and content delivery blog describes how to do this in detail.
It is too long to repeat the entire contents here but essentially it describes the following process flow:
Here is how the process works:
- Viewer navigates to website.
- Before CloudFront serves content from the cache it will trigger any Lambda function associated with the Viewer Request trigger for that behavior.
- CloudFront serves content from the cache if available, otherwise it goes to step 4.
- Only after CloudFront cache ‘Miss’, Origin Request trigger is fired for that behavior.
- S3 Origin returns content.
- After content is returned from S3 but before being cached in CloudFront, Origin Response trigger is fired.
- After content is cached in CloudFront, Viewer Response trigger is fired and is the final step before viewer receives content.
- Viewer receives content.
Once again, in case the blog linked to disappears, the below code is a sample to add security headers via Lambda (remembering this is to be run by CloudFront using Lambda@Edge integration):
'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);
};