forked from golang/vscode-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoVulncheck.ts
402 lines (360 loc) · 11.8 KB
/
goVulncheck.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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/*---------------------------------------------------------
* Copyright 2022 The Go Authors. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------*/
import path from 'path';
import fs from 'fs';
import * as vscode from 'vscode';
import { GoExtensionContext } from './context';
import { getBinPath } from './util';
import * as cp from 'child_process';
import { toolExecutionEnvironment } from './goEnv';
import { killProcessTree } from './utils/processUtils';
import * as readline from 'readline';
import { URI } from 'vscode-uri';
import { promisify } from 'util';
export class VulncheckResultViewProvider implements vscode.CustomTextEditorProvider {
public static readonly viewType = 'vulncheck.view';
public static register({ extensionUri, subscriptions }: vscode.ExtensionContext): VulncheckResultViewProvider {
const provider = new VulncheckResultViewProvider(extensionUri);
subscriptions.push(vscode.window.registerCustomEditorProvider(VulncheckResultViewProvider.viewType, provider));
return provider;
}
constructor(private readonly extensionUri: vscode.Uri) {}
/**
* Called when our custom editor is opened.
*/
public async resolveCustomTextEditor(
document: vscode.TextDocument,
webviewPanel: vscode.WebviewPanel,
_: vscode.CancellationToken // eslint-disable-line @typescript-eslint/no-unused-vars
): Promise<void> {
// Setup initial content for the webview
webviewPanel.webview.options = { enableScripts: true };
webviewPanel.webview.html = this.getHtmlForWebview(webviewPanel.webview);
// Receive message from the webview.
webviewPanel.webview.onDidReceiveMessage(this.handleMessage);
function updateWebview() {
webviewPanel.webview.postMessage({ type: 'update', text: document.getText() });
}
// Hook up event handlers so that we can synchronize the webview with the text document.
//
// The text document acts as our model, so we have to sync change in the document to our
// editor and sync changes in the editor back to the document.
//
// Remember that a single text document can also be shared between multiple custom
// editors (this happens for example when you split a custom editor)
const changeDocumentSubscription = vscode.workspace.onDidChangeTextDocument((e) => {
if (e.document.uri.toString() === document.uri.toString()) {
updateWebview();
}
});
// Make sure we get rid of the listener when our editor is closed.
webviewPanel.onDidDispose(() => {
changeDocumentSubscription.dispose();
});
updateWebview();
}
/**
* Get the static html used for the editor webviews.
*/
private getHtmlForWebview(webview: vscode.Webview): string {
const mediaUri = vscode.Uri.joinPath(this.extensionUri, 'media');
// Local path to script and css for the webview
const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(mediaUri, 'vulncheckView.js'));
const styleResetUri = webview.asWebviewUri(vscode.Uri.joinPath(mediaUri, 'reset.css'));
const styleVSCodeUri = webview.asWebviewUri(vscode.Uri.joinPath(mediaUri, 'vscode.css'));
const styleMainUri = webview.asWebviewUri(vscode.Uri.joinPath(mediaUri, 'vulncheckView.css'));
// Use a nonce to whitelist which scripts can be run
const nonce = getNonce();
return /* html */ `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--
Use a content security policy to only allow loading images from https or from our extension directory,
and only allow scripts that have a specific nonce.
-->
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src ${webview.cspSource}; style-src ${webview.cspSource}; script-src 'nonce-${nonce}';">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="${styleResetUri}" rel="stylesheet" />
<link href="${styleVSCodeUri}" rel="stylesheet" />
<link href="${styleMainUri}" rel="stylesheet" />
<title>Vulnerability Report - govulncheck</title>
</head>
<body>
<div class="log"></div>
<div class="vulns"></div>
<script nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>`;
}
private handleMessage(e: { type: string; target?: string }): void {
switch (e.type) {
case 'open':
{
if (!e.target) return;
const uri = safeURIParse(e.target);
if (!uri || !uri.scheme) return;
if (uri.scheme === 'https') {
vscode.env.openExternal(uri);
} else if (uri.scheme === 'file') {
const line = uri.query ? Number(uri.query.split(':')[0]) : undefined;
const range = line ? new vscode.Range(line, 0, line, 0) : undefined;
vscode.window.showTextDocument(
vscode.Uri.from({ scheme: uri.scheme, path: uri.path }),
// prefer the first column to present the source.
{ viewColumn: vscode.ViewColumn.One, selection: range }
);
}
}
return;
case 'snapshot-result':
// response for `snapshot-request`.
return;
default:
console.log(`unrecognized type message: ${e.type}`);
}
}
}
export class VulncheckProvider {
static scheme = 'govulncheck';
static setup({ subscriptions }: vscode.ExtensionContext, goCtx: GoExtensionContext) {
const channel = vscode.window.createOutputChannel('govulncheck');
const instance = new this(channel);
subscriptions.push(
vscode.commands.registerCommand('go.vulncheck.run', async () => {
instance.run(goCtx);
})
);
return instance;
}
constructor(private channel: vscode.OutputChannel) {}
private running = false;
async run(goCtx: GoExtensionContext) {
if (this.running) {
vscode.window.showWarningMessage('another vulncheck is in progress');
return;
}
try {
this.running = true;
await this.runInternal(goCtx);
} finally {
this.running = false;
}
}
private async runInternal(goCtx: GoExtensionContext) {
const pick = await vscode.window.showQuickPick(['Current Package', 'Workspace']);
let dir, pattern: string;
const document = vscode.window.activeTextEditor?.document;
switch (pick) {
case 'Current Package':
if (!document) {
vscode.window.showErrorMessage('vulncheck error: no current package');
return;
}
if (document.languageId !== 'go') {
vscode.window.showErrorMessage(
'File in the active editor is not a Go file, cannot find current package to check.'
);
return;
}
dir = path.dirname(document.fileName);
pattern = '.';
break;
case 'Workspace':
dir = await this.activeDir();
pattern = './...';
break;
default:
return;
}
if (!dir) {
return;
}
this.channel.clear();
this.channel.appendLine(`cd ${dir}; gopls vulncheck ${pattern}`);
try {
const start = new Date();
const vuln = await vulncheck(goCtx, dir, pattern, this.channel);
if (vuln) {
fillAffectedPkgs(vuln.Vuln);
// record run info.
vuln.Start = start;
vuln.Duration = Date.now() - start.getTime();
vuln.Dir = dir;
vuln.Pattern = pattern;
// write to file and visualize it!
const fname = path.join(dir, `vulncheck-${Date.now()}.vulncheck.json`);
const writeFile = promisify(fs.writeFile);
await writeFile(fname, JSON.stringify(vuln));
const uri = URI.file(fname);
const viewColumn = vscode.ViewColumn.Beside;
vscode.commands.executeCommand(
'vscode.openWith',
uri,
VulncheckResultViewProvider.viewType,
viewColumn
);
this.channel.appendLine(`Vulncheck - result wrote in ${fname}`);
} else {
this.channel.appendLine('Vulncheck - found no vulnerability');
}
} catch (e) {
vscode.window.showErrorMessage(`error running vulncheck: ${e}`);
this.channel.appendLine(`Vulncheck failed: ${e}`);
}
this.channel.show();
}
private async activeDir() {
const folders = vscode.workspace.workspaceFolders;
if (!folders || folders.length === 0) return;
let dir: string | undefined = '';
if (folders.length === 1) {
dir = folders[0].uri.path;
} else {
const pick = await vscode.window.showQuickPick(
folders.map((f) => ({ label: f.name, description: f.uri.path }))
);
dir = pick?.description;
}
return dir;
}
}
// run `gopls vulncheck`.
export async function vulncheck(
goCtx: GoExtensionContext,
dir: string,
pattern = './...',
channel: { appendLine: (msg: string) => void }
): Promise<VulncheckReport> {
const { languageClient, serverInfo } = goCtx;
const COMMAND = 'gopls.run_vulncheck_exp';
if (!languageClient || !serverInfo?.Commands?.includes(COMMAND)) {
throw Promise.reject('this feature requires gopls v0.8.4 or newer');
}
// TODO: read back the actual package configuration from gopls.
const gopls = getBinPath('gopls');
const options: vscode.ProgressOptions = {
cancellable: true,
title: 'Run govulncheck',
location: vscode.ProgressLocation.Notification
};
const task = vscode.window.withProgress<VulncheckReport>(options, (progress, token) => {
const p = cp.spawn(gopls, ['vulncheck', pattern], {
cwd: dir,
env: toolExecutionEnvironment(vscode.Uri.file(dir))
});
progress.report({ message: `starting command ${gopls} from ${dir} (pid; ${p.pid})` });
const d = token.onCancellationRequested(() => {
channel.appendLine(`gopls vulncheck (pid: ${p.pid}) is cancelled`);
killProcessTree(p);
d.dispose();
});
const promise = new Promise<VulncheckReport>((resolve, reject) => {
const rl = readline.createInterface({ input: p.stderr });
rl.on('line', (line) => {
channel.appendLine(line);
const msg = line.match(/^\d+\/\d+\/\d+\s+\d+:\d+:\d+\s+(.*)/);
if (msg && msg[1]) {
progress.report({ message: msg[1] });
}
});
let buf = '';
p.stdout.on('data', (chunk) => {
buf += chunk;
});
p.stdout.on('close', () => {
try {
const res: VulncheckReport = JSON.parse(buf);
resolve(res);
} catch (e) {
if (token.isCancellationRequested) {
reject('analysis cancelled');
} else {
channel.appendLine(buf);
reject(`result in unexpected format: ${e}`);
}
}
});
});
return promise;
});
return await task;
}
interface VulncheckReport {
// Vulns populated by gopls vulncheck run.
Vuln?: Vuln[];
// analysis run information.
Pattern?: string;
Dir?: string;
Start?: Date;
Duration?: number; // milliseconds
}
interface Vuln {
ID: string;
Details: string;
Aliases: string[];
Symbol: string;
PkgPath: string;
ModPath: string;
URL: string;
CurrentVersion: string;
FixedVersion: string;
CallStacks?: CallStack[][];
CallStacksSummary?: string[];
// Derived from call stacks.
// TODO(hyangah): add to gopls vulncheck.
AffectedPkgs?: string[];
}
interface CallStack {
Name: string;
URI: string;
Pos: {
line: number;
character: number;
};
}
function getNonce() {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 32; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
function safeURIParse(s: string): URI | undefined {
try {
return URI.parse(s);
} catch (_) {
return undefined;
}
}
// Computes the AffectedPkgs attribute if it's not present.
// Exported for testing.
// TODO(hyangah): move this logic to gopls vulncheck or govulncheck.
export function fillAffectedPkgs(vulns: Vuln[] | undefined): Vuln[] {
if (!vulns) return [];
const re = new RegExp(/^(\S+)\/([^/\s]+)$/);
vulns.forEach((vuln) => {
// If it's already set by gopls vulncheck, great!
if (vuln.AffectedPkgs) return;
const affected = new Set<string>();
vuln.CallStacks?.forEach((cs) => {
if (!cs || cs.length === 0) {
return;
}
const name = cs[0].Name || '';
const m = name.match(re);
if (!m) {
name && affected.add(name);
} else {
const pkg = m[2] && m[2].split('.')[0];
affected.add(`${m[1]}/${pkg}`);
}
});
vuln.AffectedPkgs = Array.from(affected);
});
return vulns;
}