-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler.js
82 lines (71 loc) · 2.28 KB
/
handler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/* fail2ban REST API server
* written for simply add/remove IPs from ban list from any application indipendent from the technogy used.
*
* (c)2018 hoverflow
*/
var express = require('express');
var app = express();
var config = require('./config.json');
const {
exec
} = require('child_process');
var banstring = ' set fail2ban-rest banip ';
var unbanstring = ' set fail2ban-rest unbanip ';
function sendBadRequest(res) {
res.status(400).end('Bad request');
}
function banUnbanIP(ban, ip, res) {
if (ban) {
exec(config.fail2ban_cli + banstring + ip, function (err, stdout, stderr) {
if (err) {
console.error(err);
res.status(500).end('Internal server error.');
} else {
console.log('ban ip response', stdout);
res.status(200).end('Ok');
}
});
} else {
exec(config.fail2ban_cli + unbanstring + ip, function (err, stdout, stderr) {
if (err) {
console.error(err);
res.status(500).end('Internal server error.');
} else {
console.log('unban ip response', stdout);
res.status(200).end('Ok');
}
});
}
}
app.get('/ban/:ip', function (req, res) {
if (req.params.ip) {
console.log('ban request for ', req.params.ip);
if (/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(req.params.ip)) {
console.log('valid IP');
banUnbanIP(true, req.params.ip, res);
} else {
console.log('invalid IP');
sendBadRequest(res);
}
} else {
sendBadRequest(res);
}
});
app.get('/unban/:ip', function (req, res) {
if (req.params.ip) {
console.log('unban request for ', req.params.ip);
if (/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(req.params.ip)) {
console.log('valid IP');
banUnbanIP(false, req.params.ip, res);
} else {
console.log('invalid IP');
sendBadRequest(res);
}
} else {
sendBadRequest(res);
}
});
app.all('*', function (req, res) {
sendBadRequest(res);
});
app.listen(config.listenport);