Last active
June 1, 2017 14:58
-
-
Save codeofnode/b301a7d38b149f1b492c44b275110898 to your computer and use it in GitHub Desktop.
A basic AWS lamda function in nodejs to block ip address is hitting more than a limit
This file contains hidden or 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'; | |
console.log('--> Loading function'); | |
const aws = require('aws-sdk'); | |
const s3 = new aws.S3({ apiVersion: '2006-03-01' }); | |
const waf = new aws.WAF({ apiVersion: '2015-08-24' }); | |
class Police { | |
constructor(maxHit=100, timeGap=(6*60*60*1000)) { | |
this.maxHit = maxHit; | |
this.timeGap = timeGap; | |
this.lastBailCheck = Date.now(); | |
this.hitMap = {}; | |
} | |
static bail(ip){ | |
// TODO bail this ip by removing entry into waf | |
} | |
static jail(ip){ | |
// TODO jail this ip by adding entry from waf | |
} | |
checkBail(){ | |
var nowDate = Date.now(); | |
if((nowDate - this.lastBailCheck) > this.timeGap){ | |
this.lastBailCheck = nowDate; | |
this.prevMap = this.hitMap; | |
this.hitMap = {}; | |
this.scanAndBail(); | |
} | |
} | |
scanAndBail(){ | |
Object.keys(this.prevMap).forEach(Police.bail); | |
delete this.prevMap; | |
} | |
watch(ip){ | |
this.hitMap[ip] = (this.hitMap[ip] || 0) + 1; | |
if(this.maxHit < this.hitMap[ip]){ | |
Police.jail(ip); | |
} | |
this.checkBail(); | |
} | |
} | |
const police = new Police(); | |
function forOneLine(line){ | |
if(typeof line === 'string') { | |
police.watch(line.split(' ')[3]); | |
} | |
} | |
function handleResponse(data){ | |
data.Body.toString().split('\n').forEach(forOneLine); | |
} | |
exports.handler = (event, context, callback) => { | |
//console.log('Received event:', JSON.stringify(event, null, 2)); | |
// Get the object from the event and show its content type | |
const bucket = event.Records[0].s3.bucket.name; | |
const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); | |
const params = { | |
Bucket: bucket, | |
Key: key, | |
}; | |
s3.getObject(params, (err, data) => { | |
if (err) { | |
console.log(err); | |
const message = `Error getting object ${key} from bucket ${bucket}.`; | |
console.log(message); | |
callback(message); | |
} else { | |
handleResponse(data); | |
callback(null, data.ContentType); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment