80 lines
2.9 KiB
JavaScript
80 lines
2.9 KiB
JavaScript
/**
|
|
* cleanup_contaminated_devices.js
|
|
* Hapus record device/flow yang terkontaminasi berdasarkan konfigurasi subnet
|
|
* dari agent_registry. Jalankan SETELAH mengisi subnet di UI Agents.
|
|
*/
|
|
const mongoose = require('mongoose');
|
|
|
|
async function cleanup() {
|
|
await mongoose.connect('mongodb://backone_inspect:backone_inspect@mongodb.prod.proit.id:27017/backone_inspect_0');
|
|
console.log("Connected to MongoDB.\n");
|
|
|
|
const agents = await mongoose.connection.collection('agent_registry').find({}).toArray();
|
|
|
|
let totalDevicesDeleted = 0;
|
|
let totalFlowsDeleted = 0;
|
|
|
|
for (const agent of agents) {
|
|
const uuid = agent.uuid;
|
|
const subnets = (agent.allowed_subnets || []).map(s => s.trim()).filter(Boolean);
|
|
|
|
if (subnets.length === 0) {
|
|
console.log(`[${uuid}] Tidak ada subnet dikonfigurasi — skip.`);
|
|
continue;
|
|
}
|
|
|
|
console.log(`[${uuid}] Subnet diizinkan: ${subnets.join(', ')}`);
|
|
|
|
// Fungsi helper CIDR
|
|
const ipToLong = (ip) => ip.split('.').reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0) >>> 0;
|
|
const ipMatchesSubnets = (ip, subnets) => {
|
|
if (!subnets || subnets.length === 0) return true;
|
|
if (!ip) return false;
|
|
return subnets.some(subnet => {
|
|
if (subnet.includes('/')) {
|
|
try {
|
|
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(ip) & mask) === (ipToLong(range) & mask);
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
}
|
|
return ip.startsWith(subnet + '.') || ip === subnet;
|
|
});
|
|
};
|
|
|
|
// Ambil semua IP dari agent ini
|
|
const ips = await mongoose.connection.collection('devicestats').distinct('ip_address', { agent_uuid: uuid });
|
|
const invalidIps = ips.filter(ip => !ipMatchesSubnets(ip, subnets));
|
|
|
|
if (invalidIps.length > 0) {
|
|
const devResult = await mongoose.connection.collection('devicestats').deleteMany({
|
|
agent_uuid: uuid,
|
|
ip_address: { $in: invalidIps }
|
|
});
|
|
console.log(` → Hapus ${devResult.deletedCount} device records (IP tidak valid)`);
|
|
totalDevicesDeleted += devResult.deletedCount;
|
|
|
|
const flowResult = await mongoose.connection.collection('flows').deleteMany({
|
|
agent_uuid: uuid,
|
|
src_ip: { $in: invalidIps }
|
|
});
|
|
console.log(` → Hapus ${flowResult.deletedCount} flow records (src_ip tidak valid)`);
|
|
totalFlowsDeleted += flowResult.deletedCount;
|
|
} else {
|
|
console.log(` → Tidak ada kontaminasi ditemukan.`);
|
|
}
|
|
console.log();
|
|
}
|
|
|
|
console.log(`\n===== SELESAI =====`);
|
|
console.log(`Total device records dihapus: ${totalDevicesDeleted}`);
|
|
console.log(`Total flow records dihapus : ${totalFlowsDeleted}`);
|
|
process.exit(0);
|
|
}
|
|
|
|
cleanup().catch(e => { console.error(e.message); process.exit(1); });
|