fix(subnets): enforce per-agent allowed_subnets isolation in Backend and Proxy with automatic DB pruning
This commit is contained in:
1 parent
2fc7e983cc
commit
4421b15393
8 files changed
+200
-28
No files matched your search
@@ -26,6 +26,9 @@ async function connectDB() {
|
||||
console.log('[MongoDB] ✓ Connected successfully to', MONGODB_URI);
|
||||
const { logCapacityStats } = require('./capacityTracker');
|
||||
logCapacityStats('[MongoDB]').catch(err => console.warn('[MongoDB] Capacity log failed:', err.message));
|
||||
const { pruneOutOfSubnetData } = require('../utils/subnetFilter');
|
||||
pruneOutOfSubnetData().catch(() => {});
|
||||
setInterval(() => pruneOutOfSubnetData().catch(() => {}), 2 * 60 * 1000).unref?.();
|
||||
return;
|
||||
} catch (error) {
|
||||
console.error(`[MongoDB] ✗ Attempt ${attempt} failed: ${error.message}`);
|
||||
|
||||
@@ -298,19 +298,9 @@ router.put('/agents/:uuid/subnets', async (req, res) => {
|
||||
{ $set: { allowed_subnets: subnets, subnets_updated_at: new Date() } }
|
||||
);
|
||||
|
||||
// Auto-cleanup background task
|
||||
if (subnets.length > 0) {
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
const ips = await db.collection('devicestats').distinct('ip_address', { agent_uuid: req.params.uuid });
|
||||
const invalidIps = ips.filter(ip => !ipMatchesSubnets(ip, subnets));
|
||||
if (invalidIps.length > 0) {
|
||||
await db.collection('devicestats').deleteMany({ agent_uuid: req.params.uuid, ip_address: { $in: invalidIps } });
|
||||
await db.collection('flows').deleteMany({ agent_uuid: req.params.uuid, src_ip: { $in: invalidIps } });
|
||||
}
|
||||
} catch (e) { console.error('Auto-cleanup error:', e); }
|
||||
}, 100);
|
||||
}
|
||||
const { invalidateSubnetCache, pruneOutOfSubnetData } = require('../../utils/subnetFilter');
|
||||
invalidateSubnetCache();
|
||||
pruneOutOfSubnetData().catch(e => console.error('Auto-cleanup error:', e));
|
||||
|
||||
res.json({ ok: true, data: { allowed_subnets: subnets } });
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const { DeviceStat, Flow } = require('../../../models/Schemas');
|
||||
const { getTimeFilter, getBaseFilter, getCustomLabelsMap } = require('../helpers');
|
||||
const { resolveDeviceTypeFromIp, resolveOSFromIp, resolveVendorFromIp, generateAutoLabel } = require('../../../deviceResolver');
|
||||
const { getAgentSubnetsMap, filterRowsByAgentSubnets } = require('../../../utils/subnetFilter');
|
||||
const User = require('../../../models/User');
|
||||
|
||||
async function getLabelingHandler(req, res) {
|
||||
@@ -100,7 +101,8 @@ async function getLabelingHandler(req, res) {
|
||||
mergedMap.set(mac, d);
|
||||
});
|
||||
|
||||
const data = Array.from(mergedMap.values());
|
||||
const subnetsMap = await getAgentSubnetsMap();
|
||||
const data = filterRowsByAgentSubnets(Array.from(mergedMap.values()), subnetsMap, 'ip_address', 'agent_uuid');
|
||||
|
||||
// Fetch agent user accounts to resolve human-readable labels
|
||||
const agentUsers = await User.find({ role: 'AGENT_VIEWER' }).lean();
|
||||
|
||||
@@ -4,6 +4,7 @@ const mongoose = require('mongoose');
|
||||
const { DeviceStat, CustomDeviceLabel, Flow } = require('../../models/Schemas');
|
||||
const { getTimeFilter, getBaseFilter, getCustomLabelsMap } = require('./helpers');
|
||||
const { generateMacFromIp, resolveDeviceTypeFromIp, resolveOSFromIp, resolveVendorFromIp, generateAutoLabel } = require('../../deviceResolver');
|
||||
const { applySubnetFilterToQuery, filterRowsByAgentSubnets } = require('../../utils/subnetFilter');
|
||||
|
||||
// GET /api/dashboard/devices
|
||||
router.get('/devices', async (req, res) => {
|
||||
@@ -12,6 +13,7 @@ router.get('/devices', async (req, res) => {
|
||||
const skip = parseInt(req.query.skip ?? 0);
|
||||
const timeFilter = getTimeFilter(req);
|
||||
const query = getBaseFilter(req, timeFilter);
|
||||
const subnetsMap = await applySubnetFilterToQuery(query, query.agent_uuid ? 'src_ip' : 'ip_address');
|
||||
|
||||
let data;
|
||||
let customLabelsMap;
|
||||
@@ -66,6 +68,7 @@ router.get('/devices', async (req, res) => {
|
||||
DeviceStat.aggregate(pipeline),
|
||||
getCustomLabelsMap()
|
||||
]);
|
||||
data = filterRowsByAgentSubnets(data, subnetsMap, 'ip_address', 'agent_uuid');
|
||||
}
|
||||
|
||||
const mapped = data.map(obj => {
|
||||
@@ -105,6 +108,7 @@ router.get('/mac-bandwidth', async (req, res) => {
|
||||
const limit = parseInt(req.query.limit ?? 50);
|
||||
const timeFilter = getTimeFilter(req);
|
||||
const matchBase = getBaseFilter(req, timeFilter);
|
||||
await applySubnetFilterToQuery(matchBase, 'ip_address');
|
||||
|
||||
const raw = await DeviceStat.aggregate([
|
||||
{ $match: { ...matchBase } },
|
||||
@@ -190,8 +194,9 @@ router.get('/security-devices', async (req, res) => {
|
||||
try {
|
||||
const timeFilter = getTimeFilter(req);
|
||||
const baseFilter = getBaseFilter(req, timeFilter);
|
||||
const subnetsMap = await applySubnetFilterToQuery(baseFilter, 'ip_address');
|
||||
|
||||
const uniqueDevices = await DeviceStat.aggregate([
|
||||
const rawUniqueDevices = await DeviceStat.aggregate([
|
||||
{ $match: baseFilter },
|
||||
{ $sort: { timestamp: -1 } },
|
||||
{ $group: {
|
||||
@@ -199,6 +204,7 @@ router.get('/security-devices', async (req, res) => {
|
||||
latestDoc: { $first: '$$ROOT' }
|
||||
}}
|
||||
]);
|
||||
const uniqueDevices = rawUniqueDevices.filter(d => filterRowsByAgentSubnets([d.latestDoc], subnetsMap, 'ip_address', 'agent_uuid').length > 0);
|
||||
|
||||
const flowStats = await Flow.aggregate([
|
||||
{ $match: baseFilter },
|
||||
|
||||
@@ -2,12 +2,14 @@ const express = require('express');
|
||||
const router = express.Router();
|
||||
const { Flow, DeviceStat } = require('../../models/Schemas');
|
||||
const { getTimeFilter, getBaseFilter, topFlowField, getCustomLabelsMap } = require('./helpers');
|
||||
const { applySubnetFilterToQuery } = require('../../utils/subnetFilter');
|
||||
|
||||
// GET /api/dashboard/flows-options
|
||||
router.get('/flows-options', async (req, res) => {
|
||||
try {
|
||||
const timeFilter = getTimeFilter(req);
|
||||
const query = getBaseFilter(req, timeFilter);
|
||||
await applySubnetFilterToQuery(query, 'src_ip');
|
||||
|
||||
// Parallel distinct queries on indexed keys
|
||||
const [protocols, srcIps, dstIps, dstPorts, apps, domains] = await Promise.all([
|
||||
@@ -43,6 +45,7 @@ router.get('/flows', async (req, res) => {
|
||||
const limit = rawLimit <= 0 ? 0 : Math.min(rawLimit, 1000000);
|
||||
const timeFilter = getTimeFilter(req);
|
||||
const query = getBaseFilter(req, timeFilter);
|
||||
await applySubnetFilterToQuery(query, 'src_ip');
|
||||
|
||||
// Apply query filters on MongoDB
|
||||
if (req.query.protocol && req.query.protocol !== 'All') {
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
// backend/utils/subnetFilter.js
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Per-Agent Subnet Isolation & Auto-Pruning Helper
|
||||
// Enforces allowed_subnets configured in agent_registry at both DB and API level.
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const mongoose = require('mongoose');
|
||||
const { DeviceStat, Flow, DeviceAppStat } = require('../models/Schemas');
|
||||
|
||||
let _subnetsCache = null;
|
||||
let _cacheTs = 0;
|
||||
const CACHE_TTL_MS = 30 * 1000;
|
||||
|
||||
function invalidateSubnetCache() {
|
||||
_subnetsCache = null;
|
||||
_cacheTs = 0;
|
||||
}
|
||||
|
||||
function ipToLong(ip) {
|
||||
if (!ip || typeof ip !== 'string') return 0;
|
||||
const parts = ip.trim().split('.');
|
||||
if (parts.length !== 4) return 0;
|
||||
return parts.reduce((acc, oct) => (acc << 8) + (parseInt(oct, 10) || 0), 0) >>> 0;
|
||||
}
|
||||
|
||||
function ipMatchesSubnets(ip, subnets) {
|
||||
if (!subnets || subnets.length === 0) return true;
|
||||
if (!ip || typeof ip !== 'string') return false;
|
||||
const cleanIp = ip.trim();
|
||||
return subnets.some(raw => {
|
||||
const subnet = String(raw || '').trim();
|
||||
if (!subnet) return false;
|
||||
if (subnet.includes('/')) {
|
||||
const [range, bitsStr] = subnet.split('/');
|
||||
const bits = parseInt(bitsStr, 10);
|
||||
if (isNaN(bits) || bits < 0 || bits > 32) return false;
|
||||
const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0;
|
||||
return (ipToLong(cleanIp) & mask) === (ipToLong(range) & mask);
|
||||
}
|
||||
return cleanIp.startsWith(subnet.endsWith('.') ? subnet : subnet + '.') || cleanIp === subnet;
|
||||
});
|
||||
}
|
||||
|
||||
function subnetToRegexStr(rawSubnet) {
|
||||
const subnet = String(rawSubnet || '').trim();
|
||||
if (!subnet) return null;
|
||||
if (!subnet.includes('/')) {
|
||||
const clean = subnet.replace(/\.$/, '').replace(/\./g, '\\.');
|
||||
return `^${clean}(\\.|$)`;
|
||||
}
|
||||
const [range, bitsStr] = subnet.split('/');
|
||||
const bits = parseInt(bitsStr, 10);
|
||||
const octets = range.split('.').map(n => parseInt(n, 10) || 0);
|
||||
if (octets.length !== 4 || isNaN(bits) || bits < 8 || bits > 32) return null;
|
||||
|
||||
if (bits === 8) return `^${octets[0]}\\.`;
|
||||
if (bits === 16) return `^${octets[0]}\\.${octets[1]}\\.`;
|
||||
if (bits === 24) return `^${octets[0]}\\.${octets[1]}\\.${octets[2]}\\.`;
|
||||
if (bits === 32) return `^${octets[0]}\\.${octets[1]}\\.${octets[2]}\\.${octets[3]}$`;
|
||||
|
||||
if (bits > 8 && bits < 16) {
|
||||
const step = 1 << (16 - bits);
|
||||
const start = octets[1] & ~(step - 1);
|
||||
const vals = Array.from({ length: step }, (_, i) => start + i).join('|');
|
||||
return `^${octets[0]}\\.(${vals})\\.`;
|
||||
}
|
||||
if (bits > 16 && bits < 24) {
|
||||
const step = 1 << (24 - bits);
|
||||
const start = octets[2] & ~(step - 1);
|
||||
const vals = Array.from({ length: step }, (_, i) => start + i).join('|');
|
||||
return `^${octets[0]}\\.${octets[1]}\\.(${vals})\\.`;
|
||||
}
|
||||
if (bits > 24 && bits < 32) {
|
||||
const step = 1 << (32 - bits);
|
||||
const start = octets[3] & ~(step - 1);
|
||||
const vals = Array.from({ length: step }, (_, i) => start + i).join('|');
|
||||
return `^${octets[0]}\\.${octets[1]}\\.${octets[2]}\\.(${vals})$`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildSubnetsRegex(subnets) {
|
||||
if (!subnets || subnets.length === 0) return null;
|
||||
const parts = subnets.map(subnetToRegexStr).filter(Boolean);
|
||||
if (parts.length === 0) return null;
|
||||
return new RegExp(parts.join('|'));
|
||||
}
|
||||
|
||||
async function getAgentSubnetsMap() {
|
||||
const now = Date.now();
|
||||
if (_subnetsCache && (now - _cacheTs) < CACHE_TTL_MS) return _subnetsCache;
|
||||
try {
|
||||
if (!mongoose.connection?.db) return {};
|
||||
const docs = await mongoose.connection.db
|
||||
.collection('agent_registry')
|
||||
.find({}, { projection: { uuid: 1, allowed_subnets: 1 } })
|
||||
.toArray();
|
||||
const map = {};
|
||||
for (const d of docs) {
|
||||
if (d.uuid && Array.isArray(d.allowed_subnets)) {
|
||||
const clean = d.allowed_subnets.map(s => String(s).trim()).filter(Boolean);
|
||||
if (clean.length > 0) map[d.uuid] = clean;
|
||||
}
|
||||
}
|
||||
_subnetsCache = map;
|
||||
_cacheTs = now;
|
||||
return map;
|
||||
} catch (e) {
|
||||
return _subnetsCache || {};
|
||||
}
|
||||
}
|
||||
|
||||
async function applySubnetFilterToQuery(query, ipField = 'ip_address') {
|
||||
const map = await getAgentSubnetsMap();
|
||||
if (typeof query.agent_uuid === 'string' && map[query.agent_uuid]) {
|
||||
const rx = buildSubnetsRegex(map[query.agent_uuid]);
|
||||
if (rx && !query[ipField]) {
|
||||
query[ipField] = { $regex: rx };
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function filterRowsByAgentSubnets(rows, subnetsMap, ipField = 'ip_address', agentField = 'agent_uuid') {
|
||||
if (!subnetsMap || Object.keys(subnetsMap).length === 0) return rows;
|
||||
return rows.filter(r => {
|
||||
const agent = r[agentField];
|
||||
const subnets = agent ? subnetsMap[agent] : null;
|
||||
if (!subnets || subnets.length === 0) return true;
|
||||
return ipMatchesSubnets(r[ipField], subnets);
|
||||
});
|
||||
}
|
||||
|
||||
async function pruneOutOfSubnetData() {
|
||||
try {
|
||||
invalidateSubnetCache();
|
||||
const map = await getAgentSubnetsMap();
|
||||
let totalDeletedDevs = 0, totalDeletedFlows = 0, totalDeletedApps = 0;
|
||||
for (const [agentUuid, subnets] of Object.entries(map)) {
|
||||
const rx = buildSubnetsRegex(subnets);
|
||||
if (!rx) continue;
|
||||
const [devRes, flowRes, appRes] = await Promise.all([
|
||||
DeviceStat.deleteMany({ agent_uuid: agentUuid, ip_address: { $not: rx } }),
|
||||
Flow.deleteMany({ agent_uuid: agentUuid, src_ip: { $not: rx } }),
|
||||
DeviceAppStat.deleteMany({ agent_uuid: agentUuid, ip_address: { $not: rx } }),
|
||||
]);
|
||||
totalDeletedDevs += devRes.deletedCount || 0;
|
||||
totalDeletedFlows += flowRes.deletedCount || 0;
|
||||
totalDeletedApps += appRes.deletedCount || 0;
|
||||
}
|
||||
if (totalDeletedDevs + totalDeletedFlows + totalDeletedApps > 0) {
|
||||
console.log(`[SubnetPruner] Cleaned out-of-subnet records: DeviceStat=${totalDeletedDevs}, Flow=${totalDeletedFlows}, DeviceAppStat=${totalDeletedApps}`);
|
||||
}
|
||||
return { totalDeletedDevs, totalDeletedFlows, totalDeletedApps };
|
||||
} catch (err) {
|
||||
console.error('[SubnetPruner] Error:', err.message);
|
||||
return { totalDeletedDevs: 0, totalDeletedFlows: 0, totalDeletedApps: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
invalidateSubnetCache,
|
||||
ipMatchesSubnets,
|
||||
buildSubnetsRegex,
|
||||
getAgentSubnetsMap,
|
||||
applySubnetFilterToQuery,
|
||||
filterRowsByAgentSubnets,
|
||||
pruneOutOfSubnetData,
|
||||
};
|
||||
@@ -4,8 +4,7 @@
|
||||
// Split from collector.js to satisfy the 256-line file size limit.
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const { DeviceStat, DeviceAppStat, Flow, Threat, Event, BlacklistRule, LookupApp } = require('./models/Schemas');
|
||||
const mongoose = require('mongoose');
|
||||
const { DeviceStat, DeviceAppStat, Flow, Threat, Event, BlacklistRule, LookupApp, AgentRegistry } = require('./models/Schemas');
|
||||
const {
|
||||
generateMacFromIp,
|
||||
resolveVendorFromIp,
|
||||
@@ -24,10 +23,8 @@ async function getAllowedSubnets(agentUuid) {
|
||||
return _subnetCache[agentUuid].subnets;
|
||||
}
|
||||
try {
|
||||
const doc = await mongoose.connection.db
|
||||
.collection('agent_registry')
|
||||
.findOne({ uuid: agentUuid }, { projection: { allowed_subnets: 1 } });
|
||||
const subnets = (doc?.allowed_subnets || []).map(s => s.trim()).filter(Boolean);
|
||||
const doc = await AgentRegistry.findOne({ uuid: agentUuid }, { allowed_subnets: 1 }).lean();
|
||||
const subnets = (doc?.allowed_subnets || []).map(s => String(s).trim()).filter(Boolean);
|
||||
_subnetCache[agentUuid] = { subnets, ts: now };
|
||||
return subnets;
|
||||
} catch (e) {
|
||||
|
||||
@@ -171,13 +171,15 @@ const auxSchemas = require('./SchemasAux');
|
||||
// ─── Agent Registry (all agents registered in BackOne, regardless of activity) ──
|
||||
// Upserted every collector cycle. Source of truth for the agents list page.
|
||||
const AgentRegistrySchema = new mongoose.Schema({
|
||||
uuid: { type: String, required: true, unique: true, index: true },
|
||||
serial: { type: String },
|
||||
label: { type: String },
|
||||
site_uuid: { type: String, index: true },
|
||||
provisioned: { type: Boolean, default: false },
|
||||
activated: { type: Boolean, default: false },
|
||||
last_seen_at: { type: mongoose.Schema.Types.Mixed },
|
||||
uuid: { type: String, required: true, unique: true, index: true },
|
||||
serial: { type: String },
|
||||
label: { type: String },
|
||||
protected_label: { type: String },
|
||||
site_uuid: { type: String, index: true },
|
||||
provisioned: { type: Boolean, default: false },
|
||||
activated: { type: Boolean, default: false },
|
||||
last_seen_at: { type: mongoose.Schema.Types.Mixed },
|
||||
allowed_subnets: { type: [String], default: [] },
|
||||
}, { ...baseOptions, collection: 'agent_registry' });
|
||||
|
||||
module.exports = {
|
||||
|
||||
Reference in new issue
Block a user