fix(auditd): join events per host and bound retained state

Address the review on #12062:

- Include the node= prefix in the event join key. Timestamp plus serial is
  only unique within one host, so a centralized log merged records from
  different hosts into one event. The reported event_id carries the node.
- Bound retained event state to a window. Duplicate and interleaving
  detection kept every PendingEvent for the whole file; records past the
  window are counted in the totals and a limitation says their status is
  not established.
- Pad the reported event timestamp millis to three digits so
  audit(1700000000.005:12) no longer reads as 500 ms, while still joining a
  padded record to an unpadded peer (via the numeric key).
- Detect duplicates per record content instead of record type plus item=,
  so split EXECVE continuations are counted, not called duplicates.
- Re-check cancellation after the coverage callback resolves, so an abort
  during the final await reports cancelled rather than success.
- Account for bytes dropped after a line overflows, so EOF trailing_bytes
  covers the whole tail.
- Drop docs/specs/linux/auditd-log/, which conflicts with AGENTS.md.
This commit is contained in:
2SinceJuly committed 2026-11-22 16:30:24 +08:00
1 parent 459053a30d
commit 053151eaf2
8 files changed
+186 -173

No files matched your search

-34
View File
@@ -1,34 +0,0 @@
# auditd log plan
## Step 1 — record and event inventory (this increment)
- `src/domain/linux/auditdLog.ts`: a streaming scanner that assembles lines,
parses the `type=… msg=audit(...)` record header, joins records on the full
audit event identity, and reports per-type, malformed, duplicate,
out-of-order and interleaved facts.
- `src/artifacts/AuditdLogArtifactReader.ts`: the reader that streams the
admitted file through the scanner and attaches the inventory to the root
occurrence, since a log declares no members.
- Format registration: the `auditd-log` id, its metadata schema, a descriptor
with a reader limitation, a recognizer for the first-line record, and the
subject, target-kind and snapshot enumerations.
- Tests: reader behavior, and recognition from a first record against plain
text.
## Step 2 — record body decoding
Decode the key-value body of each supported record type: `SYSCALL`, `EXECVE`,
`PATH`, `CWD`, `PROCTITLE`, `USER_AUTH`, `AVC`, preserving repeated fields,
argument ordering, quoted and escaped values and hex encodings. Retain raw
values beside normalized interpretations.
## Step 3 — bounded filtering
Filter events by time, record type, audit serial, process identifiers,
executable, user identifiers and result, with the filtered-out counts carried
alongside the retained events.
## Step 4 — cross-file timeline
Order events from several rotated log files by source identity and event
identity, reporting ambiguity rather than inventing an order.
-73
View File
@@ -1,73 +0,0 @@
# auditd log inspection
This specification records the first implementation increment and the original
problem statement of
[Import Linux auditd logs as structured, offline security-event Evidence (#11345)](https://github.com/morluto/rea/issues/11345).
For current behavior and limitations, see the workflow guide once one exists.
## Problem and outcome
REA has no reader for acquired Linux audit subsystem text logs (`audit.log`).
An analyst holding a log copied from a host cannot ask which events it records,
how many records each event was written in, or whether records are duplicated,
out of order or malformed, unless `ausearch` or `aureport` is available and the
analyst lets a host tool interpret the file. Add offline, read-only inventory of
a selected auditd log, delivered in steps so each one merges on its own.
## Requirements
- Recognize an auditd log by its first line: a full
`type=… msg=audit(<sec>.<millis>:<serial>): <body>` record, optionally
prefixed with `node=<host>`. A file whose first line is not such a record is
not this format. CLI and MCP target admission route it to the artifact reader.
- Join records on the whole audit event identity — timestamp seconds,
milliseconds and serial — never the serial alone, because auditd reuses
serials across boots and on wraparound.
- Report line, record and event totals, record counts by type across the whole
file, malformed line count with a bounded sample of the offending lines, and
the number of records whose event identity sorted before one already seen.
- Report interleaved events: an event whose records resumed after a later event
started. The file's own line order is preserved and reported, never reordered
into a tidy timeline.
- Count a repeated record type within one event by its `items=` index; a repeat
is counted as a duplicate and only the first occurrence contributes a type
name.
- Return the first 32 events with their identity, line span, record count and
per-type counts, and the number of events omitted from that window. Totals
cover the whole file.
- Bound a single line at a fixed 64 KiB ceiling and the whole file at 4 GiB,
reporting the file ceiling as a `limit` failure with its boundary.
- Report the trailing bytes of a final line that ends without a newline.
- Report every payload gap as a limitation: key-value fields, hex and escaped
values, argument ordering and decoded syscall or permission meanings are not
interpreted.
## Out of scope for this increment
- Decoding record bodies: `proctitle`/`path` hex, quoted and escaped values,
repeated fields, architecture and syscall tables, permission decoding.
- Correlating audit events with other Evidence, building attack timelines or
making attribution claims.
- Filtering by time, event type, serial, process, executable, user or result.
- Combining several rotated or compressed log files into one timeline.
- Authenticity: a log is not treated as trustworthy, complete or tamper-free.
## Acceptance criteria for this increment
- A structurally valid fixture yields a deterministic record and event
inventory under the `auditd-log` format.
- Records in one event join on timestamp plus serial; two events with the same
timestamp but different serials stay separate, and so do two with the same
serial at different times.
- A record type repeated within one event is counted and its duplicates
reported rather than dropping the extra records.
- A record naming an earlier event after a later one began marks its event as
interleaved and counts as out of order, with the original line order kept.
- Lines that are not auditd records are counted and sampled as diagnostics
without dropping the valid records around them.
- A file whose first line is not an auditd record is refused as a `format`
failure rather than producing an empty inventory.
- The inline event window is bounded at 32 while the totals cover the whole
file.
- Parsing is offline and read-only; nothing is executed and no external
service is contacted.
-26
View File
@@ -1,26 +0,0 @@
# auditd log tasks
## Step 1 — record and event inventory
- [x] Streaming line scanner with a fixed per-line ceiling.
- [x] Record header parsing including an optional `node=` prefix.
- [x] Event join on timestamp seconds, milliseconds and serial.
- [x] Malformed, duplicate, out-of-order and interleaved accounting.
- [x] Bounded inline event window with whole-file totals.
- [x] Reader, format descriptor, recognizer and enumeration registration.
- [x] Reader and recognition tests.
## Step 2 — record body decoding
- [ ] Parse key-value fields, keeping repeated fields and argument order.
- [ ] Decode quoted, escaped and hexadecimal values; retain raw beside derived.
- [ ] Decode architecture, syscall, result and permission fields when the
source provides enough information.
## Step 3 — bounded filtering
- [ ] Filter by time, record type, serial, process, executable, user, result.
## Step 4 — cross-file timeline
- [ ] Order events across rotated files, reporting attribution ambiguity.
+95 -4
View File
@@ -10,7 +10,7 @@ import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory
const record = (
type: string,
seconds: number,
millis: number,
millis: number | string,
serial: number,
body: string,
): string =>
@@ -171,15 +171,67 @@ it("keeps malformed lines as diagnostics without dropping valid events", async (
);
});
it("names a node= prefix record as the same event as its plain peers", async () => {
it("keeps the same event identity apart across different nodes", async () => {
const metadata = await metadataOf(
[
record("SYSCALL", 1700000000, 123, 1000, "success=yes"),
`node=host1 ${record("EXECVE", 1700000000, 123, 1000, "argc=1")}`,
`node=host2 ${record("SYSCALL", 1700000000, 123, 1000, "success=yes")}`,
].join("\n"),
);
expect(metadata.event_count).toBe(1);
expect(metadata.events[0]?.record_count).toBe(2);
// An unqualified record and a node=host2 record share a timestamp and serial
// but belong to different hosts, so they must not be joined.
expect(metadata.event_count).toBe(3);
expect(metadata.events.map((event) => event.node)).toEqual([
null,
"host1",
"host2",
]);
expect(metadata.events.every((event) => event.record_count === 1)).toBe(true);
expect(metadata.duplicate_record_count).toBe(0);
});
it("pads every event timestamp millis to three digits", async () => {
const metadata = await metadataOf(
[
record("SYSCALL", 1700000000, 7, 1000, "success=yes"),
record("EXECVE", 1700000000, "050", 1001, "argc=1"),
].join("\n"),
);
expect(metadata.events.map((event) => event.event_id)).toEqual([
"1700000000.007:1000",
"1700000000.050:1001",
]);
});
it("treats split EXECVE records as continuations, not duplicates", async () => {
const metadata = await metadataOf(
[
record("SYSCALL", 1700000000, 123, 1000, "items=0 syscall=59"),
record("EXECVE", 1700000000, 123, 1000, "argc=3 a0=10 a1=20"),
record("EXECVE", 1700000000, 123, 1000, "a2=30 a3=40"),
record("EXECVE", 1700000000, 123, 1000, "a4=50"),
].join("\n"),
);
const [event] = metadata.events;
expect(event?.duplicate_record_count).toBe(0);
expect(event?.record_types).toEqual([
{ type: "EXECVE", count: 3 },
{ type: "SYSCALL", count: 1 },
]);
});
it("still counts a byte-identical record as a duplicate", async () => {
const metadata = await metadataOf(
[
record("EXECVE", 1700000000, 123, 1000, "argc=1 a0=whoami"),
record("EXECVE", 1700000000, 123, 1000, "argc=1 a0=whoami"),
].join("\n"),
);
expect(metadata.duplicate_record_count).toBe(1);
expect(metadata.events[0]?.record_types).toEqual([
{ type: "EXECVE", count: 1 },
]);
});
it("records trailing bytes when the last line has no newline", async () => {
@@ -213,6 +265,45 @@ it("refuses a file with no auditd record as malformed", async () => {
await reader.close();
});
it("bounds retained event state and reports the window in its limitations", async () => {
const lines = Array.from({ length: 5000 }, (_unused, index) =>
record("SYSCALL", 1700000000, 100, 1000 + index, "success=yes"),
);
const reader = new AuditdLogArtifactReader(
await writeLog("audit.log", `${lines.join("\n")}\n`),
);
try {
for await (const _entry of reader.entries()) {
// No members; the parse itself builds the inventory.
}
const metadata = reader.formatMetadata();
if (metadata?.kind !== "auditd-log")
throw new Error("Expected auditd-log metadata");
expect(metadata.event_count).toBe(5000);
expect(metadata.events).toHaveLength(32);
expect(metadata.omitted_events).toBe(4968);
} finally {
await reader.close();
}
});
it("reports cancellation requested from the coverage callback", async () => {
const reader = new AuditdLogArtifactReader(
await writeLog("audit.log", `${EXECUTION_EVENT}\n`),
);
const controller = new AbortController();
try {
const entries = reader
.entries(controller.signal, {
onCoverage: () => controller.abort(),
})
[Symbol.asyncIterator]();
await expect(entries.next()).rejects.toMatchObject({ reason: "cancelled" });
} finally {
await reader.close();
}
});
it("reports no members to open", async () => {
const reader = new AuditdLogArtifactReader(
await writeLog("audit.log", `${EXECUTION_EVENT}\n`),
+4 -2
View File
@@ -1,5 +1,4 @@
import type { Readable } from "node:stream";
import { setImmediate } from "node:timers/promises";
import {
auditdLogMetadataSchema,
@@ -19,6 +18,7 @@ import {
ArtifactResourceScope,
assertArtifactReadActive,
ArtifactFileSource,
yieldArtifactRead,
} from "../resources/index.js";
import { ArtifactPreparation } from "./ArtifactPreparation.js";
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
@@ -79,7 +79,9 @@ export class AuditdLogArtifactReader implements ArtifactReader {
? { status: "complete" as const, limitations: [] }
: { status: "unknown" as const, limitations: [...this.#limitations] };
options?.onCoverage?.(coverage);
await setImmediate();
// onCoverage may abort the supplied signal; cancellation queued during the
// await must resolve as cancelled rather than as a completed traversal.
await yieldArtifactRead(signal);
}
async open(entry: ArtifactEntry, _signal?: AbortSignal): Promise<Readable> {
+1 -1
View File
@@ -512,7 +512,7 @@ const NON_ZIP_FORMATS = {
...plain,
retainClassifiedSource: true,
readerLimitation:
"auditd log inventory reports record and event totals, per-type counts and a bounded window of events joined on their full audit event identity, with duplicate, out-of-order and malformed records counted. Record key-value fields, hex and escaped values, argument ordering and decoded syscall or permission meanings are not interpreted; the log is not treated as complete or authentic.",
"auditd log inventory reports record and event totals, per-type counts and a bounded window of events joined on their full audit event identity (node, timestamp and serial), with duplicate, out-of-order and malformed records counted. Per-record identity is retained for a bounded window of recent events; events and records past it are counted in the totals but their duplicate and interleaving status is not established. Record key-value fields, hex and escaped values, argument ordering and decoded syscall or permission meanings are not interpreted; the log is not treated as complete or authentic.",
createReader: (path, options) =>
new AuditdLogArtifactReader(path, sourceOf(options)),
}),
+1
View File
@@ -403,6 +403,7 @@ export const auditdLogMetadataSchema = z.strictObject({
.array(
z.strictObject({
event_id: z.string(),
node: z.string().nullable(),
event_seconds: offset,
event_millis: offset,
serial: offset,
+85 -33
View File
@@ -1,3 +1,5 @@
import { createHash } from "node:crypto";
import { boundedList } from "../boundedList.js";
import { ok, err, type Result } from "../result.js";
import type {
@@ -19,6 +21,12 @@ export const AUDITD_INLINE_EVENT_LIMIT = 32;
export const AUDITD_INLINE_DIAGNOSTIC_LIMIT = 16;
/** Record types kept per inline event. */
export const AUDITD_INLINE_EVENT_TYPE_LIMIT = 16;
/**
* Events whose per-record identity is retained for duplicate and interleaving
* detection. A 4 GiB admission can hold millions of events, so state is kept
* for a bounded window; records past it are counted but not joined.
*/
export const AUDITD_RETAINED_EVENT_LIMIT = 4096;
/** `type=... msg=audit(<sec>.<millis>:<serial>): <body>` — the auditd record header. */
const RECORD_HEADER =
@@ -40,8 +48,10 @@ export interface AuditEventTypeCount {
}
export interface AuditEventSummary {
/** `<seconds>.<millis>:<serial>`, the identity records are joined on. */
/** `<node> <seconds>.<millis>:<serial>`, the identity records are joined on. */
readonly event_id: string;
/** The `node=` host the event's records name, or `null` when unqualified. */
readonly node: string | null;
readonly event_seconds: number;
readonly event_millis: number;
readonly serial: number;
@@ -77,11 +87,15 @@ export interface AuditdLogInventory {
/** One event under construction; records are joined on its full identity. */
interface PendingEvent {
readonly node: string | undefined;
/** Original millis spelling, so padded and unpadded records share a key. */
readonly millisText: string;
readonly seconds: number;
readonly millis: number;
readonly serial: number;
recordCount: number;
readonly typeCounts: Map<string, number>;
/** Record digests already seen in this event; the retention window bounds it. */
readonly seenRecords: Set<string>;
firstLine: number;
lastLine: number;
@@ -90,7 +104,7 @@ interface PendingEvent {
}
const eventId = (event: PendingEvent): string =>
`${String(event.seconds)}.${String(event.millis)}:${String(event.serial)}`;
`${event.node === undefined ? "" : `${event.node} `}${String(event.seconds)}.${event.millisText.padStart(3, "0")}:${String(event.serial)}`;
const sortedCounts = (counts: Map<string, number>): AuditEventTypeCount[] =>
[...counts]
@@ -115,18 +129,27 @@ class AuditdLogScanner {
#pendingLine: Buffer[] = [];
// not-an-allowance: pending bytes of the line being assembled, bounded by a fixed line ceiling rather than charged from a resource budget.
#pendingBytes = 0;
// not-an-allowance: bytes of the line being assembled that were dropped after it overflowed the fixed line ceiling; only fed to the trailing-byte tally, never charged from a resource budget.
#pendingFlushedBytes = 0;
#lineNumber = 0;
/** Bytes of a final line that ended without a newline. */
// not-an-allowance: bytes of a final line that ended without a newline, a tally of what the file held rather than a budget.
#trailingBytes = 0;
#recordCount = 0;
readonly #typeCounts = new Map<string, number>();
readonly #events = new Map<string, PendingEvent>();
readonly #eventOrder: string[] = [];
/** First-seen order of the retained events, bounded to the sample. */
readonly #sampleOrder: string[] = [];
// not-an-allowance: a tally of the events currently retained in the window, compared with the retention ceiling but never charged against a resource budget.
#windowEventCount = 0;
/** Events past the retained window; their totals stay exact, joins do not. */
#beyondWindowEventCount = 0;
#malformedCount = 0;
// sample-cap: the full malformed count is reported beside a sample of the lines.
readonly #malformed: AuditRecordDiagnostic[] = [];
#outOfOrderCount = 0;
#duplicateCount = 0;
/** Records past the retained window, whose identity is not joined. */
#skippedRecordCount = 0;
/** Lexicographically ordered event identity; a smaller one is out of order. */
#maxIdentity: string | null = null;
#lastEventKey: string | null = null;
@@ -150,8 +173,8 @@ class AuditdLogScanner {
}
finish(): Result<AuditdLogInventory, RegionDecodeFailure> {
if (this.#pendingBytes > 0) {
this.#trailingBytes = this.#pendingBytes;
if (this.#pendingBytes > 0 || this.#pendingFlushedBytes > 0) {
this.#trailingBytes = this.#pendingBytes + this.#pendingFlushedBytes;
this.#finishLine();
}
if (this.#lineOverflow)
@@ -180,14 +203,17 @@ class AuditdLogScanner {
);
if (this.#duplicateCount > 0)
limitations.push(
`${String(this.#duplicateCount)} record(s) repeat a record type and items index already seen in the same event; each occurrence is counted and only the first name is retained`,
`${String(this.#duplicateCount)} record(s) repeat a record already seen in the same event, byte for byte; each occurrence is counted and only the first name is retained`,
);
if (this.#beyondWindowEventCount > 0 || this.#skippedRecordCount > 0)
limitations.push(
`per-record identity is retained for the most recent ${String(AUDITD_RETAINED_EVENT_LIMIT)} events; the other ${String(this.#beyondWindowEventCount)} events and ${String(this.#skippedRecordCount)} record(s) are counted in the totals but their duplicate and interleaving status is not established`,
);
limitations.push(
"records are inventoried by header and record type: key-value fields, hex/escaped values, argument ordering and decoded syscall or permission meanings are not interpreted",
);
const sampled = boundedList(this.#eventOrder, AUDITD_INLINE_EVENT_LIMIT);
const events = sampled.items.map((key) =>
const events = this.#sampleOrder.map((key) =>
this.#summarize(this.#events.get(key)!),
);
return ok({
@@ -195,7 +221,7 @@ class AuditdLogScanner {
kind: "auditd-log",
line_count: this.#lineNumber,
record_count: this.#recordCount,
event_count: this.#events.size,
event_count: this.#windowEventCount + this.#beyondWindowEventCount,
event_type_counts: sortedCounts(this.#typeCounts),
malformed_line_count: this.#malformedCount,
malformed_lines: this.#malformed,
@@ -205,11 +231,12 @@ class AuditdLogScanner {
),
out_of_order_record_count: this.#outOfOrderCount,
duplicate_record_count: this.#duplicateCount,
interleaved_event_count: this.#eventOrder.filter(
interleaved_event_count: this.#sampleOrder.filter(
(key) => this.#events.get(key)!.interleaved,
).length,
events,
omitted_events: sampled.omitted,
omitted_events:
this.#windowEventCount + this.#beyondWindowEventCount - events.length,
trailing_bytes: this.#trailingBytes,
},
limitations,
@@ -217,9 +244,14 @@ class AuditdLogScanner {
}
#acceptSegment(segment: Buffer): void {
if (this.#lineOverflow) return;
if (this.#lineOverflow) {
this.#pendingFlushedBytes += segment.length;
return;
}
if (this.#pendingBytes + segment.length > MAX_RECORD_LINE_BYTES) {
this.#lineOverflow = true;
this.#pendingFlushedBytes = this.#pendingBytes + segment.length;
this.#pendingBytes = 0;
this.#pendingLine = [];
return;
}
@@ -231,6 +263,7 @@ class AuditdLogScanner {
this.#lineNumber += 1;
const lineBytes = Buffer.concat(this.#pendingLine);
this.#pendingBytes = 0;
this.#pendingFlushedBytes = 0;
this.#pendingLine = [];
if (this.#lineOverflow) {
@@ -260,8 +293,10 @@ class AuditdLogScanner {
return;
}
const seconds = Number(match.groups["sec"]);
const millis = Number(match.groups["millis"]);
const millisText = match.groups["millis"]!;
const millis = Number(millisText);
const serial = Number(match.groups["serial"]);
const node = match.groups["node"];
const type = match.groups["type"]!;
if (![seconds, millis, serial].every(Number.isSafeInteger)) {
this.#diagnose(
@@ -275,20 +310,31 @@ class AuditdLogScanner {
this.#recordCount += 1;
this.#typeCounts.set(type, (this.#typeCounts.get(type) ?? 0) + 1);
// The event identity is the whole join key: timestamp plus serial, never
// serial alone, because serials are reused across boots and wraparound.
const key = occurrenceKey(seconds, millis, serial);
const identity = `${String(seconds).padStart(12, "0")}.${String(millis).padStart(3, "0")}:${String(serial).padStart(12, "0")}`;
// The event identity is the whole join key: node, timestamp and serial.
// Serial and timestamp are only unique enough to join on within one host,
// so a centralized log's node= prefix has to stay part of the identity.
// Ordering stays temporal (timestamp then serial); node only splits events.
const key = occurrenceKey(node, seconds, millis, serial);
const identity = `${String(seconds).padStart(12, "0")}.${millisText.padStart(3, "0")}:${String(serial).padStart(12, "0")}`;
if (this.#maxIdentity !== null && identity < this.#maxIdentity)
this.#outOfOrderCount += 1;
else this.#maxIdentity = identity;
const existing = this.#events.get(key);
if (existing === undefined && this.#windowEventCount >= AUDITD_RETAINED_EVENT_LIMIT) {
this.#beyondWindowEventCount += 1;
this.#skippedRecordCount += 1;
this.#lastEventKey = key;
return;
}
if (existing !== undefined && this.#lastEventKey !== key)
existing.interleaved = true;
const event =
existing ??
({
node,
millisText,
seconds,
millis,
serial,
@@ -302,11 +348,22 @@ class AuditdLogScanner {
} satisfies PendingEvent);
if (existing === undefined) {
this.#events.set(key, event);
this.#eventOrder.push(key);
this.#windowEventCount += 1;
if (this.#sampleOrder.length < AUDITD_INLINE_EVENT_LIMIT)
this.#sampleOrder.push(key);
}
this.#lastEventKey = key;
const recordKey = `${type}\u0000${recordItemsIndex(match.groups["body"])}`;
// Duplicate detection is per record content, not per record type: a long
// execve argument list can span several EXECVE records with no item= index,
// and those are legitimate continuations, not repeats. The digest keeps
// retained state to one short key per record per event; the retention
// window bounds how many events hold those keys at once.
const recordKey = createHash("sha256")
.update(type)
.update("\u0000")
.update(match.groups["body"] ?? "")
.digest("base64");
if (event.seenRecords.has(recordKey)) {
event.duplicateCount += 1;
this.#duplicateCount += 1;
@@ -327,6 +384,7 @@ class AuditdLogScanner {
#summarize(event: PendingEvent): AuditEventSummary {
return {
event_id: eventId(event),
node: event.node ?? null,
event_seconds: event.seconds,
event_millis: event.millis,
serial: event.serial,
@@ -343,19 +401,13 @@ class AuditdLogScanner {
}
}
const occurrenceKey = (seconds: number, millis: number, serial: number) =>
`${String(seconds)}.${String(millis)}:${String(serial)}`;
/**
* `item=<n>` is the per-record index auditd gives repeated types. `items=` is
* the path count on a SYSCALL record, not an index: reading it here made every
* PATH record of a multi-path event share one key, so the second path was
* reported as a duplicate and the per-event PATH count came out as one.
*/
const recordItemsIndex = (body: string | undefined): string => {
const match = body === undefined ? null : /\bitem=(\d+)/u.exec(body);
return match === null ? "" : match[1]!;
};
const occurrenceKey = (
node: string | undefined,
seconds: number,
millis: number,
serial: number,
) =>
`${node ?? ""}\u0000${String(seconds)}.${String(millis)}:${String(serial)}`;
/**
* An auditd log has no magic: recognition reads the first line and accepts it