feat!: release v2 (#6545)
Co-authored-by: Artur <145776561+arturict@users.noreply.github.com> Co-authored-by: arturict <arturict@users.noreply.github.com> Co-authored-by: Thomas <thomas@ajnart.fr> Co-authored-by: Afonso Jorge Ramos <afonsojorgeramos@gmail.com> Co-authored-by: Danura30082 <danura30082+github@gmail.com> Co-authored-by: Kushie <122986913+kushiemoon-dev@users.noreply.github.com> Co-authored-by: ajnart <thomas@ajnart.fr> Co-authored-by: ajnart <thomas@ajnart.dev> Co-authored-by: chenjun <chenjun@foxmail.com> Co-authored-by: Wikibear <wikibear@users.noreply.github.com> Co-authored-by: Bergasha <bergasha@gmail.com> Co-authored-by: leafyelin <43306196+leafyelin@users.noreply.github.com> Co-authored-by: Lucas Araujo <lucas.lra@gmail.com> Co-authored-by: GreenMonito <86085570+GreenMonito@users.noreply.github.com> Co-authored-by: Nerdy-Technician <roffo@nerdy-technician.social> Co-authored-by: Jun <34545896+jcstrong@users.noreply.github.com> Co-authored-by: Edmond Abraham <54119952+gitedmond@users.noreply.github.com> Co-authored-by: thrawnx <tight.bulb9384@fastmail.com> Co-authored-by: Chris <58918656+nordada@users.noreply.github.com> Co-authored-by: yi111 <153097222+Yi-111-a@users.noreply.github.com> Co-authored-by: Yanis <naamaneyanis@gmail.com> Co-authored-by: Wikibear <me@sej.de> Co-authored-by: alessiottavo <93441886+alessiottavo@users.noreply.github.com>
This commit is contained in:
3286 files changed
+284386
-139176
No files matched your search
@@ -0,0 +1,91 @@
|
||||
import { matchErrorCode, ResponseError } from "@homarr/common/server";
|
||||
|
||||
import type { WazuhDataSource } from "./wazuh-types";
|
||||
|
||||
export type WazuhErrorReason =
|
||||
| "unauthorized"
|
||||
| "certificate"
|
||||
| "unreachable"
|
||||
| "timeout"
|
||||
| "status"
|
||||
| "invalidResponse"
|
||||
| "indexerRequired"
|
||||
| "unknown";
|
||||
|
||||
export interface WazuhPublicError {
|
||||
reason: WazuhErrorReason;
|
||||
target: WazuhDataSource | null;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Error thrown by the Wazuh client with a safe, user-presentable reason.
|
||||
* It never carries credentials or upstream payloads.
|
||||
*/
|
||||
export class WazuhRequestError extends Error {
|
||||
constructor(
|
||||
public readonly target: WazuhDataSource | null,
|
||||
public readonly reason: WazuhErrorReason,
|
||||
public readonly status?: number,
|
||||
options?: ErrorOptions,
|
||||
) {
|
||||
super(`Wazuh ${target ?? "integration"} request failed: ${reason}${status ? ` (${status})` : ""}`, options);
|
||||
this.name = "WazuhRequestError";
|
||||
}
|
||||
|
||||
static fromResponse(target: WazuhDataSource, response: { status: number; url?: string }) {
|
||||
const reason = response.status === 401 || response.status === 403 ? "unauthorized" : "status";
|
||||
return new WazuhRequestError(target, reason, response.status, { cause: new ResponseError(response) });
|
||||
}
|
||||
|
||||
static fromFetchError(target: WazuhDataSource, error: unknown) {
|
||||
if (error instanceof WazuhRequestError) return error;
|
||||
return new WazuhRequestError(target, reasonFromUnknown(error), undefined, { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
const reasonFromCode = (code: string): WazuhErrorReason | null => {
|
||||
const match = matchErrorCode(code);
|
||||
if (!match) return null;
|
||||
if (match.type === "certificate") return "certificate";
|
||||
if (match.type === "timeout") return "timeout";
|
||||
return "unreachable";
|
||||
};
|
||||
|
||||
const reasonFromUnknown = (error: unknown): WazuhErrorReason => {
|
||||
let current: unknown = error;
|
||||
for (let depth = 0; depth < 6 && current; depth++) {
|
||||
if (current instanceof Error && current.name === "TimeoutError") return "timeout";
|
||||
if (current instanceof Error && current.name === "AbortError") return "timeout";
|
||||
if (typeof current === "object" && "code" in current && typeof current.code === "string") {
|
||||
const reason = reasonFromCode(current.code);
|
||||
if (reason) return reason;
|
||||
if (current.code === "UND_ERR_CONNECT_TIMEOUT") return "timeout";
|
||||
if (current.code.startsWith("ERR_TLS") || current.code.includes("CERT")) return "certificate";
|
||||
}
|
||||
current = current instanceof Error ? current.cause : undefined;
|
||||
}
|
||||
return "unknown";
|
||||
};
|
||||
|
||||
/**
|
||||
* Maps any error thrown by the Wazuh integration (possibly wrapped by the integration error decorator)
|
||||
* to a safe reason that widgets can translate.
|
||||
*/
|
||||
export const toWazuhPublicError = (error: unknown): WazuhPublicError => {
|
||||
let current: unknown = error;
|
||||
for (let depth = 0; depth < 8 && current; depth++) {
|
||||
if (current instanceof WazuhRequestError) {
|
||||
return { reason: current.reason, target: current.target, status: current.status };
|
||||
}
|
||||
if (current instanceof ResponseError) {
|
||||
return {
|
||||
reason: current.statusCode === 401 || current.statusCode === 403 ? "unauthorized" : "status",
|
||||
target: null,
|
||||
status: current.statusCode,
|
||||
};
|
||||
}
|
||||
current = current instanceof Error ? current.cause : undefined;
|
||||
}
|
||||
return { reason: reasonFromUnknown(error), target: null };
|
||||
};
|
||||
@@ -0,0 +1,938 @@
|
||||
import { removeTrailingSlash } from "@homarr/common";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
|
||||
import type { fetch as undiciFetch } from "undici";
|
||||
|
||||
import type { IntegrationInput, IntegrationTestingInput } from "../base/integration";
|
||||
import { Integration } from "../base/integration";
|
||||
import type { SessionStore } from "../base/session-store";
|
||||
import { createSessionStore } from "../base/session-store";
|
||||
import { TestConnectionError } from "../base/test-connection/test-connection-error";
|
||||
import type { TestingResult } from "../base/test-connection/test-connection-service";
|
||||
import type { IntegrationHttpAuthentication } from "../http-auth";
|
||||
import { WazuhRequestError } from "./wazuh-errors";
|
||||
import type { KeyedBucket, SeverityRangeResult } from "./wazuh-queries";
|
||||
import {
|
||||
alertSourceFields,
|
||||
authFailureQuery,
|
||||
bruteForceQuery,
|
||||
getTotalHits,
|
||||
mapAlertHit,
|
||||
normalizeAgentStatus,
|
||||
normalizeGroups,
|
||||
normalizeVersion,
|
||||
resolveTimelineIntervalMs,
|
||||
severityRangeAggregation,
|
||||
timeRangeMs,
|
||||
toSeverityCounts,
|
||||
} from "./wazuh-queries";
|
||||
import type {
|
||||
WazuhAgent,
|
||||
WazuhAgentCounts,
|
||||
WazuhAgentsOverview,
|
||||
WazuhAlert,
|
||||
WazuhAlertTimeline,
|
||||
WazuhApiAgent,
|
||||
WazuhApiAgentsSummaryStatus,
|
||||
WazuhApiItems,
|
||||
WazuhApiResponse,
|
||||
WazuhAuthFailures,
|
||||
WazuhCveOrder,
|
||||
WazuhDataSource,
|
||||
WazuhFimEvent,
|
||||
WazuhFimEventFilter,
|
||||
WazuhFimOverview,
|
||||
WazuhIndexerAlertSource,
|
||||
WazuhIndexerMonitoringSource,
|
||||
WazuhIndexerSearchResponse,
|
||||
WazuhSecuritySummary,
|
||||
WazuhTimelineInterval,
|
||||
WazuhTimeRange,
|
||||
WazuhTopList,
|
||||
WazuhTopListEntry,
|
||||
WazuhTopListKind,
|
||||
WazuhVulnerabilityCounts,
|
||||
WazuhVulnerabilityOverview,
|
||||
} from "./wazuh-types";
|
||||
|
||||
const logger = createLogger({ module: "wazuhIntegration" });
|
||||
|
||||
const REQUEST_TIMEOUT_MS = 15_000;
|
||||
/** The Wazuh API issues 900 second tokens by default; refresh well before that. */
|
||||
const TOKEN_TTL_SECONDS = 600;
|
||||
/** Agent snapshots in wazuh-monitoring-* are written as one batch that spans a few milliseconds. */
|
||||
const MONITORING_SNAPSHOT_WINDOW_MS = 5 * 60 * 1000;
|
||||
/** Upper bound for agent lists; larger fleets should use the Wazuh dashboard. */
|
||||
const MAX_AGENTS = 1000;
|
||||
|
||||
interface WazuhSession {
|
||||
token: string;
|
||||
}
|
||||
|
||||
type FetchLike = typeof undiciFetch;
|
||||
|
||||
interface WazuhEndpoints {
|
||||
api: { url: string; username: string; password: string } | null;
|
||||
indexer: { url: string; username: string; password: string } | null;
|
||||
}
|
||||
|
||||
const findWazuhRequestError = (error: unknown): WazuhRequestError | null => {
|
||||
let current: unknown = error;
|
||||
for (let depth = 0; depth < 8 && current; depth++) {
|
||||
if (current instanceof WazuhRequestError) return current;
|
||||
current = current instanceof Error ? current.cause : undefined;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const basicAuth = (username: string, password: string) =>
|
||||
`Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
|
||||
|
||||
export class WazuhIntegration extends Integration {
|
||||
private readonly sessionStore: SessionStore<WazuhSession>;
|
||||
|
||||
constructor(integration: IntegrationInput) {
|
||||
super(integration);
|
||||
this.sessionStore = createSessionStore(integration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Credential alternatives:
|
||||
* - username + password: the integration URL is the Wazuh server API (default port 55000).
|
||||
* - username + password + indexer URL/credentials: server API plus the indexer for alerts.
|
||||
* - indexer username + password only: the integration URL is the Wazuh indexer (default port 9200).
|
||||
*/
|
||||
private getEndpoints(): WazuhEndpoints {
|
||||
const hasApi = this.hasSecretValue("username") && this.hasSecretValue("password");
|
||||
const hasIndexerCredentials =
|
||||
this.hasSecretValue("wazuhIndexerUsername") && this.hasSecretValue("wazuhIndexerPassword");
|
||||
|
||||
const api = hasApi
|
||||
? {
|
||||
url: removeTrailingSlash(this.integration.url),
|
||||
username: this.getSecretValue("username"),
|
||||
password: this.getSecretValue("password"),
|
||||
}
|
||||
: null;
|
||||
|
||||
let indexerUrl: string | null = null;
|
||||
if (hasIndexerCredentials) {
|
||||
if (this.hasSecretValue("wazuhIndexerUrl")) indexerUrl = this.getSecretValue("wazuhIndexerUrl");
|
||||
else if (!hasApi) indexerUrl = this.integration.url;
|
||||
}
|
||||
|
||||
const indexer =
|
||||
indexerUrl !== null
|
||||
? {
|
||||
url: removeTrailingSlash(indexerUrl),
|
||||
username: this.getSecretValue("wazuhIndexerUsername"),
|
||||
password: this.getSecretValue("wazuhIndexerPassword"),
|
||||
}
|
||||
: null;
|
||||
|
||||
return { api, indexer };
|
||||
}
|
||||
|
||||
public get hasIndexer() {
|
||||
return this.getEndpoints().indexer !== null;
|
||||
}
|
||||
|
||||
public override async getHttpAuthenticationAsync(): Promise<IntegrationHttpAuthentication> {
|
||||
const { api, indexer } = this.getEndpoints();
|
||||
if (api) {
|
||||
const token = await this.getApiTokenAsync();
|
||||
return { headers: { Authorization: `Bearer ${token}` }, redactValues: [token] };
|
||||
}
|
||||
if (indexer) {
|
||||
const header = basicAuth(indexer.username, indexer.password);
|
||||
return { headers: { Authorization: header }, redactValues: [header, indexer.password] };
|
||||
}
|
||||
throw new Error("Wazuh integration has no usable credentials");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Low level requests
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
private async requestAsync(
|
||||
target: WazuhDataSource,
|
||||
url: string,
|
||||
init: { method?: string; headers?: Record<string, string>; body?: string },
|
||||
fetchAsync?: FetchLike,
|
||||
) {
|
||||
const start = performance.now();
|
||||
try {
|
||||
const response = fetchAsync
|
||||
? await fetchAsync(url, {
|
||||
...init,
|
||||
redirect: "error",
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
})
|
||||
: await fetchWithTrustedCertificatesAsync(url, { ...init, redirect: "error", timeout: REQUEST_TIMEOUT_MS });
|
||||
logger.debug("Wazuh response", {
|
||||
integrationId: this.integration.id,
|
||||
target,
|
||||
path: new URL(url).pathname,
|
||||
status: response.status,
|
||||
durationMs: Math.round(performance.now() - start),
|
||||
});
|
||||
return response;
|
||||
} catch (error) {
|
||||
throw WazuhRequestError.fromFetchError(target, error);
|
||||
}
|
||||
}
|
||||
|
||||
private async authenticateApiAsync(fetchAsync?: FetchLike): Promise<string> {
|
||||
const { api } = this.getEndpoints();
|
||||
if (!api) throw new WazuhRequestError("api", "unauthorized");
|
||||
|
||||
const response = await this.requestAsync(
|
||||
"api",
|
||||
`${api.url}/security/user/authenticate?raw=true`,
|
||||
{ method: "POST", headers: { Authorization: basicAuth(api.username, api.password) } },
|
||||
fetchAsync,
|
||||
);
|
||||
if (!response.ok) throw WazuhRequestError.fromResponse("api", response);
|
||||
|
||||
const token = (await response.text()).trim();
|
||||
if (!token || token.startsWith("{")) throw new WazuhRequestError("api", "invalidResponse");
|
||||
return token;
|
||||
}
|
||||
|
||||
private async getApiTokenAsync(): Promise<string> {
|
||||
const existing = await this.sessionStore.getAsync();
|
||||
if (existing) return existing.token;
|
||||
|
||||
const token = await this.authenticateApiAsync();
|
||||
await this.sessionStore.setAsync({ token }, { ttlSeconds: TOKEN_TTL_SECONDS });
|
||||
return token;
|
||||
}
|
||||
|
||||
private async apiGetAsync<TData>(path: `/${string}`, query?: Record<string, string | number>): Promise<TData> {
|
||||
const { api } = this.getEndpoints();
|
||||
if (!api) throw new WazuhRequestError("api", "unauthorized");
|
||||
|
||||
const url = new URL(`${api.url}${path}`);
|
||||
for (const [key, value] of Object.entries(query ?? {})) url.searchParams.set(key, String(value));
|
||||
|
||||
const doRequest = async (token: string) =>
|
||||
await this.requestAsync("api", url.toString(), { headers: { Authorization: `Bearer ${token}` } });
|
||||
|
||||
let response = await doRequest(await this.getApiTokenAsync());
|
||||
if (response.status === 401) {
|
||||
await this.sessionStore.clearAsync();
|
||||
response = await doRequest(await this.getApiTokenAsync());
|
||||
}
|
||||
if (!response.ok) throw WazuhRequestError.fromResponse("api", response);
|
||||
|
||||
const body = (await response.json()) as WazuhApiResponse<TData>;
|
||||
if (typeof body !== "object" || !("data" in body)) throw new WazuhRequestError("api", "invalidResponse");
|
||||
return body.data;
|
||||
}
|
||||
|
||||
private async indexerSearchAsync<TSource, TAggregations = undefined>(
|
||||
indexPattern: string,
|
||||
query: Record<string, unknown>,
|
||||
fetchAsync?: FetchLike,
|
||||
): Promise<WazuhIndexerSearchResponse<TSource, TAggregations>> {
|
||||
const { indexer } = this.getEndpoints();
|
||||
if (!indexer) throw new WazuhRequestError("indexer", "indexerRequired");
|
||||
|
||||
const response = await this.requestAsync(
|
||||
"indexer",
|
||||
`${indexer.url}/${indexPattern}/_search?ignore_unavailable=true&allow_no_indices=true`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: basicAuth(indexer.username, indexer.password),
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(query),
|
||||
},
|
||||
fetchAsync,
|
||||
);
|
||||
if (!response.ok) throw WazuhRequestError.fromResponse("indexer", response);
|
||||
return (await response.json()) as WazuhIndexerSearchResponse<TSource, TAggregations>;
|
||||
}
|
||||
|
||||
private async indexerGetAsync<TData>(path: `/${string}`): Promise<TData> {
|
||||
const { indexer } = this.getEndpoints();
|
||||
if (!indexer) throw new WazuhRequestError("indexer", "indexerRequired");
|
||||
const response = await this.requestAsync("indexer", `${indexer.url}${path}`, {
|
||||
headers: { Authorization: basicAuth(indexer.username, indexer.password) },
|
||||
});
|
||||
if (!response.ok) throw WazuhRequestError.fromResponse("indexer", response);
|
||||
return (await response.json()) as TData;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Dashboard links
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Base URL of the Wazuh dashboard used for deep links. Prefers the optional "Dashboard URL" field and falls back
|
||||
* to the linked app, as long as that app does not simply point at the API/indexer URL.
|
||||
*/
|
||||
public getDashboardUrl(): string | null {
|
||||
if (this.hasSecretValue("wazuhDashboardUrl")) {
|
||||
return removeTrailingSlash(this.getSecretValue("wazuhDashboardUrl"));
|
||||
}
|
||||
const external = this.integration.externalUrl;
|
||||
if (external && removeTrailingSlash(external) !== removeTrailingSlash(this.integration.url)) {
|
||||
return removeTrailingSlash(external);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Agents
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
public async getAgentsOverviewAsync(): Promise<WazuhAgentsOverview> {
|
||||
const { api } = this.getEndpoints();
|
||||
if (api) return await this.getAgentsOverviewFromApiAsync();
|
||||
return await this.getAgentsOverviewFromIndexerAsync();
|
||||
}
|
||||
|
||||
private async getAgentsOverviewFromApiAsync(): Promise<WazuhAgentsOverview> {
|
||||
const [summary, agents] = await Promise.all([
|
||||
this.apiGetAsync<WazuhApiAgentsSummaryStatus>("/agents/summary/status"),
|
||||
this.apiGetAsync<WazuhApiItems<WazuhApiAgent>>("/agents", {
|
||||
select: "id,name,ip,status,version,lastKeepAlive,group,os.name,os.version,os.platform",
|
||||
sort: "+name",
|
||||
limit: MAX_AGENTS,
|
||||
}),
|
||||
]);
|
||||
|
||||
const connection = summary.connection ?? {};
|
||||
const counts: WazuhAgentCounts = {
|
||||
active: connection.active ?? 0,
|
||||
disconnected: connection.disconnected ?? 0,
|
||||
neverConnected: connection.never_connected ?? 0,
|
||||
pending: connection.pending ?? 0,
|
||||
total: connection.total ?? 0,
|
||||
};
|
||||
|
||||
return {
|
||||
source: "api",
|
||||
asOf: new Date().toISOString(),
|
||||
counts,
|
||||
agents: agents.affected_items
|
||||
// Agent 000 is the manager itself; the Wazuh dashboard hides it from the agent list as well.
|
||||
.filter((agent) => agent.id !== "000")
|
||||
.map((agent) => ({
|
||||
id: agent.id,
|
||||
name: agent.name ?? agent.id,
|
||||
status: normalizeAgentStatus(agent.status),
|
||||
ip: agent.ip ?? null,
|
||||
osName: agent.os?.name ?? null,
|
||||
osVersion: agent.os?.version ?? null,
|
||||
osPlatform: agent.os?.platform?.toLowerCase() ?? null,
|
||||
version: normalizeVersion(agent.version),
|
||||
lastKeepAlive: agent.lastKeepAlive ?? null,
|
||||
groups: normalizeGroups(agent.group),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
private async getAgentsOverviewFromIndexerAsync(): Promise<WazuhAgentsOverview> {
|
||||
const latest = await this.indexerSearchAsync<never, { latest: { value: number | null } }>("wazuh-monitoring-*", {
|
||||
size: 0,
|
||||
aggs: { latest: { max: { field: "timestamp" } } },
|
||||
});
|
||||
const latestTimestamp = latest.aggregations?.latest.value;
|
||||
const counts: WazuhAgentCounts = { total: 0, active: 0, disconnected: 0, neverConnected: 0, pending: 0 };
|
||||
if (!latestTimestamp) {
|
||||
return { source: "indexer", asOf: new Date().toISOString(), counts, agents: [] };
|
||||
}
|
||||
|
||||
const snapshot = await this.indexerSearchAsync<WazuhIndexerMonitoringSource>("wazuh-monitoring-*", {
|
||||
size: MAX_AGENTS,
|
||||
sort: [{ timestamp: { order: "desc" } }],
|
||||
_source: ["id", "name", "ip", "status", "version", "lastKeepAlive", "timestamp", "group", "os"],
|
||||
query: {
|
||||
range: {
|
||||
timestamp: {
|
||||
gte: new Date(latestTimestamp - MONITORING_SNAPSHOT_WINDOW_MS).toISOString(),
|
||||
lte: new Date(latestTimestamp).toISOString(),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Keep the newest document per agent in case the window overlaps two snapshots.
|
||||
const agents = new Map<string, WazuhAgent>();
|
||||
for (const hit of snapshot.hits.hits) {
|
||||
const source = hit._source;
|
||||
const id = source.id;
|
||||
if (!id || id === "000" || agents.has(id)) continue;
|
||||
agents.set(id, {
|
||||
id,
|
||||
name: source.name ?? id,
|
||||
status: normalizeAgentStatus(source.status),
|
||||
ip: source.ip ?? null,
|
||||
osName: source.os?.name ?? null,
|
||||
osVersion: source.os?.version ?? null,
|
||||
osPlatform: source.os?.platform?.toLowerCase() ?? null,
|
||||
version: normalizeVersion(source.version),
|
||||
lastKeepAlive: source.lastKeepAlive ?? null,
|
||||
groups: normalizeGroups(source.group),
|
||||
});
|
||||
}
|
||||
|
||||
for (const agent of agents.values()) {
|
||||
counts.total++;
|
||||
if (agent.status === "active") counts.active++;
|
||||
else if (agent.status === "disconnected") counts.disconnected++;
|
||||
else if (agent.status === "never_connected") counts.neverConnected++;
|
||||
else if (agent.status === "pending") counts.pending++;
|
||||
}
|
||||
|
||||
return {
|
||||
source: "indexer",
|
||||
asOf: new Date(latestTimestamp).toISOString(),
|
||||
counts,
|
||||
agents: [...agents.values()].toSorted((left, right) => left.name.localeCompare(right.name)),
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Alerts (indexer only, the server API has no alert search)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
public async getRecentAlertsAsync(input: { minLevel: number; limit: number; hours: number }): Promise<WazuhAlert[]> {
|
||||
const response = await this.indexerSearchAsync<WazuhIndexerAlertSource>("wazuh-alerts-*", {
|
||||
size: input.limit,
|
||||
sort: [{ timestamp: { order: "desc" } }],
|
||||
_source: alertSourceFields,
|
||||
query: {
|
||||
bool: {
|
||||
filter: [
|
||||
{ range: { "rule.level": { gte: input.minLevel } } },
|
||||
{ range: { timestamp: { gte: `now-${input.hours}h` } } },
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return response.hits.hits.map(mapAlertHit);
|
||||
}
|
||||
|
||||
public async getAlertTimelineAsync(input: {
|
||||
range: WazuhTimeRange;
|
||||
interval: WazuhTimelineInterval;
|
||||
minLevel: number;
|
||||
}): Promise<WazuhAlertTimeline> {
|
||||
const intervalMs = resolveTimelineIntervalMs(input.range, input.interval);
|
||||
const now = Date.now();
|
||||
// Query exactly the selected window (so totals match the summary widget) but align the buckets to the
|
||||
// interval so they stay stable across refreshes. The first and last buckets can therefore be partial.
|
||||
const windowStart = now - timeRangeMs[input.range];
|
||||
const end = Math.ceil(now / intervalMs) * intervalMs;
|
||||
const start = Math.floor(windowStart / intervalMs) * intervalMs;
|
||||
|
||||
const response = await this.indexerSearchAsync<
|
||||
never,
|
||||
{
|
||||
timeline: { buckets: (KeyedBucket<number> & { severity: SeverityRangeResult })[] };
|
||||
severity: SeverityRangeResult;
|
||||
}
|
||||
>("wazuh-alerts-*", {
|
||||
size: 0,
|
||||
track_total_hits: true,
|
||||
query: {
|
||||
bool: {
|
||||
filter: [
|
||||
{ range: { timestamp: { gte: windowStart, lte: now, format: "epoch_millis" } } },
|
||||
...(input.minLevel > 0 ? [{ range: { "rule.level": { gte: input.minLevel } } }] : []),
|
||||
],
|
||||
},
|
||||
},
|
||||
aggs: {
|
||||
timeline: {
|
||||
date_histogram: {
|
||||
field: "timestamp",
|
||||
fixed_interval: `${Math.round(intervalMs / 1000)}s`,
|
||||
min_doc_count: 0,
|
||||
extended_bounds: { min: start, max: end - intervalMs },
|
||||
},
|
||||
aggs: { severity: severityRangeAggregation },
|
||||
},
|
||||
severity: severityRangeAggregation,
|
||||
},
|
||||
});
|
||||
|
||||
const buckets = response.aggregations?.timeline.buckets ?? [];
|
||||
return {
|
||||
range: input.range,
|
||||
intervalMs,
|
||||
totals: toSeverityCounts(response.aggregations?.severity, getTotalHits(response.hits.total)),
|
||||
points: buckets.map((bucket) => {
|
||||
const counts = toSeverityCounts(bucket.severity, bucket.doc_count);
|
||||
return {
|
||||
timestamp: bucket.key,
|
||||
low: counts.low,
|
||||
medium: counts.medium,
|
||||
high: counts.high,
|
||||
critical: counts.critical,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
public async getTopListAsync(input: {
|
||||
kind: WazuhTopListKind;
|
||||
range: WazuhTimeRange;
|
||||
limit: number;
|
||||
minLevel: number;
|
||||
}): Promise<WazuhTopList> {
|
||||
const fields: Record<WazuhTopListKind, string> = {
|
||||
rules: "rule.id",
|
||||
agents: "agent.name",
|
||||
sourceIps: "data.srcip",
|
||||
mitreTactics: "rule.mitre.tactic",
|
||||
mitreTechniques: "rule.mitre.technique",
|
||||
};
|
||||
const field = fields[input.kind];
|
||||
|
||||
const subAggregations: Record<string, unknown> = {
|
||||
maxLevel: { max: { field: "rule.level" } },
|
||||
agents: { cardinality: { field: "agent.id" } },
|
||||
};
|
||||
if (input.kind === "rules") subAggregations.label = { terms: { field: "rule.description", size: 1 } };
|
||||
if (input.kind === "agents") subAggregations.detail = { terms: { field: "agent.id", size: 1 } };
|
||||
if (input.kind === "mitreTechniques") subAggregations.detail = { terms: { field: "rule.mitre.id", size: 6 } };
|
||||
|
||||
type TopBucket = KeyedBucket & {
|
||||
maxLevel: { value: number | null };
|
||||
agents: { value: number };
|
||||
label?: { buckets: KeyedBucket[] };
|
||||
detail?: { buckets: KeyedBucket[] };
|
||||
};
|
||||
|
||||
const response = await this.indexerSearchAsync<
|
||||
never,
|
||||
{ top: { buckets: TopBucket[]; sum_other_doc_count: number }; withField: { doc_count: number } }
|
||||
>("wazuh-alerts-*", {
|
||||
size: 0,
|
||||
track_total_hits: true,
|
||||
query: {
|
||||
bool: {
|
||||
filter: [
|
||||
{ range: { timestamp: { gte: `now-${input.range}` } } },
|
||||
...(input.minLevel > 0 ? [{ range: { "rule.level": { gte: input.minLevel } } }] : []),
|
||||
],
|
||||
},
|
||||
},
|
||||
aggs: {
|
||||
top: { terms: { field, size: input.limit }, aggs: subAggregations },
|
||||
withField: { filter: { exists: { field } } },
|
||||
},
|
||||
});
|
||||
|
||||
const buckets = response.aggregations?.top.buckets ?? [];
|
||||
const entries = buckets.map((bucket): WazuhTopListEntry => {
|
||||
let label = bucket.key;
|
||||
let detail: string | null = null;
|
||||
if (input.kind === "rules") {
|
||||
label = bucket.label?.buckets[0]?.key ?? bucket.key;
|
||||
detail = bucket.key;
|
||||
} else if (input.kind === "agents") {
|
||||
detail = bucket.detail?.buckets[0]?.key ?? null;
|
||||
} else if (input.kind === "mitreTechniques") {
|
||||
// Technique names and ids are parallel arrays; the id that always co-occurs with the name belongs to it.
|
||||
detail = bucket.detail?.buckets.find((candidate) => candidate.doc_count === bucket.doc_count)?.key ?? null;
|
||||
}
|
||||
return {
|
||||
key: bucket.key,
|
||||
label,
|
||||
detail,
|
||||
count: bucket.doc_count,
|
||||
maxLevel: bucket.maxLevel.value,
|
||||
agents: input.kind === "agents" ? null : bucket.agents.value,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
kind: input.kind,
|
||||
range: input.range,
|
||||
total: response.aggregations?.withField.doc_count ?? getTotalHits(response.hits.total),
|
||||
others: response.aggregations?.top.sum_other_doc_count ?? 0,
|
||||
entries,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Security summary (severity breakdown with trend)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
public async getSecuritySummaryAsync(input: { range: WazuhTimeRange }): Promise<WazuhSecuritySummary> {
|
||||
const { api, indexer } = this.getEndpoints();
|
||||
|
||||
const [periods, managerVersion, indexerHealth] = await Promise.all([
|
||||
indexer ? this.getAlertPeriodsAsync(input.range) : Promise.resolve(null),
|
||||
api
|
||||
? this.apiGetAsync<WazuhApiItems<{ version?: string }>>("/manager/info")
|
||||
.then((data) => data.affected_items[0]?.version ?? null)
|
||||
.catch((error: unknown) => {
|
||||
logger.warn("Failed to read Wazuh manager info", {
|
||||
integrationId: this.integration.id,
|
||||
error: String(error),
|
||||
});
|
||||
return null;
|
||||
})
|
||||
: Promise.resolve(null),
|
||||
indexer
|
||||
? this.indexerGetAsync<{ status?: "green" | "yellow" | "red" }>("/_cluster/health")
|
||||
.then((data) => data.status ?? null)
|
||||
// Restricted indexer users may not read cluster health; that must not break the widget.
|
||||
.catch(() => null)
|
||||
: Promise.resolve(null),
|
||||
]);
|
||||
|
||||
if (!indexer && !api) throw new WazuhRequestError(null, "unauthorized");
|
||||
if (!indexer && managerVersion === null) throw new WazuhRequestError("indexer", "indexerRequired");
|
||||
|
||||
return {
|
||||
range: input.range,
|
||||
alerts: periods?.current ?? null,
|
||||
previousAlerts: periods?.previous ?? null,
|
||||
maxLevel: periods?.maxLevel ?? null,
|
||||
managerVersion,
|
||||
indexerHealth,
|
||||
};
|
||||
}
|
||||
|
||||
private async getAlertPeriodsAsync(range: WazuhTimeRange) {
|
||||
const duration = timeRangeMs[range];
|
||||
const now = Date.now();
|
||||
type PeriodBucket = KeyedBucket & { severity: SeverityRangeResult; maxLevel: { value: number | null } };
|
||||
const response = await this.indexerSearchAsync<never, { periods: { buckets: PeriodBucket[] } }>("wazuh-alerts-*", {
|
||||
size: 0,
|
||||
query: { range: { timestamp: { gte: now - 2 * duration, lt: now, format: "epoch_millis" } } },
|
||||
aggs: {
|
||||
periods: {
|
||||
date_range: {
|
||||
field: "timestamp",
|
||||
format: "epoch_millis",
|
||||
keyed: false,
|
||||
ranges: [
|
||||
{ key: "previous", from: now - 2 * duration, to: now - duration },
|
||||
{ key: "current", from: now - duration, to: now },
|
||||
],
|
||||
},
|
||||
aggs: { severity: severityRangeAggregation, maxLevel: { max: { field: "rule.level" } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const find = (key: string) => response.aggregations?.periods.buckets.find((bucket) => bucket.key === key);
|
||||
const current = find("current");
|
||||
const previous = find("previous");
|
||||
return {
|
||||
current: toSeverityCounts(current?.severity, current?.doc_count ?? 0),
|
||||
previous: toSeverityCounts(previous?.severity, previous?.doc_count ?? 0),
|
||||
maxLevel: current?.maxLevel.value ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Vulnerabilities (wazuh-states-vulnerabilities-*, Wazuh 4.8+)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
public async getVulnerabilitiesAsync(input: {
|
||||
cveLimit: number;
|
||||
agentLimit: number;
|
||||
cveOrder: WazuhCveOrder;
|
||||
minSeverity: "all" | "medium" | "high" | "critical";
|
||||
}): Promise<WazuhVulnerabilityOverview> {
|
||||
const severityFilters: Record<typeof input.minSeverity, string[] | null> = {
|
||||
all: null,
|
||||
medium: ["Medium", "High", "Critical"],
|
||||
high: ["High", "Critical"],
|
||||
critical: ["Critical"],
|
||||
};
|
||||
const cveSeverities = severityFilters[input.minSeverity];
|
||||
|
||||
type CveBucket = KeyedBucket & {
|
||||
maxScore: { value: number | null };
|
||||
agents: { value: number };
|
||||
severity: { buckets: KeyedBucket[] };
|
||||
packages: { buckets: KeyedBucket[] };
|
||||
reference: { buckets: KeyedBucket[] };
|
||||
};
|
||||
type AgentBucket = KeyedBucket & {
|
||||
critical: { doc_count: number };
|
||||
high: { doc_count: number };
|
||||
name: { buckets: KeyedBucket[] };
|
||||
};
|
||||
|
||||
const response = await this.indexerSearchAsync<
|
||||
never,
|
||||
{
|
||||
severity: { buckets: KeyedBucket[] };
|
||||
agents: { value: number };
|
||||
cves: { top: { buckets: CveBucket[] } };
|
||||
topAgents: { buckets: AgentBucket[] };
|
||||
}
|
||||
>("wazuh-states-vulnerabilities-*", {
|
||||
size: 0,
|
||||
track_total_hits: true,
|
||||
aggs: {
|
||||
severity: { terms: { field: "vulnerability.severity", size: 10, missing: "-" } },
|
||||
agents: { cardinality: { field: "agent.id" } },
|
||||
cves: {
|
||||
filter: cveSeverities ? { terms: { "vulnerability.severity": cveSeverities } } : { match_all: {} },
|
||||
aggs: {
|
||||
top: {
|
||||
terms: {
|
||||
field: "vulnerability.id",
|
||||
size: input.cveLimit,
|
||||
order:
|
||||
input.cveOrder === "score"
|
||||
? [{ maxScore: "desc" }, { agents: "desc" }]
|
||||
: [{ agents: "desc" }, { maxScore: "desc" }],
|
||||
},
|
||||
aggs: {
|
||||
maxScore: { max: { field: "vulnerability.score.base" } },
|
||||
agents: { cardinality: { field: "agent.id" } },
|
||||
severity: { terms: { field: "vulnerability.severity", size: 1 } },
|
||||
packages: { terms: { field: "package.name", size: 3 } },
|
||||
reference: { terms: { field: "vulnerability.scanner.reference", size: 1 } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
topAgents: {
|
||||
terms: {
|
||||
field: "agent.id",
|
||||
size: input.agentLimit,
|
||||
order: [{ critical: "desc" }, { high: "desc" }, { _count: "desc" }],
|
||||
},
|
||||
aggs: {
|
||||
critical: { filter: { term: { "vulnerability.severity": "Critical" } } },
|
||||
high: { filter: { term: { "vulnerability.severity": "High" } } },
|
||||
name: { terms: { field: "agent.name", size: 1 } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const counts: WazuhVulnerabilityCounts = { critical: 0, high: 0, medium: 0, low: 0, unscored: 0 };
|
||||
for (const bucket of response.aggregations?.severity.buckets ?? []) {
|
||||
const key = bucket.key.toLowerCase();
|
||||
if (key === "critical" || key === "high" || key === "medium" || key === "low") counts[key] += bucket.doc_count;
|
||||
else counts.unscored += bucket.doc_count;
|
||||
}
|
||||
|
||||
return {
|
||||
counts,
|
||||
total: getTotalHits(response.hits.total),
|
||||
affectedAgents: response.aggregations?.agents.value ?? 0,
|
||||
topCves: (response.aggregations?.cves.top.buckets ?? []).map((bucket) => ({
|
||||
id: bucket.key,
|
||||
severity: bucket.severity.buckets[0]?.key ?? "-",
|
||||
score: bucket.maxScore.value,
|
||||
agents: bucket.agents.value,
|
||||
packages: bucket.packages.buckets.map((pkg) => pkg.key),
|
||||
reference: bucket.reference.buckets[0]?.key ?? null,
|
||||
})),
|
||||
topAgents: (response.aggregations?.topAgents.buckets ?? []).map((bucket) => ({
|
||||
id: bucket.key,
|
||||
name: bucket.name.buckets[0]?.key ?? bucket.key,
|
||||
total: bucket.doc_count,
|
||||
critical: bucket.critical.doc_count,
|
||||
high: bucket.high.doc_count,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// File integrity monitoring (syscheck alerts)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
public async getFimEventsAsync(input: {
|
||||
range: WazuhTimeRange;
|
||||
event: WazuhFimEventFilter;
|
||||
limit: number;
|
||||
includeRegistry: boolean;
|
||||
}): Promise<WazuhFimOverview> {
|
||||
const response = await this.indexerSearchAsync<WazuhIndexerAlertSource, { events: { buckets: KeyedBucket[] } }>(
|
||||
"wazuh-alerts-*",
|
||||
{
|
||||
size: input.limit,
|
||||
sort: [{ timestamp: { order: "desc" } }],
|
||||
_source: [
|
||||
"id",
|
||||
"timestamp",
|
||||
"rule.level",
|
||||
"rule.description",
|
||||
"rule.groups",
|
||||
"agent.id",
|
||||
"agent.name",
|
||||
"syscheck.path",
|
||||
"syscheck.event",
|
||||
"syscheck.value_name",
|
||||
"syscheck.uname_after",
|
||||
"syscheck.audit.user.name",
|
||||
],
|
||||
query: {
|
||||
bool: {
|
||||
filter: [{ term: { "rule.groups": "syscheck" } }, { range: { timestamp: { gte: `now-${input.range}` } } }],
|
||||
must_not: input.includeRegistry ? [] : [{ term: { "rule.groups": "syscheck_registry" } }],
|
||||
},
|
||||
},
|
||||
// The event filter only narrows the list; the counts in the header always show all three events.
|
||||
...(input.event !== "all" ? { post_filter: { term: { "syscheck.event": input.event } } } : {}),
|
||||
aggs: { events: { terms: { field: "syscheck.event", size: 5 } } },
|
||||
},
|
||||
);
|
||||
|
||||
const counts: Record<WazuhFimEvent, number> = { added: 0, modified: 0, deleted: 0 };
|
||||
for (const bucket of response.aggregations?.events.buckets ?? []) {
|
||||
if (bucket.key === "added" || bucket.key === "modified" || bucket.key === "deleted") {
|
||||
counts[bucket.key] = bucket.doc_count;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
range: input.range,
|
||||
counts,
|
||||
entries: response.hits.hits.map((hit) => {
|
||||
const source = hit._source;
|
||||
const event = source.syscheck?.event;
|
||||
return {
|
||||
id: hit._id,
|
||||
alertId: source.id ?? null,
|
||||
timestamp: source.timestamp ?? new Date(0).toISOString(),
|
||||
event: event === "added" || event === "modified" || event === "deleted" ? event : "unknown",
|
||||
path: source.syscheck?.path ?? "",
|
||||
valueName: source.syscheck?.value_name ?? null,
|
||||
isRegistry: source.rule?.groups?.includes("syscheck_registry") ?? false,
|
||||
agentId: source.agent?.id ?? null,
|
||||
agentName: source.agent?.name ?? null,
|
||||
level: source.rule?.level ?? 0,
|
||||
description: source.rule?.description ?? "",
|
||||
user: source.syscheck?.uname_after ?? source.syscheck?.audit?.user?.name ?? null,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Authentication failures / brute force
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
public async getAuthFailuresAsync(input: { hours: number; limit: number }): Promise<WazuhAuthFailures> {
|
||||
const bucketHours = Math.max(1, Math.ceil(input.hours / 24));
|
||||
const bucketMs = bucketHours * 60 * 60 * 1000;
|
||||
const end = Math.ceil(Date.now() / bucketMs) * bucketMs;
|
||||
const start = end - Math.ceil(input.hours / bucketHours) * bucketMs;
|
||||
const histogram = {
|
||||
date_histogram: {
|
||||
field: "timestamp",
|
||||
fixed_interval: `${bucketHours}h`,
|
||||
min_doc_count: 0,
|
||||
extended_bounds: { min: start, max: end - bucketMs },
|
||||
},
|
||||
};
|
||||
|
||||
type AgentBucket = KeyedBucket & {
|
||||
bruteForce: { doc_count: number };
|
||||
id: { buckets: KeyedBucket[] };
|
||||
series: { buckets: KeyedBucket<number>[] };
|
||||
sourceIps: { buckets: KeyedBucket[] };
|
||||
lastSeen: { value: number | null; value_as_string?: string };
|
||||
};
|
||||
|
||||
const response = await this.indexerSearchAsync<
|
||||
never,
|
||||
{
|
||||
bruteForce: { doc_count: number };
|
||||
sourceIps: { value: number };
|
||||
series: { buckets: KeyedBucket<number>[] };
|
||||
agents: { buckets: AgentBucket[] };
|
||||
}
|
||||
>("wazuh-alerts-*", {
|
||||
size: 0,
|
||||
track_total_hits: true,
|
||||
query: {
|
||||
bool: {
|
||||
filter: [{ range: { timestamp: { gte: start, lt: end, format: "epoch_millis" } } }, authFailureQuery],
|
||||
},
|
||||
},
|
||||
aggs: {
|
||||
bruteForce: { filter: bruteForceQuery },
|
||||
sourceIps: { cardinality: { field: "data.srcip" } },
|
||||
series: histogram,
|
||||
agents: {
|
||||
terms: { field: "agent.name", size: input.limit },
|
||||
aggs: {
|
||||
bruteForce: { filter: bruteForceQuery },
|
||||
id: { terms: { field: "agent.id", size: 1 } },
|
||||
series: histogram,
|
||||
sourceIps: { terms: { field: "data.srcip", size: 3 } },
|
||||
lastSeen: { max: { field: "timestamp" } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const total = getTotalHits(response.hits.total);
|
||||
const bruteForce = response.aggregations?.bruteForce.doc_count ?? 0;
|
||||
return {
|
||||
hours: input.hours,
|
||||
totals: {
|
||||
total,
|
||||
bruteForce,
|
||||
failed: total - bruteForce,
|
||||
sourceIps: response.aggregations?.sourceIps.value ?? 0,
|
||||
},
|
||||
series: (response.aggregations?.series.buckets ?? []).map((bucket) => bucket.doc_count),
|
||||
agents: (response.aggregations?.agents.buckets ?? []).map((bucket) => ({
|
||||
agentId: bucket.id.buckets[0]?.key ?? null,
|
||||
agentName: bucket.key,
|
||||
total: bucket.doc_count,
|
||||
bruteForce: bucket.bruteForce.doc_count,
|
||||
failed: bucket.doc_count - bucket.bruteForce.doc_count,
|
||||
series: bucket.series.buckets.map((point) => point.doc_count),
|
||||
topSourceIps: bucket.sourceIps.buckets.map((ip) => ({ ip: ip.key, count: ip.doc_count })),
|
||||
lastSeen: bucket.lastSeen.value !== null ? new Date(bucket.lastSeen.value).toISOString() : null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Test connection
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
|
||||
const { api, indexer } = this.getEndpoints();
|
||||
|
||||
try {
|
||||
if (api) {
|
||||
await this.authenticateApiAsync(input.fetchAsync);
|
||||
}
|
||||
if (indexer) {
|
||||
// A secondary indexer URL may live on another host; it is checked with the same trust settings.
|
||||
await this.indexerSearchAsync("wazuh-alerts-*", { size: 0 }, input.fetchAsync);
|
||||
}
|
||||
} catch (thrown) {
|
||||
// Methods are wrapped by the integration error decorator, so the Wazuh error may sit in the cause chain.
|
||||
const error = findWazuhRequestError(thrown) ?? thrown;
|
||||
if (error instanceof WazuhRequestError) {
|
||||
if (error.reason === "unauthorized") return TestConnectionError.UnauthorizedResult(error.status ?? 401);
|
||||
if (error.reason === "status" && error.status !== undefined) {
|
||||
const url = error.target === "indexer" ? (indexer?.url ?? this.integration.url) : this.integration.url;
|
||||
return TestConnectionError.StatusResult({ status: error.status, url });
|
||||
}
|
||||
// Rethrow the original fetch error so the shared test-connection flow can offer certificate trust.
|
||||
if (error.cause !== undefined) throw error.cause;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (!api && !indexer) return TestConnectionError.UnauthorizedResult(401);
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
import type {
|
||||
WazuhAgentsOverview,
|
||||
WazuhAlert,
|
||||
WazuhAlertTimeline,
|
||||
WazuhAuthFailures,
|
||||
WazuhFimOverview,
|
||||
WazuhSecuritySummary,
|
||||
WazuhTopList,
|
||||
WazuhVulnerabilityOverview,
|
||||
} from "./wazuh-types";
|
||||
|
||||
const wave = (index: number, base: number, amplitude: number) =>
|
||||
Math.max(0, Math.round(base + amplitude * Math.sin(index / 3) + ((index * 7919) % 5)));
|
||||
|
||||
const mitre = (ids: string[], tactics: string[], techniques: string[]) => ({ ids, tactics, techniques });
|
||||
|
||||
/** Deterministic demo data for the Wazuh widgets (used by the mock integration and the widget previews). */
|
||||
export const createWazuhMockData = (demoTimestamp: string) => {
|
||||
const now = new Date(demoTimestamp).getTime();
|
||||
const hour = 60 * 60 * 1000;
|
||||
const iso = (offsetMs: number) => new Date(now - offsetMs).toISOString();
|
||||
return {
|
||||
wazuhAgents: {
|
||||
source: "api",
|
||||
asOf: demoTimestamp,
|
||||
counts: { total: 6, active: 4, disconnected: 1, neverConnected: 1, pending: 0 },
|
||||
agents: [
|
||||
{
|
||||
id: "001",
|
||||
name: "edge-proxy",
|
||||
status: "active",
|
||||
ip: "10.0.0.3",
|
||||
osName: "Ubuntu",
|
||||
osVersion: "24.04.3 LTS",
|
||||
osPlatform: "ubuntu",
|
||||
version: "v4.14.8",
|
||||
lastKeepAlive: iso(20_000),
|
||||
groups: ["default", "dmz"],
|
||||
},
|
||||
{
|
||||
id: "002",
|
||||
name: "vpn-gateway",
|
||||
status: "active",
|
||||
ip: "10.0.0.7",
|
||||
osName: "Debian GNU/Linux",
|
||||
osVersion: "13",
|
||||
osPlatform: "debian",
|
||||
version: "v4.14.8",
|
||||
lastKeepAlive: iso(35_000),
|
||||
groups: ["default"],
|
||||
},
|
||||
{
|
||||
id: "003",
|
||||
name: "office-laptop",
|
||||
status: "active",
|
||||
ip: "10.0.0.31",
|
||||
osName: "Microsoft Windows 11 Pro",
|
||||
osVersion: "10.0.26200",
|
||||
osPlatform: "windows",
|
||||
version: "v4.14.1",
|
||||
lastKeepAlive: iso(50_000),
|
||||
groups: ["workstations"],
|
||||
},
|
||||
{
|
||||
id: "004",
|
||||
name: "design-mac",
|
||||
status: "active",
|
||||
ip: "10.0.0.44",
|
||||
osName: "macOS",
|
||||
osVersion: "15.6",
|
||||
osPlatform: "darwin",
|
||||
version: "v4.14.1",
|
||||
lastKeepAlive: iso(15_000),
|
||||
groups: ["workstations"],
|
||||
},
|
||||
{
|
||||
id: "005",
|
||||
name: "media-server",
|
||||
status: "disconnected",
|
||||
ip: "10.0.0.14",
|
||||
osName: "Ubuntu",
|
||||
osVersion: "22.04.5 LTS",
|
||||
osPlatform: "ubuntu",
|
||||
version: "v4.12.0",
|
||||
lastKeepAlive: iso(3 * 24 * hour),
|
||||
groups: ["default"],
|
||||
},
|
||||
{
|
||||
id: "006",
|
||||
name: "new-nas",
|
||||
status: "never_connected",
|
||||
ip: null,
|
||||
osName: null,
|
||||
osVersion: null,
|
||||
osPlatform: null,
|
||||
version: null,
|
||||
lastKeepAlive: null,
|
||||
groups: [],
|
||||
},
|
||||
],
|
||||
} satisfies WazuhAgentsOverview,
|
||||
wazuhAlerts: [
|
||||
{
|
||||
id: "a1",
|
||||
alertId: "1756036680.1",
|
||||
timestamp: iso(2 * 60_000),
|
||||
level: 12,
|
||||
ruleId: "5763",
|
||||
description: "sshd: brute force trying to get access to the system. Authentication failed.",
|
||||
agentId: "001",
|
||||
agentName: "edge-proxy",
|
||||
sourceIp: "203.0.113.24",
|
||||
groups: ["syslog", "sshd", "authentication_failures"],
|
||||
mitre: mitre(["T1110"], ["Credential Access"], ["Brute Force"]),
|
||||
},
|
||||
{
|
||||
id: "a2",
|
||||
alertId: "1756036260.2",
|
||||
timestamp: iso(9 * 60_000),
|
||||
level: 10,
|
||||
ruleId: "5551",
|
||||
description: "PAM: Multiple failed logins in a small period of time.",
|
||||
agentId: "002",
|
||||
agentName: "vpn-gateway",
|
||||
sourceIp: null,
|
||||
groups: ["pam", "syslog", "authentication_failures"],
|
||||
mitre: mitre(["T1110"], ["Credential Access"], ["Brute Force"]),
|
||||
},
|
||||
{
|
||||
id: "a3",
|
||||
alertId: "1756035600.3",
|
||||
timestamp: iso(20 * 60_000),
|
||||
level: 7,
|
||||
ruleId: "533",
|
||||
description: "Listened ports status (netstat) changed (new port opened or closed).",
|
||||
agentId: "003",
|
||||
agentName: "office-laptop",
|
||||
sourceIp: null,
|
||||
groups: ["ossec"],
|
||||
mitre: mitre([], [], []),
|
||||
},
|
||||
] satisfies WazuhAlert[],
|
||||
wazuhSummary: {
|
||||
range: "24h",
|
||||
alerts: { total: 4821, low: 4410, medium: 392, high: 18, critical: 1 },
|
||||
previousAlerts: { total: 5230, low: 4870, medium: 340, high: 20, critical: 0 },
|
||||
maxLevel: 15,
|
||||
managerVersion: "v4.14.8",
|
||||
indexerHealth: "green",
|
||||
} satisfies WazuhSecuritySummary,
|
||||
wazuhTimeline: {
|
||||
range: "24h",
|
||||
intervalMs: hour,
|
||||
totals: { total: 4821, low: 4410, medium: 392, high: 18, critical: 1 },
|
||||
points: Array.from({ length: 24 }, (_, index) => ({
|
||||
timestamp: now - (23 - index) * hour,
|
||||
low: wave(index, 180, 60),
|
||||
medium: wave(index + 4, 16, 8),
|
||||
high: index % 7 === 3 ? 3 : 0,
|
||||
critical: index === 17 ? 1 : 0,
|
||||
})),
|
||||
} satisfies WazuhAlertTimeline,
|
||||
wazuhTopList: {
|
||||
kind: "rules",
|
||||
range: "24h",
|
||||
total: 4821,
|
||||
others: 1240,
|
||||
entries: [
|
||||
{ key: "5503", label: "PAM: User login failed.", detail: "5503", count: 1458, maxLevel: 5, agents: 2 },
|
||||
{
|
||||
key: "5710",
|
||||
label: "sshd: Attempt to login using a non-existent user",
|
||||
detail: "5710",
|
||||
count: 1120,
|
||||
maxLevel: 5,
|
||||
agents: 2,
|
||||
},
|
||||
{ key: "5760", label: "sshd: authentication failed.", detail: "5760", count: 731, maxLevel: 5, agents: 1 },
|
||||
{
|
||||
key: "5551",
|
||||
label: "PAM: Multiple failed logins in a small period of time.",
|
||||
detail: "5551",
|
||||
count: 162,
|
||||
maxLevel: 10,
|
||||
agents: 2,
|
||||
},
|
||||
{
|
||||
key: "5763",
|
||||
label: "sshd: brute force trying to get access to the system.",
|
||||
detail: "5763",
|
||||
count: 110,
|
||||
maxLevel: 10,
|
||||
agents: 1,
|
||||
},
|
||||
],
|
||||
} satisfies WazuhTopList,
|
||||
wazuhVulnerabilities: {
|
||||
counts: { critical: 12, high: 87, medium: 240, low: 31, unscored: 4 },
|
||||
total: 374,
|
||||
affectedAgents: 5,
|
||||
topCves: [
|
||||
{ id: "CVE-2026-1001", severity: "Critical", score: 9.8, agents: 4, packages: ["openssl"], reference: null },
|
||||
{
|
||||
id: "CVE-2026-2044",
|
||||
severity: "Critical",
|
||||
score: 9.1,
|
||||
agents: 2,
|
||||
packages: ["linux-image"],
|
||||
reference: null,
|
||||
},
|
||||
{ id: "CVE-2026-0311", severity: "High", score: 8.8, agents: 5, packages: ["sudo"], reference: null },
|
||||
],
|
||||
topAgents: [
|
||||
{ id: "005", name: "media-server", total: 160, critical: 7, high: 40 },
|
||||
{ id: "001", name: "edge-proxy", total: 92, critical: 3, high: 21 },
|
||||
{ id: "003", name: "office-laptop", total: 70, critical: 2, high: 18 },
|
||||
],
|
||||
} satisfies WazuhVulnerabilityOverview,
|
||||
wazuhFim: {
|
||||
range: "24h",
|
||||
counts: { added: 4, modified: 21, deleted: 2 },
|
||||
entries: [
|
||||
{
|
||||
id: "f1",
|
||||
alertId: "1756036000.10",
|
||||
timestamp: iso(5 * 60_000),
|
||||
event: "modified",
|
||||
path: "/etc/ssh/sshd_config",
|
||||
valueName: null,
|
||||
isRegistry: false,
|
||||
agentId: "001",
|
||||
agentName: "edge-proxy",
|
||||
level: 7,
|
||||
description: "Integrity checksum changed.",
|
||||
user: "root",
|
||||
},
|
||||
{
|
||||
id: "f2",
|
||||
alertId: "1756035000.11",
|
||||
timestamp: iso(40 * 60_000),
|
||||
event: "added",
|
||||
path: "/usr/local/bin/backup.sh",
|
||||
valueName: null,
|
||||
isRegistry: false,
|
||||
agentId: "002",
|
||||
agentName: "vpn-gateway",
|
||||
level: 5,
|
||||
description: "File added to the system.",
|
||||
user: "admin",
|
||||
},
|
||||
],
|
||||
} satisfies WazuhFimOverview,
|
||||
wazuhAuthFailures: {
|
||||
hours: 24,
|
||||
totals: { failed: 2410, bruteForce: 96, total: 2506, sourceIps: 41 },
|
||||
series: Array.from({ length: 24 }, (_, index) => wave(index, 100, 40)),
|
||||
agents: [
|
||||
{
|
||||
agentId: "001",
|
||||
agentName: "edge-proxy",
|
||||
failed: 1480,
|
||||
bruteForce: 70,
|
||||
total: 1550,
|
||||
series: Array.from({ length: 24 }, (_, index) => wave(index, 64, 30)),
|
||||
topSourceIps: [
|
||||
{ ip: "203.0.113.24", count: 620 },
|
||||
{ ip: "198.51.100.8", count: 211 },
|
||||
],
|
||||
lastSeen: iso(60_000),
|
||||
},
|
||||
{
|
||||
agentId: "002",
|
||||
agentName: "vpn-gateway",
|
||||
failed: 930,
|
||||
bruteForce: 26,
|
||||
total: 956,
|
||||
series: Array.from({ length: 24 }, (_, index) => wave(index + 5, 40, 20)),
|
||||
topSourceIps: [{ ip: "192.0.2.77", count: 300 }],
|
||||
lastSeen: iso(7 * 60_000),
|
||||
},
|
||||
],
|
||||
} satisfies WazuhAuthFailures,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,150 @@
|
||||
import type {
|
||||
WazuhAgentStatus,
|
||||
WazuhAlertSeverityCounts,
|
||||
WazuhIndexerAlertSource,
|
||||
WazuhIndexerHit,
|
||||
WazuhTimelineInterval,
|
||||
WazuhTimeRange,
|
||||
} from "./wazuh-types";
|
||||
|
||||
export const timeRangeMs: Record<WazuhTimeRange, number> = {
|
||||
"1h": 60 * 60 * 1000,
|
||||
"24h": 24 * 60 * 60 * 1000,
|
||||
"7d": 7 * 24 * 60 * 60 * 1000,
|
||||
"30d": 30 * 24 * 60 * 60 * 1000,
|
||||
};
|
||||
|
||||
const intervalMs: Record<Exclude<WazuhTimelineInterval, "auto">, number> = {
|
||||
"1m": 60 * 1000,
|
||||
"5m": 5 * 60 * 1000,
|
||||
"15m": 15 * 60 * 1000,
|
||||
"30m": 30 * 60 * 1000,
|
||||
"1h": 60 * 60 * 1000,
|
||||
"3h": 3 * 60 * 60 * 1000,
|
||||
"6h": 6 * 60 * 60 * 1000,
|
||||
"12h": 12 * 60 * 60 * 1000,
|
||||
"1d": 24 * 60 * 60 * 1000,
|
||||
};
|
||||
|
||||
const autoInterval: Record<WazuhTimeRange, Exclude<WazuhTimelineInterval, "auto">> = {
|
||||
"1h": "1m",
|
||||
"24h": "30m",
|
||||
"7d": "3h",
|
||||
"30d": "12h",
|
||||
};
|
||||
|
||||
/** Upper bound for histogram buckets so a small interval on a long range cannot overload the indexer. */
|
||||
const MAX_TIMELINE_BUCKETS = 400;
|
||||
|
||||
export const resolveTimelineIntervalMs = (range: WazuhTimeRange, interval: WazuhTimelineInterval) => {
|
||||
const requested = intervalMs[interval === "auto" ? autoInterval[range] : interval];
|
||||
const minimum = Math.ceil(timeRangeMs[range] / MAX_TIMELINE_BUCKETS);
|
||||
if (requested >= minimum) return requested;
|
||||
// Pick the smallest predefined interval that keeps the bucket count in bounds.
|
||||
return Object.values(intervalMs).find((value) => value >= minimum) ?? intervalMs["1d"];
|
||||
};
|
||||
|
||||
/** Rule level buckets used by the Wazuh dashboard. */
|
||||
export const severityRangeAggregation = {
|
||||
range: {
|
||||
field: "rule.level",
|
||||
keyed: false,
|
||||
ranges: [
|
||||
{ key: "low", to: 7 },
|
||||
{ key: "medium", from: 7, to: 12 },
|
||||
{ key: "high", from: 12, to: 15 },
|
||||
{ key: "critical", from: 15 },
|
||||
],
|
||||
},
|
||||
} as const;
|
||||
|
||||
export interface KeyedBucket<TKey = string> {
|
||||
key: TKey;
|
||||
doc_count: number;
|
||||
}
|
||||
|
||||
export type SeverityRangeResult = { buckets: KeyedBucket[] } | undefined;
|
||||
|
||||
export const toSeverityCounts = (result: SeverityRangeResult, total: number): WazuhAlertSeverityCounts => {
|
||||
const bucketCount = (key: string) => result?.buckets.find((bucket) => bucket.key === key)?.doc_count ?? 0;
|
||||
return {
|
||||
total,
|
||||
low: bucketCount("low"),
|
||||
medium: bucketCount("medium"),
|
||||
high: bucketCount("high"),
|
||||
critical: bucketCount("critical"),
|
||||
};
|
||||
};
|
||||
|
||||
export const getTotalHits = (total: { value: number } | number | undefined) =>
|
||||
typeof total === "number" ? total : (total?.value ?? 0);
|
||||
|
||||
/** Auth failure groups. Brute force = Wazuh correlation rules (authentication_failures) or MITRE T1110. */
|
||||
export const authFailureQuery = {
|
||||
bool: {
|
||||
should: [
|
||||
{ terms: { "rule.groups": ["authentication_failed", "authentication_failures", "invalid_login"] } },
|
||||
{ term: { "rule.mitre.id": "T1110" } },
|
||||
],
|
||||
minimum_should_match: 1,
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const bruteForceQuery = {
|
||||
bool: {
|
||||
should: [{ term: { "rule.groups": "authentication_failures" } }, { term: { "rule.mitre.id": "T1110" } }],
|
||||
minimum_should_match: 1,
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const alertSourceFields = [
|
||||
"id",
|
||||
"timestamp",
|
||||
"rule.id",
|
||||
"rule.level",
|
||||
"rule.description",
|
||||
"rule.groups",
|
||||
"rule.mitre.id",
|
||||
"rule.mitre.tactic",
|
||||
"rule.mitre.technique",
|
||||
"agent.id",
|
||||
"agent.name",
|
||||
"data.srcip",
|
||||
];
|
||||
|
||||
const asArray = (value: string[] | string | undefined): string[] => {
|
||||
if (value === undefined) return [];
|
||||
return Array.isArray(value) ? value : [value];
|
||||
};
|
||||
|
||||
export const mapAlertHit = (hit: WazuhIndexerHit<WazuhIndexerAlertSource>) => {
|
||||
const source = hit._source;
|
||||
return {
|
||||
id: hit._id,
|
||||
alertId: source.id ?? null,
|
||||
timestamp: source.timestamp ?? new Date(0).toISOString(),
|
||||
level: source.rule?.level ?? 0,
|
||||
ruleId: source.rule?.id ?? null,
|
||||
description: source.rule?.description ?? "",
|
||||
agentId: source.agent?.id ?? null,
|
||||
agentName: source.agent?.name ?? null,
|
||||
sourceIp: source.data?.srcip ?? null,
|
||||
groups: asArray(source.rule?.groups),
|
||||
mitre: {
|
||||
ids: asArray(source.rule?.mitre?.id),
|
||||
tactics: asArray(source.rule?.mitre?.tactic),
|
||||
techniques: asArray(source.rule?.mitre?.technique),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const normalizeAgentStatus = (status: string | undefined): WazuhAgentStatus | "unknown" => {
|
||||
if (status === "active" || status === "disconnected" || status === "never_connected" || status === "pending") {
|
||||
return status;
|
||||
}
|
||||
return "unknown";
|
||||
};
|
||||
|
||||
export const normalizeGroups = (group: string[] | string | undefined) => asArray(group);
|
||||
|
||||
export const normalizeVersion = (version: string | undefined) => version?.replace(/^Wazuh\s+/i, "") ?? null;
|
||||
@@ -0,0 +1,281 @@
|
||||
export type WazuhDataSource = "api" | "indexer";
|
||||
|
||||
export type WazuhAgentStatus = "active" | "disconnected" | "never_connected" | "pending";
|
||||
|
||||
export type WazuhSeverity = "low" | "medium" | "high" | "critical";
|
||||
|
||||
export const wazuhTimeRanges = ["1h", "24h", "7d", "30d"] as const;
|
||||
export type WazuhTimeRange = (typeof wazuhTimeRanges)[number];
|
||||
|
||||
export const wazuhTimelineIntervals = ["auto", "1m", "5m", "15m", "30m", "1h", "3h", "6h", "12h", "1d"] as const;
|
||||
export type WazuhTimelineInterval = (typeof wazuhTimelineIntervals)[number];
|
||||
|
||||
export const wazuhTopListKinds = ["rules", "agents", "sourceIps", "mitreTactics", "mitreTechniques"] as const;
|
||||
export type WazuhTopListKind = (typeof wazuhTopListKinds)[number];
|
||||
|
||||
export const wazuhFimEvents = ["all", "added", "modified", "deleted"] as const;
|
||||
export type WazuhFimEventFilter = (typeof wazuhFimEvents)[number];
|
||||
export type WazuhFimEvent = Exclude<WazuhFimEventFilter, "all">;
|
||||
|
||||
export const wazuhCveOrders = ["score", "agents"] as const;
|
||||
export type WazuhCveOrder = (typeof wazuhCveOrders)[number];
|
||||
|
||||
export interface WazuhAgentCounts {
|
||||
total: number;
|
||||
active: number;
|
||||
disconnected: number;
|
||||
neverConnected: number;
|
||||
pending: number;
|
||||
}
|
||||
|
||||
export interface WazuhAgent {
|
||||
id: string;
|
||||
name: string;
|
||||
status: WazuhAgentStatus | "unknown";
|
||||
ip: string | null;
|
||||
osName: string | null;
|
||||
osVersion: string | null;
|
||||
/** Lower-case platform identifier (ubuntu, windows, darwin, debian, ...) used to pick an icon. */
|
||||
osPlatform: string | null;
|
||||
version: string | null;
|
||||
lastKeepAlive: string | null;
|
||||
groups: string[];
|
||||
}
|
||||
|
||||
export interface WazuhAgentsOverview {
|
||||
source: WazuhDataSource;
|
||||
/** When the data was taken. Indexer snapshots (wazuh-monitoring-*) can lag behind the manager. */
|
||||
asOf: string;
|
||||
counts: WazuhAgentCounts;
|
||||
agents: WazuhAgent[];
|
||||
}
|
||||
|
||||
export interface WazuhMitre {
|
||||
ids: string[];
|
||||
tactics: string[];
|
||||
techniques: string[];
|
||||
}
|
||||
|
||||
export interface WazuhAlert {
|
||||
id: string;
|
||||
/** The Wazuh alert id ("1790466949.5285465"), used for dashboard deep links. */
|
||||
alertId: string | null;
|
||||
timestamp: string;
|
||||
level: number;
|
||||
ruleId: string | null;
|
||||
description: string;
|
||||
agentId: string | null;
|
||||
agentName: string | null;
|
||||
sourceIp: string | null;
|
||||
groups: string[];
|
||||
mitre: WazuhMitre;
|
||||
}
|
||||
|
||||
export interface WazuhAlertSeverityCounts {
|
||||
total: number;
|
||||
low: number;
|
||||
medium: number;
|
||||
high: number;
|
||||
critical: number;
|
||||
}
|
||||
|
||||
export interface WazuhVulnerabilityCounts {
|
||||
critical: number;
|
||||
high: number;
|
||||
medium: number;
|
||||
low: number;
|
||||
unscored: number;
|
||||
}
|
||||
|
||||
export interface WazuhSecuritySummary {
|
||||
range: WazuhTimeRange;
|
||||
alerts: WazuhAlertSeverityCounts | null;
|
||||
previousAlerts: WazuhAlertSeverityCounts | null;
|
||||
/** Highest rule level seen in the current period. */
|
||||
maxLevel: number | null;
|
||||
managerVersion: string | null;
|
||||
indexerHealth: "green" | "yellow" | "red" | null;
|
||||
}
|
||||
|
||||
export interface WazuhTimelinePoint {
|
||||
timestamp: number;
|
||||
low: number;
|
||||
medium: number;
|
||||
high: number;
|
||||
critical: number;
|
||||
}
|
||||
|
||||
export interface WazuhAlertTimeline {
|
||||
range: WazuhTimeRange;
|
||||
intervalMs: number;
|
||||
totals: WazuhAlertSeverityCounts;
|
||||
points: WazuhTimelinePoint[];
|
||||
}
|
||||
|
||||
export interface WazuhTopListEntry {
|
||||
key: string;
|
||||
label: string;
|
||||
/** Secondary information: rule id / agent id / MITRE technique id. */
|
||||
detail: string | null;
|
||||
count: number;
|
||||
/** Highest rule level seen for this entry, when meaningful. */
|
||||
maxLevel: number | null;
|
||||
/** Number of distinct agents involved, when meaningful. */
|
||||
agents: number | null;
|
||||
}
|
||||
|
||||
export interface WazuhTopList {
|
||||
kind: WazuhTopListKind;
|
||||
range: WazuhTimeRange;
|
||||
total: number;
|
||||
others: number;
|
||||
entries: WazuhTopListEntry[];
|
||||
}
|
||||
|
||||
export interface WazuhCve {
|
||||
id: string;
|
||||
severity: string;
|
||||
score: number | null;
|
||||
agents: number;
|
||||
packages: string[];
|
||||
reference: string | null;
|
||||
}
|
||||
|
||||
export interface WazuhVulnerableAgent {
|
||||
id: string;
|
||||
name: string;
|
||||
total: number;
|
||||
critical: number;
|
||||
high: number;
|
||||
}
|
||||
|
||||
export interface WazuhVulnerabilityOverview {
|
||||
counts: WazuhVulnerabilityCounts;
|
||||
total: number;
|
||||
affectedAgents: number;
|
||||
topCves: WazuhCve[];
|
||||
topAgents: WazuhVulnerableAgent[];
|
||||
}
|
||||
|
||||
export interface WazuhFimEntry {
|
||||
id: string;
|
||||
alertId: string | null;
|
||||
timestamp: string;
|
||||
event: WazuhFimEvent | "unknown";
|
||||
path: string;
|
||||
/** Registry value name on Windows. */
|
||||
valueName: string | null;
|
||||
isRegistry: boolean;
|
||||
agentId: string | null;
|
||||
agentName: string | null;
|
||||
level: number;
|
||||
description: string;
|
||||
user: string | null;
|
||||
}
|
||||
|
||||
export interface WazuhFimOverview {
|
||||
range: WazuhTimeRange;
|
||||
counts: Record<WazuhFimEvent, number>;
|
||||
entries: WazuhFimEntry[];
|
||||
}
|
||||
|
||||
export interface WazuhAuthFailureAgent {
|
||||
agentId: string | null;
|
||||
agentName: string;
|
||||
failed: number;
|
||||
bruteForce: number;
|
||||
total: number;
|
||||
/** Hourly counts (oldest first) for the sparkline. */
|
||||
series: number[];
|
||||
topSourceIps: { ip: string; count: number }[];
|
||||
lastSeen: string | null;
|
||||
}
|
||||
|
||||
export interface WazuhAuthFailures {
|
||||
hours: number;
|
||||
totals: { failed: number; bruteForce: number; total: number; sourceIps: number };
|
||||
series: number[];
|
||||
agents: WazuhAuthFailureAgent[];
|
||||
}
|
||||
|
||||
/** Levels follow the Wazuh dashboard buckets: low 0-6, medium 7-11, high 12-14, critical 15+. */
|
||||
export const getWazuhSeverityForLevel = (level: number): WazuhSeverity => {
|
||||
if (level >= 15) return "critical";
|
||||
if (level >= 12) return "high";
|
||||
if (level >= 7) return "medium";
|
||||
return "low";
|
||||
};
|
||||
|
||||
/** Raw shapes returned by the Wazuh server API and indexer. Only the fields we read are listed. */
|
||||
export interface WazuhApiResponse<TData> {
|
||||
data: TData;
|
||||
error?: number;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface WazuhApiAgentsSummaryStatus {
|
||||
connection?: Partial<Record<WazuhAgentStatus | "total", number>>;
|
||||
}
|
||||
|
||||
export interface WazuhApiItems<TItem> {
|
||||
affected_items: TItem[];
|
||||
total_affected_items: number;
|
||||
}
|
||||
|
||||
export interface WazuhApiAgent {
|
||||
id: string;
|
||||
name?: string;
|
||||
ip?: string;
|
||||
status?: string;
|
||||
version?: string;
|
||||
lastKeepAlive?: string;
|
||||
group?: string[];
|
||||
os?: { name?: string; version?: string; platform?: string };
|
||||
}
|
||||
|
||||
export interface WazuhIndexerHit<TSource> {
|
||||
_id: string;
|
||||
_index?: string;
|
||||
_source: TSource;
|
||||
}
|
||||
|
||||
export interface WazuhIndexerSearchResponse<TSource, TAggregations = undefined> {
|
||||
hits: {
|
||||
total?: { value: number; relation: string } | number;
|
||||
hits: WazuhIndexerHit<TSource>[];
|
||||
};
|
||||
aggregations?: TAggregations;
|
||||
}
|
||||
|
||||
export interface WazuhIndexerMonitoringSource {
|
||||
id?: string;
|
||||
name?: string;
|
||||
ip?: string;
|
||||
status?: string;
|
||||
version?: string;
|
||||
lastKeepAlive?: string;
|
||||
timestamp?: string;
|
||||
group?: string[] | string;
|
||||
os?: { name?: string; version?: string; platform?: string };
|
||||
}
|
||||
|
||||
export interface WazuhIndexerAlertSource {
|
||||
id?: string;
|
||||
timestamp?: string;
|
||||
rule?: {
|
||||
id?: string;
|
||||
level?: number;
|
||||
description?: string;
|
||||
groups?: string[];
|
||||
mitre?: { id?: string[]; tactic?: string[]; technique?: string[] };
|
||||
};
|
||||
agent?: { id?: string; name?: string; ip?: string };
|
||||
data?: { srcip?: string; dstuser?: string };
|
||||
syscheck?: {
|
||||
path?: string;
|
||||
event?: string;
|
||||
value_name?: string;
|
||||
uname_after?: string;
|
||||
audit?: { effective_user?: { name?: string }; user?: { name?: string } };
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user