Last active
March 13, 2019 06:59
-
-
Save hugobcar/8be59aaf801a652c67840cd7aeb6d520 to your computer and use it in GitHub Desktop.
Instant block of attacks to AWS Websites using CloudFront + Lambda@Edge + DynamoDB + WAF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var http = require('http'); | |
// Load the SDK for JavaScript | |
const https = require('https'); | |
var AWS = require('aws-sdk'); | |
// Set the region | |
AWS.config.update({region: 'sa-east-1'}); | |
// Create the DynamoDB service object | |
var ddb = new AWS.DynamoDB({ | |
region: "sa-east-1", | |
httpOptions: { | |
agent: new https.Agent({ | |
rejectUnauthorized: true, | |
keepAlive: true | |
}) | |
} | |
}); | |
// Search in array | |
function isInArray(array, search) | |
{ | |
return array.indexOf(search) >= 0; | |
} | |
exports.handler = (event, context, callback) => { | |
const response = event.Records[0].cf.response; | |
const request = event.Records[0].cf.request; | |
// EndPoints (request.uri) analysis and insert in DynamoDB | |
var endPointsAnalyse = ['/login','/test','/healthcheck']; | |
var blockErrorCodes = ['400','401']; | |
if (isInArray(blockErrorCodes, response.status)) { | |
if(isInArray(endPointsAnalyse, request.uri.replace(/\/$/, ""))){ | |
// Date and Time | |
var d = new Date() | |
var timestamp_seconds = Math.floor(d.getTime() / 1000) | |
// Prepare datas to be sent to DDB | |
var params = { | |
TableName: 'Cf_analyserequests_Waf_PROD', | |
Item: { | |
'ID': {S: d.getTime().toString()+request.clientIp}, | |
'CLIENTIP' : {S: request.clientIp}, | |
'HTTPCODE' : {N: response.status}, | |
'ENDPOINT' : {S: request.uri}, | |
'DATETIME' : {S: d.toString()}, | |
'TIMESTAMP' : {N: timestamp_seconds.toString()}, | |
} | |
}; | |
// Call DynamoDB to add the item to the table | |
ddb.putItem(params, function(err, data) { | |
if (err) { | |
console.log("Error", err); | |
} else { | |
console.log("Success", data); | |
} | |
}); | |
} | |
} | |
callback(null, response); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment