47 lines
1.5 KiB
JavaScript
47 lines
1.5 KiB
JavaScript
|
|
'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();
|
||
|
|
});
|
||
|
|
}
|