@shieldaai/security-watch 1.2.1 → 1.4.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.
- package/CHANGELOG.md +45 -0
- package/CONTRIBUTING.md +2 -0
- package/README.md +69 -42
- package/SECURITY.md +4 -1
- package/dist/check.d.ts +193 -0
- package/dist/check.js +1000 -0
- package/dist/cli.js +301 -6
- package/dist/config.d.ts +22 -0
- package/dist/config.js +32 -0
- package/dist/cve-now.js +2 -0
- package/dist/delivery.js +30 -0
- package/dist/engine.d.ts +25 -0
- package/dist/engine.js +64 -4
- package/dist/index.d.ts +8 -1
- package/dist/index.js +3 -0
- package/dist/inventory.d.ts +2 -1
- package/dist/inventory.js +2 -3
- package/dist/manifests.d.ts +7 -0
- package/dist/manifests.js +16 -0
- package/dist/mcp-server.d.ts +256 -0
- package/dist/mcp-server.js +755 -0
- package/dist/mitigations.d.ts +137 -0
- package/dist/mitigations.js +426 -0
- package/dist/rehearsal.d.ts +25 -0
- package/dist/rehearsal.js +2 -0
- package/dist/sbom.d.ts +12 -1
- package/dist/sbom.js +37 -7
- package/dist/shield-candidates.d.ts +97 -0
- package/dist/shield-candidates.js +251 -0
- package/dist/shield-inputs.d.ts +49 -0
- package/dist/shield-inputs.js +297 -0
- package/dist/shirudo-sboms.d.ts +62 -0
- package/dist/shirudo-sboms.js +598 -0
- package/dist/sources.d.ts +2 -0
- package/dist/sources.js +14 -0
- package/dist/store.js +6 -4
- package/dist/types.d.ts +31 -0
- package/dist/vex.d.ts +62 -0
- package/dist/vex.js +246 -0
- package/docs/agents.md +139 -0
- package/docs/configuration.md +20 -1
- package/docs/mitigations.md +139 -0
- package/docs/offline-advisory-preview.md +2 -2
- package/docs/sbom.md +4 -4
- package/docs/shirudo.md +113 -0
- package/npm-shrinkwrap.json +237 -0
- package/package.json +10 -5
|
@@ -0,0 +1,598 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { lstatSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
|
|
3
|
+
import { basename, join, sep } from 'node:path';
|
|
4
|
+
import { cycloneDxMinor, importCycloneDxValue } from './sbom.js';
|
|
5
|
+
import { MAX_EXPORT_BYTES, MAX_EXPORT_ROWS } from './mitigations.js';
|
|
6
|
+
/**
|
|
7
|
+
* Copies the SBOMs of Shirudo's images from its SBOM store (`<image_id>/<image_version>/<root>/
|
|
8
|
+
* sbom.cdx.json`, a `file://` store) into Security Watch's SBOM folder, one file per image.
|
|
9
|
+
*
|
|
10
|
+
* The system ID is the image ID, so it stays the same across upgrades and a finding is not reported
|
|
11
|
+
* again for each new version. With a `node_vulns` export, the versions machines run are read; when
|
|
12
|
+
* several run (a rolling upgrade, a canary), their SBOMs are merged so the old version stays watched
|
|
13
|
+
* until it is gone. Without one, the newest version is taken.
|
|
14
|
+
*
|
|
15
|
+
* Only files this command wrote are replaced or removed; it marks them with a property. Nothing is
|
|
16
|
+
* written unless `apply` is set.
|
|
17
|
+
*/
|
|
18
|
+
export const WRITTEN_BY = 'shirudo-sboms';
|
|
19
|
+
const ID = /^[A-Za-z0-9_~+-][A-Za-z0-9._~+-]{0,254}$/;
|
|
20
|
+
const ROOT = /^(?:[0-9a-f]{64}|-)$/;
|
|
21
|
+
const MAX_SBOM_BYTES = 20 * 1024 * 1024;
|
|
22
|
+
const MAX_IMAGES = 1000;
|
|
23
|
+
const MAX_VERSIONS = 1000;
|
|
24
|
+
function directoryEntries(path) {
|
|
25
|
+
return readdirSync(path).sort();
|
|
26
|
+
}
|
|
27
|
+
/** A real directory, not a link to one: a link could lead the command out of the store. */
|
|
28
|
+
function isDirectory(path) {
|
|
29
|
+
try {
|
|
30
|
+
return lstatSync(path).isDirectory();
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** Natural order: 2026.11.10 after 2026.11.9, 1.10 after 1.9; text parts compare as text. */
|
|
37
|
+
export function compareVersions(a, b) {
|
|
38
|
+
const parts = (value) => value.match(/\d+|\D+/g) ?? [];
|
|
39
|
+
const left = parts(a);
|
|
40
|
+
const right = parts(b);
|
|
41
|
+
for (let index = 0; index < Math.max(left.length, right.length); index++) {
|
|
42
|
+
const x = left[index];
|
|
43
|
+
const y = right[index];
|
|
44
|
+
if (x === undefined)
|
|
45
|
+
return -1;
|
|
46
|
+
if (y === undefined)
|
|
47
|
+
return 1;
|
|
48
|
+
const numeric = /^\d/.test(x) && /^\d/.test(y);
|
|
49
|
+
const order = numeric
|
|
50
|
+
? BigInt(x) < BigInt(y)
|
|
51
|
+
? -1
|
|
52
|
+
: BigInt(x) > BigInt(y)
|
|
53
|
+
? 1
|
|
54
|
+
: 0
|
|
55
|
+
: x < y
|
|
56
|
+
? -1
|
|
57
|
+
: x > y
|
|
58
|
+
? 1
|
|
59
|
+
: 0;
|
|
60
|
+
if (order)
|
|
61
|
+
return order;
|
|
62
|
+
}
|
|
63
|
+
return 0;
|
|
64
|
+
}
|
|
65
|
+
/** The versions machines run, per image, with the hosts on each; and whether the export is whole. */
|
|
66
|
+
function runningVersions(path, problems) {
|
|
67
|
+
const stat = statSync(path);
|
|
68
|
+
if (!stat.isFile())
|
|
69
|
+
throw new Error('The export is not a regular file');
|
|
70
|
+
if (stat.size > MAX_EXPORT_BYTES)
|
|
71
|
+
throw new Error('The export is larger than 64 MiB');
|
|
72
|
+
const running = new Map();
|
|
73
|
+
let rows = 0;
|
|
74
|
+
let unusable = 0;
|
|
75
|
+
for (const raw of readFileSync(path, 'utf8')
|
|
76
|
+
.replace(/^\ufeff/, '')
|
|
77
|
+
.split('\n')) {
|
|
78
|
+
const line = raw.trim();
|
|
79
|
+
if (!line)
|
|
80
|
+
continue;
|
|
81
|
+
if (++rows > MAX_EXPORT_ROWS)
|
|
82
|
+
throw new Error(`The export has more than ${MAX_EXPORT_ROWS} rows`);
|
|
83
|
+
let row;
|
|
84
|
+
try {
|
|
85
|
+
row = JSON.parse(line);
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
unusable++;
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (!isObject(row)) {
|
|
92
|
+
unusable++;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const { image_id: image, image_version: version, node_id: node } = row;
|
|
96
|
+
// A machine bound to no image runs nothing to watch; it is not a damaged row.
|
|
97
|
+
if (image === '' || image === null)
|
|
98
|
+
continue;
|
|
99
|
+
if (typeof image !== 'string' ||
|
|
100
|
+
typeof version !== 'string' ||
|
|
101
|
+
(typeof node !== 'string' && !Number.isSafeInteger(node)) ||
|
|
102
|
+
!ID.test(image) ||
|
|
103
|
+
!ID.test(version) ||
|
|
104
|
+
String(node) === '') {
|
|
105
|
+
unusable++;
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
const versions = running.get(image) ?? new Map();
|
|
109
|
+
const hosts = versions.get(version) ?? new Set();
|
|
110
|
+
hosts.add(String(node));
|
|
111
|
+
versions.set(version, hosts);
|
|
112
|
+
running.set(image, versions);
|
|
113
|
+
}
|
|
114
|
+
if (unusable)
|
|
115
|
+
problems.push(`${unusable} export row(s) without a usable image_id, image_version and node_id were left out; nothing is removed while the export is incomplete.`);
|
|
116
|
+
if (!rows)
|
|
117
|
+
problems.push('The export is empty: no image is known to run. Nothing is written or removed.');
|
|
118
|
+
return { running, complete: rows > 0 && unusable === 0 };
|
|
119
|
+
}
|
|
120
|
+
/** The SBOM of one version: the newest of its builds (roots), with a note when there are several. */
|
|
121
|
+
function versionSbom(dir, image, version, problems) {
|
|
122
|
+
const roots = directoryEntries(dir).filter((name) => ROOT.test(name) && isDirectory(join(dir, name)));
|
|
123
|
+
const files = roots
|
|
124
|
+
.map((root) => join(dir, root, 'sbom.cdx.json'))
|
|
125
|
+
.filter((file) => {
|
|
126
|
+
try {
|
|
127
|
+
const stat = lstatSync(file);
|
|
128
|
+
return stat.isFile() && stat.size <= MAX_SBOM_BYTES;
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
})
|
|
134
|
+
.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs || a.localeCompare(b));
|
|
135
|
+
if (!files.length) {
|
|
136
|
+
problems.push(`${image} ${version}: no readable sbom.cdx.json of at most 20 MiB in the store.`);
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
if (files.length > 1)
|
|
140
|
+
problems.push(`${image} ${version}: ${files.length} builds in the store; the most recently stored one is used.`);
|
|
141
|
+
return files[0];
|
|
142
|
+
}
|
|
143
|
+
const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
144
|
+
/** Prefixes every component reference so that the SBOMs of several versions can be merged. */
|
|
145
|
+
function prefixComponents(components, prefix, renamed) {
|
|
146
|
+
return components.map((entry) => {
|
|
147
|
+
if (!isObject(entry))
|
|
148
|
+
return entry;
|
|
149
|
+
const copy = { ...entry };
|
|
150
|
+
if (typeof copy['bom-ref'] === 'string') {
|
|
151
|
+
const ref = `${prefix}${copy['bom-ref']}`;
|
|
152
|
+
renamed.set(copy['bom-ref'], ref);
|
|
153
|
+
copy['bom-ref'] = ref;
|
|
154
|
+
}
|
|
155
|
+
if (Array.isArray(copy.components))
|
|
156
|
+
copy.components = prefixComponents(copy.components, prefix, renamed);
|
|
157
|
+
return copy;
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* One document from the SBOMs of the running versions. Components with the same package URL are kept
|
|
162
|
+
* once; references are prefixed per version; dependency entries are kept where both ends survive.
|
|
163
|
+
*/
|
|
164
|
+
export function mergeCycloneDx(documents) {
|
|
165
|
+
if (documents.length === 1)
|
|
166
|
+
return structuredClone(documents[0]);
|
|
167
|
+
const minor = Math.max(...documents.map((doc) => cycloneDxMinor(doc.specVersion) ?? 2));
|
|
168
|
+
const components = [];
|
|
169
|
+
const seen = new Map();
|
|
170
|
+
const kept = new Set();
|
|
171
|
+
const alias = new Map();
|
|
172
|
+
const dependencies = new Map();
|
|
173
|
+
documents.forEach((doc, index) => {
|
|
174
|
+
const prefix = `v${index}:`;
|
|
175
|
+
const renamed = new Map();
|
|
176
|
+
// Nested components count too: a package that one version lists inside another component and
|
|
177
|
+
// a second version lists at the top level is still one package, and the importer would read it
|
|
178
|
+
// twice. A duplicate with components of its own passes those on in its place.
|
|
179
|
+
const unique = (entries) => {
|
|
180
|
+
const result = [];
|
|
181
|
+
for (const entry of entries) {
|
|
182
|
+
if (!isObject(entry)) {
|
|
183
|
+
result.push(entry);
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
const purl = typeof entry.purl === 'string' ? entry.purl : undefined;
|
|
187
|
+
const ref = typeof entry['bom-ref'] === 'string' ? entry['bom-ref'] : undefined;
|
|
188
|
+
const children = Array.isArray(entry.components) ? entry.components : undefined;
|
|
189
|
+
if (purl && seen.has(purl)) {
|
|
190
|
+
// The same package in an earlier version: its references point at the one kept.
|
|
191
|
+
const first = seen.get(purl);
|
|
192
|
+
if (ref && first)
|
|
193
|
+
alias.set(ref, first);
|
|
194
|
+
if (children)
|
|
195
|
+
result.push(...unique(children));
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
if (purl)
|
|
199
|
+
seen.set(purl, ref);
|
|
200
|
+
if (!children)
|
|
201
|
+
result.push(entry);
|
|
202
|
+
else {
|
|
203
|
+
const rest = unique(children);
|
|
204
|
+
const { components: _children, ...copy } = entry;
|
|
205
|
+
result.push(rest.length ? { ...copy, components: rest } : copy);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return result;
|
|
209
|
+
};
|
|
210
|
+
const own = unique(prefixComponents(Array.isArray(doc.components) ? doc.components : [], prefix, renamed));
|
|
211
|
+
components.push(...own);
|
|
212
|
+
const collect = (entries) => {
|
|
213
|
+
for (const entry of entries)
|
|
214
|
+
if (isObject(entry)) {
|
|
215
|
+
if (typeof entry['bom-ref'] === 'string')
|
|
216
|
+
kept.add(entry['bom-ref']);
|
|
217
|
+
if (Array.isArray(entry.components))
|
|
218
|
+
collect(entry.components);
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
collect(own);
|
|
222
|
+
for (const dependency of Array.isArray(doc.dependencies) ? doc.dependencies : []) {
|
|
223
|
+
if (!isObject(dependency) || typeof dependency.ref !== 'string')
|
|
224
|
+
continue;
|
|
225
|
+
const source = renamed.get(dependency.ref);
|
|
226
|
+
if (!source)
|
|
227
|
+
continue;
|
|
228
|
+
const targets = dependencies.get(source) ?? new Set();
|
|
229
|
+
for (const target of Array.isArray(dependency.dependsOn) ? dependency.dependsOn : [])
|
|
230
|
+
if (typeof target === 'string' && renamed.has(target))
|
|
231
|
+
targets.add(renamed.get(target));
|
|
232
|
+
dependencies.set(source, targets);
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
const resolve = (ref) => alias.get(ref) ?? ref;
|
|
236
|
+
const merged = new Map();
|
|
237
|
+
for (const [source, targets] of dependencies) {
|
|
238
|
+
const from = resolve(source);
|
|
239
|
+
if (!kept.has(from) || alias.has(from))
|
|
240
|
+
continue;
|
|
241
|
+
const list = merged.get(from) ?? new Set();
|
|
242
|
+
for (const target of targets) {
|
|
243
|
+
const to = resolve(target);
|
|
244
|
+
if (kept.has(to) && !alias.has(to) && to !== from)
|
|
245
|
+
list.add(to);
|
|
246
|
+
}
|
|
247
|
+
merged.set(from, list);
|
|
248
|
+
}
|
|
249
|
+
const first = documents[0];
|
|
250
|
+
return {
|
|
251
|
+
bomFormat: 'CycloneDX',
|
|
252
|
+
specVersion: `1.${minor}`,
|
|
253
|
+
version: 1,
|
|
254
|
+
...(isObject(first.metadata) ? { metadata: structuredClone(first.metadata) } : {}),
|
|
255
|
+
components,
|
|
256
|
+
dependencies: [...merged].map(([ref, targets]) => ({ ref, dependsOn: [...targets].sort() })),
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
/** Sets the Security Watch properties first (the importer takes the first of each name). */
|
|
260
|
+
function described(doc, image, note, observedAt) {
|
|
261
|
+
const metadata = isObject(doc.metadata) ? { ...doc.metadata } : {};
|
|
262
|
+
const others = Array.isArray(metadata.properties)
|
|
263
|
+
? metadata.properties.filter((property) => !(isObject(property) &&
|
|
264
|
+
typeof property.name === 'string' &&
|
|
265
|
+
property.name.startsWith('security-watch:')))
|
|
266
|
+
: [];
|
|
267
|
+
metadata.properties = [
|
|
268
|
+
{ name: 'security-watch:system-id', value: image },
|
|
269
|
+
{ name: 'security-watch:note', value: note },
|
|
270
|
+
{ name: 'security-watch:written-by', value: WRITTEN_BY },
|
|
271
|
+
...others,
|
|
272
|
+
];
|
|
273
|
+
// Seen running now: the list is current, whenever the image was built.
|
|
274
|
+
if (observedAt)
|
|
275
|
+
metadata.timestamp = observedAt;
|
|
276
|
+
return { ...doc, metadata };
|
|
277
|
+
}
|
|
278
|
+
/** The system ID a file in the SBOM folder describes, as the folder's reader takes it. */
|
|
279
|
+
function systemIdOf(name, doc) {
|
|
280
|
+
const properties = isObject(doc) && isObject(doc.metadata) ? doc.metadata.properties : undefined;
|
|
281
|
+
if (Array.isArray(properties))
|
|
282
|
+
for (const property of properties)
|
|
283
|
+
if (isObject(property) &&
|
|
284
|
+
property.name === 'security-watch:system-id' &&
|
|
285
|
+
typeof property.value === 'string')
|
|
286
|
+
return property.value;
|
|
287
|
+
return name.replace(/(?:\.(?:cdx|spdx|bom|sbom|cyclonedx))?\.json$/i, '');
|
|
288
|
+
}
|
|
289
|
+
/** What each file in the folder is: one this command wrote, and the system each describes. */
|
|
290
|
+
function folderContents(folder) {
|
|
291
|
+
const files = new Map();
|
|
292
|
+
for (const name of directoryEntries(folder)) {
|
|
293
|
+
if (!name.toLowerCase().endsWith('.json') || name.startsWith('.'))
|
|
294
|
+
continue;
|
|
295
|
+
const path = join(folder, name);
|
|
296
|
+
let doc;
|
|
297
|
+
try {
|
|
298
|
+
const stat = lstatSync(path);
|
|
299
|
+
// Larger files are read by nobody: the folder's reader refuses them too.
|
|
300
|
+
if (stat.isFile() && stat.size <= 64 * 1024 * 1024)
|
|
301
|
+
doc = JSON.parse(readFileSync(path, 'utf8').replace(/^\ufeff/, ''));
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
doc = undefined;
|
|
305
|
+
}
|
|
306
|
+
const properties = isObject(doc) && isObject(doc.metadata) ? doc.metadata.properties : undefined;
|
|
307
|
+
const ours = Array.isArray(properties) &&
|
|
308
|
+
properties.some((property) => isObject(property) &&
|
|
309
|
+
property.name === 'security-watch:written-by' &&
|
|
310
|
+
property.value === WRITTEN_BY);
|
|
311
|
+
files.set(name, { ours, system: systemIdOf(name, doc) });
|
|
312
|
+
}
|
|
313
|
+
return files;
|
|
314
|
+
}
|
|
315
|
+
function hostWord(count) {
|
|
316
|
+
return `${count} host${count === 1 ? '' : 's'}`;
|
|
317
|
+
}
|
|
318
|
+
/** A file name the file system takes: at most 255 bytes. */
|
|
319
|
+
const MAX_NAME_BYTES = 255;
|
|
320
|
+
export function syncShirudoSboms(options) {
|
|
321
|
+
const now = options.now ?? Date.now();
|
|
322
|
+
const problems = [];
|
|
323
|
+
if (!statSync(options.store).isDirectory())
|
|
324
|
+
throw new Error('The store is not a directory');
|
|
325
|
+
if (!statSync(options.output).isDirectory())
|
|
326
|
+
throw new Error('The output is not a directory');
|
|
327
|
+
// The SBOM folder inside the store would be read as an image, and the store inside the folder would
|
|
328
|
+
// put store files where the scan reads SBOMs.
|
|
329
|
+
const store = realpathSync(options.store);
|
|
330
|
+
const output = realpathSync(options.output);
|
|
331
|
+
const inside = (child, parent) => child === parent || child.startsWith(parent.endsWith(sep) ? parent : parent + sep);
|
|
332
|
+
if (inside(output, store) || inside(store, output))
|
|
333
|
+
throw new Error('The SBOM folder and the store must be separate folders, neither inside the other');
|
|
334
|
+
const exported = options.exposure ? runningVersions(options.exposure, problems) : undefined;
|
|
335
|
+
const running = exported?.running;
|
|
336
|
+
const plan = {
|
|
337
|
+
store: options.store,
|
|
338
|
+
output: options.output,
|
|
339
|
+
applied: Boolean(options.apply),
|
|
340
|
+
selection: running ? 'running' : 'newest',
|
|
341
|
+
images: [],
|
|
342
|
+
remove: [],
|
|
343
|
+
problems,
|
|
344
|
+
};
|
|
345
|
+
// An empty export says nothing about what runs: nothing is changed on its word.
|
|
346
|
+
if (exported && !running.size)
|
|
347
|
+
return plan;
|
|
348
|
+
// A name that is in the store but not a real directory (a link) is held: its file is kept.
|
|
349
|
+
const unusable = new Set();
|
|
350
|
+
const images = directoryEntries(options.store).filter((name) => {
|
|
351
|
+
if (!ID.test(name))
|
|
352
|
+
return false;
|
|
353
|
+
if (!isDirectory(join(options.store, name))) {
|
|
354
|
+
problems.push(`${name}: not a directory (or a link) in the store; left as it was.`);
|
|
355
|
+
unusable.add(name);
|
|
356
|
+
return false;
|
|
357
|
+
}
|
|
358
|
+
return true;
|
|
359
|
+
});
|
|
360
|
+
if (images.length > MAX_IMAGES)
|
|
361
|
+
throw new Error(`The store holds more than ${MAX_IMAGES} images`);
|
|
362
|
+
// An empty store is an unmounted disk or a copy that failed, not a fleet without images.
|
|
363
|
+
if (!images.length) {
|
|
364
|
+
problems.push('The store holds no image: it may not be mounted or copied. Nothing is written or removed.');
|
|
365
|
+
return plan;
|
|
366
|
+
}
|
|
367
|
+
if (running)
|
|
368
|
+
for (const image of running.keys())
|
|
369
|
+
if (!images.includes(image))
|
|
370
|
+
problems.push(`${image}: runs on machines but is not in the store.`);
|
|
371
|
+
const folder = folderContents(options.output);
|
|
372
|
+
// Systems described by files this command did not write, and by hand: an image with one of these
|
|
373
|
+
// IDs would displace that system or be refused by every scan.
|
|
374
|
+
const taken = new Map();
|
|
375
|
+
for (const [name, item] of folder)
|
|
376
|
+
if (!item.ours)
|
|
377
|
+
taken.set(item.system, name);
|
|
378
|
+
for (const id of options.reserved ?? [])
|
|
379
|
+
if (!taken.has(id))
|
|
380
|
+
taken.set(id, 'the inventory');
|
|
381
|
+
/** Images whose earlier file must stay as it is, because this run could not establish their list. */
|
|
382
|
+
const held = new Set();
|
|
383
|
+
const files = new Map();
|
|
384
|
+
// The store and, with an export, the machines confirm the list is current; the scan's staleness
|
|
385
|
+
// check then measures how long ago the sync last ran, not when the image was built.
|
|
386
|
+
const observedAt = new Date(now).toISOString();
|
|
387
|
+
const contents = new Map();
|
|
388
|
+
for (const image of images) {
|
|
389
|
+
const hold = (problem) => {
|
|
390
|
+
problems.push(problem);
|
|
391
|
+
held.add(image);
|
|
392
|
+
};
|
|
393
|
+
const dir = join(options.store, image);
|
|
394
|
+
const stored = directoryEntries(dir).filter((name) => ID.test(name) && isDirectory(join(dir, name)));
|
|
395
|
+
if (stored.length > MAX_VERSIONS) {
|
|
396
|
+
hold(`${image}: more than ${MAX_VERSIONS} versions in the store; left as it was.`);
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
let chosen;
|
|
400
|
+
const versions = running?.get(image);
|
|
401
|
+
if (running) {
|
|
402
|
+
if (!versions)
|
|
403
|
+
continue; // In the store but not running: not watched.
|
|
404
|
+
chosen = [...versions]
|
|
405
|
+
.filter(([version]) => {
|
|
406
|
+
if (stored.includes(version))
|
|
407
|
+
return true;
|
|
408
|
+
problems.push(`${image} ${version}: runs on ${hostWord(versions.get(version).size)} but has no SBOM in the store.`);
|
|
409
|
+
return false;
|
|
410
|
+
})
|
|
411
|
+
.map(([version, hosts]) => ({ version, hosts: hosts.size }));
|
|
412
|
+
}
|
|
413
|
+
else {
|
|
414
|
+
const newest = [...stored].sort(compareVersions).at(-1);
|
|
415
|
+
chosen = newest ? [{ version: newest }] : [];
|
|
416
|
+
}
|
|
417
|
+
chosen.sort((a, b) => compareVersions(b.version, a.version));
|
|
418
|
+
if (!chosen.length) {
|
|
419
|
+
// With an export, each running version without an SBOM was named above.
|
|
420
|
+
if (running)
|
|
421
|
+
held.add(image);
|
|
422
|
+
else
|
|
423
|
+
hold(`${image}: no version in the store; left as it was.`);
|
|
424
|
+
continue;
|
|
425
|
+
}
|
|
426
|
+
const documents = [];
|
|
427
|
+
const used = [];
|
|
428
|
+
for (const item of chosen) {
|
|
429
|
+
const file = versionSbom(join(dir, item.version), image, item.version, problems);
|
|
430
|
+
if (!file)
|
|
431
|
+
continue;
|
|
432
|
+
try {
|
|
433
|
+
const doc = JSON.parse(readFileSync(file, 'utf8').replace(/^\ufeff/, ''));
|
|
434
|
+
if (!isObject(doc) || doc.bomFormat !== 'CycloneDX' || cycloneDxMinor(doc.specVersion) === undefined)
|
|
435
|
+
throw new Error('not CycloneDX JSON 1.2 or later 1.x');
|
|
436
|
+
documents.push(doc);
|
|
437
|
+
used.push(item);
|
|
438
|
+
}
|
|
439
|
+
catch (error) {
|
|
440
|
+
problems.push(`${image} ${item.version}: the SBOM cannot be read (${error.message}).`);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
// A running version whose SBOM is missing or unreadable: a new list without it would stop watching
|
|
444
|
+
// that version's packages while hosts still run it, so an earlier list is kept instead. With no
|
|
445
|
+
// earlier list, the versions that can be read are better than nothing.
|
|
446
|
+
// Running versions with no SBOM in the store count too: they were left out of `chosen`.
|
|
447
|
+
const failed = used.length < (versions?.size ?? chosen.length);
|
|
448
|
+
const earlier = [...folder].some(([file, item]) => item.ours && file.toLowerCase() === `${image}.cdx.json`.toLowerCase());
|
|
449
|
+
if (failed && earlier && documents.length) {
|
|
450
|
+
held.add(image);
|
|
451
|
+
problems.push(`${image}: kept as it was, because not every running version's SBOM could be read.`);
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
// No version could be read: the earlier list, if any, is kept rather than lost.
|
|
455
|
+
if (!documents.length) {
|
|
456
|
+
held.add(image);
|
|
457
|
+
if (!problems.some((problem) => problem.startsWith(`${image} `) || problem.startsWith(`${image}:`)))
|
|
458
|
+
problems.push(`${image}: no SBOM could be read; left as it was.`);
|
|
459
|
+
continue;
|
|
460
|
+
}
|
|
461
|
+
const name = `${image}.cdx.json`;
|
|
462
|
+
if (Buffer.byteLength(name) > MAX_NAME_BYTES) {
|
|
463
|
+
hold(`${image}: the image ID is too long for a file name; left out.`);
|
|
464
|
+
continue;
|
|
465
|
+
}
|
|
466
|
+
if (taken.has(image)) {
|
|
467
|
+
hold(`${image}: the system ID is already used by ${taken.get(image)}; this image is not written. Rename that system, or watch the image under another ID.`);
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
const note = `Shirudo image ${image}: ${used
|
|
471
|
+
.map((item) => item.hosts === undefined
|
|
472
|
+
? `version ${item.version} (newest in the store)`
|
|
473
|
+
: `version ${item.version} on ${hostWord(item.hosts)}`)
|
|
474
|
+
.join(', ')}`;
|
|
475
|
+
const doc = described(mergeCycloneDx(documents), image, note.slice(0, 1000), observedAt);
|
|
476
|
+
// Compact: the folder's reader takes at most 20 MiB, and indentation would cost a third more.
|
|
477
|
+
const text = JSON.stringify(doc) + '\n';
|
|
478
|
+
if (Buffer.byteLength(text) > MAX_SBOM_BYTES) {
|
|
479
|
+
hold(`${image}: the SBOM would be larger than 20 MiB, which a scan refuses; left as it was.`);
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
try {
|
|
483
|
+
// What a scan will read, checked now: a file it would refuse is not written.
|
|
484
|
+
importCycloneDxValue(JSON.parse(text), `sha256:${createHash('sha256').update(text).digest('hex')}`);
|
|
485
|
+
}
|
|
486
|
+
catch (error) {
|
|
487
|
+
hold(`${image}: the SBOM would not be accepted by a scan (${error.message}); left as it was.`);
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
// On a case-insensitive file system Fleet-OS and fleet-os are one file.
|
|
491
|
+
const folded = name.toLowerCase();
|
|
492
|
+
if (files.has(folded)) {
|
|
493
|
+
hold(`${image}: its file name differs from ${files.get(folded)}'s only in letter case; left out.`);
|
|
494
|
+
continue;
|
|
495
|
+
}
|
|
496
|
+
files.set(folded, image);
|
|
497
|
+
const target = join(options.output, name);
|
|
498
|
+
// On a case-insensitive file system app.cdx.json is App.cdx.json: look the name up without case.
|
|
499
|
+
const found = [...folder].find(([existing]) => existing.toLowerCase() === folded);
|
|
500
|
+
if (found && found[0] !== name) {
|
|
501
|
+
hold(`${image}: ${found[0]} in the SBOM folder differs from ${name} only in letter case; left out.`);
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
const present = found?.[1];
|
|
505
|
+
if (present && !present.ours) {
|
|
506
|
+
hold(`${name} exists in the SBOM folder and was not written by this command; it is not replaced.`);
|
|
507
|
+
continue;
|
|
508
|
+
}
|
|
509
|
+
const existing = present ? readFileSync(target, 'utf8') : undefined;
|
|
510
|
+
// An unchanged list is not rewritten, so its time is kept; a confirmed time alone is not a change...
|
|
511
|
+
const comparable = (value) => {
|
|
512
|
+
try {
|
|
513
|
+
const parsed = JSON.parse(value);
|
|
514
|
+
if (isObject(parsed.metadata))
|
|
515
|
+
delete parsed.metadata.timestamp;
|
|
516
|
+
return JSON.stringify(parsed);
|
|
517
|
+
}
|
|
518
|
+
catch {
|
|
519
|
+
return value;
|
|
520
|
+
}
|
|
521
|
+
};
|
|
522
|
+
// ...but it is confirmed at least daily, so a stable image never looks stale.
|
|
523
|
+
const confirmedRecently = (() => {
|
|
524
|
+
if (existing === undefined)
|
|
525
|
+
return true;
|
|
526
|
+
try {
|
|
527
|
+
const parsed = JSON.parse(existing);
|
|
528
|
+
const time = isObject(parsed.metadata) ? Date.parse(String(parsed.metadata.timestamp)) : Number.NaN;
|
|
529
|
+
return Number.isFinite(time) && now - time < 86_400_000;
|
|
530
|
+
}
|
|
531
|
+
catch {
|
|
532
|
+
return false;
|
|
533
|
+
}
|
|
534
|
+
})();
|
|
535
|
+
const unchanged = existing !== undefined && confirmedRecently && comparable(existing) === comparable(text);
|
|
536
|
+
plan.images.push({
|
|
537
|
+
image_id: image,
|
|
538
|
+
file: name,
|
|
539
|
+
versions: used,
|
|
540
|
+
action: unchanged ? 'unchanged' : 'write',
|
|
541
|
+
});
|
|
542
|
+
if (!unchanged)
|
|
543
|
+
contents.set(target, text);
|
|
544
|
+
}
|
|
545
|
+
// A file is removed only when its image is known to be gone: not run by any machine of a complete
|
|
546
|
+
// export, or no longer in the store. A failed read, an incomplete export or any problem with the
|
|
547
|
+
// image keeps the file, so a scan never loses a system because the sync could not see it.
|
|
548
|
+
const removable = !exported || exported.complete;
|
|
549
|
+
const selected = new Set(plan.images.map((item) => item.file));
|
|
550
|
+
let kept = 0;
|
|
551
|
+
for (const [name, item] of folder) {
|
|
552
|
+
if (!item.ours || selected.has(name) || held.has(item.system) || unusable.has(item.system))
|
|
553
|
+
continue;
|
|
554
|
+
const gone = running ? !running.has(item.system) : !images.includes(item.system);
|
|
555
|
+
if (!gone)
|
|
556
|
+
continue;
|
|
557
|
+
if (removable)
|
|
558
|
+
plan.remove.push(name);
|
|
559
|
+
else
|
|
560
|
+
kept++;
|
|
561
|
+
}
|
|
562
|
+
if (kept)
|
|
563
|
+
problems.push(`${kept} file(s) for images no longer seen were kept, because the export is incomplete.`);
|
|
564
|
+
// Most of the watched images disappearing at once is more likely a half-copied store or a cut
|
|
565
|
+
// export than a fleet that changed: it is done only when asked for.
|
|
566
|
+
const ours = [...folder.values()].filter((item) => item.ours).length;
|
|
567
|
+
if (plan.remove.length >= 2 && plan.remove.length * 2 > ours && !options.allowRemovals) {
|
|
568
|
+
problems.push(`${plan.remove.length} of ${ours} watched images would be removed; nothing is removed. If the fleet really changed, run again with --allow-removals.`);
|
|
569
|
+
plan.remove = [];
|
|
570
|
+
}
|
|
571
|
+
// The SBOM folder holds at most 1,000 files; a sync that would pass that is refused whole.
|
|
572
|
+
const added = plan.images.filter((item) => !folder.has(item.file)).length;
|
|
573
|
+
if (folder.size + added - plan.remove.length > 1000)
|
|
574
|
+
throw new Error('The SBOM folder would hold more than 1,000 SBOM files');
|
|
575
|
+
if (options.apply) {
|
|
576
|
+
for (const [target, text] of contents) {
|
|
577
|
+
// A hidden temporary name: the SBOM folder skips names that start with a dot, so a scan never
|
|
578
|
+
// reads a half-written file, and the rename makes the new file appear whole.
|
|
579
|
+
const temporary = join(options.output, `.${randomUUID()}.tmp`);
|
|
580
|
+
try {
|
|
581
|
+
writeFileSync(temporary, text, { flag: 'wx', mode: 0o600 });
|
|
582
|
+
renameSync(temporary, target);
|
|
583
|
+
}
|
|
584
|
+
catch (error) {
|
|
585
|
+
problems.push(`${basename(target)}: could not be written (${error.message}); left as it was.`);
|
|
586
|
+
const entry = plan.images.find((item) => join(options.output, item.file) === target);
|
|
587
|
+
if (entry)
|
|
588
|
+
entry.action = 'unchanged';
|
|
589
|
+
}
|
|
590
|
+
finally {
|
|
591
|
+
rmSync(temporary, { force: true });
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
for (const name of plan.remove)
|
|
595
|
+
rmSync(join(options.output, name), { force: true });
|
|
596
|
+
}
|
|
597
|
+
return plan;
|
|
598
|
+
}
|
package/dist/sources.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
import type { Config, CoverageReceipt, Evidence, HttpClient, Inventory, SourceResult } from './types.js';
|
|
2
|
+
/** One OSV record (`GET /v1/vulns/ID`) read as evidence, for a one-off lookup by identifier. */
|
|
3
|
+
export declare function osvEvidence(raw: unknown, id: string, now: number): Evidence;
|
|
2
4
|
/** Collect source evidence and report failures without advancing failed sources' checkpoints. */
|
|
3
5
|
export declare function collectSources(inventory: Inventory, config: Config, checkpoints: Record<string, string>, http: HttpClient, now?: number, previousEvidence?: Evidence[], previousCoverage?: CoverageReceipt[]): Promise<SourceResult>;
|
package/dist/sources.js
CHANGED
|
@@ -3,6 +3,7 @@ import { defaultTreeAdapter, parse, parseFragment } from 'parse5';
|
|
|
3
3
|
import { compare, valid } from 'semver';
|
|
4
4
|
import { cvssV4BaseScore } from './cvss4.js';
|
|
5
5
|
import { cleanText, hash, highest, singleLine, timestamp } from './util.js';
|
|
6
|
+
import { githubReferences, githubWeaknesses, osvFixCommits, osvReferences, osvWeaknesses, shieldInputs, } from './shield-inputs.js';
|
|
6
7
|
import { collectCveNow, evidenceRelevant } from './cve-now.js';
|
|
7
8
|
import { VENDOR_FEEDS, vendorArticleBody, vendorArticleTarget } from './vendor-sources.js';
|
|
8
9
|
import { exactLibraryVersion, normalizeEcosystem, normalizePackageName, osvPackageNames, samePackage, } from './ecosystems.js';
|
|
@@ -363,8 +364,17 @@ function osvRecord(raw, expectedId, matches, now) {
|
|
|
363
364
|
packages: packageClaims,
|
|
364
365
|
withdrawn: data.withdrawn === undefined || data.withdrawn === null ? false : !!date(data.withdrawn),
|
|
365
366
|
malware: /^MAL-/.test(expectedId),
|
|
367
|
+
...shieldInputs({
|
|
368
|
+
references: osvReferences(data.references),
|
|
369
|
+
fix_commits: osvFixCommits(data.affected),
|
|
370
|
+
weaknesses: osvWeaknesses(data),
|
|
371
|
+
}),
|
|
366
372
|
};
|
|
367
373
|
}
|
|
374
|
+
/** One OSV record (`GET /v1/vulns/ID`) read as evidence, for a one-off lookup by identifier. */
|
|
375
|
+
export function osvEvidence(raw, id, now) {
|
|
376
|
+
return osvRecord(raw, id, [], now);
|
|
377
|
+
}
|
|
368
378
|
async function osv(inventory, previous, http, now) {
|
|
369
379
|
const unique = new Map();
|
|
370
380
|
for (const system of inventory.systems)
|
|
@@ -597,6 +607,10 @@ function githubRecord(raw, type, now) {
|
|
|
597
607
|
packages,
|
|
598
608
|
withdrawn: data.withdrawn_at === undefined || data.withdrawn_at === null ? false : !!date(data.withdrawn_at),
|
|
599
609
|
malware: type === 'malware',
|
|
610
|
+
...shieldInputs({
|
|
611
|
+
references: githubReferences(data.references),
|
|
612
|
+
weaknesses: githubWeaknesses(data.cwes),
|
|
613
|
+
}),
|
|
600
614
|
};
|
|
601
615
|
}
|
|
602
616
|
function nextGithubLink(link) {
|
package/dist/store.js
CHANGED
|
@@ -3,6 +3,7 @@ import { closeSync, constants, existsSync, linkSync, lstatSync, mkdirSync, mkdte
|
|
|
3
3
|
import { dirname, join, resolve } from 'node:path';
|
|
4
4
|
import { randomUUID } from 'node:crypto';
|
|
5
5
|
import { hash, canonicalHash } from './util.js';
|
|
6
|
+
import { evidenceContent } from './shield-inputs.js';
|
|
6
7
|
import { decide } from './assessment.js';
|
|
7
8
|
import { aggregatePilotReport, validatePilotWindow, PilotReportError, } from './pilot-report.js';
|
|
8
9
|
import { validateRetentionPolicy, } from './maintenance.js';
|
|
@@ -59,8 +60,8 @@ function notification(row) {
|
|
|
59
60
|
};
|
|
60
61
|
}
|
|
61
62
|
function evidenceFingerprint(evidence) {
|
|
62
|
-
|
|
63
|
-
return hash(
|
|
63
|
+
// Links, fix commits, weaknesses and exploit-code entries are shield inputs, not a new revision.
|
|
64
|
+
return hash(evidenceContent(evidence));
|
|
64
65
|
}
|
|
65
66
|
function fingerprint(a, decision) {
|
|
66
67
|
// Article wording, source arrival order and AI phrasing are not new security events.
|
|
@@ -391,8 +392,9 @@ export class Store {
|
|
|
391
392
|
: [];
|
|
392
393
|
// Where the finding lives (inventory names and notes) is shown to the reader; it is not part
|
|
393
394
|
// of the conclusion a reviewer approves, so editing a note does not ask for a new review.
|
|
394
|
-
// EPSS changes daily and
|
|
395
|
-
|
|
395
|
+
// EPSS changes daily and mitigation status with every export; both are shown only and are
|
|
396
|
+
// not part of the conclusion either.
|
|
397
|
+
const { updated_at: _updated, location: _location, epss: _epss, mitigations: _mitigations, ...reviewedAssessment } = assessment;
|
|
396
398
|
// Ordinary alert deduplication stays semantic. A human review instead binds the exact
|
|
397
399
|
// supplied conclusion, source content and host inventory/model context, excluding scan time.
|
|
398
400
|
const signature = decision.review
|