Skip to content

Visual Studio Code, rebuilt in Rust

Rust
9.3 KB
Raw Blame
diff --git a/src/vs/base/node/uncFsGuard.ts b/src/vs/base/node/uncFsGuard.ts
new file mode 100644
index 0000000..9c7a277
--- /dev/null
+++ b/src/vs/base/node/uncFsGuard.ts
@@ -0,0 +1,105 @@
+/*---------------------------------------------------------------------------------------------
+ *  Copyright (c) Microsoft Corporation. All rights reserved.
+ *  Licensed under the MIT License. See License.txt in the project root for license information.
+ *--------------------------------------------------------------------------------------------*/
+
+// Electron's Node refuses an `fs` path on a UNC host outside `process.uncHostAllowlist` on Windows
+// (ERR_UNC_HOST_NOT_ALLOWED), filled from the NODE_UNC_HOST_ALLOWLIST that utilityProcess.ts passes. The native app
+// runs the extension host on Bun or Node, which have no such check, so this wraps the `fs` functions that take paths.
+// build-exthost routes the bundle's own `fs` imports here, as Bun's ESM imports of builtins do not see these wrappers.
+import { createRequire } from 'module';
+import { fileURLToPath } from 'url';
+import { getUNCHost, isPathAllowedByUNCHostAllowlist } from './unc.js';
+
+const onePath = ['access', 'appendFile', 'chmod', 'chown', 'lchmod', 'lchown', 'lutimes', 'lstat', 'mkdir', 'mkdtemp', 'open', 'openAsBlob', 'opendir', 'readdir', 'readFile', 'readlink', 'realpath', 'rm', 'rmdir', 'stat', 'statfs', 'truncate', 'unlink', 'utimes', 'writeFile', 'createReadStream', 'createWriteStream', 'watch', 'watchFile', 'exists'];
+const twoPaths = ['copyFile', 'cp', 'link', 'rename', 'symlink'];
+// Their last function argument is a listener, not a callback: they throw as Node does.
+const throwing = ['createReadStream', 'createWriteStream', 'watch', 'watchFile', 'openAsBlob'];
+const guarded = Symbol('uncGuarded');
+
+type Restrictions = { uncHostAllowlist?: Set<string>; restrictUNCAccess?: boolean };
+type FsModule = Record<string | symbol, unknown> & { promises?: FsModule };
+
+/** The `ERR_UNC_HOST_NOT_ALLOWED` error for a path the restrictions refuse. */
+export function uncAccessError(path: unknown, restrictions: Restrictions): Error | undefined {
+	if (restrictions.restrictUNCAccess === false) {
+		return undefined;
+	}
+	const text = pathText(path);
+	if (text === undefined || isPathAllowedByUNCHostAllowlist(text, [...restrictions.uncHostAllowlist ?? []])) {
+		return undefined;
+	}
+	return Object.assign(new Error(`UNC host '${getUNCHost(text) ?? ''}' access is not allowed`), { code: 'ERR_UNC_HOST_NOT_ALLOWED' });
+}
+
+// Node checks the namespaced path, where `/` is a separator too; a file descriptor is no path.
+function pathText(path: unknown): string | undefined {
+	if (typeof path === 'string') {
+		return path.replaceAll('/', '\\');
+	}
+	if (path instanceof Uint8Array) {
+		return Buffer.from(path).toString().replaceAll('/', '\\');
+	}
+	if (path instanceof URL && path.protocol === 'file:') {
+		return path.host ? `\\\\${path.host}${decodeURIComponent(path.pathname).replaceAll('/', '\\')}` : fileURLToPath(path).replaceAll('/', '\\');
+	}
+	return undefined;
+}
+
+/** Wraps the path-taking functions of `fs` (or `fs.promises` with `promises`) to refuse what `restrictions` refuses. */
+export function guardFs(fs: FsModule, restrictions: Restrictions, promises = false): void {
+	if (fs[guarded]) {
+		return;
+	}
+	fs[guarded] = true;
+	for (const name of [...onePath, ...twoPaths]) {
+		const pathCount = twoPaths.includes(name) ? 2 : 1;
+		wrap(fs, name, pathCount, restrictions, promises ? 'promise' : name === 'exists' ? 'exists' : throwing.includes(name) ? 'throw' : 'callback');
+		if (!promises) {
+			wrap(fs, `${name}Sync`, pathCount, restrictions, name === 'exists' ? 'exists' : 'throw');
+		}
+	}
+	const realpath = fs.realpath as FsModule | undefined;
+	const realpathSync = fs.realpathSync as FsModule | undefined;
+	if (!promises && realpath && realpathSync) {
+		wrap(realpath, 'native', 1, restrictions, 'callback');
+		wrap(realpathSync, 'native', 1, restrictions, 'throw');
+	}
+}
+
+function wrap(owner: FsModule, name: string, pathCount: number, restrictions: Restrictions, refuse: 'callback' | 'throw' | 'promise' | 'exists'): void {
+	const original = owner[name];
+	if (typeof original !== 'function') {
+		return;
+	}
+	const wrapper = function (this: unknown, ...args: unknown[]) {
+		const error = args.slice(0, pathCount).map(path => uncAccessError(path, restrictions)).find(error => error);
+		if (!error) {
+			return original.apply(this, args);
+		}
+		const callback = args.at(-1);
+		switch (refuse) {
+			case 'promise': return Promise.reject(error);
+			case 'exists': return typeof callback === 'function' ? void process.nextTick(callback, false) : false;
+			case 'callback': if (typeof callback === 'function') { return void process.nextTick(callback, error); } throw error;
+			case 'throw': throw error;
+		}
+	};
+	for (const key of Reflect.ownKeys(original)) {
+		if (key !== 'length' && key !== 'name' && key !== 'prototype') {
+			Object.defineProperty(wrapper, key, Object.getOwnPropertyDescriptor(original, key)!);
+		}
+	}
+	owner[name] = wrapper;
+}
+
+// Electron's Node: Windows only, and off with NODE_DISABLE_UNC_ACCESS_CHECKS; unc.ts reads and extends the same set.
+if (process.platform === 'win32' && process.env['NODE_DISABLE_UNC_ACCESS_CHECKS'] !== '1') {
+	const restrictions = process as unknown as Restrictions;
+	restrictions.uncHostAllowlist = new Set((process.env['NODE_UNC_HOST_ALLOWLIST'] ?? '').split('\\').filter(host => host).map(host => host.toLowerCase()));
+	const require = createRequire(import.meta.url);
+	const fs = require('fs') as FsModule;
+	guardFs(fs, restrictions);
+	guardFs(fs.promises!, restrictions, true);
+	guardFs(require('fs/promises') as FsModule, restrictions, true);
+}
diff --git a/src/vs/base/test/node/uncFsGuard.test.ts b/src/vs/base/test/node/uncFsGuard.test.ts
new file mode 100644
index 0000000..285144f
--- /dev/null
+++ b/src/vs/base/test/node/uncFsGuard.test.ts
@@ -0,0 +1,52 @@
+/*---------------------------------------------------------------------------------------------
+ *  Copyright (c) Microsoft Corporation. All rights reserved.
+ *  Licensed under the MIT License. See License.txt in the project root for license information.
+ *--------------------------------------------------------------------------------------------*/
+
+// Run with `bun test` from out-exthost/build after port/tools/build-exthost.
+import { expect, test } from 'bun:test';
+import { guardFs, uncAccessError } from '../../node/uncFsGuard.js';
+
+function fakeFs() {
+	const calls: string[] = [];
+	const record = (name: string) => (...args: unknown[]) => { calls.push(`${name} ${String(args[0])}`); const callback = args.at(-1); if (typeof callback === 'function') { callback(null, 'ok'); } return 'ok'; };
+	const realpath = Object.assign(record('realpath'), { native: record('realpath.native') });
+	const fs = { stat: record('stat'), statSync: record('statSync'), existsSync: record('existsSync'), exists: record('exists'), rename: record('rename'), createReadStream: record('createReadStream'), realpath, realpathSync: Object.assign(record('realpathSync'), { native: record('realpathSync.native') }) };
+	const promises = { stat: async (path: unknown) => { calls.push(`promises.stat ${String(path)}`); return 'ok'; } };
+	return { fs, promises, calls };
+}
+
+test('a refused host is not probed, an allowed one is', async () => {
+	const restrictions = { uncHostAllowlist: new Set(['allowed-host']) };
+	const { fs, promises, calls } = fakeFs();
+	guardFs(fs, restrictions);
+	guardFs(promises, restrictions, true);
+
+	expect(() => fs.statSync('\\\\evil\\share\\a')).toThrow("UNC host 'evil' access is not allowed");
+	expect(() => fs.statSync('//evil/share/a')).toThrow("UNC host 'evil' access is not allowed");
+	expect(() => fs.statSync(new URL('file://evil/share/a'))).toThrow("UNC host 'evil' access is not allowed");
+	expect(() => fs.realpathSync.native('\\\\?\\UNC\\evil\\share')).toThrow("UNC host 'evil' access is not allowed");
+	expect(() => fs.createReadStream('\\\\evil\\share\\a', () => { })).toThrow("UNC host 'evil' access is not allowed");
+	expect(fs.existsSync('\\\\evil\\share\\a')).toBe(false);
+	const error = await new Promise<unknown>(resolve => fs.stat('\\\\evil\\share\\a', resolve));
+	expect((error as { code: string }).code).toBe('ERR_UNC_HOST_NOT_ALLOWED');
+	expect(await new Promise<unknown>(resolve => fs.exists('\\\\evil\\share\\a', resolve))).toBe(false);
+	await expect(promises.stat('\\\\evil\\share\\a')).rejects.toThrow("UNC host 'evil' access is not allowed");
+	expect(() => fs.rename('c:\\a', '\\\\evil\\share\\a', () => { })).not.toThrow();
+	expect(calls).toEqual([]);
+
+	fs.statSync('\\\\Allowed-Host\\share\\a');
+	fs.statSync('c:\\a');
+	fs.statSync(3);
+	await promises.stat('\\\\?\\UNC\\allowed-host\\share');
+	expect(calls).toEqual(['statSync \\\\Allowed-Host\\share\\a', 'statSync c:\\a', 'statSync 3', 'promises.stat \\\\?\\UNC\\allowed-host\\share']);
+});
+
+test('the allowlist and the switch are read on each call, as unc.ts changes them', () => {
+	const restrictions: { uncHostAllowlist: Set<string>; restrictUNCAccess?: boolean } = { uncHostAllowlist: new Set() };
+	expect(uncAccessError('\\\\later\\share', restrictions)).toBeDefined();
+	restrictions.uncHostAllowlist.add('later');
+	expect(uncAccessError('\\\\later\\share', restrictions)).toBeUndefined();
+	restrictions.restrictUNCAccess = false;
+	expect(uncAccessError('\\\\other\\share', restrictions)).toBeUndefined();
+});