Skip to content

Visual Studio Code, rebuilt in Rust

Rust

feat(windows): guard UNC hosts in the extension host fs

rokartur927abfdb26a9
diff --git a/native/crates/app/src/main.rs b/native/crates/app/src/main.rs
index ea01d959df3..a4b21b300db 100644
--- a/native/crates/app/src/main.rs
+++ b/native/crates/app/src/main.rs
@@ -781,7 +781,7 @@ fn run_extension_host(
None => (runtime, Vec::new()),
};
let waker = inbox.waker();
- let host = ExtensionHost::start(HostOptions { runtime, entry: &entry, extra_env: host_debug.env, extra_args, inbox }, &init)?;
+ let host = ExtensionHost::start(HostOptions { runtime, entry: &entry, extra_env: host_debug.env.into_iter().chain(files::unc::utility_process_env()).collect(), extra_args, inbox }, &init)?;
let _ = status.unbounded_send(format!("{HANDSHAKE_PREFIX}{}", host.child.id()));
let mut session = Session::new(host);
let folders: Vec<PathBuf> = workspace.iter().flat_map(|workspace| workspace.folders.iter().map(|folder| folder.path.clone())).collect();
diff --git a/native/crates/files/src/unc.rs b/native/crates/files/src/unc.rs
index 464031c30e8..9de8eea79d4 100644
--- a/native/crates/files/src/unc.rs
+++ b/native/crates/files/src/unc.rs
@@ -57,6 +57,18 @@ pub fn unc_host(path: &str) -> Option<&str> {
None
}
+/// utilityProcess.ts: the variables that carry this process's UNC restrictions to a Node process it starts.
+pub fn utility_process_env() -> Option<(String, String)> {
+ cfg!(windows).then(|| unc_env(is_unc_access_restrictions_disabled(), &unc_host_allowlist()))
+}
+
+fn unc_env(disabled: bool, allowlist: &[String]) -> (String, String) {
+ match disabled {
+ true => ("NODE_DISABLE_UNC_ACCESS_CHECKS".to_owned(), "1".to_owned()),
+ false => ("NODE_UNC_HOST_ALLOWLIST".to_owned(), allowlist.join("\\")),
+ }
+}
+
/// `isPathAllowedByUNCHostAllowlist`: not a UNC path, or one of an allowed host; a path that starts like a UNC path
/// without a host it understands fails closed.
pub fn is_path_allowed_by_unc_host_allowlist(path: &str, allowed_hosts: &[String]) -> bool {
diff --git a/native/crates/files/src/unc/tests.rs b/native/crates/files/src/unc/tests.rs
index 4b777c653ea..7e570f0d98b 100644
--- a/native/crates/files/src/unc/tests.rs
+++ b/native/crates/files/src/unc/tests.rs
@@ -1,4 +1,12 @@
-use super::{is_path_allowed_by_unc_host_allowlist, unc_access_error, unc_host};
+use super::{is_path_allowed_by_unc_host_allowlist, unc_access_error, unc_env, unc_host};
+
+/// utilityProcess.ts joins the allowlist with backslashes, which a host name cannot hold.
+#[test]
+fn a_utility_process_gets_the_allowlist_or_the_disabled_checks() {
+ let hosts = ["a".to_owned(), "b".to_owned()];
+ assert_eq!(unc_env(false, &hosts), ("NODE_UNC_HOST_ALLOWLIST".to_owned(), r"a\b".to_owned()));
+ assert_eq!(unc_env(true, &hosts), ("NODE_DISABLE_UNC_ACCESS_CHECKS".to_owned(), "1".to_owned()));
+}
/// base/test/node/unc.test.ts `getUNCHost`.
#[test]
diff --git a/port/patches/src-bootstrap-exthost.patch b/port/patches/src-bootstrap-exthost.patch
index 8daf66641a3..155c4df9326 100644
--- a/port/patches/src-bootstrap-exthost.patch
+++ b/port/patches/src-bootstrap-exthost.patch
@@ -3,7 +3,7 @@ new file mode 100644
index 00000000000..2294a81537f
--- /dev/null
+++ b/src/bootstrap-exthost.ts
-@@ -0,0 +1,17 @@
+@@ -0,0 +1,19 @@
+/*---------------------------------------------------------------------------------------------
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT License. See License.txt in the project root for license information.
@@ -11,6 +11,8 @@ index 00000000000..2294a81537f
+
+// Entry of the extension host bundle that the native (GPUI) app starts, on Bun or on Node.
+// It does what bootstrap-fork.ts and bootstrap-esm.ts do for the host, minus Electron's ASAR and crash reporter.
++// First: Electron's UNC host check on every `fs` path (utilityProcess.ts NODE_UNC_HOST_ALLOWLIST).
++import './vs/base/node/uncFsGuard.js';
+import { product, pkg } from './bootstrap-meta.js';
+import { removeGlobalNodeJsModuleLookupPaths } from './bootstrap-node.js';
+
diff --git a/port/patches/src-uncFsGuard.patch b/port/patches/src-uncFsGuard.patch
new file mode 100644
index 00000000000..978e7337289
--- /dev/null
+++ b/port/patches/src-uncFsGuard.patch
@@ -0,0 +1,169 @@
+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();
++});
diff --git a/port/tools/build-exthost b/port/tools/build-exthost
index 2984be31579..8c360e7feb4 100755
--- a/port/tools/build-exthost
+++ b/port/tools/build-exthost
@@ -3,6 +3,7 @@
// It is built from a copy of the VS Code tree's src/ (VSCODE_SRC) with port/patches/src-*.patch applied, and inlines
// product.json (port/product.json over it) and package.json as upstream's build does (src/bootstrap-meta.ts).
import { $, Glob } from 'bun';
+import * as fs from 'node:fs';
import { lstatSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { vscodeSrc } from './vscode-src.ts';
@@ -40,4 +41,31 @@ if (!lstatSync('node_modules', { throwIfNoEntry: false })?.isDirectory()) {
rmSync('node_modules', { force: true });
symlinkSync(join(vscodeSrc, 'node_modules'), 'node_modules', 'junction');
}
-await $`bun build ${build}/src/bootstrap-exthost.ts --target=node --format=esm --packages=external --outdir out-exthost`;
+// Bun's ESM imports of `fs` do not see uncFsGuard.ts's wrappers (port/patches/src-uncFsGuard.patch), so the bundle's
+// `fs` and `fs/promises` imports resolve to a module that loads the guard and re-exports the wrapped functions.
+const guard = resolve(build, 'src/vs/base/node/uncFsGuard.ts');
+const exportNames = (module: object) => Object.keys(module).filter(name => /^[A-Za-z_$][\w$]*$/.test(name) && name !== 'default');
+const result = await Bun.build({
+ entrypoints: [`${build}/src/bootstrap-exthost.ts`],
+ target: 'node',
+ format: 'esm',
+ packages: 'external',
+ outdir: 'out-exthost',
+ plugins: [{
+ name: 'unc-guarded-fs',
+ setup(builder) {
+ builder.onResolve({ filter: /^(node:)?fs(\/promises)?$/ }, args => args.importer === guard || args.namespace === 'unc-guarded-fs'
+ ? { path: args.path, external: true }
+ : { path: args.path.replace('node:', ''), namespace: 'unc-guarded-fs' });
+ builder.onLoad({ filter: /.*/, namespace: 'unc-guarded-fs' }, args => {
+ const member = args.path === 'fs/promises' ? '.promises' : '';
+ const names = exportNames(member ? fs.promises : fs);
+ const contents = `import ${JSON.stringify(guard)};\nimport { createRequire } from 'module';\nconst target = createRequire(import.meta.url)('fs')${member};\nexport default target;\nexport const { ${names.join(', ')} } = target;\n`;
+ return { contents, loader: 'js' };
+ });
+ },
+ }],
+});
+if (!result.success) {
+ throw new AggregateError(result.logs, 'bun build out-exthost failed');
+}