从Express减轻http攻击


0

我正在使用Express和Node.JS提供一些静态文件,我该怎么做才能防止诸如POST攻击和GET攻击等http泛滥?

Answers:


2

所有请求都预先使用app.use并注入中间件函数。这是在请求生成之前使用的,然后是express.static或app.rest(req对象),还有一次在beeing响应客户端(res对象)之前。您可以更改req,res和optionnally使用回调函数(此处命名为next)。这是诀窍。如果您的中间件函数从不调用next()回调,则不会提供请求。您可以使用中间件,每次计算每个ip的请求数,并为页面提供服务。想想被阻止的IP列表将会增长,并会降低你的应用程序速度。中间件需要同步到拦截。这里是您所需代码的示例,基于快速API文档示例:

var express = require('express'),
app = express(),
util= require(util);
app.use(express.static(__dirname + '/public'));

// a first middleware, a logger in console, just to show ip
// usefull to debug
app.use(function(req, res, next){
  console.log('%s %s from %s , proxy: %s', req.method, req.url, req.ip, util.inspect(req.ips));
  next();
});

// a second middleware, what u need
app.use(filterUrReq);

app.get("blah", function(req, res) {
    res.send(req.url + " well served to " + req.ip)
});

app.listen(8080);

// here the middleware function, it filters by ip, if ip is clean, call next callback.
function filterUrReq (req, res, next) {

    if (req.ip == "15.89.111.111") {
        console.log('i dont want to serve this IP, dont call next');
    } else {
        console.log('ok clean ip, go to next app.use');
        next();
    }

}

这里是expressJS的良好实践。http://expressjs.com/4x/api.html#app.use。也许你的问题应该在stackoverflow中,或者你可能需要像fail2ban这样更全局的东西,看看jails的问题。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.