-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathvulnerability.ts
386 lines (349 loc) · 13.4 KB
/
vulnerability.ts
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import get from 'lodash.get';
import { isJsonString, trimArray, shortenNodePath } from './common';
import { color, getSeverityBgColor } from './color';
import { printExceptionReport } from './print';
import { analyzeExpiry } from './date';
import {
NpmAuditJson,
v7VulnerabilityVia,
ProcessedResult,
ProcessedReport,
v6Advisory,
v7Vulnerability,
NsprcConfigs,
NsprcFile,
AuditLevel,
AuditNumber,
} from 'src/types';
const MAX_PATHS_SIZE = 5;
/**
* Converts an audit level to a numeric value
* @param {String} auditLevel Audit level
* @return {Number} Numeric level: the higher the number, the more severe it is
*/
export function mapLevelToNumber(auditLevel: AuditLevel | string): AuditNumber {
switch (auditLevel) {
case 'info':
return 0;
case 'low':
return 1;
case 'moderate':
return 2;
case 'high':
return 3;
case 'critical':
return 4;
default:
return 0;
}
}
/**
* Validate if the vulnerability should be excepted
* @param {Object} vulnerability NPM v6 audit report's vulnerability
* @param {Array} exceptionIds Exception IDs
* @return {Object} Validation result
*/
export function validateV6Vulnerability(
vulnerability: v6Advisory,
exceptionIds: string[],
): { isExcepted: boolean; usedExceptionKey: string } {
return exceptionIds.reduce(
(acc: { isExcepted: boolean; usedExceptionKey: string }, id) => {
// check if ID matches
if (id === String(vulnerability.id)) {
return { isExcepted: true, usedExceptionKey: id };
}
// check if any of the CVEs matches
if (Array.isArray(vulnerability.cves) && vulnerability.cves.includes(id)) {
return { isExcepted: true, usedExceptionKey: id };
}
// check if the CWE matches
if (vulnerability.cwe === id) {
return { isExcepted: true, usedExceptionKey: id };
}
// check if the URL matches
if (vulnerability.url && vulnerability.url.includes(id)) {
return { isExcepted: true, usedExceptionKey: id };
}
return acc;
},
{
isExcepted: false,
usedExceptionKey: '',
},
);
}
/**
* Validate if the vulnerability should be excepted
* @param {Object} vulnerability NPM v7 audit report's vulnerability
* @param {Array} exceptionIds Exception IDs
* @return {Object} Validation result
*/
export function validateV7Vulnerability(
vulnerability: v7VulnerabilityVia,
exceptionIds: string[],
): { isExcepted: boolean; usedExceptionKey: string } {
return exceptionIds.reduce(
(acc: { isExcepted: boolean; usedExceptionKey: string }, id) => {
// check if ID matches
if (id === String(vulnerability.source)) {
return { isExcepted: true, usedExceptionKey: id };
}
// check if the URL matches
if (vulnerability.url && vulnerability.url.includes(id)) {
return { isExcepted: true, usedExceptionKey: id };
}
return acc;
},
{
isExcepted: false,
usedExceptionKey: '',
},
);
}
/**
* Analyze the JSON string buffer
* @param {String} jsonBuffer NPM Audit JSON string buffer
* @param {String} auditLevel User's target audit level
* @param {Array} exceptionIds Exception IDs (ID to be ignored)
* @param {Array} exceptionModules Exception modules (modules to be ignored)
* @param {Array} columnsToInclude List of columns to include in audit results
* @return {Object} Processed vulnerabilities details
*/
export function processAuditJson(
jsonBuffer = '',
auditLevel: AuditLevel = 'info',
exceptionIds: string[] = [],
exceptionModules: string[] = [],
columnsToInclude: string[] = [],
): ProcessedResult {
if (!isJsonString(jsonBuffer)) {
return {
unhandledIds: [],
vulnerabilityIds: [],
vulnerabilityModules: [],
unusedExceptionIds: exceptionIds,
unusedExceptionModules: exceptionModules,
report: [],
failed: true,
};
}
// NPM v6 uses `advisories`
// NPM v7 uses `vulnerabilities`
// Refer to the `test/__mocks__` folder for some sample mockups
const { advisories, vulnerabilities }: NpmAuditJson = JSON.parse(jsonBuffer);
// NPM v6 handling
if (advisories) {
return Object.values(advisories).reduce(
(acc: ProcessedResult, cur: v6Advisory) => {
const shouldAudit = mapLevelToNumber(cur.severity) >= mapLevelToNumber(auditLevel);
const { isExcepted: isIdExcepted, usedExceptionKey } = validateV6Vulnerability(cur, exceptionIds);
const isModuleExcepted = exceptionModules.includes(cur.module_name);
const isExcepted = isIdExcepted || isModuleExcepted;
// Record used exception ID/module
if (isIdExcepted) {
acc.unusedExceptionIds = acc.unusedExceptionIds.filter((id) => id !== usedExceptionKey);
}
if (isModuleExcepted) {
acc.unusedExceptionModules = acc.unusedExceptionModules.filter((module) => module !== cur.module_name);
}
const rowData = [
{ key: 'ID', value: cur.id.toString() },
{ key: 'Module', value: cur.module_name },
{ key: 'Title', value: cur.title },
{
key: 'Paths',
value: trimArray(
cur.findings.reduce((a, c) => [...a, ...c.paths] as [], []),
MAX_PATHS_SIZE,
).join('\n'),
},
{ key: 'Severity', value: cur.severity },
{ key: 'URL', value: cur.url },
{ key: 'Ex.', value: isExcepted ? 'y' : 'n' },
]
.filter(({ key }) => (columnsToInclude.length ? columnsToInclude.includes(key) : true))
.map(({ key, value }) =>
color(value, isExcepted ? '' : 'yellow', key === 'Severity' ? getSeverityBgColor(cur.severity) : undefined),
);
// Record this vulnerability into the report, and highlight it using yellow color if it's new
acc.report.push(rowData);
acc.vulnerabilityIds.push(cur.id.toString());
if (!acc.vulnerabilityModules.includes(cur.module_name)) {
acc.vulnerabilityModules.push(cur.module_name);
}
// Found unhandled vulnerabilities
if (shouldAudit && !isExcepted) {
acc.unhandledIds.push(cur.id.toString());
}
return acc;
},
{
unhandledIds: [],
vulnerabilityIds: [],
vulnerabilityModules: [],
unusedExceptionIds: exceptionIds,
unusedExceptionModules: exceptionModules,
report: [],
},
);
}
// NPM v7 handling
if (vulnerabilities) {
return Object.values(vulnerabilities).reduce(
(acc: ProcessedResult, cur: v7Vulnerability | string) => {
// Inside `via` array, its either the related module name or the vulnerability source object.
get(cur, 'via', []).forEach((vul: v7VulnerabilityVia | string) => {
// The vulnerability ID is labeled as `source`
const id = get(vul, 'source');
const moduleName = get(vul, 'name', '');
// Let's skip if ID is a string (module name), and only focus on the root vulnerabilities
if (!id || typeof id === 'string' || typeof vul === 'string') {
return;
}
const shouldAudit = mapLevelToNumber(vul.severity) >= mapLevelToNumber(auditLevel);
const { isExcepted: isIdExcepted, usedExceptionKey } = validateV7Vulnerability(vul, exceptionIds);
const isModuleExcepted = exceptionModules.includes(moduleName);
const isExcepted = isIdExcepted || isModuleExcepted;
// Record used exception ID/module
if (isIdExcepted) {
acc.unusedExceptionIds = acc.unusedExceptionIds.filter((id) => id !== usedExceptionKey);
}
if (isModuleExcepted) {
acc.unusedExceptionModules = acc.unusedExceptionModules.filter((module) => module !== moduleName);
}
const rowData = [
{ key: 'ID', value: String(id) },
{ key: 'Module', value: vul.name },
{ key: 'Title', value: vul.title },
{ key: 'Paths', value: trimArray(get(cur, 'nodes', []).map(shortenNodePath), MAX_PATHS_SIZE).join('\n') },
{ key: 'Severity', value: vul.severity, bgColor: getSeverityBgColor(vul.severity) },
{ key: 'URL', value: vul.url },
{ key: 'Ex.', value: isExcepted ? 'y' : 'n' },
]
.filter(({ key }) => (columnsToInclude.length ? columnsToInclude.includes(key) : true))
.map(({ key, value, bgColor }) => color(value, isExcepted ? '' : 'yellow', key === 'Severity' ? bgColor : undefined));
// Record this vulnerability into the report, and highlight it using yellow color if it's new
acc.report.push(rowData);
acc.vulnerabilityIds.push(String(id));
if (!acc.vulnerabilityModules.includes(moduleName)) {
acc.vulnerabilityModules.push(moduleName);
}
// Found unhandled vulnerabilities
if (shouldAudit && !isExcepted) {
acc.unhandledIds.push(String(id));
}
});
return acc;
},
{
unhandledIds: [],
vulnerabilityIds: [],
vulnerabilityModules: [],
unusedExceptionIds: exceptionIds,
unusedExceptionModules: exceptionModules,
report: [],
},
);
}
return {
unhandledIds: [],
vulnerabilityIds: [],
vulnerabilityModules: [],
unusedExceptionIds: exceptionIds,
unusedExceptionModules: exceptionModules,
report: [],
failed: true,
};
}
/**
* Process all exceptions and return a list of exception IDs
* @param {Object | Boolean} nsprc File content from `.nsprc`
* @param {Array} cmdExceptions Exceptions passed in via command line
* @return {Array} List of found vulnerabilities
*/
export function getExceptionsIds(nsprc?: NsprcFile | boolean, cmdExceptions: string[] = []): string[] {
// If file does not exists
if (!nsprc || typeof nsprc !== 'object') {
// If there are exceptions passed in from command line
if (cmdExceptions.length) {
// Display simple info
console.info(`Exception IDs: ${cmdExceptions.join(', ')}`);
return cmdExceptions;
}
return [];
}
// Process the content of the file along with the command line exceptions
const { exceptionIds, report } = processExceptions(nsprc, cmdExceptions);
printExceptionReport(report);
return exceptionIds;
}
/**
* Filter the given list in the `.nsprc` file for valid exceptions
* @param {Object} nsprc The nsprc file content, contains exception info
* @param {Array} cmdExceptions Exceptions passed in via command line
* @return {Object} Processed vulnerabilities details
*/
export function processExceptions(nsprc: NsprcFile, cmdExceptions: string[] = []): ProcessedReport {
return Object.entries(nsprc).reduce(
(acc: ProcessedReport, [id, details]: [string, string | NsprcConfigs]) => {
const isActive = Boolean(get(details, 'active', true)); // default to true
const notes = typeof details === 'string' ? details : get(details, 'notes', '');
const { valid, expired, years } = analyzeExpiry(get(details, 'expiry'));
// Color the status accordingly
let status = color('active', 'green');
if (expired) {
status = color('expired', 'red');
} else if (!valid) {
status = color('invalid', 'red');
} else if (!isActive) {
status = color('inactive', 'yellow');
}
// Color the date accordingly
let expiryDate = get(details, 'expiry') ? new Date(get(details, 'expiry')).toUTCString() : '';
// If it was expired for more than 5 years ago, warn by coloring the date in red
if (years && years <= -5) {
expiryDate = color(expiryDate, 'red');
} else if (years && years <= -1) {
expiryDate = color(expiryDate, 'yellow');
}
acc.report.push([id, status, expiryDate, notes]);
if (isActive && !expired) {
acc.exceptionIds.push(id);
}
return acc;
},
{
exceptionIds: cmdExceptions,
report: cmdExceptions.map((id) => [String(id), color('active', 'green'), '', '']),
},
);
}
/**
* Handle unused exceptions from user: console log them
* @param {Array} unusedExceptionIds List of unused exception IDs
* @param {Array} unusedExceptionModules List of unused exception module names
*/
export function handleUnusedExceptions(unusedExceptionIds: string[], unusedExceptionModules: string[]): void {
const cleanedUnusedExceptionIds = unusedExceptionIds.filter(Boolean);
const cleanedUnusedExceptionModules = unusedExceptionModules.filter(Boolean);
const message = [
cleanedUnusedExceptionIds.length &&
`${
cleanedUnusedExceptionIds.length
} of the excluded vulnerabilities did not match any of the found vulnerabilities: ${cleanedUnusedExceptionIds.join(', ')}.`,
cleanedUnusedExceptionIds.length &&
`${cleanedUnusedExceptionIds.length > 1 ? 'They' : 'It'} can be removed from the .nsprc file or --exclude -x flags.`,
cleanedUnusedExceptionModules.length &&
`${
cleanedUnusedExceptionModules.length
} of the ignored modules did not match any of the found vulnerabilities: ${cleanedUnusedExceptionModules.join(', ')}.`,
cleanedUnusedExceptionModules.length &&
`${cleanedUnusedExceptionModules.length > 1 ? 'They' : 'It'} can be removed from the --module-ignore -m flags.`,
]
.filter(Boolean)
.join(' ');
if (message) {
console.warn(message);
}
}