forked from PaloAltoNetworks/prisma-cloud-scan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
344 lines (314 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
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
const fs = require('fs');
const axios = require('axios');
const core = require('@actions/core');
const { exec } = require('@actions/exec');
const tc = require('@actions/tool-cache');
const os = require('os');
const TRUE_VALUES = ['true', 'yes', 'y', '1'];
function toSentenceCase(string) {
return string[0].toUpperCase() + string.slice(1).toLowerCase();
}
// https://github.com/nodejs/node/issues/18288#issuecomment-475864601
// Necessary for Console URLs that already have a path (all SaaS Consoles)
function joinUrlPath(...parts) {
// Filter handles cases where Console URL pathname is '/' in order to avoid '//api/v1/etc/' (double slash)
return '/' + parts.filter(part => part !== '/').map(part => part.replace(/(^\/|\/$)/g, '')).join('/');
}
// Wrapper around 'authenticate' Console API endpoint
async function authenticate(url, user, pass) {
let parsedUrl;
try {
parsedUrl = new URL(url);
} catch (err) {
console.log(`Invalid Console address: ${url}`);
process.exit(1);
}
const endpoint = '/api/v1/authenticate';
parsedUrl.pathname = joinUrlPath(parsedUrl.pathname, endpoint);
try {
const res = await axios({
method: 'post',
url: parsedUrl.toString(),
headers: {
'Content-Type': 'application/json',
},
data: {
username: user,
password: pass,
},
});
return res.data.token;
} catch (err) {
core.setFailed(`Failed getting authentication token: ${err.message}`);
process.exit(1);
}
}
// Wrapper around 'version' Console API endpoint
async function getVersion(url, token) {
let parsedUrl;
try {
parsedUrl = new URL(url);
} catch (err) {
console.log(`Invalid Console address: ${url}`);
process.exit(1);
}
const endpoint = '/api/v1/version';
parsedUrl.pathname = joinUrlPath(parsedUrl.pathname, endpoint);
try {
const res = await axios({
method: 'get',
url: parsedUrl.toString(),
headers: {
'Authorization': `Bearer ${token}`,
},
});
return res.data;
} catch (err) {
core.setFailed(`Failed getting version: ${err.message}`);
process.exit(1);
}
}
// GitHub Action-specific wrapper around 'util/twistcli' Console API endpoint
// Saves twistcli using GitHub Action's tool-cache library
async function getTwistcli(version, url, authToken, platform, architecture) {
let parsedUrl;
try {
parsedUrl = new URL(url);
} catch (err) {
console.log(`Invalid Console address: ${url}`);
process.exit(1);
}
let endpointPrefix = '';
let endpointValue = 'twistcli';
if(platform === 'win32') {
endpointPrefix = 'windows/';
endpointValue = 'twistcli.exe';
} else if(platform === 'darwin') {
endpointPrefix = 'osx/';
if (architecture === 'arm64') endpointPrefix += 'arm64/';
} else if(platform === 'linux') {
if (architecture === 'arm64') endpointPrefix += 'arm64/';
}
parsedUrl.pathname = joinUrlPath(parsedUrl.pathname, '/api/v1/util/' + endpointPrefix + endpointValue);
let twistcli = tc.find('twistcli', version);
if (!twistcli) {
const twistcliPath = await tc.downloadTool(parsedUrl.toString(), undefined, `Bearer ${authToken}`);
if (platform !== 'win32') await exec(`chmod a+x ${twistcliPath}`);
twistcli = await tc.cacheFile(twistcliPath, endpointValue, 'twistcli', version);
}
core.addPath(twistcli);
return endpointValue;
}
function formatSarifToolDriverRules(results) {
// Only 1 image can be scanned at a time
const result = results[0];
const vulnerabilities = result.vulnerabilities;
const compliances = result.compliances;
let vulns = [];
if (vulnerabilities) {
vulns = vulnerabilities.map(vuln => {
return {
id: `${vuln.id}`,
shortDescription: {
text: `[Prisma Cloud] ${vuln.id} in ${vuln.packageName} (${vuln.severity})`,
},
fullDescription: {
text: `${toSentenceCase(vuln.severity)} severity ${vuln.id} found in ${vuln.packageName} version ${vuln.packageVersion}`,
},
help: {
text: '',
markdown: '| CVE | Severity | CVSS | Package | Version | Fix Status | Published | Discovered |\n' +
'| --- | --- | --- | --- | --- | --- | --- | --- |\n' +
'| [' + vuln.id + '](' + vuln.link + ') | ' + vuln.severity + ' | ' + (vuln.cvss || 'N/A') + ' | ' + vuln.packageName + ' | ' + vuln.packageVersion + ' | ' + (vuln.status || 'not fixed') + ' | ' + vuln.publishedDate + ' | ' + vuln.discoveredDate + ' |',
},
};
});
}
let comps = [];
if (compliances) {
comps = compliances.map(comp => {
return {
id: `${comp.id}`,
shortDescription: {
text: `[Prisma Cloud] Compliance check ${comp.id} violated (${comp.severity})`,
},
fullDescription: {
text: `${toSentenceCase(comp.severity)} severity compliance check "${comp.title}" violated`,
},
help: {
text: '',
markdown: '| Compliance Check | Severity | Title |\n' +
'| --- | --- | --- |\n' +
'| ' + comp.id + ' | ' + comp.severity + ' | ' + comp.title + ' |',
},
};
});
}
return [...vulns, ...comps];
}
/**
* convert prima severity to github severity
* @param {string} severity
* @throws {Error} unknown severity
* @returns string
*/
function convertPrismaSeverity(severity) {
// prisma: critical, high, important, medium, low
// gh: error, warning, note, none
switch (severity) {
case "important":
return "warning";
case "critical":
return "error";
case "high":
return "warning";
case "medium":
return "note";
case "low":
return "none";
default:
throw new Error(`Unknown severities: ${severity}`);
}
}
function formatSarifResults(results) {
// Only 1 image can be scanned at a time
const result = results[0];
const imageName = result.name;
let findings = [];
if (result.vulnerabilities) {
findings = [...findings, ...result.vulnerabilities];
}
if (result.compliances) {
findings = [...findings, ...result.compliances];
}
if (findings) {
return findings.map(finding => {
return {
ruleId: `${finding.id}`,
level: `${convertPrismaSeverity(finding.severity)}`,
message: {
text: `Description:\n${finding.description}`,
},
locations: [{
physicalLocation: {
artifactLocation: {
uri: `${imageName}`,
},
region: {
startLine: 1,
startColumn: 1,
endLine: 1,
endColumn: 1,
},
},
}],
};
});
}
return [];
}
function formatSarif(twistcliVersion, resultsFile) {
try {
const scan = JSON.parse(fs.readFileSync(resultsFile, 'utf8'));
const sarif = {
$schema: 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json',
version: '2.1.0',
runs: [{
tool: {
driver: {
name: 'Prisma Cloud (twistcli)',
version: `${twistcliVersion}`,
rules: formatSarifToolDriverRules(scan.results),
},
},
results: formatSarifResults(scan.results),
}],
};
return sarif;
} catch (err) {
core.setFailed(`Failed formatting SARIF: ${err.message}`);
process.exit(1);
}
}
async function scan() {
const httpProxy = process.env.https_proxy || process.env.HTTPS_PROXY || process.env.http_proxy || process.env.HTTP_PROXY;
const consoleUrl = core.getInput('pcc_console_url');
const username = core.getInput('pcc_user');
const password = core.getInput('pcc_pass');
const imageName = core.getInput('image_name');
const containerized = core.getInput('containerized').toLowerCase();
const dockerAddress = core.getInput('docker_address') || process.env.DOCKER_ADDRESS || process.env.DOCKER_HOST;
const dockerTlsCaCert = core.getInput('docker_tlscacert');
const dockerTlsCert = core.getInput('docker_tlscert');
const dockerTlsKey = core.getInput('docker_tlskey');
const project = core.getInput('project');
const resultsFile = core.getInput('results_file');
const sarifFile = core.getInput('sarif_file');
try {
let token;
try {
token = await authenticate(consoleUrl, username, password, httpProxy);
} catch (err) {
core.setFailed(`Failed authenticating: ${err.message}`);
process.exit(1);
}
let twistcliVersion;
try {
twistcliVersion = await getVersion(consoleUrl, token, httpProxy);
} catch (err) {
core.setFailed(`Failed getting version: ${err.message}`);
process.exit(1);
}
twistcliVersion = twistcliVersion.replace(/"/g, '');
let twistcliCmd = await getTwistcli(twistcliVersion, consoleUrl, token, os.platform(), os.arch());
twistcliCmd = [twistcliCmd];
if (httpProxy) {
twistcliCmd = twistcliCmd.concat([`--http-proxy ${httpProxy}`]);
}
twistcliCmd = twistcliCmd.concat([
'images', 'scan',
`--address ${consoleUrl}`,
`--user ${username}`, `--password ${password}`,
`--output-file ${resultsFile}`,
'--details',
]);
if (dockerAddress) {
twistcliCmd = twistcliCmd.concat([`--docker-address ${dockerAddress}`]);
}
if (dockerTlsCaCert) {
twistcliCmd = twistcliCmd.concat([`--docker-tlscacert ${dockerTlsCaCert}`]);
}
if (dockerTlsCert) {
twistcliCmd = twistcliCmd.concat([`--docker-tlscert ${dockerTlsCert}`]);
}
if (dockerTlsKey) {
twistcliCmd = twistcliCmd.concat([`--docker-tlskey ${dockerTlsKey}`]);
}
if (project) {
twistcliCmd = twistcliCmd.concat([`--project ${project}`]);
}
if (TRUE_VALUES.includes(containerized)) {
twistcliCmd = twistcliCmd.concat(['--containerized']);
}
twistcliCmd = twistcliCmd.concat([imageName]);
const exitCode = await exec(twistcliCmd.join(' '), undefined, {
ignoreReturnCode: true,
});
if (exitCode > 0) {
core.setFailed('Image scan failed');
}
fs.writeFileSync(sarifFile, JSON.stringify(formatSarif(twistcliVersion, resultsFile)));
core.setOutput('results_file', resultsFile);
core.setOutput('sarif_file', sarifFile);
} catch (err) {
core.setFailed(`Image scan failed: ${err.message}`);
process.exit(1);
}
}
if (require.main === module) {
try {
scan();
} catch (err) {
core.setFailed(err.message);
}
}