@shieldaai/security-watch 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,426 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import { timestamp } from './util.js';
3
+ /**
4
+ * Runtime mitigation status (a shield, a blocking policy, a firewall rule, a live patch) read from
5
+ * JSON Lines files that the operator writes on a timer: Shirudo's `node_vulns` export, or the generic
6
+ * format any tool can produce. Security Watch never connects to the tool and holds no credential for it.
7
+ *
8
+ * The status is shown only, like EPSS: it never changes applicability, priority, routing or a
9
+ * finding's revision, and a mitigation never closes a finding. It is temporary; the fix is not.
10
+ */
11
+ export const MITIGATION_STATES = [
12
+ 'mitigated',
13
+ 'pending',
14
+ 'failed',
15
+ 'excluded',
16
+ 'withdrawn',
17
+ 'expired',
18
+ 'unmitigated',
19
+ 'unknown',
20
+ ];
21
+ /** Worst first: a host reported in several rows for one finding counts once, by its worst row. */
22
+ const WORST_FIRST = [
23
+ 'unmitigated',
24
+ 'expired',
25
+ 'withdrawn',
26
+ 'excluded',
27
+ 'failed',
28
+ 'unknown',
29
+ 'pending',
30
+ 'mitigated',
31
+ ];
32
+ const WORDS = {
33
+ mitigated: 'mitigated',
34
+ pending: 'mitigation waiting to load',
35
+ failed: 'mitigation failed to load',
36
+ excluded: 'mitigation excludes the host',
37
+ withdrawn: 'mitigation withdrawn',
38
+ expired: 'mitigation expired',
39
+ unmitigated: 'not mitigated',
40
+ unknown: 'status unknown',
41
+ };
42
+ /** Shirudo's `exposure` values in the generic vocabulary. */
43
+ const SHIRUDO_STATES = {
44
+ shielded: 'mitigated',
45
+ shield_pending: 'pending',
46
+ shield_module_absent: 'failed',
47
+ shield_excludes_node: 'excluded',
48
+ shield_withdrawn: 'withdrawn',
49
+ exposed_no_shield: 'unmitigated',
50
+ unknown: 'unknown',
51
+ none: 'none',
52
+ };
53
+ export const MAX_EXPORT_BYTES = 64 * 1024 * 1024;
54
+ export const MAX_EXPORT_ROWS = 500_000;
55
+ const MAX_FIELD = 512;
56
+ /** Line and paragraph separators, other C1 controls, zero-width and bidirectional marks. */
57
+ const UNSAFE_TEXT = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069\ufeff]/;
58
+ function field(value, required) {
59
+ if (value === undefined || value === null || value === '') {
60
+ if (required)
61
+ throw new Error('missing field');
62
+ return undefined;
63
+ }
64
+ // A number beyond 2^53 has already lost digits: two machine IDs would become one.
65
+ if (typeof value !== 'string' && (typeof value !== 'number' || !Number.isSafeInteger(value)))
66
+ throw new Error('not text');
67
+ const text = String(value).trim();
68
+ if (!text) {
69
+ if (required)
70
+ throw new Error('missing field');
71
+ return undefined;
72
+ }
73
+ if (text.length > MAX_FIELD || UNSAFE_TEXT.test(text))
74
+ throw new Error('invalid text');
75
+ return text;
76
+ }
77
+ /** A display-only field: an odd value is left out instead of costing the row. */
78
+ function optionalField(value) {
79
+ try {
80
+ return field(value, false);
81
+ }
82
+ catch {
83
+ return undefined;
84
+ }
85
+ }
86
+ function objectOf(line) {
87
+ let data;
88
+ try {
89
+ data = JSON.parse(line);
90
+ }
91
+ catch {
92
+ throw new Error('not JSON');
93
+ }
94
+ if (!data || typeof data !== 'object' || Array.isArray(data))
95
+ throw new Error('not an object');
96
+ return data;
97
+ }
98
+ function withOptional(row, extra) {
99
+ return {
100
+ ...row,
101
+ ...(extra.package ? { package: extra.package } : {}),
102
+ ...(extra.mitigation ? { mitigation: extra.mitigation } : {}),
103
+ ...(extra.expires !== undefined ? { expires: extra.expires } : {}),
104
+ };
105
+ }
106
+ /**
107
+ * One line of a Shirudo `node_vulns` export; throws with a short reason when it is not one. A node
108
+ * that has stopped reporting (`status: stale`) proves nothing about its shields: its rows are
109
+ * `unknown`. A row of a node bound to no image belongs to no system and is set aside.
110
+ */
111
+ export function parseShirudoRow(line) {
112
+ const row = objectOf(line);
113
+ if (row.image_id === '' || row.image_id === null || row.image_id === undefined) {
114
+ field(row.node_id, true);
115
+ return { unbound: true };
116
+ }
117
+ const known = typeof row.exposure === 'string' && Object.hasOwn(SHIRUDO_STATES, row.exposure);
118
+ let state = known ? SHIRUDO_STATES[row.exposure] : 'unknown';
119
+ if (state !== 'none' && optionalField(row.status) === 'stale')
120
+ state = 'unknown';
121
+ // The fields used for matching must be valid, or the row is skipped and counted; the rest are shown
122
+ // only and are left out when odd.
123
+ const identifier = (field(row.vuln_id, state !== 'none') ?? '').toUpperCase();
124
+ return {
125
+ row: withOptional({
126
+ system: field(row.image_id, true),
127
+ host: field(row.node_id, true),
128
+ identifier,
129
+ ...(optionalField(row.source) === 'kernel' ? { kernel: true } : {}),
130
+ state,
131
+ }, { package: field(row.package, false), mitigation: optionalField(row.upatch_id) }),
132
+ unknown_value: !known,
133
+ };
134
+ }
135
+ /** ISO 8601 with a zone, or a plain date (read as UTC midnight); nothing else is a time. */
136
+ const ISO_TIME = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:\d{2}))?$/;
137
+ /**
138
+ * One line of the generic format:
139
+ * `{"system_id", "host", "identifier", "package"?, "kernel"?, "status", "mitigation"?, "expires_at"?}`.
140
+ * A mitigated or pending row whose `expires_at` has passed is `expired`.
141
+ */
142
+ export function parseGenericRow(line, now) {
143
+ const row = objectOf(line);
144
+ const status = row.status;
145
+ const known = status === 'none' ||
146
+ (typeof status === 'string' && MITIGATION_STATES.includes(status));
147
+ let state = known ? status : 'unknown';
148
+ let expires;
149
+ if (row.expires_at !== undefined && row.expires_at !== null) {
150
+ if (typeof row.expires_at !== 'string' || !ISO_TIME.test(row.expires_at))
151
+ throw new Error('invalid expires_at');
152
+ expires = Date.parse(/T/.test(row.expires_at) ? row.expires_at : `${row.expires_at}T00:00:00Z`);
153
+ if (!Number.isFinite(expires))
154
+ throw new Error('invalid expires_at');
155
+ if (expires <= now && (state === 'mitigated' || state === 'pending'))
156
+ state = 'expired';
157
+ }
158
+ if (row.kernel !== undefined && typeof row.kernel !== 'boolean')
159
+ throw new Error('kernel is not true or false');
160
+ const identifier = (field(row.identifier, state !== 'none') ?? '').toUpperCase();
161
+ return {
162
+ row: withOptional({
163
+ system: field(row.system_id, true),
164
+ host: field(row.host, true),
165
+ identifier,
166
+ ...(row.kernel === true ? { kernel: true } : {}),
167
+ state,
168
+ }, {
169
+ package: field(row.package, false),
170
+ mitigation: optionalField(row.mitigation),
171
+ ...(state === 'mitigated' || state === 'pending' ? { expires } : {}),
172
+ }),
173
+ unknown_value: !known,
174
+ };
175
+ }
176
+ /**
177
+ * Reads an export. Throws when the file is missing, not a regular file, too large, not UTF-8 text or
178
+ * has no readable row at all; individual bad lines are skipped and counted, so one odd row never
179
+ * hides the rest.
180
+ */
181
+ export function readMitigationExport(source, now) {
182
+ const stat = statSync(source.file);
183
+ if (!stat.isFile())
184
+ throw new Error('not a regular file');
185
+ if (stat.size > MAX_EXPORT_BYTES)
186
+ throw new Error(`larger than ${MAX_EXPORT_BYTES / 1024 / 1024} MiB`);
187
+ const bytes = readFileSync(source.file);
188
+ if (bytes.length >= 2 &&
189
+ ((bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0xfe && bytes[1] === 0xff)))
190
+ throw new Error('the file is UTF-16 text; write it as UTF-8 (PowerShell: Out-File -Encoding utf8)');
191
+ // A byte order mark is not part of the first row; Windows line ends are line ends.
192
+ const text = bytes.toString('utf8').replace(/^\ufeff/, '');
193
+ const parse = source.format === 'shirudo' ? parseShirudoRow : (line) => parseGenericRow(line, now);
194
+ const rows = [];
195
+ let skipped = 0;
196
+ let unknown = 0;
197
+ let unbound = 0;
198
+ let firstProblem;
199
+ let lineNumber = 0;
200
+ for (const raw of text.split('\n')) {
201
+ lineNumber++;
202
+ const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
203
+ if (!line.trim())
204
+ continue;
205
+ if (rows.length + skipped + unbound >= MAX_EXPORT_ROWS)
206
+ throw new Error(`more than ${MAX_EXPORT_ROWS} rows`);
207
+ try {
208
+ const parsed = parse(line);
209
+ if ('unbound' in parsed)
210
+ unbound++;
211
+ else {
212
+ rows.push(parsed.row);
213
+ if (parsed.unknown_value)
214
+ unknown++;
215
+ }
216
+ }
217
+ catch (error) {
218
+ skipped++;
219
+ firstProblem ??= `line ${lineNumber}: ${error.message}`;
220
+ }
221
+ }
222
+ if (!rows.length && skipped)
223
+ throw new Error(`no readable row (${firstProblem})`);
224
+ return {
225
+ exported_at: timestamp(stat.mtimeMs),
226
+ // A modification time ahead of the clock is not fresh either: the file cannot be trusted to be current.
227
+ stale: now - stat.mtimeMs > source.max_age_minutes * 60_000 || stat.mtimeMs - now > 5 * 60_000,
228
+ rows,
229
+ skipped,
230
+ ...(firstProblem ? { first_problem: firstProblem } : {}),
231
+ unknown_values: unknown,
232
+ unbound,
233
+ };
234
+ }
235
+ /** Problems with an export that should reach monitoring health. */
236
+ export function exportProblems(exported, source, now) {
237
+ const problems = [];
238
+ const age = Math.round((now - Date.parse(exported.exported_at)) / 60_000);
239
+ if (exported.stale)
240
+ problems.push(age < 0
241
+ ? `${source.name}: the export's modification time is ${-age} minutes in the future; check the clock of the machine that writes it.`
242
+ : `${source.name}: the export was written ${age} minutes ago, more than max_age_minutes (${source.max_age_minutes}); its status may be out of date.`);
243
+ if (!exported.rows.length && !exported.skipped)
244
+ problems.push(`${source.name}: the export has no row for any system, so no mitigation status is shown. Check the export job: a fleet with hosts has at least one row per host.`);
245
+ if (exported.skipped)
246
+ problems.push(`${source.name}: ${exported.skipped} line(s) of the export could not be read and were left out (${exported.first_problem}).`);
247
+ if (exported.unknown_values)
248
+ problems.push(`${source.name}: ${exported.unknown_values} row(s) have a status this release does not know and are shown as status unknown; the tool may have added a value.`);
249
+ return problems;
250
+ }
251
+ /** Whether an export says anything about the inventory's systems: rows that all miss is a mapping mistake. */
252
+ export function unmatchedSystems(exported, source, systemIds) {
253
+ const keys = new Set(exported.rows.map((row) => row.system));
254
+ return [...keys].filter((key) => !systemIds.has(Object.hasOwn(source.systems, key) ? source.systems[key] : key));
255
+ }
256
+ /** Package names compare as their ecosystem compares them: PyPI folds case and separators, the rest only case. */
257
+ function samePackage(row, component) {
258
+ const fold = (name) => component.ecosystem === 'PyPI'
259
+ ? name
260
+ .trim()
261
+ .toLowerCase()
262
+ .replace(/[-_.]+/g, '-')
263
+ : name.trim().toLowerCase();
264
+ return fold(row) === fold(component.name);
265
+ }
266
+ function plural(count, word) {
267
+ return `${count} ${word}${count === 1 ? '' : 's'}`;
268
+ }
269
+ /**
270
+ * Finds one source's rows for a finding: rows whose system key belongs to the finding's system, whose
271
+ * identifier is the finding's event or one of its current advisories' aliases, and, for a library
272
+ * finding, whose package is the finding's package. A row without a package says nothing about a
273
+ * library (one CVE can name several packages); a kernel row matches by identifier alone.
274
+ */
275
+ export class MitigationIndex {
276
+ #systems = new Map();
277
+ #export;
278
+ #source;
279
+ constructor(exported, source) {
280
+ this.#export = exported;
281
+ this.#source = source;
282
+ for (const row of exported.rows) {
283
+ const system = Object.hasOwn(source.systems, row.system) ? source.systems[row.system] : row.system;
284
+ let entry = this.#systems.get(system);
285
+ if (!entry) {
286
+ entry = { hosts: new Set(), byIdentifier: new Map() };
287
+ this.#systems.set(system, entry);
288
+ }
289
+ // A host is named per system key: the same name under two keys is two machines.
290
+ entry.hosts.add(`${row.system}\u0000${row.host}`);
291
+ if (row.state === 'none')
292
+ continue;
293
+ const list = entry.byIdentifier.get(row.identifier) ?? [];
294
+ list.push(row);
295
+ entry.byIdentifier.set(row.identifier, list);
296
+ }
297
+ }
298
+ status(finding, evidence, inventory) {
299
+ if (finding.category === 'health' || finding.category === 'malware')
300
+ return undefined;
301
+ const entry = this.#systems.get(finding.system_id);
302
+ if (!entry)
303
+ return undefined;
304
+ const identifiers = new Set([finding.event_id.toUpperCase()]);
305
+ for (const id of finding.evidence_ids) {
306
+ const item = evidence.get(id);
307
+ if (item && item.kind !== 'news' && item.kind !== 'health' && !item.withdrawn)
308
+ for (const alias of item.aliases)
309
+ identifiers.add(alias.toUpperCase());
310
+ }
311
+ const component = finding.component_id && inventory
312
+ ? inventory.systems
313
+ .find((system) => system.id === finding.system_id)
314
+ ?.components.find((item) => item.id === finding.component_id)
315
+ : undefined;
316
+ const library = finding.category === 'library';
317
+ const worst = new Map();
318
+ const mitigations = new Set();
319
+ let expires;
320
+ for (const identifier of identifiers)
321
+ for (const row of entry.byIdentifier.get(identifier) ?? []) {
322
+ if (library && !row.kernel) {
323
+ if (!row.package)
324
+ continue;
325
+ if (component && !samePackage(row.package, component))
326
+ continue;
327
+ }
328
+ // Rows of `none` are never indexed by identifier; this keeps the type exact.
329
+ if (row.state === 'none')
330
+ continue;
331
+ const host = `${row.system}\u0000${row.host}`;
332
+ const known = worst.get(host);
333
+ if (!known || WORST_FIRST.indexOf(row.state) < WORST_FIRST.indexOf(known))
334
+ worst.set(host, row.state);
335
+ if (row.state === 'mitigated' || row.state === 'pending') {
336
+ if (row.mitigation)
337
+ mitigations.add(row.mitigation);
338
+ if (row.expires !== undefined)
339
+ expires = Math.min(expires ?? row.expires, row.expires);
340
+ }
341
+ }
342
+ const hosts = entry.hosts.size;
343
+ const states = {};
344
+ for (const value of worst.values())
345
+ states[value] = (states[value] ?? 0) + 1;
346
+ const base = {
347
+ source: this.#source.name,
348
+ format: this.#source.format,
349
+ exported_at: this.#export.exported_at,
350
+ stale: this.#export.stale,
351
+ hosts,
352
+ states,
353
+ mitigations: [...mitigations].sort().slice(0, 20),
354
+ ...(expires !== undefined ? { expires_at: timestamp(expires) } : {}),
355
+ };
356
+ if (!worst.size)
357
+ return {
358
+ ...base,
359
+ not_listed: true,
360
+ summary: `${this.#source.name} lists no such finding on the ${plural(hosts, 'host')} running this system, so no mitigation is linked to it.`,
361
+ };
362
+ // How many hosts are covered comes first, then those that are not, worst first.
363
+ const parts = [
364
+ `mitigated on ${states.mitigated ?? 0} of ${plural(hosts, 'host')}`,
365
+ ...WORST_FIRST.filter((value) => value !== 'mitigated' && states[value]).map((value) => `${states[value]} ${WORDS[value]}`),
366
+ ];
367
+ const unreported = hosts - worst.size;
368
+ if (unreported)
369
+ parts.push(`${unreported} not listed for it`);
370
+ return { ...base, summary: `${this.#source.name}: ${parts.join('; ')}.` };
371
+ }
372
+ }
373
+ /**
374
+ * Whether a status proves that every host it covers is mitigated now: fresh, listed, all hosts
375
+ * mitigated, and no counted mitigation expired since the export.
376
+ */
377
+ export function mitigatedEverywhere(status, now = Date.now()) {
378
+ const expiry = status.expires_at === undefined ? undefined : Date.parse(status.expires_at);
379
+ return (!status.stale &&
380
+ !status.not_listed &&
381
+ status.hosts > 0 &&
382
+ status.states.mitigated === status.hosts &&
383
+ (expiry === undefined || expiry > now));
384
+ }
385
+ /**
386
+ * A saved status as it stands now. Statuses are saved at each scan; when scans stop, or a mitigation
387
+ * expires between scans, a reader must not show the saved one as current. `maxAgeByName` holds each
388
+ * configured source's `max_age_minutes`; a source that is no longer configured proves nothing.
389
+ */
390
+ export function currentStatus(status, maxAgeByName, now) {
391
+ if (status.stale)
392
+ return status;
393
+ const exported = Date.parse(status.exported_at);
394
+ const expiry = status.expires_at === undefined ? undefined : Date.parse(status.expires_at);
395
+ let reason;
396
+ if (maxAgeByName && !Object.hasOwn(maxAgeByName, status.source))
397
+ reason = 'source_removed';
398
+ else if (!Number.isFinite(exported) ||
399
+ (maxAgeByName && now - exported > maxAgeByName[status.source] * 60_000))
400
+ reason = 'old_export';
401
+ else if (expiry !== undefined && expiry <= now)
402
+ reason = 'expired';
403
+ return reason ? { ...status, stale: true, stale_reason: reason } : status;
404
+ }
405
+ /** A finding with its saved statuses as they stand now. */
406
+ export function withCurrentMitigations(finding, maxAgeByName, now) {
407
+ return finding.mitigations?.length
408
+ ? {
409
+ ...finding,
410
+ mitigations: finding.mitigations.map((status) => currentStatus(status, maxAgeByName, now)),
411
+ }
412
+ : finding;
413
+ }
414
+ /** Each configured source's limit, by name, for `currentStatus`. */
415
+ export function maxAges(sources) {
416
+ return Object.fromEntries((sources ?? []).map((source) => [source.name, source.max_age_minutes]));
417
+ }
418
+ /** Attaches the current statuses, or removes earlier ones when there are none now. */
419
+ export function attachMitigations(finding, indexes, evidence, inventory) {
420
+ // `runtime_shield` was this field's name in unreleased development builds; it is dropped too.
421
+ const { mitigations: _previous, runtime_shield: _old, ...rest } = finding;
422
+ const statuses = indexes
423
+ .map((index) => index.status(rest, evidence, inventory))
424
+ .filter((status) => status !== undefined);
425
+ return statuses.length ? { ...rest, mitigations: statuses } : rest;
426
+ }
@@ -59,6 +59,31 @@ declare const scenarioSchema: z.ZodObject<{
59
59
  withdrawn: z.ZodOptional<z.ZodBoolean>;
60
60
  exploited: z.ZodOptional<z.ZodBoolean>;
61
61
  malware: z.ZodOptional<z.ZodBoolean>;
62
+ references: z.ZodOptional<z.ZodArray<z.ZodObject<{
63
+ type: z.ZodEnum<{
64
+ advisory: "advisory";
65
+ detection: "detection";
66
+ evidence: "evidence";
67
+ fix: "fix";
68
+ introduced: "introduced";
69
+ package: "package";
70
+ report: "report";
71
+ source: "source";
72
+ web: "web";
73
+ }>;
74
+ url: z.ZodURL;
75
+ }, z.core.$strict>>>;
76
+ fix_commits: z.ZodOptional<z.ZodArray<z.ZodObject<{
77
+ repo: z.ZodURL;
78
+ commit: z.ZodString;
79
+ }, z.core.$strict>>>;
80
+ weaknesses: z.ZodOptional<z.ZodArray<z.ZodString>>;
81
+ exploit_sources: z.ZodOptional<z.ZodArray<z.ZodEnum<{
82
+ "exploit-db": "exploit-db";
83
+ "github-poc": "github-poc";
84
+ metasploit: "metasploit";
85
+ nuclei: "nuclei";
86
+ }>>>;
62
87
  }, z.core.$strict>>;
63
88
  inventory: z.ZodOptional<z.ZodObject<{
64
89
  systems: z.ZodArray<z.ZodObject<{
package/dist/rehearsal.js CHANGED
@@ -189,6 +189,8 @@ export async function runRehearsal(options) {
189
189
  }
190
190
  // Clone validated objects before changing effective runtime settings. No source/provider path can run.
191
191
  config.models.enabled = false;
192
+ // A rehearsal reads no live state: not the operator's mitigation exports either.
193
+ delete config.mitigations;
192
194
  config.sources = {
193
195
  ...config.sources,
194
196
  cve_now: false,
package/dist/sbom.d.ts CHANGED
@@ -8,6 +8,8 @@ export interface SbomImport {
8
8
  spec_version: string;
9
9
  digest: string;
10
10
  };
11
+ /** Things to read once that do not make the import incomplete, such as a newer CycloneDX 1.x. */
12
+ notices?: string[];
11
13
  /**
12
14
  * What the document says about the system it describes: its name, when it was created, and the
13
15
  * `security-watch:*` properties written by `security-watch sbom`. Used by an SBOM folder.
@@ -21,8 +23,17 @@ export interface SbomImport {
21
23
  /** Bounded local metadata import: never follows references, runs scripts or fetches packages. */
22
24
  export declare function importCycloneDx(path: string): SbomImport;
23
25
  /**
24
- * Imports a CycloneDX (1.4 to 1.6) or SPDX (2.2, 2.3) JSON document, whichever the file is. This
26
+ * Imports a CycloneDX (1.2 to 1.7, and later 1.x) or SPDX (2.2, 2.3) JSON document, whichever the file is. This
25
27
  * accepts the output of `security-watch sbom`, Trivy, Syft, cdxgen and GitHub's dependency-graph
26
28
  * export ("Export SBOM", or the REST API's `{ "sbom": ... }` response) without conversion.
27
29
  */
28
30
  export declare function importSbom(path: string): SbomImport;
31
+ /** The newest CycloneDX version this release was checked against. */
32
+ export declare const CYCLONEDX_KNOWN_MINOR = 7;
33
+ /**
34
+ * The CycloneDX 1.x minor version, or nothing. 1.2 is the first with `metadata` and `dependencies`.
35
+ * Minor versions add fields and deprecate, they do not remove what is read here (components, package
36
+ * URLs, references, dependencies, metadata, properties), so a later 1.x is read by the 1.7 rules.
37
+ * A 2.x is a different format and is refused.
38
+ */
39
+ export declare function cycloneDxMinor(specVersion: unknown): number | undefined;
package/dist/sbom.js CHANGED
@@ -27,7 +27,7 @@ export function importCycloneDx(path) {
27
27
  return importCycloneDxDocument(document, digest);
28
28
  }
29
29
  /**
30
- * Imports a CycloneDX (1.4 to 1.6) or SPDX (2.2, 2.3) JSON document, whichever the file is. This
30
+ * Imports a CycloneDX (1.2 to 1.7, and later 1.x) or SPDX (2.2, 2.3) JSON document, whichever the file is. This
31
31
  * accepts the output of `security-watch sbom`, Trivy, Syft, cdxgen and GitHub's dependency-graph
32
32
  * export ("Export SBOM", or the REST API's `{ "sbom": ... }` response) without conversion.
33
33
  */
@@ -38,7 +38,7 @@ export function importSbom(path) {
38
38
  const spdx = object(document) && object(document.sbom) ? document.sbom : document;
39
39
  if (object(spdx) && typeof spdx.spdxVersion === 'string')
40
40
  return importSpdxDocument(spdx, digest);
41
- throw new Error('Expected a CycloneDX JSON (1.4 to 1.6) or SPDX JSON (2.2, 2.3) SBOM');
41
+ throw new Error('Expected a CycloneDX JSON (1.2 or later 1.x) or SPDX JSON (2.2, 2.3) SBOM');
42
42
  }
43
43
  const SPDX_RELATIONSHIPS = 100_000;
44
44
  /** SPDX packages become CycloneDX-shaped components so that both formats pass the same checks. */
@@ -129,17 +129,47 @@ function importSpdxDocument(spdx, digest) {
129
129
  result.subject = { ...(name ? { name } : {}), ...(created ? { created } : {}), properties: {} };
130
130
  return result;
131
131
  }
132
+ /** The newest CycloneDX version this release was checked against. */
133
+ export const CYCLONEDX_KNOWN_MINOR = 7;
134
+ /**
135
+ * The CycloneDX 1.x minor version, or nothing. 1.2 is the first with `metadata` and `dependencies`.
136
+ * Minor versions add fields and deprecate, they do not remove what is read here (components, package
137
+ * URLs, references, dependencies, metadata, properties), so a later 1.x is read by the 1.7 rules.
138
+ * A 2.x is a different format and is refused.
139
+ */
140
+ export function cycloneDxMinor(specVersion) {
141
+ // Only text or a number: String(['1.6']) is '1.6', and a one-element array is not a version.
142
+ const match = typeof specVersion === 'string' || typeof specVersion === 'number'
143
+ ? // No leading zero: no generator writes "1.07", and "1.07" is not "1.7".
144
+ /^1\.(0|[1-9]\d{0,2})$/.exec(String(specVersion))
145
+ : null;
146
+ const minor = match ? Number(match[1]) : undefined;
147
+ return minor !== undefined && minor >= 2 ? minor : undefined;
148
+ }
149
+ /** @internal Checks a CycloneDX document held in memory, as a scan will read it. */
150
+ export function importCycloneDxValue(bom, digest) {
151
+ return importCycloneDxDocument(bom, digest);
152
+ }
132
153
  function importCycloneDxDocument(bom, digest, provenance = 'CycloneDX') {
154
+ const minor = object(bom) ? cycloneDxMinor(bom.specVersion) : undefined;
155
+ // `components` is optional in CycloneDX: an image with no packages is a valid, empty list.
133
156
  if (!object(bom) ||
134
157
  bom.bomFormat !== 'CycloneDX' ||
135
- !['1.4', '1.5', '1.6'].includes(String(bom.specVersion)) ||
136
- !Array.isArray(bom.components))
137
- throw new Error('Expected CycloneDX JSON 1.4, 1.5 or 1.6 with components');
158
+ minor === undefined ||
159
+ (bom.components !== undefined && !Array.isArray(bom.components)))
160
+ throw new Error('Expected CycloneDX JSON 1.2 or later 1.x');
138
161
  const result = {
139
162
  components: [],
140
163
  warnings: [],
141
164
  dependencies: [],
142
- source: { format: 'CycloneDX', spec_version: String(bom.specVersion), digest },
165
+ source: { format: 'CycloneDX', spec_version: `1.${minor}`, digest },
166
+ ...(minor > CYCLONEDX_KNOWN_MINOR
167
+ ? {
168
+ notices: [
169
+ `CycloneDX 1.${minor} is newer than this release knows (1.${CYCLONEDX_KNOWN_MINOR}); it was read by the 1.${CYCLONEDX_KNOWN_MINOR} rules.`,
170
+ ],
171
+ }
172
+ : {}),
143
173
  };
144
174
  const ids = new Set();
145
175
  const componentIds = new Set();
@@ -287,7 +317,7 @@ function importCycloneDxDocument(bom, digest, provenance = 'CycloneDX') {
287
317
  result.components.push(component);
288
318
  }
289
319
  };
290
- visit(bom.components, 0);
320
+ visit(bom.components ?? [], 0);
291
321
  if (bom.dependencies !== undefined) {
292
322
  if (!Array.isArray(bom.dependencies) || bom.dependencies.length > 20_000)
293
323
  throw new Error('Invalid SBOM dependencies');
@@ -0,0 +1,97 @@
1
+ import type { AdvisoryReference, Assessment, EpssScore, Evidence, FindingLocation, FixCommit, Inventory, Severity } from './types.js';
2
+ import { type MitigationStatus } from './mitigations.js';
3
+ /**
4
+ * Findings worth a temporary runtime shield (for example a Shirudo upatch) while the real fix is
5
+ * deployed, with what is known that a person or an agent needs to write one.
6
+ *
7
+ * A shield blocks one code path, so it can only be written when the vulnerable code can be found.
8
+ * `readiness` says how far the sources get there; `missing` says what is not known yet. This is a
9
+ * handoff, not advice that a shield is safe: whoever writes it tests it, and the operator approves it.
10
+ */
11
+ export type ShieldReadiness = 'fix_known' | 'fixed_version_known' | 'advisory_only' | 'news_only';
12
+ export interface ShieldCandidate {
13
+ finding_id: string;
14
+ revision?: number;
15
+ readiness: ShieldReadiness;
16
+ /** What is not known yet, in plain words. Empty only when nothing listed below is missing. */
17
+ missing: string[];
18
+ event_id: string;
19
+ /** The event and the CVE, GHSA and other identifiers of the advisories behind it. */
20
+ identifiers: string[];
21
+ title: string;
22
+ category: Assessment['category'];
23
+ applicability: Assessment['applicability'];
24
+ source_severity: Severity;
25
+ priority: Severity;
26
+ /** Listed in a known-exploited catalog (CISA KEV) or marked exploited by an advisory source. */
27
+ exploited: boolean;
28
+ /** A news article reports exploitation; not a catalog entry. */
29
+ exploitation_reported: boolean;
30
+ /** Published exploit code reported by a source (`exploit-db`, `github-poc`, ...) or by news (`news`). */
31
+ public_exploit: string[];
32
+ epss?: EpssScore;
33
+ /** Left out with `omitLocation`: a system ID is often its name. */
34
+ system_id?: string;
35
+ location?: FindingLocation;
36
+ package?: {
37
+ ecosystem: string;
38
+ name: string;
39
+ installed?: string;
40
+ fixed?: string;
41
+ purl?: string;
42
+ };
43
+ /** Links that are code changes: fix commits, pull requests, patches. The best input for a shield. */
44
+ fix_links: string[];
45
+ fix_commits: FixCommit[];
46
+ /** Other links the advisories publish: advisories, reports, exploit evidence. */
47
+ references: AdvisoryReference[];
48
+ weaknesses: string[];
49
+ /** Conditions for exploitation quoted from articles by the analysis model, when one ran. */
50
+ prerequisites?: string[];
51
+ advisories: {
52
+ id: string;
53
+ source: string;
54
+ url: string;
55
+ }[];
56
+ /** Runtime shield status read from Shirudo, when configured. */
57
+ /** Runtime mitigation status per configured source, when any covers the system. */
58
+ mitigations?: MitigationStatus[];
59
+ /** With `omitLocation`, in place of `mitigations`: whether every source proves every host mitigated. */
60
+ mitigated_everywhere?: boolean;
61
+ acknowledged?: boolean;
62
+ suppressed_until?: string;
63
+ }
64
+ export interface ShieldCandidateReport {
65
+ generated_at: string;
66
+ selection: 'urgent' | 'all';
67
+ location: 'included' | 'omitted';
68
+ counts: Record<ShieldReadiness, number>;
69
+ candidates: ShieldCandidate[];
70
+ notes: string[];
71
+ }
72
+ export interface FindingControls {
73
+ revision: number;
74
+ acknowledged: boolean;
75
+ suppressed: boolean;
76
+ suppressed_until: number | null;
77
+ }
78
+ export interface ShieldCandidateInput {
79
+ findings: Assessment[];
80
+ evidence: (ids: readonly string[]) => Evidence[];
81
+ /** The inventory as it is now, for package versions. Without it the stored location is used. */
82
+ inventory?: Inventory;
83
+ controls?: (id: string) => FindingControls | undefined;
84
+ all?: boolean;
85
+ omitLocation?: boolean;
86
+ /**
87
+ * Each configured mitigation source's `max_age_minutes`, by name: an older saved status, or one of a
88
+ * source no longer configured, is marked out of date.
89
+ */
90
+ mitigationMaxAge?: Record<string, number>;
91
+ /** Leave out findings that a fresh status shows mitigated on every host. */
92
+ unmitigatedOnly?: boolean;
93
+ now?: number;
94
+ }
95
+ /** A finding that matters enough to consider a shield: critical, or exploited in any reported way. */
96
+ export declare function urgent(finding: Assessment): boolean;
97
+ export declare function shieldCandidates(input: ShieldCandidateInput): ShieldCandidateReport;