feat(api,gui): implement target groups CRUD, scanner hot-reload, and CSV export
This commit is contained in:
1 parent
bc72dbffbd
commit
e8e529b09c
7 files changed
+1154
-41
No files matched your search
+29
-6
@@ -321,7 +321,7 @@ html[data-theme="light"] .bar-track { fill: rgba(20, 48, 64, 0.06); }
|
|||||||
|
|
||||||
.field { display: grid; gap: 6px; flex: 1; }
|
.field { display: grid; gap: 6px; flex: 1; }
|
||||||
.field > span { color: var(--muted); font-size: 0.72rem; letter-spacing: 0.08em; text-transform: uppercase; font-weight: 600; }
|
.field > span { color: var(--muted); font-size: 0.72rem; letter-spacing: 0.08em; text-transform: uppercase; font-weight: 600; }
|
||||||
input, select {
|
input, select, textarea {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
padding: 10px 12px;
|
padding: 10px 12px;
|
||||||
border: 1px solid var(--line-strong);
|
border: 1px solid var(--line-strong);
|
||||||
@@ -330,11 +330,17 @@ input, select {
|
|||||||
outline: none;
|
outline: none;
|
||||||
color: var(--text);
|
color: var(--text);
|
||||||
font-size: 0.85rem;
|
font-size: 0.85rem;
|
||||||
|
font-family: inherit;
|
||||||
|
resize: vertical;
|
||||||
}
|
}
|
||||||
html[data-theme="light"] input, html[data-theme="light"] select { background: rgba(255, 255, 255, 0.8); }
|
html[data-theme="light"] input, html[data-theme="light"] select, html[data-theme="light"] textarea { background: rgba(255, 255, 255, 0.8); }
|
||||||
input:focus, select:focus { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(56, 189, 248, 0.14); }
|
input:focus, select:focus, textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(56, 189, 248, 0.14); }
|
||||||
|
|
||||||
.btn {
|
.btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 6px;
|
||||||
padding: 10px 15px;
|
padding: 10px 15px;
|
||||||
border: 1px solid var(--line-strong);
|
border: 1px solid var(--line-strong);
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
@@ -342,13 +348,30 @@ input:focus, select:focus { border-color: var(--accent); box-shadow: 0 0 0 3px r
|
|||||||
color: var(--text);
|
color: var(--text);
|
||||||
font-size: 0.84rem;
|
font-size: 0.84rem;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
|
text-decoration: none;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
transition: 140ms ease;
|
transition: 140ms ease;
|
||||||
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
.btn:hover { border-color: var(--accent); }
|
.btn:hover { border-color: var(--accent); text-decoration: none; color: var(--text); }
|
||||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: #041b24; font-weight: 700; }
|
.btn.primary { background: var(--accent); border-color: var(--accent); color: #041b24; font-weight: 700; }
|
||||||
.btn.primary:hover { filter: brightness(1.08); }
|
.btn.primary:hover { filter: brightness(1.08); color: #041b24; }
|
||||||
.btn.small { padding: 6px 10px; font-size: 0.72rem; }
|
.btn.secondary { background: rgba(255, 255, 255, 0.03); border-color: var(--line); }
|
||||||
|
.btn.secondary:hover { border-color: var(--line-strong); background: rgba(255, 255, 255, 0.07); }
|
||||||
|
.btn.danger { background: rgba(244, 63, 94, 0.12); border-color: rgba(244, 63, 94, 0.35); color: #fda4af; }
|
||||||
|
.btn.danger:hover { background: rgba(244, 63, 94, 0.22); border-color: #f43f5e; color: #fff; }
|
||||||
|
.btn:disabled, .btn[disabled] { opacity: 0.45; cursor: not-allowed; pointer-events: none; }
|
||||||
|
.btn.small, .btn.btn-sm, .btn-sm { padding: 6px 11px; font-size: 0.74rem; border-radius: 8px; }
|
||||||
|
|
||||||
|
.panel-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||||
|
.group-card-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 14px; padding-top: 10px; border-top: 1px solid var(--line); }
|
||||||
|
.group-card-targets { font-family: var(--mono); font-size: 0.74rem; color: var(--muted); margin: 6px 0; word-break: break-all; }
|
||||||
|
.group-card-badge { display: inline-block; padding: 2px 7px; border-radius: 6px; font-size: 0.68rem; font-weight: 600; text-transform: uppercase; background: rgba(56, 189, 248, 0.12); color: var(--accent); }
|
||||||
|
.group-dlg { width: min(540px, calc(100vw - 32px)); }
|
||||||
|
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||||
|
.form-error { background: rgba(244, 63, 94, 0.15); border: 1px solid #f43f5e; color: #fda4af; padding: 10px 14px; border-radius: 8px; font-size: 0.8rem; margin-bottom: 14px; line-height: 1.4; }
|
||||||
|
.field-hint { font-size: 0.72rem; color: var(--muted); margin-top: 2px; display: block; }
|
||||||
|
.dlg-actions { display: flex; justify-content: flex-end; gap: 8px; margin: 20px 0 0; padding: 0; }
|
||||||
|
|
||||||
/* ------------------------------------------------------------------ SEVERITY BADGES */
|
/* ------------------------------------------------------------------ SEVERITY BADGES */
|
||||||
.sev-badge {
|
.sev-badge {
|
||||||
|
|||||||
+211
-1
@@ -55,12 +55,28 @@ const findingsList = $('#findingsList');
|
|||||||
const groupsCount = $('#groupsCount');
|
const groupsCount = $('#groupsCount');
|
||||||
const groupsGrid = $('#groupsGrid');
|
const groupsGrid = $('#groupsGrid');
|
||||||
const feedsSummary = $('#feedsSummary');
|
const feedsSummary = $('#feedsSummary');
|
||||||
|
const btnNewGroup = $('#btnNewGroup');
|
||||||
|
|
||||||
|
// Group Modal
|
||||||
|
const groupDlg = $('#groupDlg');
|
||||||
|
const groupForm = $('#groupForm');
|
||||||
|
const groupDlgTitle = $('#groupDlgTitle');
|
||||||
|
const closeGroupDlg = $('#closeGroupDlg');
|
||||||
|
const cancelGroupDlg = $('#cancelGroupDlg');
|
||||||
|
const groupFormError = $('#groupFormError');
|
||||||
|
const groupName = $('#groupName');
|
||||||
|
const groupTargets = $('#groupTargets');
|
||||||
|
const groupExclude = $('#groupExclude');
|
||||||
|
const groupCron = $('#groupCron');
|
||||||
|
const groupProfile = $('#groupProfile');
|
||||||
|
const groupCriticality = $('#groupCriticality');
|
||||||
|
|
||||||
// Changes View
|
// Changes View
|
||||||
const changesCount = $('#changesCount');
|
const changesCount = $('#changesCount');
|
||||||
const changesPeriodFilters = $('#changesPeriodFilters');
|
const changesPeriodFilters = $('#changesPeriodFilters');
|
||||||
const changesSearch = $('#changesSearch');
|
const changesSearch = $('#changesSearch');
|
||||||
const changesTimeline = $('#changesTimeline');
|
const changesTimeline = $('#changesTimeline');
|
||||||
|
const btnExportChangesCsv = $('#btnExportChangesCsv');
|
||||||
|
|
||||||
// Application State
|
// Application State
|
||||||
const state = {
|
const state = {
|
||||||
@@ -69,6 +85,7 @@ const state = {
|
|||||||
status: null,
|
status: null,
|
||||||
hosts: [],
|
hosts: [],
|
||||||
changes: [],
|
changes: [],
|
||||||
|
config: null,
|
||||||
lastUpdated: null,
|
lastUpdated: null,
|
||||||
pollTimer: null,
|
pollTimer: null,
|
||||||
expandedHosts: new Set(),
|
expandedHosts: new Set(),
|
||||||
@@ -84,6 +101,8 @@ const state = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let editingGroupName = null;
|
||||||
|
|
||||||
const VIEW_META = {
|
const VIEW_META = {
|
||||||
overview: {
|
overview: {
|
||||||
title: 'Visão geral',
|
title: 'Visão geral',
|
||||||
@@ -211,11 +230,12 @@ function getAllFindings() {
|
|||||||
async function fetchData() {
|
async function fetchData() {
|
||||||
try {
|
try {
|
||||||
const period = state.filters.changesPeriod || '24h';
|
const period = state.filters.changesPeriod || '24h';
|
||||||
const [healthRes, statusRes, hostsRes, changesRes] = await Promise.all([
|
const [healthRes, statusRes, hostsRes, changesRes, configRes] = await Promise.all([
|
||||||
fetch('/api/health').catch(() => null),
|
fetch('/api/health').catch(() => null),
|
||||||
fetch('/api/status').catch(() => null),
|
fetch('/api/status').catch(() => null),
|
||||||
fetch('/api/hosts').catch(() => null),
|
fetch('/api/hosts').catch(() => null),
|
||||||
fetch(`/api/changes?since=${encodeURIComponent(period)}`).catch(() => null),
|
fetch(`/api/changes?since=${encodeURIComponent(period)}`).catch(() => null),
|
||||||
|
fetch('/api/config').catch(() => null),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (!healthRes || !statusRes || !hostsRes) {
|
if (!healthRes || !statusRes || !hostsRes) {
|
||||||
@@ -226,6 +246,7 @@ async function fetchData() {
|
|||||||
state.status = await statusRes.json();
|
state.status = await statusRes.json();
|
||||||
state.hosts = await hostsRes.json();
|
state.hosts = await hostsRes.json();
|
||||||
state.changes = changesRes && changesRes.ok ? await changesRes.json() : [];
|
state.changes = changesRes && changesRes.ok ? await changesRes.json() : [];
|
||||||
|
state.config = configRes && configRes.ok ? await configRes.json() : null;
|
||||||
|
|
||||||
state.lastUpdated = new Date();
|
state.lastUpdated = new Date();
|
||||||
connection.classList.remove('offline');
|
connection.classList.remove('offline');
|
||||||
@@ -1031,8 +1052,22 @@ function renderGroups() {
|
|||||||
el('span', 'group-name', g.group),
|
el('span', 'group-name', g.group),
|
||||||
el('span', 'cron-tag', g.cron),
|
el('span', 'cron-tag', g.cron),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const configGroup = state.config && state.config.grupo
|
||||||
|
? state.config.grupo.find((cg) => cg.nome === g.group)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
if (configGroup && configGroup.criticidade) {
|
||||||
|
head.append(el('span', 'group-card-badge', configGroup.criticidade));
|
||||||
|
}
|
||||||
card.append(head);
|
card.append(head);
|
||||||
|
|
||||||
|
if (configGroup && configGroup.alvos && configGroup.alvos.length > 0) {
|
||||||
|
const targetsDiv = el('div', 'group-card-targets');
|
||||||
|
targetsDiv.textContent = configGroup.alvos.join(', ');
|
||||||
|
card.append(targetsDiv);
|
||||||
|
}
|
||||||
|
|
||||||
const details = el('div', 'hint');
|
const details = el('div', 'hint');
|
||||||
details.append(
|
details.append(
|
||||||
el('span', '', `${t('Perfil:')} `),
|
el('span', '', `${t('Perfil:')} `),
|
||||||
@@ -1047,6 +1082,19 @@ function renderGroups() {
|
|||||||
);
|
);
|
||||||
card.append(next);
|
card.append(next);
|
||||||
|
|
||||||
|
// Actions row
|
||||||
|
const actions = el('div', 'group-card-actions');
|
||||||
|
const editBtn = el('button', 'btn secondary small', t('Editar'));
|
||||||
|
editBtn.type = 'button';
|
||||||
|
editBtn.addEventListener('click', () => openEditGroupDialog(g.group));
|
||||||
|
|
||||||
|
const removeBtn = el('button', 'btn danger small', t('Remover'));
|
||||||
|
removeBtn.type = 'button';
|
||||||
|
removeBtn.addEventListener('click', () => deleteGroup(g.group));
|
||||||
|
|
||||||
|
actions.append(editBtn, removeBtn);
|
||||||
|
card.append(actions);
|
||||||
|
|
||||||
groupsGrid.append(card);
|
groupsGrid.append(card);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1072,6 +1120,146 @@ function renderGroups() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function populateProfilesDropdown() {
|
||||||
|
groupProfile.replaceChildren();
|
||||||
|
const profiles = state.config && state.config.perfis ? Object.keys(state.config.perfis) : ['padrao'];
|
||||||
|
if (!profiles.includes('padrao')) {
|
||||||
|
profiles.unshift('padrao');
|
||||||
|
}
|
||||||
|
profiles.forEach((p) => {
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = p;
|
||||||
|
opt.textContent = p;
|
||||||
|
groupProfile.append(opt);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function openCreateGroupDialog() {
|
||||||
|
editingGroupName = null;
|
||||||
|
groupDlgTitle.textContent = t('Novo Grupo');
|
||||||
|
groupFormError.hidden = true;
|
||||||
|
groupFormError.textContent = '';
|
||||||
|
groupName.value = '';
|
||||||
|
groupName.disabled = false;
|
||||||
|
groupTargets.value = '';
|
||||||
|
groupExclude.value = '';
|
||||||
|
groupCron.value = '';
|
||||||
|
populateProfilesDropdown();
|
||||||
|
groupProfile.value = 'padrao';
|
||||||
|
groupCriticality.value = '';
|
||||||
|
groupDlg.showModal();
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEditGroupDialog(name) {
|
||||||
|
const group = state.config && state.config.grupo
|
||||||
|
? state.config.grupo.find((g) => g.nome === name)
|
||||||
|
: null;
|
||||||
|
if (!group) return;
|
||||||
|
|
||||||
|
editingGroupName = name;
|
||||||
|
groupDlgTitle.textContent = `${t('Editar Grupo')} — ${name}`;
|
||||||
|
groupFormError.hidden = true;
|
||||||
|
groupFormError.textContent = '';
|
||||||
|
groupName.value = group.nome || '';
|
||||||
|
groupName.disabled = false;
|
||||||
|
groupTargets.value = (group.alvos || []).join('\n');
|
||||||
|
groupExclude.value = (group.excluir || []).join('\n');
|
||||||
|
groupCron.value = group.cron || '';
|
||||||
|
populateProfilesDropdown();
|
||||||
|
groupProfile.value = group.perfil || 'padrao';
|
||||||
|
groupCriticality.value = group.criticidade || '';
|
||||||
|
groupDlg.showModal();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleGroupFormSubmit(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
groupFormError.hidden = true;
|
||||||
|
groupFormError.textContent = '';
|
||||||
|
|
||||||
|
const name = groupName.value.trim();
|
||||||
|
if (!name) {
|
||||||
|
groupFormError.hidden = false;
|
||||||
|
groupFormError.textContent = t('Nome do grupo é obrigatório.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const targets = groupTargets.value
|
||||||
|
.split(/[\n,]+/)
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
if (targets.length === 0) {
|
||||||
|
groupFormError.hidden = false;
|
||||||
|
groupFormError.textContent = t('Pelo menos um alvo autorizado é obrigatório.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const exclude = groupExclude.value
|
||||||
|
.split(/[\n,]+/)
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
nome: name,
|
||||||
|
alvos: targets,
|
||||||
|
};
|
||||||
|
if (exclude.length > 0) payload.excluir = exclude;
|
||||||
|
if (groupCron.value.trim()) payload.cron = groupCron.value.trim();
|
||||||
|
if (groupProfile.value) payload.perfil = groupProfile.value;
|
||||||
|
if (groupCriticality.value) payload.criticidade = groupCriticality.value;
|
||||||
|
|
||||||
|
try {
|
||||||
|
let res;
|
||||||
|
if (editingGroupName) {
|
||||||
|
res = await fetch(`/api/config/groups/${encodeURIComponent(editingGroupName)}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
res = await fetch('/api/config/groups', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const errText = await res.text();
|
||||||
|
groupFormError.hidden = false;
|
||||||
|
groupFormError.textContent = errText || t('Erro ao salvar grupo');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
groupDlg.close();
|
||||||
|
await fetchData();
|
||||||
|
} catch (err) {
|
||||||
|
groupFormError.hidden = false;
|
||||||
|
groupFormError.textContent = err.message || t('Erro de rede ao salvar grupo');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteGroup(name) {
|
||||||
|
const confirmed = window.confirm(
|
||||||
|
`${t('Tem certeza que deseja remover o grupo')} "${name}"?`
|
||||||
|
);
|
||||||
|
if (!confirmed) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/config/groups/${encodeURIComponent(name)}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const errText = await res.text();
|
||||||
|
alert(errText || t('Erro ao remover grupo'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await fetchData();
|
||||||
|
} catch (err) {
|
||||||
|
alert(err.message || t('Erro de rede ao remover grupo'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------ CHANGES VIEW
|
// ------------------------------------------------------------------ CHANGES VIEW
|
||||||
function renderChanges() {
|
function renderChanges() {
|
||||||
changesTimeline.replaceChildren();
|
changesTimeline.replaceChildren();
|
||||||
@@ -1260,10 +1448,32 @@ function initEvents() {
|
|||||||
changesPeriodFilters.querySelectorAll('button').forEach((b) => b.classList.remove('active'));
|
changesPeriodFilters.querySelectorAll('button').forEach((b) => b.classList.remove('active'));
|
||||||
btn.classList.add('active');
|
btn.classList.add('active');
|
||||||
state.filters.changesPeriod = btn.dataset.period;
|
state.filters.changesPeriod = btn.dataset.period;
|
||||||
|
if (btnExportChangesCsv) {
|
||||||
|
btnExportChangesCsv.href = `/api/export/changes.csv?since=${encodeURIComponent(btn.dataset.period)}`;
|
||||||
|
}
|
||||||
fetchData();
|
fetchData();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Group Dialog
|
||||||
|
if (btnNewGroup) {
|
||||||
|
btnNewGroup.addEventListener('click', openCreateGroupDialog);
|
||||||
|
}
|
||||||
|
if (closeGroupDlg) {
|
||||||
|
closeGroupDlg.addEventListener('click', () => groupDlg.close());
|
||||||
|
}
|
||||||
|
if (cancelGroupDlg) {
|
||||||
|
cancelGroupDlg.addEventListener('click', () => groupDlg.close());
|
||||||
|
}
|
||||||
|
if (groupForm) {
|
||||||
|
groupForm.addEventListener('submit', handleGroupFormSubmit);
|
||||||
|
}
|
||||||
|
if (groupDlg) {
|
||||||
|
groupDlg.addEventListener('keydown', (e) => {
|
||||||
|
if (e.key === 'Escape') groupDlg.close();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Keyboard shortcut for settings: Escape to close dialog
|
// Keyboard shortcut for settings: Escape to close dialog
|
||||||
settingsDlg.addEventListener('keydown', (e) => {
|
settingsDlg.addEventListener('keydown', (e) => {
|
||||||
if (e.key === 'Escape') settingsDlg.close();
|
if (e.key === 'Escape') settingsDlg.close();
|
||||||
|
|||||||
@@ -152,4 +152,26 @@ export const EN = {
|
|||||||
'Auto': 'Auto',
|
'Auto': 'Auto',
|
||||||
'Português': 'Português',
|
'Português': 'Português',
|
||||||
'English': 'English',
|
'English': 'English',
|
||||||
|
|
||||||
|
// Actions, Exports & Group Management
|
||||||
|
'Exportar CSV': 'Export CSV',
|
||||||
|
'Exportar relatório executivo (em breve)': 'Export executive report (coming soon)',
|
||||||
|
'+ Novo grupo': '+ New group',
|
||||||
|
'Novo Grupo': 'New Group',
|
||||||
|
'Editar Grupo': 'Edit Group',
|
||||||
|
'Editar': 'Edit',
|
||||||
|
'Remover': 'Remove',
|
||||||
|
'Nome do grupo *': 'Group name *',
|
||||||
|
'Alvos autorizados (um por linha ou separados por vírgula) *': 'Authorized targets (one per line or comma-separated) *',
|
||||||
|
'Exclusões (opcional, um por linha ou separados por vírgula)': 'Exclusions (optional, one per line or comma-separated)',
|
||||||
|
'Expressão Cron (opcional)': 'Cron expression (optional)',
|
||||||
|
'Em branco usa o padrão global (@daily)': 'Blank uses global default (@daily)',
|
||||||
|
'Perfil de portas': 'Port profile',
|
||||||
|
'Criticidade (opcional)': 'Criticality (optional)',
|
||||||
|
'Padrão / Não definida': 'Default / Unset',
|
||||||
|
'Salvar Grupo': 'Save Group',
|
||||||
|
'Cancelar': 'Cancel',
|
||||||
|
'Tem certeza que deseja remover o grupo': 'Are you sure you want to remove the group',
|
||||||
|
'Pelo menos um alvo autorizado é obrigatório.': 'At least one authorized target is required.',
|
||||||
|
'Nome do grupo é obrigatório.': 'Group name is required.',
|
||||||
};
|
};
|
||||||
+65
-4
@@ -154,7 +154,11 @@
|
|||||||
<h2>Hosts e Superfície Descoberta</h2>
|
<h2>Hosts e Superfície Descoberta</h2>
|
||||||
<p class="hint">Ativos mapeados no escopo. Clique em uma linha para ver as portas abertas, serviços e achados correlacionados.</p>
|
<p class="hint">Ativos mapeados no escopo. Clique em uma linha para ver as portas abertas, serviços e achados correlacionados.</p>
|
||||||
</div>
|
</div>
|
||||||
<span id="hostCount" class="panel-tag">—</span>
|
<div class="panel-actions">
|
||||||
|
<span id="hostCount" class="panel-tag">—</span>
|
||||||
|
<a href="/api/export/hosts.csv" class="btn secondary btn-sm" download>Exportar CSV</a>
|
||||||
|
<button type="button" class="btn secondary btn-sm" disabled title="Em breve">Exportar relatório executivo (em breve)</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="toolbar toolbar-slim">
|
<div class="toolbar toolbar-slim">
|
||||||
@@ -201,7 +205,10 @@
|
|||||||
<h2>Inventário de Vulnerabilidades e Checagens</h2>
|
<h2>Inventário de Vulnerabilidades e Checagens</h2>
|
||||||
<p class="hint">Filtre, ordene e expanda cada achado para inspecionar a evidência determinística completa.</p>
|
<p class="hint">Filtre, ordene e expanda cada achado para inspecionar a evidência determinística completa.</p>
|
||||||
</div>
|
</div>
|
||||||
<span id="findingsCount" class="panel-tag">—</span>
|
<div class="panel-actions">
|
||||||
|
<span id="findingsCount" class="panel-tag">—</span>
|
||||||
|
<a href="/api/export/findings.csv" class="btn secondary btn-sm" download>Exportar CSV</a>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="toolbar">
|
<div class="toolbar">
|
||||||
@@ -242,7 +249,10 @@
|
|||||||
<h2>Grupos e Cadência de Varredura</h2>
|
<h2>Grupos e Cadência de Varredura</h2>
|
||||||
<p class="hint">Definições de alvos, perfis de portas e próximas execuções do agendador contínuo.</p>
|
<p class="hint">Definições de alvos, perfis de portas e próximas execuções do agendador contínuo.</p>
|
||||||
</div>
|
</div>
|
||||||
<span id="groupsCount" class="panel-tag">—</span>
|
<div class="panel-actions">
|
||||||
|
<span id="groupsCount" class="panel-tag">—</span>
|
||||||
|
<button type="button" id="btnNewGroup" class="btn primary btn-sm">+ Novo grupo</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="groupsGrid" class="groups-grid">
|
<div id="groupsGrid" class="groups-grid">
|
||||||
@@ -269,7 +279,10 @@
|
|||||||
<h2>Histórico de Mudanças na Superfície</h2>
|
<h2>Histórico de Mudanças na Superfície</h2>
|
||||||
<p class="hint">Diferenças detectadas entre lotes: hosts novos ou sumidos, portas abertas/fechadas e alterações de serviço.</p>
|
<p class="hint">Diferenças detectadas entre lotes: hosts novos ou sumidos, portas abertas/fechadas e alterações de serviço.</p>
|
||||||
</div>
|
</div>
|
||||||
<span id="changesCount" class="panel-tag">—</span>
|
<div class="panel-actions">
|
||||||
|
<span id="changesCount" class="panel-tag">—</span>
|
||||||
|
<a id="btnExportChangesCsv" href="/api/export/changes.csv?since=24h" class="btn secondary btn-sm" download>Exportar CSV</a>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="toolbar toolbar-slim">
|
<div class="toolbar toolbar-slim">
|
||||||
@@ -327,6 +340,54 @@
|
|||||||
</form>
|
</form>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
|
||||||
|
<!-- MODAL DE CRIAR / EDITAR GRUPO -->
|
||||||
|
<dialog id="groupDlg" class="group-dlg" aria-labelledby="groupDlgTitle">
|
||||||
|
<form id="groupForm" method="dialog">
|
||||||
|
<div class="dialog-head">
|
||||||
|
<h2 id="groupDlgTitle">Novo Grupo</h2>
|
||||||
|
<button type="button" id="closeGroupDlg" class="icon-btn" aria-label="Fechar" title="Fechar">×</button>
|
||||||
|
</div>
|
||||||
|
<div id="groupFormError" class="form-error" hidden></div>
|
||||||
|
<label class="field">
|
||||||
|
<span>Nome do grupo *</span>
|
||||||
|
<input type="text" id="groupName" name="name" required placeholder="ex: servidores-web" autocomplete="off">
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>Alvos autorizados (um por linha ou separados por vírgula) *</span>
|
||||||
|
<textarea id="groupTargets" name="targets" rows="3" required placeholder="192.168.1.0/24 10.0.0.1" spellcheck="false"></textarea>
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>Exclusões (opcional, um por linha ou separados por vírgula)</span>
|
||||||
|
<textarea id="groupExclude" name="exclude" rows="2" placeholder="192.168.1.1" spellcheck="false"></textarea>
|
||||||
|
</label>
|
||||||
|
<div class="form-row">
|
||||||
|
<label class="field">
|
||||||
|
<span>Expressão Cron (opcional)</span>
|
||||||
|
<input type="text" id="groupCron" name="cron" placeholder="ex: 0 2 * * * ou @daily" autocomplete="off">
|
||||||
|
<small class="field-hint">Em branco usa o padrão global (@daily)</small>
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>Perfil de portas</span>
|
||||||
|
<select id="groupProfile" name="profile"></select>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<label class="field">
|
||||||
|
<span>Criticidade (opcional)</span>
|
||||||
|
<select id="groupCriticality" name="criticality">
|
||||||
|
<option value="">Padrão / Não definida</option>
|
||||||
|
<option value="baixa">Baixa</option>
|
||||||
|
<option value="media">Média</option>
|
||||||
|
<option value="alta">Alta</option>
|
||||||
|
<option value="critica">Crítica</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<menu class="dlg-actions">
|
||||||
|
<button type="button" id="cancelGroupDlg" class="btn secondary">Cancelar</button>
|
||||||
|
<button type="submit" id="saveGroupBtn" class="btn primary">Salvar Grupo</button>
|
||||||
|
</menu>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
<script type="module" src="/app.js"></script>
|
<script type="module" src="/app.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
+406
-13
@@ -7,8 +7,8 @@ use std::sync::atomic::{AtomicUsize, Ordering};
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use axum::extract::{Query, State};
|
use axum::extract::{Path as AxumPath, Query, State};
|
||||||
use axum::http::{header, StatusCode};
|
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
|
||||||
use axum::response::IntoResponse;
|
use axum::response::IntoResponse;
|
||||||
use axum::{Json, Router};
|
use axum::{Json, Router};
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
@@ -16,8 +16,8 @@ use clap::{Parser, Subcommand};
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use tokio::sync::{Mutex, RwLock};
|
use tokio::sync::{Mutex, RwLock};
|
||||||
use xexeu_core::batch::{EngineMode, ServiceObservation, SweepBatch, SweepManifest, SweepStatus};
|
use xexeu_core::batch::{EngineMode, ServiceObservation, SweepBatch, SweepManifest, SweepStatus};
|
||||||
use xexeu_core::config::{ValidationReport, XexeuConfig};
|
use xexeu_core::config::{GroupConfig, ValidationReport, XexeuConfig};
|
||||||
use xexeu_core::diff::{diff_batch, DiffOptions};
|
use xexeu_core::diff::{diff_batch, DiffOptions, EventKind};
|
||||||
use xexeu_core::scan::{
|
use xexeu_core::scan::{
|
||||||
discover_hosts_tcp, fingerprint_service, scan_hosts_tcp_connect, DiscoveryConfig, HostState,
|
discover_hosts_tcp, fingerprint_service, scan_hosts_tcp_connect, DiscoveryConfig, HostState,
|
||||||
PortScanConfig, PortState, PortTarget, DEFAULT_DISCOVERY_PORTS,
|
PortScanConfig, PortState, PortTarget, DEFAULT_DISCOVERY_PORTS,
|
||||||
@@ -28,7 +28,7 @@ use xexeu_core::targets::{
|
|||||||
effective_cadence, expand_group, filter_in_scope, resolve_name, scope_ranges, IpRange,
|
effective_cadence, expand_group, filter_in_scope, resolve_name, scope_ranges, IpRange,
|
||||||
};
|
};
|
||||||
use xexeu_core::vuln::checks::{check_tls_certificate_der, evaluate_http_admin_response};
|
use xexeu_core::vuln::checks::{check_tls_certificate_der, evaluate_http_admin_response};
|
||||||
use xexeu_core::vuln::matcher::{match_banner, Finding};
|
use xexeu_core::vuln::matcher::{match_banner, Confidence, Finding};
|
||||||
use xexeu_core::vuln::{import_kev, import_nvd, sync_feeds, KevCatalog, SyncOptions, VulnDatabase};
|
use xexeu_core::vuln::{import_kev, import_nvd, sync_feeds, KevCatalog, SyncOptions, VulnDatabase};
|
||||||
|
|
||||||
const DEFAULT_CONFIG: &str = "config/xexeu.toml";
|
const DEFAULT_CONFIG: &str = "config/xexeu.toml";
|
||||||
@@ -515,7 +515,7 @@ async fn scan_once(
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn run_scanner(config_path: &Path, out_dir: &Path, data_dir: &Path) -> Result<(), String> {
|
async fn run_scanner(config_path: &Path, out_dir: &Path, data_dir: &Path) -> Result<(), String> {
|
||||||
let (config, _report) = validated_config(config_path)?;
|
let (mut config, _report) = validated_config(config_path)?;
|
||||||
fs::create_dir_all(out_dir)
|
fs::create_dir_all(out_dir)
|
||||||
.map_err(|error| format!("falha ao criar {}: {error}", out_dir.display()))?;
|
.map_err(|error| format!("falha ao criar {}: {error}", out_dir.display()))?;
|
||||||
|
|
||||||
@@ -535,7 +535,36 @@ async fn run_scanner(config_path: &Path, out_dir: &Path, data_dir: &Path) -> Res
|
|||||||
.map(Duration::from_secs)
|
.map(Duration::from_secs)
|
||||||
.unwrap_or(Duration::from_secs(10));
|
.unwrap_or(Duration::from_secs(10));
|
||||||
|
|
||||||
|
let mut last_mtime = fs::metadata(config_path).and_then(|m| m.modified()).ok();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
|
// Hot-reload configuration if file modified time changed
|
||||||
|
if let Ok(mtime) = fs::metadata(config_path).and_then(|m| m.modified()) {
|
||||||
|
if Some(mtime) != last_mtime {
|
||||||
|
last_mtime = Some(mtime);
|
||||||
|
match validated_config(config_path) {
|
||||||
|
Ok((new_config, _)) => {
|
||||||
|
println!(
|
||||||
|
"scanner: configuração recarregada com sucesso ({} grupos)",
|
||||||
|
new_config.groups.len()
|
||||||
|
);
|
||||||
|
let current_group_names: BTreeSet<String> =
|
||||||
|
new_config.groups.iter().map(|g| g.name.clone()).collect();
|
||||||
|
histories.retain(|name, _| current_group_names.contains(name));
|
||||||
|
for group in &new_config.groups {
|
||||||
|
histories.entry(group.name.clone()).or_default();
|
||||||
|
}
|
||||||
|
config = new_config;
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!(
|
||||||
|
"aviso: configuração alterada em disco mas inválida ({err}); mantendo configuração anterior em memória"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let now = Utc::now();
|
let now = Utc::now();
|
||||||
for group in &config.groups {
|
for group in &config.groups {
|
||||||
let history = histories.entry(group.name.clone()).or_default();
|
let history = histories.entry(group.name.clone()).or_default();
|
||||||
@@ -684,7 +713,7 @@ async fn poll_sweeps(
|
|||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct ServerState {
|
struct ServerState {
|
||||||
config: Arc<XexeuConfig>,
|
config: Arc<RwLock<XexeuConfig>>,
|
||||||
config_path: PathBuf,
|
config_path: PathBuf,
|
||||||
storage: Arc<Mutex<SqliteStorage>>,
|
storage: Arc<Mutex<SqliteStorage>>,
|
||||||
sweeps_ingested: Arc<AtomicUsize>,
|
sweeps_ingested: Arc<AtomicUsize>,
|
||||||
@@ -727,9 +756,9 @@ struct GroupScheduleDto {
|
|||||||
|
|
||||||
async fn status_handler(State(state): State<ServerState>) -> Json<StatusResponse> {
|
async fn status_handler(State(state): State<ServerState>) -> Json<StatusResponse> {
|
||||||
let now = Utc::now();
|
let now = Utc::now();
|
||||||
let schedules = next_runs(&state.config, now).unwrap_or_default();
|
let config = state.config.read().await;
|
||||||
let groups = state
|
let schedules = next_runs(&config, now).unwrap_or_default();
|
||||||
.config
|
let groups = config
|
||||||
.groups
|
.groups
|
||||||
.iter()
|
.iter()
|
||||||
.map(|group| {
|
.map(|group| {
|
||||||
@@ -740,8 +769,8 @@ async fn status_handler(State(state): State<ServerState>) -> Json<StatusResponse
|
|||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
GroupScheduleDto {
|
GroupScheduleDto {
|
||||||
group: group.name.clone(),
|
group: group.name.clone(),
|
||||||
profile: group.effective_profile(&state.config).to_string(),
|
profile: group.effective_profile(&config).to_string(),
|
||||||
cron: group.effective_cron(&state.config).to_string(),
|
cron: group.effective_cron(&config).to_string(),
|
||||||
next_run,
|
next_run,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -768,6 +797,349 @@ async fn status_handler(State(state): State<ServerState>) -> Json<StatusResponse
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn get_config_handler(State(state): State<ServerState>) -> Json<XexeuConfig> {
|
||||||
|
let config = state.config.read().await;
|
||||||
|
Json(config.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create_group_handler(
|
||||||
|
State(state): State<ServerState>,
|
||||||
|
Json(new_group): Json<GroupConfig>,
|
||||||
|
) -> Result<(StatusCode, Json<GroupConfig>), (StatusCode, String)> {
|
||||||
|
let group_name = new_group.name.trim().to_string();
|
||||||
|
if group_name.is_empty() {
|
||||||
|
return Err((
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"nome do grupo não pode ser vazio".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut config_guard = state.config.write().await;
|
||||||
|
let mut draft = config_guard.clone();
|
||||||
|
|
||||||
|
if draft.groups.iter().any(|g| g.name == group_name) {
|
||||||
|
return Err((
|
||||||
|
StatusCode::CONFLICT,
|
||||||
|
format!("grupo `{group_name}` já existe"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
draft.groups.push(new_group.clone());
|
||||||
|
|
||||||
|
if let Err(err) = draft.validate() {
|
||||||
|
return Err((
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
format!("configuração inválida: {err}"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
draft.save_to_file(&state.config_path).map_err(|err| {
|
||||||
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
format!("erro ao salvar configuração: {err}"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
*config_guard = draft;
|
||||||
|
Ok((StatusCode::CREATED, Json(new_group)))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update_group_handler(
|
||||||
|
State(state): State<ServerState>,
|
||||||
|
AxumPath(group_name): AxumPath<String>,
|
||||||
|
Json(updated_group): Json<GroupConfig>,
|
||||||
|
) -> Result<Json<GroupConfig>, (StatusCode, String)> {
|
||||||
|
let mut config_guard = state.config.write().await;
|
||||||
|
let mut draft = config_guard.clone();
|
||||||
|
|
||||||
|
let pos = draft
|
||||||
|
.groups
|
||||||
|
.iter()
|
||||||
|
.position(|g| g.name == group_name)
|
||||||
|
.ok_or_else(|| {
|
||||||
|
(
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
format!("grupo `{group_name}` não encontrado"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let new_name = updated_group.name.trim();
|
||||||
|
if new_name.is_empty() {
|
||||||
|
return Err((
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"nome do grupo não pode ser vazio".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if new_name != group_name && draft.groups.iter().any(|g| g.name == new_name) {
|
||||||
|
return Err((
|
||||||
|
StatusCode::CONFLICT,
|
||||||
|
format!("grupo `{new_name}` já existe"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
draft.groups[pos] = updated_group.clone();
|
||||||
|
|
||||||
|
if let Err(err) = draft.validate() {
|
||||||
|
return Err((
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
format!("configuração inválida: {err}"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
draft.save_to_file(&state.config_path).map_err(|err| {
|
||||||
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
format!("erro ao salvar configuração: {err}"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
*config_guard = draft;
|
||||||
|
Ok(Json(updated_group))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete_group_handler(
|
||||||
|
State(state): State<ServerState>,
|
||||||
|
AxumPath(group_name): AxumPath<String>,
|
||||||
|
) -> Result<StatusCode, (StatusCode, String)> {
|
||||||
|
let mut config_guard = state.config.write().await;
|
||||||
|
let mut draft = config_guard.clone();
|
||||||
|
|
||||||
|
if !draft.groups.iter().any(|g| g.name == group_name) {
|
||||||
|
return Err((
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
format!("grupo `{group_name}` não encontrado"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if draft.groups.len() <= 1 {
|
||||||
|
return Err((
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"não é permitido remover o último grupo configurado".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
draft.groups.retain(|g| g.name != group_name);
|
||||||
|
|
||||||
|
if let Err(err) = draft.validate() {
|
||||||
|
return Err((
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
format!("configuração inválida: {err}"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
draft.save_to_file(&state.config_path).map_err(|err| {
|
||||||
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
format!("erro ao salvar configuração: {err}"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
*config_guard = draft;
|
||||||
|
Ok(StatusCode::OK)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn csv_escape(s: &str) -> String {
|
||||||
|
if s.contains(',') || s.contains('"') || s.contains('\n') || s.contains('\r') {
|
||||||
|
let escaped = s.replace('"', "\"\"");
|
||||||
|
format!("\"{escaped}\"")
|
||||||
|
} else {
|
||||||
|
s.to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn export_hosts_csv_handler(
|
||||||
|
State(state): State<ServerState>,
|
||||||
|
) -> Result<impl IntoResponse, (StatusCode, String)> {
|
||||||
|
let storage = state.storage.lock().await;
|
||||||
|
let current_state = storage.load_state(&[]).map_err(|error| {
|
||||||
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
format!("erro ao consultar estado: {error}"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let mut csv = String::new();
|
||||||
|
csv.push_str("Endereço IP,Grupo,Status do Host,Protocolo,Porta,Status da Porta,Produto,Versão,CPE,Maior CVSS,Quantidade de Achados\r\n");
|
||||||
|
|
||||||
|
for asset in ¤t_state.assets {
|
||||||
|
if asset.ports.is_empty() {
|
||||||
|
let row = [
|
||||||
|
csv_escape(&asset.ip.to_string()),
|
||||||
|
csv_escape(&asset.network),
|
||||||
|
csv_escape(asset.status.as_str()),
|
||||||
|
String::new(),
|
||||||
|
String::new(),
|
||||||
|
String::new(),
|
||||||
|
String::new(),
|
||||||
|
String::new(),
|
||||||
|
String::new(),
|
||||||
|
String::new(),
|
||||||
|
"0".to_string(),
|
||||||
|
];
|
||||||
|
csv.push_str(&row.join(","));
|
||||||
|
csv.push_str("\r\n");
|
||||||
|
} else {
|
||||||
|
for port in &asset.ports {
|
||||||
|
let max_cvss = port
|
||||||
|
.findings
|
||||||
|
.iter()
|
||||||
|
.filter_map(|f| f.cvss)
|
||||||
|
.fold(None, |acc, v| Some(acc.map_or(v, |m: f32| m.max(v))));
|
||||||
|
let max_cvss_str = max_cvss.map(|c| format!("{c:.1}")).unwrap_or_default();
|
||||||
|
let findings_count = port.findings.len().to_string();
|
||||||
|
|
||||||
|
let row = [
|
||||||
|
csv_escape(&asset.ip.to_string()),
|
||||||
|
csv_escape(&asset.network),
|
||||||
|
csv_escape(asset.status.as_str()),
|
||||||
|
csv_escape(&port.protocol),
|
||||||
|
csv_escape(&port.port.to_string()),
|
||||||
|
csv_escape(port.status.as_str()),
|
||||||
|
csv_escape(port.product.as_deref().unwrap_or("")),
|
||||||
|
csv_escape(port.version.as_deref().unwrap_or("")),
|
||||||
|
csv_escape(port.cpe.as_deref().unwrap_or("")),
|
||||||
|
csv_escape(&max_cvss_str),
|
||||||
|
csv_escape(&findings_count),
|
||||||
|
];
|
||||||
|
csv.push_str(&row.join(","));
|
||||||
|
csv.push_str("\r\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let timestamp = Utc::now().format("%Y%m%d-%H%M%S");
|
||||||
|
let disposition = format!("attachment; filename=\"xexeu-hosts-{timestamp}.csv\"");
|
||||||
|
let mut headers = HeaderMap::new();
|
||||||
|
headers.insert(
|
||||||
|
header::CONTENT_TYPE,
|
||||||
|
HeaderValue::from_static("text/csv; charset=utf-8"),
|
||||||
|
);
|
||||||
|
if let Ok(val) = HeaderValue::from_str(&disposition) {
|
||||||
|
headers.insert(header::CONTENT_DISPOSITION, val);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok((headers, csv))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn export_findings_csv_handler(
|
||||||
|
State(state): State<ServerState>,
|
||||||
|
) -> Result<impl IntoResponse, (StatusCode, String)> {
|
||||||
|
let storage = state.storage.lock().await;
|
||||||
|
let current_state = storage.load_state(&[]).map_err(|error| {
|
||||||
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
format!("erro ao consultar estado: {error}"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let mut csv = String::new();
|
||||||
|
csv.push_str("Endereço IP,Porta,CVE / ID,CVSS,No KEV,Confiança,Título,Descrição\r\n");
|
||||||
|
|
||||||
|
for asset in ¤t_state.assets {
|
||||||
|
for port in &asset.ports {
|
||||||
|
for finding in &port.findings {
|
||||||
|
let cvss_str = finding.cvss.map(|c| format!("{c:.1}")).unwrap_or_default();
|
||||||
|
let kev_str = if finding.kev { "Sim" } else { "Não" };
|
||||||
|
let confianca_str = match finding.confianca {
|
||||||
|
Confidence::Alto => "Alta",
|
||||||
|
Confidence::Medio => "Média",
|
||||||
|
Confidence::Baixo => "Baixa",
|
||||||
|
};
|
||||||
|
|
||||||
|
let row = [
|
||||||
|
csv_escape(&asset.ip.to_string()),
|
||||||
|
csv_escape(&port.port.to_string()),
|
||||||
|
csv_escape(&finding.id),
|
||||||
|
csv_escape(&cvss_str),
|
||||||
|
csv_escape(kev_str),
|
||||||
|
csv_escape(confianca_str),
|
||||||
|
csv_escape(&finding.title),
|
||||||
|
csv_escape(&finding.description),
|
||||||
|
];
|
||||||
|
csv.push_str(&row.join(","));
|
||||||
|
csv.push_str("\r\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let timestamp = Utc::now().format("%Y%m%d-%H%M%S");
|
||||||
|
let disposition = format!("attachment; filename=\"xexeu-findings-{timestamp}.csv\"");
|
||||||
|
let mut headers = HeaderMap::new();
|
||||||
|
headers.insert(
|
||||||
|
header::CONTENT_TYPE,
|
||||||
|
HeaderValue::from_static("text/csv; charset=utf-8"),
|
||||||
|
);
|
||||||
|
if let Ok(val) = HeaderValue::from_str(&disposition) {
|
||||||
|
headers.insert(header::CONTENT_DISPOSITION, val);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok((headers, csv))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn export_changes_csv_handler(
|
||||||
|
State(state): State<ServerState>,
|
||||||
|
Query(query): Query<ChangesQuery>,
|
||||||
|
) -> Result<impl IntoResponse, (StatusCode, String)> {
|
||||||
|
let since = query.since.as_deref().and_then(parse_since);
|
||||||
|
let storage = state.storage.lock().await;
|
||||||
|
let events = storage.events(since).map_err(|error| {
|
||||||
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
format!("erro ao consultar eventos: {error}"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let mut csv = String::new();
|
||||||
|
csv.push_str("Data/Hora (UTC),Tipo de Evento,Alvo / Host,Grupo,Detalhe\r\n");
|
||||||
|
|
||||||
|
for event in &events {
|
||||||
|
let tipo_str = match event.kind {
|
||||||
|
EventKind::HostNew => "Novo Host",
|
||||||
|
EventKind::HostReturned => "Host Retornado",
|
||||||
|
EventKind::HostDisappeared => "Host Sumido",
|
||||||
|
EventKind::PortNew => "Nova Porta Aberta",
|
||||||
|
EventKind::PortClosed => "Porta Fechada",
|
||||||
|
EventKind::ServiceChanged => "Serviço Alterado",
|
||||||
|
};
|
||||||
|
|
||||||
|
let detail = if let Some(svc) = &event.service {
|
||||||
|
if let (Some(prev), Some(curr)) = (&event.previous, &event.current) {
|
||||||
|
format!("{}/{}: {} -> {}", svc.protocol, svc.port, prev, curr)
|
||||||
|
} else {
|
||||||
|
format!("{}/{}", svc.protocol, svc.port)
|
||||||
|
}
|
||||||
|
} else if !event.evidence.is_null() && event.evidence != serde_json::json!({}) {
|
||||||
|
event.evidence.to_string()
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
|
||||||
|
let row = [
|
||||||
|
csv_escape(&event.occurred_at.to_rfc3339()),
|
||||||
|
csv_escape(tipo_str),
|
||||||
|
csv_escape(&event.asset_key),
|
||||||
|
csv_escape(&event.group),
|
||||||
|
csv_escape(&detail),
|
||||||
|
];
|
||||||
|
csv.push_str(&row.join(","));
|
||||||
|
csv.push_str("\r\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
let timestamp = Utc::now().format("%Y%m%d-%H%M%S");
|
||||||
|
let disposition = format!("attachment; filename=\"xexeu-changes-{timestamp}.csv\"");
|
||||||
|
let mut headers = HeaderMap::new();
|
||||||
|
headers.insert(
|
||||||
|
header::CONTENT_TYPE,
|
||||||
|
HeaderValue::from_static("text/csv; charset=utf-8"),
|
||||||
|
);
|
||||||
|
if let Ok(val) = HeaderValue::from_str(&disposition) {
|
||||||
|
headers.insert(header::CONTENT_DISPOSITION, val);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok((headers, csv))
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
struct HostDto {
|
struct HostDto {
|
||||||
asset_key: String,
|
asset_key: String,
|
||||||
@@ -1048,7 +1420,7 @@ async fn run_serve(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let state = ServerState {
|
let state = ServerState {
|
||||||
config: Arc::new(config),
|
config: Arc::new(RwLock::new(config)),
|
||||||
config_path: config_path.to_path_buf(),
|
config_path: config_path.to_path_buf(),
|
||||||
storage: shared_storage,
|
storage: shared_storage,
|
||||||
sweeps_ingested,
|
sweeps_ingested,
|
||||||
@@ -1061,6 +1433,27 @@ async fn run_serve(
|
|||||||
.route("/api/status", axum::routing::get(status_handler))
|
.route("/api/status", axum::routing::get(status_handler))
|
||||||
.route("/api/hosts", axum::routing::get(hosts_handler))
|
.route("/api/hosts", axum::routing::get(hosts_handler))
|
||||||
.route("/api/changes", axum::routing::get(changes_handler))
|
.route("/api/changes", axum::routing::get(changes_handler))
|
||||||
|
.route("/api/config", axum::routing::get(get_config_handler))
|
||||||
|
.route(
|
||||||
|
"/api/config/groups",
|
||||||
|
axum::routing::post(create_group_handler),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/config/groups/{nome}",
|
||||||
|
axum::routing::put(update_group_handler).delete(delete_group_handler),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/export/hosts.csv",
|
||||||
|
axum::routing::get(export_hosts_csv_handler),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/export/findings.csv",
|
||||||
|
axum::routing::get(export_findings_csv_handler),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/export/changes.csv",
|
||||||
|
axum::routing::get(export_changes_csv_handler),
|
||||||
|
)
|
||||||
.route("/", axum::routing::get(index_handler))
|
.route("/", axum::routing::get(index_handler))
|
||||||
.route("/dashboard", axum::routing::get(index_handler))
|
.route("/dashboard", axum::routing::get(index_handler))
|
||||||
.route("/app.css", axum::routing::get(css_handler))
|
.route("/app.css", axum::routing::get(css_handler))
|
||||||
|
|||||||
@@ -0,0 +1,304 @@
|
|||||||
|
use std::fs;
|
||||||
|
use std::io::{BufRead, BufReader, Read, Write};
|
||||||
|
use std::net::TcpStream;
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use tempfile::TempDir;
|
||||||
|
|
||||||
|
struct ChildGuard(std::process::Child);
|
||||||
|
|
||||||
|
impl Drop for ChildGuard {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = self.0.kill();
|
||||||
|
let _ = self.0.wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn http_request(addr: &str, method: &str, path: &str, body: Option<&str>) -> (u16, String, String) {
|
||||||
|
let mut stream = TcpStream::connect(addr).expect("connect to server");
|
||||||
|
stream
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||||
|
.expect("set read timeout");
|
||||||
|
|
||||||
|
let payload = body.unwrap_or("");
|
||||||
|
let request = format!(
|
||||||
|
"{method} {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}",
|
||||||
|
payload.len()
|
||||||
|
);
|
||||||
|
stream.write_all(request.as_bytes()).expect("write request");
|
||||||
|
|
||||||
|
let mut response = String::new();
|
||||||
|
stream.read_to_string(&mut response).expect("read response");
|
||||||
|
|
||||||
|
let parts: Vec<&str> = response.split("\r\n\r\n").collect();
|
||||||
|
let header_part = parts.first().copied().unwrap_or("");
|
||||||
|
let body_part = parts.get(1).copied().unwrap_or("").to_string();
|
||||||
|
|
||||||
|
let status_line = header_part.lines().next().unwrap_or("");
|
||||||
|
let code: u16 = status_line
|
||||||
|
.split_whitespace()
|
||||||
|
.nth(1)
|
||||||
|
.unwrap_or("0")
|
||||||
|
.parse()
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
|
(code, header_part.to_string(), body_part)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_crud_and_export_e2e() {
|
||||||
|
let workspace = TempDir::new().expect("temporary directory");
|
||||||
|
let config_path = workspace.path().join("xexeu.toml");
|
||||||
|
let sweeps_dir = workspace.path().join("sweeps");
|
||||||
|
let data_dir = workspace.path().join("data");
|
||||||
|
|
||||||
|
fs::write(
|
||||||
|
&config_path,
|
||||||
|
r#"
|
||||||
|
[escopo]
|
||||||
|
autorizado = ["127.0.0.1/32", "10.0.0.0/24"]
|
||||||
|
responsavel = "SecOps Test"
|
||||||
|
|
||||||
|
[padrao]
|
||||||
|
cron = "@daily"
|
||||||
|
hosts_simultaneos = 2
|
||||||
|
|
||||||
|
[perfis.padrao]
|
||||||
|
tcp = "80"
|
||||||
|
|
||||||
|
[[grupo]]
|
||||||
|
nome = "inicial"
|
||||||
|
alvos = ["127.0.0.1/32"]
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.expect("write configuration");
|
||||||
|
|
||||||
|
// 1. Spawn `xexeu serve --bind 127.0.0.1:0`.
|
||||||
|
let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu"))
|
||||||
|
.args([
|
||||||
|
"serve",
|
||||||
|
"--bind",
|
||||||
|
"127.0.0.1:0",
|
||||||
|
"--config",
|
||||||
|
config_path.to_str().expect("config path"),
|
||||||
|
"--sweeps",
|
||||||
|
sweeps_dir.to_str().expect("sweeps path"),
|
||||||
|
"--data-dir",
|
||||||
|
data_dir.to_str().expect("data dir"),
|
||||||
|
])
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::inherit())
|
||||||
|
.spawn()
|
||||||
|
.expect("spawn xexeu serve");
|
||||||
|
|
||||||
|
let stdout = child.stdout.take().expect("take stdout");
|
||||||
|
let mut reader = BufReader::new(stdout);
|
||||||
|
let mut server_addr = None;
|
||||||
|
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(10);
|
||||||
|
while Instant::now() < deadline {
|
||||||
|
let mut line = String::new();
|
||||||
|
if reader.read_line(&mut line).is_ok() {
|
||||||
|
if let Some(pos) = line.find("http://") {
|
||||||
|
let addr = line[pos + 7..].trim();
|
||||||
|
server_addr = Some(addr.to_string());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
|
||||||
|
let _server_guard = ChildGuard(child);
|
||||||
|
let addr = server_addr.expect("server must output listening address");
|
||||||
|
|
||||||
|
// 2. Test GET /api/config
|
||||||
|
let (code, _, body) = http_request(&addr, "GET", "/api/config", None);
|
||||||
|
assert_eq!(code, 200);
|
||||||
|
assert!(body.contains("\"escopo\""));
|
||||||
|
assert!(body.contains("\"inicial\""));
|
||||||
|
|
||||||
|
// 3. Test POST /api/config/groups - out of scope rejection
|
||||||
|
let (code, _, body) = http_request(
|
||||||
|
&addr,
|
||||||
|
"POST",
|
||||||
|
"/api/config/groups",
|
||||||
|
Some(r#"{"nome": "fora-escopo", "alvos": ["192.168.1.1"]}"#),
|
||||||
|
);
|
||||||
|
assert_eq!(code, 400);
|
||||||
|
assert!(body.contains("fora do escopo autorizado"));
|
||||||
|
|
||||||
|
// 4. Test POST /api/config/groups - invalid cron rejection
|
||||||
|
let (code, _, body) = http_request(
|
||||||
|
&addr,
|
||||||
|
"POST",
|
||||||
|
"/api/config/groups",
|
||||||
|
Some(r#"{"nome": "cron-ruim", "alvos": ["10.0.0.1"], "cron": "isto-nao-e-cron"}"#),
|
||||||
|
);
|
||||||
|
assert_eq!(code, 400);
|
||||||
|
assert!(body.contains("cron inválido"));
|
||||||
|
|
||||||
|
// 5. Test POST /api/config/groups - valid creation
|
||||||
|
let (code, _, body) = http_request(
|
||||||
|
&addr,
|
||||||
|
"POST",
|
||||||
|
"/api/config/groups",
|
||||||
|
Some(
|
||||||
|
r#"{"nome": "novo-grupo", "alvos": ["10.0.0.10"], "cron": "0 3 * * *", "criticidade": "alta"}"#,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
assert_eq!(code, 201);
|
||||||
|
assert!(body.contains("\"novo-grupo\""));
|
||||||
|
|
||||||
|
// Verify config file was updated on disk
|
||||||
|
let file_content = fs::read_to_string(&config_path).expect("read config file");
|
||||||
|
assert!(file_content.contains("novo-grupo"));
|
||||||
|
|
||||||
|
// 6. Test PUT /api/config/groups/novo-grupo - update group
|
||||||
|
let (code, _, body) = http_request(
|
||||||
|
&addr,
|
||||||
|
"PUT",
|
||||||
|
"/api/config/groups/novo-grupo",
|
||||||
|
Some(
|
||||||
|
r#"{"nome": "novo-grupo", "alvos": ["10.0.0.20"], "cron": "0 4 * * *", "criticidade": "critica"}"#,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
assert_eq!(code, 200);
|
||||||
|
assert!(body.contains("10.0.0.20"));
|
||||||
|
assert!(body.contains("critica"));
|
||||||
|
|
||||||
|
// 7. Test DELETE /api/config/groups/novo-grupo - delete group
|
||||||
|
let (code, _, _) = http_request(&addr, "DELETE", "/api/config/groups/novo-grupo", None);
|
||||||
|
assert_eq!(code, 200);
|
||||||
|
|
||||||
|
// Verify file on disk has only 1 group
|
||||||
|
let file_content = fs::read_to_string(&config_path).expect("read config file");
|
||||||
|
assert!(!file_content.contains("novo-grupo"));
|
||||||
|
|
||||||
|
// 8. Test DELETE /api/config/groups/inicial - cannot delete last group
|
||||||
|
let (code, _, body) = http_request(&addr, "DELETE", "/api/config/groups/inicial", None);
|
||||||
|
assert_eq!(code, 400);
|
||||||
|
assert!(body.contains("último grupo"));
|
||||||
|
|
||||||
|
// 9. Test CSV Exports
|
||||||
|
// Hosts CSV
|
||||||
|
let (code, headers, body) = http_request(&addr, "GET", "/api/export/hosts.csv", None);
|
||||||
|
assert_eq!(code, 200);
|
||||||
|
assert!(headers.contains("content-type: text/csv; charset=utf-8"));
|
||||||
|
assert!(headers.contains("content-disposition: attachment; filename=\"xexeu-hosts-"));
|
||||||
|
assert!(body.starts_with("Endereço IP,Grupo,Status do Host,Protocolo,Porta,Status da Porta,Produto,Versão,CPE,Maior CVSS,Quantidade de Achados"));
|
||||||
|
|
||||||
|
// Findings CSV
|
||||||
|
let (code, headers, body) = http_request(&addr, "GET", "/api/export/findings.csv", None);
|
||||||
|
assert_eq!(code, 200);
|
||||||
|
assert!(headers.contains("content-type: text/csv; charset=utf-8"));
|
||||||
|
assert!(headers.contains("content-disposition: attachment; filename=\"xexeu-findings-"));
|
||||||
|
assert!(body.starts_with("Endereço IP,Porta,CVE / ID,CVSS,No KEV,Confiança,Título,Descrição"));
|
||||||
|
|
||||||
|
// Changes CSV
|
||||||
|
let (code, headers, body) =
|
||||||
|
http_request(&addr, "GET", "/api/export/changes.csv?since=24h", None);
|
||||||
|
assert_eq!(code, 200);
|
||||||
|
assert!(headers.contains("content-type: text/csv; charset=utf-8"));
|
||||||
|
assert!(headers.contains("content-disposition: attachment; filename=\"xexeu-changes-"));
|
||||||
|
assert!(body.starts_with("Data/Hora (UTC),Tipo de Evento,Alvo / Host,Grupo,Detalhe"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scanner_hot_reload_on_config_file_change() {
|
||||||
|
let workspace = TempDir::new().expect("temporary directory");
|
||||||
|
let config_path = workspace.path().join("xexeu.toml");
|
||||||
|
let sweeps_dir = workspace.path().join("sweeps");
|
||||||
|
let data_dir = workspace.path().join("data");
|
||||||
|
|
||||||
|
fs::write(
|
||||||
|
&config_path,
|
||||||
|
r#"
|
||||||
|
[escopo]
|
||||||
|
autorizado = ["127.0.0.1/32", "10.0.0.0/24"]
|
||||||
|
|
||||||
|
[padrao]
|
||||||
|
cron = "@daily"
|
||||||
|
|
||||||
|
[perfis.padrao]
|
||||||
|
tcp = "80"
|
||||||
|
|
||||||
|
[[grupo]]
|
||||||
|
nome = "primeiro"
|
||||||
|
alvos = ["127.0.0.1/32"]
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.expect("write initial configuration");
|
||||||
|
|
||||||
|
let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu"))
|
||||||
|
.env("XEXEU_SCANNER_TICK_SECS", "1")
|
||||||
|
.args([
|
||||||
|
"scanner",
|
||||||
|
"--config",
|
||||||
|
config_path.to_str().expect("config path"),
|
||||||
|
"--out",
|
||||||
|
sweeps_dir.to_str().expect("sweeps path"),
|
||||||
|
"--data-dir",
|
||||||
|
data_dir.to_str().expect("data dir"),
|
||||||
|
])
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::inherit())
|
||||||
|
.spawn()
|
||||||
|
.expect("spawn xexeu scanner");
|
||||||
|
|
||||||
|
let stdout = child.stdout.take().expect("take stdout");
|
||||||
|
let mut reader = BufReader::new(stdout);
|
||||||
|
let _scanner_guard = ChildGuard(child);
|
||||||
|
|
||||||
|
// Read initial startup line
|
||||||
|
let mut initial_line = String::new();
|
||||||
|
reader
|
||||||
|
.read_line(&mut initial_line)
|
||||||
|
.expect("read initial line");
|
||||||
|
assert!(initial_line.contains("1 grupo(s) configurado(s)"));
|
||||||
|
|
||||||
|
// Sleep briefly so filesystem mtime changes
|
||||||
|
std::thread::sleep(Duration::from_millis(1100));
|
||||||
|
|
||||||
|
// Append second group to config file
|
||||||
|
fs::write(
|
||||||
|
&config_path,
|
||||||
|
r#"
|
||||||
|
[escopo]
|
||||||
|
autorizado = ["127.0.0.1/32", "10.0.0.0/24"]
|
||||||
|
|
||||||
|
[padrao]
|
||||||
|
cron = "@daily"
|
||||||
|
|
||||||
|
[perfis.padrao]
|
||||||
|
tcp = "80"
|
||||||
|
|
||||||
|
[[grupo]]
|
||||||
|
nome = "primeiro"
|
||||||
|
alvos = ["127.0.0.1/32"]
|
||||||
|
|
||||||
|
[[grupo]]
|
||||||
|
nome = "segundo"
|
||||||
|
alvos = ["10.0.0.1/32"]
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.expect("update configuration");
|
||||||
|
|
||||||
|
// Wait for reload log message
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(5);
|
||||||
|
let mut reloaded = false;
|
||||||
|
while Instant::now() < deadline {
|
||||||
|
let mut line = String::new();
|
||||||
|
if reader.read_line(&mut line).is_ok()
|
||||||
|
&& line.contains("configuração recarregada com sucesso (2 grupos)")
|
||||||
|
{
|
||||||
|
reloaded = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
reloaded,
|
||||||
|
"scanner should detect modified config file and reload"
|
||||||
|
);
|
||||||
|
}
|
||||||
+117
-17
@@ -3,7 +3,7 @@
|
|||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
use chrono::{DateTime, TimeZone, Utc};
|
use chrono::{DateTime, TimeZone, Utc};
|
||||||
use serde::Deserialize;
|
use serde::{Deserialize, Serialize};
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
use crate::schedule::{CronSpec, Jitter, ScheduleError};
|
use crate::schedule::{CronSpec, Jitter, ScheduleError};
|
||||||
@@ -15,7 +15,7 @@ pub const MIN_INTERVAL_SECS: i64 = 300;
|
|||||||
const REFERENCE_INSTANT: i64 = 1_700_000_000;
|
const REFERENCE_INSTANT: i64 = 1_700_000_000;
|
||||||
|
|
||||||
/// Root configuration document.
|
/// Root configuration document.
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
pub struct XexeuConfig {
|
pub struct XexeuConfig {
|
||||||
/// Authorized scope shared by every group.
|
/// Authorized scope shared by every group.
|
||||||
#[serde(rename = "escopo")]
|
#[serde(rename = "escopo")]
|
||||||
@@ -32,18 +32,22 @@ pub struct XexeuConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// `[escopo]`: what the operator is allowed to touch.
|
/// `[escopo]`: what the operator is allowed to touch.
|
||||||
#[derive(Debug, Clone, Default, Deserialize)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct ScopeConfig {
|
pub struct ScopeConfig {
|
||||||
/// CIDRs and addresses that bound every expanded target.
|
/// CIDRs and addresses that bound every expanded target.
|
||||||
#[serde(rename = "autorizado", default)]
|
#[serde(rename = "autorizado", default)]
|
||||||
pub authorized: Vec<String>,
|
pub authorized: Vec<String>,
|
||||||
/// Person or team accountable for the authorization.
|
/// Person or team accountable for the authorization.
|
||||||
#[serde(rename = "responsavel", default)]
|
#[serde(
|
||||||
|
rename = "responsavel",
|
||||||
|
default,
|
||||||
|
skip_serializing_if = "Option::is_none"
|
||||||
|
)]
|
||||||
pub responsible: Option<String>,
|
pub responsible: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `[padrao]`: values inherited by groups.
|
/// `[padrao]`: values inherited by groups.
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
pub struct DefaultsConfig {
|
pub struct DefaultsConfig {
|
||||||
/// Cron expression for groups without their own.
|
/// Cron expression for groups without their own.
|
||||||
#[serde(rename = "cron", default = "default_cron")]
|
#[serde(rename = "cron", default = "default_cron")]
|
||||||
@@ -52,16 +56,28 @@ pub struct DefaultsConfig {
|
|||||||
#[serde(rename = "jitter", default = "default_jitter")]
|
#[serde(rename = "jitter", default = "default_jitter")]
|
||||||
pub jitter: String,
|
pub jitter: String,
|
||||||
/// Profile for groups without their own.
|
/// Profile for groups without their own.
|
||||||
#[serde(rename = "perfil", default)]
|
#[serde(rename = "perfil", default, skip_serializing_if = "Option::is_none")]
|
||||||
pub profile: Option<String>,
|
pub profile: Option<String>,
|
||||||
/// Global packet-per-second budget shared by all groups.
|
/// Global packet-per-second budget shared by all groups.
|
||||||
#[serde(rename = "taxa_maxima_pps", default)]
|
#[serde(
|
||||||
|
rename = "taxa_maxima_pps",
|
||||||
|
default,
|
||||||
|
skip_serializing_if = "Option::is_none"
|
||||||
|
)]
|
||||||
pub max_pps: Option<u32>,
|
pub max_pps: Option<u32>,
|
||||||
/// Hosts scanned concurrently.
|
/// Hosts scanned concurrently.
|
||||||
#[serde(rename = "hosts_simultaneos", default)]
|
#[serde(
|
||||||
|
rename = "hosts_simultaneos",
|
||||||
|
default,
|
||||||
|
skip_serializing_if = "Option::is_none"
|
||||||
|
)]
|
||||||
pub simultaneous_hosts: Option<usize>,
|
pub simultaneous_hosts: Option<usize>,
|
||||||
/// Consecutive unanswered scans before a host is considered gone.
|
/// Consecutive unanswered scans before a host is considered gone.
|
||||||
#[serde(rename = "ausencias_para_sumir", default)]
|
#[serde(
|
||||||
|
rename = "ausencias_para_sumir",
|
||||||
|
default,
|
||||||
|
skip_serializing_if = "Option::is_none"
|
||||||
|
)]
|
||||||
pub absences_before_disappear: Option<u32>,
|
pub absences_before_disappear: Option<u32>,
|
||||||
/// Vulnerability feeds synchronization settings.
|
/// Vulnerability feeds synchronization settings.
|
||||||
#[serde(rename = "feeds", default)]
|
#[serde(rename = "feeds", default)]
|
||||||
@@ -69,7 +85,7 @@ pub struct DefaultsConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Vulnerability feeds synchronization settings under `[padrao.feeds]`.
|
/// Vulnerability feeds synchronization settings under `[padrao.feeds]`.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct FeedsConfig {
|
pub struct FeedsConfig {
|
||||||
/// Whether to automatically sync vulnerability feeds periodically in the server.
|
/// Whether to automatically sync vulnerability feeds periodically in the server.
|
||||||
#[serde(rename = "sincronizar_automaticamente", default = "default_false")]
|
#[serde(rename = "sincronizar_automaticamente", default = "default_false")]
|
||||||
@@ -111,13 +127,13 @@ impl Default for DefaultsConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// `[perfis.<nome>]`: how each group is scanned.
|
/// `[perfis.<nome>]`: how each group is scanned.
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct ProfileConfig {
|
pub struct ProfileConfig {
|
||||||
/// TCP port selection, such as `top-1000` or `1-65535`.
|
/// TCP port selection, such as `top-1000` or `1-65535`.
|
||||||
#[serde(rename = "tcp", default = "default_tcp")]
|
#[serde(rename = "tcp", default = "default_tcp")]
|
||||||
pub tcp: String,
|
pub tcp: String,
|
||||||
/// UDP ports to probe.
|
/// UDP ports to probe.
|
||||||
#[serde(rename = "udp", default)]
|
#[serde(rename = "udp", default, skip_serializing_if = "Vec::is_empty")]
|
||||||
pub udp: Vec<String>,
|
pub udp: Vec<String>,
|
||||||
/// Scanner engine, such as `nativo` or `nmap`.
|
/// Scanner engine, such as `nativo` or `nmap`.
|
||||||
#[serde(rename = "motor", default = "default_engine")]
|
#[serde(rename = "motor", default = "default_engine")]
|
||||||
@@ -128,7 +144,7 @@ pub struct ProfileConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// `[[grupo]]`: one set of targets with its own cadence.
|
/// `[[grupo]]`: one set of targets with its own cadence.
|
||||||
#[derive(Debug, Clone, Default, Deserialize)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct GroupConfig {
|
pub struct GroupConfig {
|
||||||
/// Group name, unique in the document.
|
/// Group name, unique in the document.
|
||||||
#[serde(rename = "nome", default)]
|
#[serde(rename = "nome", default)]
|
||||||
@@ -137,16 +153,20 @@ pub struct GroupConfig {
|
|||||||
#[serde(rename = "alvos", default)]
|
#[serde(rename = "alvos", default)]
|
||||||
pub targets: Vec<String>,
|
pub targets: Vec<String>,
|
||||||
/// Ranges subtracted after expansion.
|
/// Ranges subtracted after expansion.
|
||||||
#[serde(rename = "excluir", default)]
|
#[serde(rename = "excluir", default, skip_serializing_if = "Vec::is_empty")]
|
||||||
pub exclude: Vec<String>,
|
pub exclude: Vec<String>,
|
||||||
/// Cron expression overriding the default.
|
/// Cron expression overriding the default.
|
||||||
#[serde(rename = "cron", default)]
|
#[serde(rename = "cron", default, skip_serializing_if = "Option::is_none")]
|
||||||
pub cron: Option<String>,
|
pub cron: Option<String>,
|
||||||
/// Profile overriding the default.
|
/// Profile overriding the default.
|
||||||
#[serde(rename = "perfil", default)]
|
#[serde(rename = "perfil", default, skip_serializing_if = "Option::is_none")]
|
||||||
pub profile: Option<String>,
|
pub profile: Option<String>,
|
||||||
/// Free-form criticality label.
|
/// Free-form criticality label.
|
||||||
#[serde(rename = "criticidade", default)]
|
#[serde(
|
||||||
|
rename = "criticidade",
|
||||||
|
default,
|
||||||
|
skip_serializing_if = "Option::is_none"
|
||||||
|
)]
|
||||||
pub criticality: Option<String>,
|
pub criticality: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -257,6 +277,9 @@ pub enum ConfigError {
|
|||||||
/// Prefix length supplied.
|
/// Prefix length supplied.
|
||||||
prefix: u8,
|
prefix: u8,
|
||||||
},
|
},
|
||||||
|
/// I/O error reading or writing configuration.
|
||||||
|
#[error("erro de E/S na configuração: {0}")]
|
||||||
|
Io(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Result of a successful validation.
|
/// Result of a successful validation.
|
||||||
@@ -300,6 +323,39 @@ impl XexeuConfig {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Serializes the configuration to a pretty TOML string.
|
||||||
|
pub fn to_toml_string(&self) -> Result<String, ConfigError> {
|
||||||
|
toml::to_string_pretty(self).map_err(|error| ConfigError::Toml {
|
||||||
|
reason: error.to_string(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Saves the configuration to a file atomically via a temporary file in the same directory.
|
||||||
|
pub fn save_to_file(&self, path: &std::path::Path) -> Result<(), ConfigError> {
|
||||||
|
use std::io::Write;
|
||||||
|
let content = self.to_toml_string()?;
|
||||||
|
let parent = path.parent().unwrap_or_else(|| std::path::Path::new("."));
|
||||||
|
let mut temp = tempfile::NamedTempFile::new_in(parent).map_err(|err| {
|
||||||
|
ConfigError::Io(format!(
|
||||||
|
"não foi possível criar arquivo temporário em {}: {err}",
|
||||||
|
parent.display()
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
temp.write_all(content.as_bytes()).map_err(|err| {
|
||||||
|
ConfigError::Io(format!("erro escrevendo configuração temporária: {err}"))
|
||||||
|
})?;
|
||||||
|
temp.flush().map_err(|err| {
|
||||||
|
ConfigError::Io(format!("erro descarregando configuração temporária: {err}"))
|
||||||
|
})?;
|
||||||
|
temp.persist(path).map_err(|err| {
|
||||||
|
ConfigError::Io(format!(
|
||||||
|
"não foi possível substituir {} atomicamente: {err}",
|
||||||
|
path.display()
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Parses and validates the document.
|
/// Parses and validates the document.
|
||||||
pub fn load_validated(raw: &str) -> Result<(Self, ValidationReport), ConfigError> {
|
pub fn load_validated(raw: &str) -> Result<(Self, ValidationReport), ConfigError> {
|
||||||
let config = Self::from_toml_str(raw)?;
|
let config = Self::from_toml_str(raw)?;
|
||||||
@@ -731,4 +787,48 @@ alvos = ["10.0.0.0/24"]
|
|||||||
let (_, report) = XexeuConfig::load_validated(&raw).expect("config is valid");
|
let (_, report) = XexeuConfig::load_validated(&raw).expect("config is valid");
|
||||||
assert_eq!(report.groups[0].addresses, 128);
|
assert_eq!(report.groups[0].addresses, 128);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn toml_serialization_and_save_roundtrips() {
|
||||||
|
let raw = r#"[escopo]
|
||||||
|
autorizado = ["10.0.0.0/16", "192.168.1.0/24"]
|
||||||
|
responsavel = "SecOps Team"
|
||||||
|
|
||||||
|
[padrao]
|
||||||
|
cron = "@daily"
|
||||||
|
jitter = "10%"
|
||||||
|
taxa_maxima_pps = 500
|
||||||
|
|
||||||
|
[padrao.feeds]
|
||||||
|
sincronizar_automaticamente = true
|
||||||
|
intervalo_sincronizacao = "12h"
|
||||||
|
|
||||||
|
[perfis.padrao]
|
||||||
|
tcp = "top-100"
|
||||||
|
motor = "nativo"
|
||||||
|
vulnerabilidades = true
|
||||||
|
|
||||||
|
[[grupo]]
|
||||||
|
nome = "dmz"
|
||||||
|
alvos = ["10.0.1.0/24"]
|
||||||
|
excluir = ["10.0.1.1"]
|
||||||
|
cron = "0 2 * * *"
|
||||||
|
criticidade = "alta"
|
||||||
|
"#;
|
||||||
|
let (config, _) = XexeuConfig::load_validated(raw).expect("config parses and validates");
|
||||||
|
let toml_str = config.to_toml_string().expect("serializes to toml");
|
||||||
|
let (reloaded, _) =
|
||||||
|
XexeuConfig::load_validated(&toml_str).expect("reloaded config is valid");
|
||||||
|
assert_eq!(config, reloaded);
|
||||||
|
|
||||||
|
let temp_dir = tempfile::tempdir().expect("tempdir");
|
||||||
|
let file_path = temp_dir.path().join("xexeu.toml");
|
||||||
|
config
|
||||||
|
.save_to_file(&file_path)
|
||||||
|
.expect("save_to_file succeeds");
|
||||||
|
let file_content = std::fs::read_to_string(&file_path).expect("read file");
|
||||||
|
let (from_disk, _) =
|
||||||
|
XexeuConfig::load_validated(&file_content).expect("from disk validates");
|
||||||
|
assert_eq!(config, from_disk);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user