firewall: implement blocklist

This commit is contained in:
Girish Ramakrishnan
2020-08-31 18:22:33 -07:00
parent 491af5bd9a
commit e4b06b16a9
12 changed files with 135 additions and 0 deletions
+46
View File
@@ -0,0 +1,46 @@
'use strict';
exports = module.exports = {
getBlocklist,
setBlocklist
};
const assert = require('assert'),
BoxError = require('./boxerror.js'),
path = require('path'),
paths = require('./paths.js'),
safe = require('safetydance'),
shell = require('./shell.js'),
validator = require('validator');
const SET_BLOCKLIST_CMD = path.join(__dirname, 'scripts/setblocklist.sh');
function getBlocklist(callback) {
assert.strictEqual(typeof callback, 'function');
const data = safe.fs.readFileSync(paths.FIREWALL_CONFIG_FILE, 'utf8');
const config = safe.JSON.parse(data);
const blocklist = config && config.blocklist ? config.blocklist : [];
callback(null, blocklist);
}
function setBlocklist(blocklist, callback) {
assert(Array.isArray(blocklist));
assert.strictEqual(typeof callback, 'function');
if (!blocklist.every(x => validator.isIP(x) || validator.isIPRange(x))) return callback(new BoxError(BoxError.BAD_FIELD, 'blocklist must contain IP or IP range'));
const data = safe.fs.readFileSync(paths.FIREWALL_CONFIG_FILE, 'utf8');
const config = safe.JSON.parse(data) || {};
config.blocklist = blocklist;
if (!safe.fs.writeFileSync(paths.FIREWALL_CONFIG_FILE, JSON.stringify(config, null, 4), 'utf8')) return callback(new BoxError(BoxError.FS_ERROR, safe.error.message));
shell.sudo('setBlocklist', [ SET_BLOCKLIST_CMD ], {}, function (error) {
if (error) return callback(new BoxError(BoxError.IPTABLES_ERROR, `Error setting blocklist: ${error.message}`));
callback();
});
}