使用node.js,这是用于构建可以处理http请求的tcp服务器的网络模块。
我想防止dos攻击,所以我所做的就像这样:
if (status.numOfCurrentRequests + 1 >= MAX_NUM_OF_CONNECTIONS) {
socket.end();
return;
}
我想知道使用它是否更好:
socket.destroy();
来自API的:
socket.destroy()#确保不再发生I / O活动 插座。仅在出现错误时才需要(解析错误等)。
有什么区别和好处?
答案 0 :(得分:27)
您的HTTP服务器实际上不应该处理DOS攻击。一旦请求到达它,攻击者通过建立连接(无论多短)就“赢了”。即使它们很短,也可以用数千/秒的时间猛击它并防止其他人连接。此外,他们可能不会尝试通过TCP“连接”,只是向服务器充斥各种请求。
在较低级别或通过防火墙阻止/检测DOS攻击,我相信很多软件和硬件版本都支持一些基本类型的DOS检测和预防。
答案 1 :(得分:3)
应该巧妙地使用:
server.pause(msecs)
停止接受给定号码的连接 毫秒(默认为一秒)。这可能是有用的 限制针对DoS攻击或其他攻击的新连接 超额预订。
答案 2 :(得分:2)
Total.js框架: https://github.com/totaljs/modules/blob/master/ddos/ddos.js
var counter = 0;
var ip = {};
var ban = {};
var ban_length = 0;
var interval = 0;
exports.install = function () {
framework.onRequest = function (req, res) {
if (ban_length > 0 && ban[req.ip]) {
req.connection.destroy();
return true
}
var count = (ip[req.ip] || 0) + 1;
ip[req.ip] = count;
if (count === 1) counter++;
if (count < exports.options.maximum) return false;
ban[req.ip] = exports.options.minutes + 1;
ban_length++;
return true
};
setInterval(function () {
interval++;
var keys;
var length;
var count;
if (ban_length > 0 && interval % 60 === 0) {
keys = Object.keys(ban);
length = keys.length;
count = 0;
for (var i = 0; i < length; i++) {
var key = keys[i];
if (ban[key]-- > 0) continue;
ban_length--;
delete ban[key]
}
if (ban_length < 0) ban_length = 0
}
if (counter <= 0) return;
keys = Object.keys(ip);
length = keys.length;
counter = length;
for (var i = 0; i < length; i++) {
var key = keys[i];
var count = ip[key]--;
if (count > 0) continue;
counter--;
delete ip[key]
}
if (counter < 0) counter = 0
}, 1e3)
};
exports.usage = function () {
return {
bans: ban_length
}
};
exports.options = {
maximum: 1e3,
minutes: 5
};
答案 3 :(得分:0)
使用Express Rate Limiter避免DOS攻击
安装npm install --save express-rate-limit
var RateLimit = require('express-rate-limit');
app.enable('trust proxy'); // only if you're behind a reverse proxy (Heroku, Bluemix, AWS if you use an ELB, custom Nginx setup, etc)
var limiter = new RateLimit({
windowMs: 15*60*1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
delayMs: 0 // disable delaying - full speed until the max limit is reached
});
// apply to all requests
app.use(limiter);