-
Notifications
You must be signed in to change notification settings - Fork 37
/
index.js
317 lines (265 loc) · 10.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
const { api, callRateLimitAPI } = require("./requests");
const { existsSync, mkdirSync } = require("node:fs");
const { logger } = require("@docusaurus/logger");
const fs = require("fs").promises;
const path = require("path");
const { formatDateCveDetails } = require("../helpers/date");
const { escapeMDXSpecialChars } = require("../helpers/string");
const { generateMarkdownTable } = require("../helpers/affected-table");
const { generateRevisionHistory } = require("../helpers/revision-history");
const { generateCVEOfficialDetailsUrl } = require("../helpers/urls");
const { generateCVEMap } = require("../helpers/cveHelpers");
async function getSecurityBulletins(payload) {
const limit = 300;
const maxIterations = 1000;
let results = [];
try {
let request = await callRateLimitAPI(() =>
api.post(`https://dso.teams.spectrocloud.com/v1/advisories?limit=${limit}`, payload)
);
results = request.data.advisories;
let iteration = 0;
while (request.data.continue && iteration < maxIterations) {
iteration++;
request = await callRateLimitAPI(() =>
api.post(
`https://dso.teams.spectrocloud.com/v1/advisories?${limit}&offset=${request.data.offset + limit}`,
payload
)
);
results = results.concat(request.data.advisories);
}
if (iteration === maxIterations) {
logger.warn("Max iterations reached. Verify the API response is setting the continue flag correctly.");
}
return { data: results };
} catch (error) {
logger.error("Error:", error.response ? `${error.response.status} - ${error.response.data}` : error.message);
}
}
// This function filters the items by UID and returns only the items that start with the keyword, such as "PA-", "VA-", etc.
function filterByUID(items, keyword) {
if (!Array.isArray(items)) {
throw new Error("Input must be an array of objects");
}
return items.filter((item) => {
if (!item.metadata || typeof item.metadata.uid !== "string") {
console.warn("Skipping item due to missing or invalid metadata.uid:", item);
return false;
}
return item.metadata.uid.startsWith(keyword);
});
}
async function generateCVEs() {
let GlobalCVEData = {};
const securityBulletins = new Map();
const dirname = path.join(".docusaurus", "security-bulletins", "default");
const filename = path.join(dirname, "data.json");
if (process.env.DISABLE_SECURITY_INTEGRATIONS === "true") {
logger.info("Security integrations are disabled. Skipping generation of security bulletins.");
if (!existsSync(dirname) || !existsSync(filename)) {
// Write the security bulletins data to a JSON file
mkdirSync(dirname, { recursive: true });
await fs.writeFile(filename, JSON.stringify({}, null, 2));
}
return;
}
if (existsSync(dirname) && existsSync(filename)) {
logger.info("Security bulletins JSON file already exists. Skipping fetching.");
GlobalCVEData = JSON.parse(await fs.readFile(filename, "utf-8"));
} else {
logger.info("Fetching security bulletins...");
try {
const palette = await getSecurityBulletins({
filters: [
{
field: "metadata.nistSeverity",
operator: "in",
options: ["CRITICAL", "HIGH"],
},
{
field: "spec.impact.impactedProducts.palette",
operator: "ex",
},
{
field: "spec.impact.impactedDeployments.connected",
operator: "ex",
},
{
field: "status.state",
options: ["Analyzed", "Modified", "Awaiting Analyses", "Reopened", "Resolved"],
operator: "in",
},
],
});
const paletteAirgap = await getSecurityBulletins({
filters: [
{
field: "metadata.nistSeverity",
operator: "in",
options: ["CRITICAL", "HIGH"],
},
{
field: "spec.impact.impactedProducts.palette",
operator: "ex",
},
{
field: "spec.impact.impactedDeployments.airgap",
operator: "ex",
},
{
field: "status.state",
options: ["Analyzed", "Modified", "Awaiting Analyses", "Reopened", "Resolved"],
operator: "in",
},
],
});
const vertex = await getSecurityBulletins({
filters: [
{
field: "metadata.nistSeverity",
operator: "in",
options: ["CRITICAL", "HIGH"],
},
{
field: "spec.impact.impactedProducts.vertex",
operator: "ex",
},
{
field: "spec.impact.impactedDeployments.connected",
operator: "ex",
},
{
field: "status.state",
options: ["Analyzed", "Modified", "Awaiting Analyses", "Reopened", "Resolved"],
operator: "in",
},
],
});
const vertexAirgap = await getSecurityBulletins({
filters: [
{
field: "metadata.nistSeverity",
operator: "in",
options: ["CRITICAL", "HIGH"],
},
{
field: "spec.impact.impactedProducts.vertex",
operator: "ex",
},
{
field: "spec.impact.impactedDeployments.airgap",
operator: "ex",
},
{
field: "status.state",
options: ["Analyzed", "Modified", "Awaiting Analyses", "Reopened", "Resolved"],
operator: "in",
},
],
});
// There is no way to filter by product in the API, so we need to filter the results manually to get a list of CVEs for each product
const filterdPalette = filterByUID(palette.data, "PC-");
const filterdPaletteAirgap = filterByUID(paletteAirgap.data, "PA-");
const filterdVertex = filterByUID(vertex.data, "VC-");
const filterdVertexAirgap = filterByUID(vertexAirgap.data, "VA-");
// Debug logs
// logger.info(`Palette CVEs:", ${filterdPalette.length}`);
// logger.info(`Palette Airgap CVEs:", ${filterdPaletteAirgap.length}`);
// logger.info(`Vertex CVEs:", ${filterdVertex.length}`);
// logger.info(`Vertex Airgap CVEs:", ${filterdVertexAirgap.length}`);
securityBulletins.set("palette", filterdPalette);
securityBulletins.set("paletteAirgap", filterdPaletteAirgap);
securityBulletins.set("vertex", filterdVertex);
securityBulletins.set("vertexAirgap", filterdVertexAirgap);
const plainObject = Object.fromEntries(
Array.from(securityBulletins.entries()).map(([key, value]) => [key, value])
);
GlobalCVEData = plainObject;
// Write the security bulletins data to a JSON file
mkdirSync(dirname, { recursive: true });
await fs.writeFile(filename, JSON.stringify(GlobalCVEData, null, 2));
logger.info("Finished fetching security bulletins data.");
} catch (error) {
logger.error(error);
logger.error("Error:", error.response ? error.response.status : error.message);
}
}
await generateMarkdownForCVEs(GlobalCVEData);
}
async function generateMarkdownForCVEs(GlobalCVEData) {
const allCVEs = Object.values(GlobalCVEData).reduce((acc, curr) => acc.concat(curr), []);
// To generate the Impact Product & Versions table we need to track all the instances of the same CVE
// The following hashmap will store the data for each CVE and aggregate the impact data for each product
const cveImpactMap = generateCVEMap(allCVEs);
const markdownPromises = allCVEs.map((item) =>
createCveMarkdown(item, cveImpactMap[item.metadata.cve], "docs/docs-content/security-bulletins/reports/")
);
const results = await Promise.all(markdownPromises);
const failedFiles = results.filter((result) => !result.success);
if (failedFiles.length > 0) {
logger.error("Failed to generate the following markdown files:");
failedFiles.forEach((failure) => {
logger.error(`File: ${failure.file}, Error: ${failure.error.message}`);
});
}
logger.success("All security bulletin markdown files generated.");
}
function createCveMarkdown(item, cveImpactData, location) {
const upperCaseCve = item.metadata.cve.toUpperCase();
const revisions = item.spec.revision;
const uid = item.metadata.uid.toLowerCase();
// Generate a table of impacted products
let table = generateMarkdownTable(cveImpactData);
let revisionHistory = generateRevisionHistory(revisions);
const content = `---
sidebar_label: "${upperCaseCve}"
title: "${upperCaseCve}"
description: "Lifecycle of ${upperCaseCve}"
sidebar_class_name: "hide-from-sidebar"
hide_table_of_contents: false
toc_max_heading_level: 2
tags: ["security", "cve"]
---
## CVE Details
Visit the official vulnerability details page for [${upperCaseCve}](${generateCVEOfficialDetailsUrl(item.metadata.cve)}) to learn more.
## Initial Publication
${formatDateCveDetails(item.metadata.advCreatedTimestamp)}
## Last Update
${formatDateCveDetails(item.metadata.advLastModifiedTimestamp)}
${item.spec.assessment?.thirdParty?.dependentPackage != "" ? `## Third Party Dependency \n\n${item.spec.assessment.thirdParty.dependentPackage}` : "This CVE does not have a third party dependency."}
## NIST CVE Summary
${escapeMDXSpecialChars(item.metadata.summary)}
## CVE Severity
[${item.metadata.cvssScore}](${generateCVEOfficialDetailsUrl(item.metadata.cve)})
## Our Official Summary
${item.spec.assessment.justification ? escapeMDXSpecialChars(item.spec.assessment.justification) : "Investigation is ongoing to determine how this vulnerability affects our products."}
## Status
${item.status.status}
## Affected Products & Versions
${item.spec.impact.isImpacting ? table : "This CVE is non-impacting as the impacting symbol and/or function is not used in the product"}
## Revision History
${revisionHistory ? revisionHistory : "No revision history available."}
`;
const filePath = path.join(location, `${uid}.md`);
// Return a promise and include the CVE or file path in the error log
return fs
.writeFile(filePath, content)
.then(() => ({
success: true,
file: filePath,
}))
.catch((err) => {
console.error(`Error writing file for ${upperCaseCve} at ${filePath}:`, err);
return {
success: false,
file: filePath,
error: err,
};
});
}
try {
generateCVEs();
} catch (error) {
process.exit(5);
}