Skip to content

Commit c1fe792

Browse files
authored
fix(ssh): apply only known deployment SSH options (#1240)
- Limit deployment SSH options to an allow list of connection settings: timeouts, keepalives, connection sharing (ControlMaster, ControlPersist), algorithms, authentication methods and logging - Skip everything else, including an option sent more than once in different case, with the existing warning instead of failing the connection - Keep Coder's pinned options (ProxyCommand, StrictHostKeyChecking, UserKnownHostsFile, PermitLocalCommand) over the deployment's - Let users still set any option via coder.sshConfig or `coder config-ssh --ssh-option`; a user override now replaces every spelling of a key BREAKING CHANGE: deployments that relied on other options, such as ForwardAgent or IdentityFile, now need users to add them to coder.sshConfig. Refs CLIENT-1123
1 parent 99dce67 commit c1fe792

6 files changed

Lines changed: 239 additions & 221 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@
1313
troubleshooting guide, opening the relay section when connected through a
1414
relay.
1515

16+
### Changed
17+
18+
- **Breaking:** of the SSH options your deployment sets, only connection
19+
settings such as timeouts, keepalives, and algorithms are applied. The rest,
20+
including options that used to stop the connection, are skipped with a
21+
warning; add any you need to `coder.sshConfig`.
22+
1623
### Fixed
1724

1825
- Links that open a workspace or dev container are rejected before any prompt

‎docs/ARCHITECTURE.md‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -103,10 +103,9 @@ Host coder-cursor.dev.coder.com--*
103103
Options merge from three sources, highest priority first: the
104104
`coder.sshConfig` setting, `--ssh-option` flags from a `coder config-ssh`
105105
block, and the deployment's SSH config. Only the deployment's options are
106-
deny-listed (`DENIED_DEPLOYMENT_KEYS` in `src/remote/sshConfig.ts`), since the
107-
other two are the user's own. Deployment options that send local environment
108-
variables or sockets to the workspace are ignored with a warning
109-
(`IGNORED_DEPLOYMENT_KEYS`). The user's
106+
filtered, since the other two are the user's own: options outside
107+
`ALLOWED_DEPLOYMENT_KEYS` in `src/remote/sshConfig.ts` are ignored with a
108+
warning. The user's
110109
`SetEnv` and `SendEnv` values accumulate across sources. The session app goes
111110
to the CLI as `--usage-app` and to the agent as `CODER_SSH_SESSION_TYPE`, set in the
112111
environment ssh inherits and forwarded with `SendEnv`. It is the editor's URI

‎src/remote/remote.ts‎

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -923,9 +923,6 @@ export class Remote {
923923
await readSshConfig(userConfigPath),
924924
);
925925

926-
// Options the user set themselves win the merge below, so they are exempt
927-
// from the deny list. Both sources are local and already trusted: whoever
928-
// can write the SSH config could write any Host block directly.
929926
const userConfigSsh = vscode.workspace
930927
.getConfiguration("coder")
931928
.get<string[]>("sshConfig", []);
@@ -936,7 +933,6 @@ export class Remote {
936933
const deploymentConfig = await workspaceClient.getDeploymentSSHConfig();
937934
const { options, ignored } = validateDeploymentSshOptions(
938935
deploymentConfig.ssh_config_options,
939-
{ ...configSshOptions, ...userConfig },
940936
);
941937
deploymentSshConfig = options;
942938
if (ignored.length > 0) {
@@ -958,32 +954,37 @@ export class Remote {
958954
}
959955
}
960956

957+
const pinnedSshValues = {
958+
ProxyCommand: buildSshProxyCommand({
959+
pathResolver: this.pathResolver,
960+
binaryPath,
961+
cliAuth,
962+
logArgs: await this.getLogArgs(logDir),
963+
sessionApp,
964+
hostPrefix,
965+
}),
966+
StrictHostKeyChecking: "no",
967+
UserKnownHostsFile: "/dev/null",
968+
PermitLocalCommand: "no",
969+
};
970+
961971
// Merge SSH config from three sources (highest to lowest priority):
962972
// 1. User's VS Code coder.sshConfig setting
963973
// 2. coder config-ssh --ssh-option flags from the CLI block
964-
// 3. Deployment SSH config from the coderd API
965-
// Only 3 is deny listed; 1 and 2 are the user's own options.
974+
// 3. Deployment SSH config from the coderd API, with the pinned values over it
975+
// Only 3 is allow listed; 1 and 2 are the user's own options.
966976
const sshConfigOverrides = mergeSshConfigValues(
967-
mergeSshConfigValues(deploymentSshConfig, configSshOptions),
977+
mergeSshConfigValues(
978+
mergeSshConfigValues(deploymentSshConfig, pinnedSshValues),
979+
configSshOptions,
980+
),
968981
userConfig,
969982
);
970983

971-
const proxyCommand = buildSshProxyCommand({
972-
pathResolver: this.pathResolver,
973-
binaryPath,
974-
cliAuth,
975-
logArgs: await this.getLogArgs(logDir),
976-
sessionApp,
977-
hostPrefix,
978-
});
979-
980984
const sshValues: SshValues = {
981985
Host: hostPrefix + `*`,
982-
ProxyCommand: proxyCommand,
986+
...pinnedSshValues,
983987
ConnectTimeout: "0",
984-
StrictHostKeyChecking: "no",
985-
UserKnownHostsFile: "/dev/null",
986-
PermitLocalCommand: "no",
987988
LogLevel: "ERROR",
988989
ServerAliveInterval: "10",
989990
ServerAliveCountMax: "3",

‎src/remote/sshConfig.ts‎

Lines changed: 67 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -175,86 +175,77 @@ function toMsysPath(dir: string): string {
175175
const CODER_SSH_CONFIG_HEADER = `# Coder workspace hosts. Do not edit; the Coder extension rewrites this file
176176
# on every connection. Override options with the "coder.sshConfig" setting.`;
177177

178-
/**
179-
* SSH options a deployment may not set, mirroring the server's validation of
180-
* --ssh-config-options (codersdk.ValidateSSHConfigOption).
181-
*/
182-
const DENIED_DEPLOYMENT_KEYS: ReadonlySet<Lowercase<string>> = new Set([
183-
// Structural directives that escape Coder's managed block.
184-
"host",
185-
"match",
186-
"include",
187-
// Directives that run an attacker-supplied command string.
188-
"proxycommand",
189-
"localcommand",
190-
"permitlocalcommand",
191-
"remotecommand",
192-
"knownhostscommand",
193-
// Directives that load an attacker-controlled shared library.
194-
"pkcs11provider",
195-
"securitykeyprovider",
196-
"smartcarddevice",
197-
// Directives that execute a command for X11 authentication.
198-
"xauthlocation",
199-
// Conflicts with Coder's managed ProxyCommand.
200-
"proxyjump",
178+
/** SSH options a deployment may set; the rest are ignored. */
179+
const ALLOWED_DEPLOYMENT_KEYS: ReadonlySet<Lowercase<string>> = new Set([
180+
"addressfamily",
181+
"batchmode",
182+
"bindaddress",
183+
"bindinterface",
184+
"casignaturealgorithms",
185+
"challengeresponseauthentication",
186+
"channeltimeout",
187+
"checkhostip",
188+
"ciphers",
189+
"clearallforwardings",
190+
"compression",
191+
"connectionattempts",
192+
"connecttimeout",
193+
"controlmaster",
194+
"controlpersist",
195+
"escapechar",
196+
"exitonforwardfailure",
197+
"fingerprinthash",
198+
"hashknownhosts",
199+
"hostbasedacceptedalgorithms",
200+
"hostkeyalgorithms",
201+
"identitiesonly",
202+
"ipqos",
203+
"kbdinteractiveauthentication",
204+
"kbdinteractivedevices",
205+
"kexalgorithms",
206+
"loglevel",
207+
"logverbose",
208+
"macs",
209+
"nohostauthenticationforlocalhost",
210+
"numberofpasswordprompts",
211+
"obscurekeystroketiming",
212+
"passwordauthentication",
213+
"port",
214+
"preferredauthentications",
215+
"pubkeyacceptedalgorithms",
216+
"pubkeyacceptedkeytypes",
217+
"pubkeyauthentication",
218+
"rekeylimit",
219+
"requesttty",
220+
"requiredrsasize",
221+
"serveralivecountmax",
222+
"serveraliveinterval",
223+
"syslogfacility",
224+
"tcpkeepalive",
225+
"verifyhostkeydns",
226+
"visualhostkey",
201227
]);
202228

203229
/**
204-
* Options that send local environment variables (directly or through `${VAR}`
205-
* expansion) or local sockets to the workspace. Ignored rather than rejected,
206-
* since the server accepts them.
207-
*/
208-
const IGNORED_DEPLOYMENT_KEYS: ReadonlySet<Lowercase<string>> = new Set([
209-
"sendenv",
210-
"setenv",
211-
"user",
212-
"remoteforward",
213-
]);
214-
215-
/**
216-
* Connection-critical options Coder always writes itself, so the error must
217-
* not suggest overriding them in coder.sshConfig.
218-
*/
219-
const PINNED_KEYS: ReadonlySet<Lowercase<string>> = new Set([
220-
"proxycommand",
221-
"userknownhostsfile",
222-
"stricthostkeychecking",
223-
]);
224-
225-
/**
226-
* Validate SSH options sent by the Coder deployment, removing the ignored ones.
227-
* Keys in `userOverrides` are exempt from the deny list: the user's value wins
228-
* the merge, so the deployment's value is never written.
229-
* @throws {Error} when an option is malformed or denied.
230+
* Validate SSH options sent by the Coder deployment, removing the ones outside
231+
* the allow list or repeated in another case.
232+
* @throws {Error} when an option is malformed.
230233
*/
231234
export function validateDeploymentSshOptions(
232235
options: Record<string, unknown>,
233-
userOverrides: Record<string, string>,
234-
): { options: Record<string, string>; ignored: string[] } {
236+
): {
237+
options: Record<string, string>;
238+
ignored: string[];
239+
} {
235240
validateSshConfigOptions(options);
236-
const overridden = new Set(Object.keys(userOverrides).map(lowercase));
237-
const denied = Object.keys(options).filter((key) => {
238-
const lower = lowercase(key);
239-
return DENIED_DEPLOYMENT_KEYS.has(lower) && !overridden.has(lower);
241+
const lowerKeys = Object.keys(options).map(lowercase);
242+
const ignored = Object.keys(options).filter((_key, i) => {
243+
const lower = lowerKeys[i];
244+
return (
245+
!ALLOWED_DEPLOYMENT_KEYS.has(lower) ||
246+
lowerKeys.indexOf(lower) !== lowerKeys.lastIndexOf(lower)
247+
);
240248
});
241-
if (denied.length > 0) {
242-
const quote = (keys: string[]) =>
243-
keys.map((key) => JSON.stringify(key)).join(", ");
244-
const pinned = denied.filter((key) => PINNED_KEYS.has(lowercase(key)));
245-
const overridable = denied.filter((key) => !pinned.includes(key));
246-
let message = `The Coder deployment tried to set SSH options that could run code or change how Coder connects: ${quote(denied)}.`;
247-
if (overridable.length > 0) {
248-
message += ` To allow ${quote(overridable)}, set the option yourself in the "coder.sshConfig" setting, which overrides the deployment.`;
249-
}
250-
if (pinned.length > 0) {
251-
message += ` Coder manages ${quote(pinned)}, which cannot be overridden.`;
252-
}
253-
throw new Error(message);
254-
}
255-
const ignored = Object.keys(options).filter((key) =>
256-
IGNORED_DEPLOYMENT_KEYS.has(lowercase(key)),
257-
);
258249
return {
259250
options: Object.fromEntries(
260251
Object.entries(options).filter(([key]) => !ignored.includes(key)),
@@ -363,6 +354,7 @@ export function mergeSshConfigValues(
363354
Object.keys(overrides).forEach((key) => {
364355
caseInsensitiveOverrides[key.toLowerCase()] = key;
365356
});
357+
const overridden = new Set(Object.keys(caseInsensitiveOverrides));
366358

367359
Object.keys(config).forEach((key) => {
368360
const lower = key.toLowerCase();
@@ -384,6 +376,9 @@ export function mergeSshConfigValues(
384376

385377
return;
386378
}
379+
if (overridden.has(lower)) {
380+
return;
381+
}
387382
if (config[key] !== "") {
388383
merged[key] = config[key];
389384
}

‎test/unit/remote/remote.test.ts‎

Lines changed: 47 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@ import {
1414
Remote,
1515
workspaceLabelSuffix,
1616
} from "@/remote/remote";
17-
import { getGitForWindowsSshConfigPath } from "@/remote/sshConfig";
17+
import {
18+
getGitForWindowsSshConfigPath,
19+
validateDeploymentSshOptions,
20+
} from "@/remote/sshConfig";
1821
import {
1922
resolveSshProperties,
2023
SshProxyCommandMissingError,
@@ -86,10 +89,14 @@ vi.mock(import("@/remote/sshSupport"), async (importOriginal) => ({
8689
...(await importOriginal()),
8790
resolveSshProperties: vi.fn(),
8891
}));
89-
vi.mock(import("@/remote/sshConfig"), async (importOriginal) => ({
90-
...(await importOriginal()),
91-
getGitForWindowsSshConfigPath: vi.fn(),
92-
}));
92+
vi.mock(import("@/remote/sshConfig"), async (importOriginal) => {
93+
const original = await importOriginal();
94+
return {
95+
...original,
96+
getGitForWindowsSshConfigPath: vi.fn(),
97+
validateDeploymentSshOptions: vi.fn(original.validateDeploymentSshOptions),
98+
};
99+
});
93100

94101
const SAFE_HOSTNAME = "coder.example.com";
95102
const REMOTE_AUTHORITY =
@@ -603,6 +610,41 @@ describe("Remote", () => {
603610
expect(config.permitlocalcommand).toBe("no");
604611
});
605612

613+
it("keeps Coder's pinned options and host over the deployment's", async () => {
614+
const config = await writeConfig({
615+
HostName: "other.example.com",
616+
UserKnownHostsFile: "",
617+
StrictHostKeyChecking: "ask",
618+
});
619+
expect(config).toMatchObject({
620+
userknownhostsfile: "/dev/null",
621+
stricthostkeychecking: "no",
622+
});
623+
expect(config).not.toHaveProperty("hostname");
624+
});
625+
626+
it("keeps Coder's pinned options over unfiltered deployment options, not the user's", async () => {
627+
const deployment = {
628+
ProxyCommand: "other",
629+
StrictHostKeyChecking: "ask",
630+
UserKnownHostsFile: "",
631+
PermitLocalCommand: "yes",
632+
};
633+
vi.mocked(validateDeploymentSshOptions).mockReturnValue({
634+
options: deployment,
635+
ignored: [],
636+
});
637+
const context = createRemote();
638+
context.config.set("coder.sshConfig", ["StrictHostKeyChecking yes"]);
639+
const config = await writeConfig(deployment, context);
640+
expect(config).toMatchObject({
641+
proxycommand: expect.stringContaining("--usage-app="),
642+
stricthostkeychecking: "yes",
643+
userknownhostsfile: "/dev/null",
644+
permitlocalcommand: "no",
645+
});
646+
});
647+
606648
it("ignores deployment SetEnv and SendEnv, warning until dismissed", async () => {
607649
const context = createRemote();
608650
context.userInteraction.setResponse(/^Ignored SSH/, "Don't Show Again");

0 commit comments

Comments
 (0)