Skip to content

Commit bdfa840

Browse files
committed
feat(cli): let users refuse unverified SSH host keys
OPENSHELL_SSH_REQUIRE_HOST_KEY turns the two unverified cases, a sandbox with no published fingerprint and a caller that predates host-key verification, from a warning into a refusal. It is off by default. Signed-off-by: Adrien Langou <alangou@nvidia.com>
1 parent d50650b commit bdfa840

6 files changed

Lines changed: 116 additions & 14 deletions

File tree

‎crates/openshell-cli/src/main.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@ use openshell_cli::completers;
2121
use openshell_cli::run;
2222
use openshell_cli::tls::TlsOptions;
2323
use openshell_core::proto::{GpuResourceRequirements, ServiceAuthorizationMode};
24-
use openshell_core::ssh_host_key::{HostKeyCheck, HostKeyExpectation, KnownHostsPin};
24+
use openshell_core::ssh_host_key::{
25+
HostKeyCheck, HostKeyExpectation, KnownHostsPin, permit_unverified,
26+
};
2527

2628
/// Resolved gateway context: name + gateway endpoint.
2729
struct GatewayContext {
@@ -4367,6 +4369,7 @@ async fn run_async() -> Result<()> {
43674369
"openshell: warning: this SSH connection was started by an OpenShell client that predates host-key verification, so the SSH host key is NOT verified.\n\
43684370
Restart that client (the openshell command or openshell term)."
43694371
);
4372+
permit_unverified().map_err(|err| miette::miette!("{err}"))?;
43704373
None
43714374
}
43724375
// Nothing would pin a key for the `ssh` that reads the file.

‎crates/openshell-cli/src/ssh.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ use openshell_core::proto::{
2424
};
2525
use openshell_core::ssh_host_key::{
2626
HostKeyCheck, HostKeyExpectation, HostKeyGate, KnownHostsPin, SandboxSshTarget,
27-
host_key_alias as host_alias,
27+
host_key_alias as host_alias, permit_unverified,
2828
};
2929
use openshell_core::upload::{
3030
DestinationKind as UploadDestinationKind, ExpectedDestination, UploadPlan,
@@ -2202,6 +2202,7 @@ pub async fn sandbox_ssh_proxy_by_name(
22022202
"{}",
22032203
stale_ssh_config_warning(gateway_name, workspace, name)
22042204
);
2205+
permit_unverified().into_diagnostic()?;
22052206
None
22062207
};
22072208
let server = grpc_server_from_ssh_gateway_url(&session.gateway_url)?;

‎crates/openshell-cli/tests/ssh_proxy_host_key_integration.rs‎

Lines changed: 41 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use hyper_util::rt::{TokioExecutor, TokioIo};
99
use openshell_core::proto::{
1010
CreateSshSessionResponse, Sandbox, SandboxResponse, TcpForwardFrame, tcp_forward_frame,
1111
};
12+
use openshell_core::ssh_host_key::REQUIRE_HOST_KEY_ENV;
1213
use prost::Message;
1314
use russh::keys::ssh_key::private::Ed25519Keypair;
1415
use russh::keys::{HashAlg, PrivateKey};
@@ -190,8 +191,18 @@ fn old_name_mode(gateway: SocketAddr) -> String {
190191
format!("ssh-proxy --server http://{gateway} --name {SANDBOX} --workspace {WORKSPACE}")
191192
}
192193

193-
/// Runs `command` to completion.
194-
async fn finished(mut command: tokio::process::Command, config: &Path) -> Output {
194+
/// Runs `command` to completion. `require_host_key` is whether the user set
195+
/// `OPENSHELL_SSH_REQUIRE_HOST_KEY`.
196+
async fn finished(
197+
mut command: tokio::process::Command,
198+
config: &Path,
199+
require_host_key: bool,
200+
) -> Output {
201+
if require_host_key {
202+
command.env(REQUIRE_HOST_KEY_ENV, "1");
203+
} else {
204+
command.env_remove(REQUIRE_HOST_KEY_ENV);
205+
}
195206
let run = command
196207
.env("XDG_CONFIG_HOME", config)
197208
.env("OPENSHELL_TELEMETRY_ENABLED", "false")
@@ -208,10 +219,10 @@ async fn finished(mut command: tokio::process::Command, config: &Path) -> Output
208219
}
209220

210221
/// Runs `openshell` with `args`, which are separated by single spaces.
211-
async fn openshell(args: &str, config: &Path) -> Output {
222+
async fn openshell(args: &str, config: &Path, require_host_key: bool) -> Output {
212223
let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_openshell"));
213224
command.args(args.split(' '));
214-
finished(command, config).await
225+
finished(command, config, require_host_key).await
215226
}
216227

217228
fn mismatch_message(published: &PrivateKey, presented: &PrivateKey) -> String {
@@ -272,7 +283,7 @@ async fn name_mode_proxy_withholds_a_key_the_gateway_did_not_publish() {
272283
let scratch = tempfile::tempdir().unwrap();
273284
let pin = scratch.path().join("known_hosts/pin");
274285

275-
let proxy = openshell(&name_mode(gateway, &pin), scratch.path()).await;
286+
let proxy = openshell(&name_mode(gateway, &pin), scratch.path(), false).await;
276287

277288
let stderr = String::from_utf8_lossy(&proxy.stderr);
278289
assert_eq!(proxy.status.code(), Some(1), "{stderr}");
@@ -301,7 +312,7 @@ async fn name_mode_proxy_warns_and_relays_when_the_gateway_published_no_key() {
301312
let scratch = tempfile::tempdir().unwrap();
302313
let pin = scratch.path().join("known_hosts/pin");
303314

304-
let proxy = openshell(&name_mode(gateway, &pin), scratch.path()).await;
315+
let proxy = openshell(&name_mode(gateway, &pin), scratch.path(), false).await;
305316

306317
let stderr = String::from_utf8_lossy(&proxy.stderr);
307318
assert!(proxy.status.success(), "{stderr}");
@@ -314,6 +325,16 @@ async fn name_mode_proxy_warns_and_relays_when_the_gateway_published_no_key() {
314325
std::fs::read_to_string(&pin).unwrap(),
315326
pin_content(Some(&key))
316327
);
328+
329+
let refused = openshell(&name_mode(gateway, &pin), scratch.path(), true).await;
330+
331+
let stderr = String::from_utf8_lossy(&refused.stderr);
332+
assert!(!refused.status.success(), "{stderr}");
333+
assert_eq!(refused.stdout, b"");
334+
// The error is wrapped to the terminal width.
335+
assert!(stderr.contains("fingerprint"), "{stderr}");
336+
assert!(stderr.contains(REQUIRE_HOST_KEY_ENV), "{stderr}");
337+
assert_eq!(std::fs::read_to_string(&pin).unwrap(), pin_content(None));
317338
}
318339

319340
/// An `ssh` started by a client or a config entry from before host-key
@@ -339,7 +360,7 @@ async fn proxy_warns_and_relays_for_a_caller_that_predates_host_key_verification
339360
"SSH config entry for sandbox 'my-sb'",
340361
),
341362
] {
342-
let proxy = openshell(&args, scratch.path()).await;
363+
let proxy = openshell(&args, scratch.path(), false).await;
343364

344365
let stderr = String::from_utf8_lossy(&proxy.stderr);
345366
assert!(proxy.status.success(), "{stderr}");
@@ -349,6 +370,14 @@ async fn proxy_warns_and_relays_for_a_caller_that_predates_host_key_verification
349370
stderr.contains("the SSH host key is NOT verified"),
350371
"{stderr}"
351372
);
373+
374+
let refused = openshell(&args, scratch.path(), true).await;
375+
376+
let stderr = String::from_utf8_lossy(&refused.stderr);
377+
assert!(!refused.status.success(), "{stderr}");
378+
assert_eq!(refused.stdout, b"");
379+
assert!(stderr.contains(caller), "{stderr}");
380+
assert!(stderr.contains(REQUIRE_HOST_KEY_ENV), "{stderr}");
352381
}
353382
}
354383

@@ -457,11 +486,12 @@ mod openssh {
457486
.args(overrides.iter().flat_map(|option| ["-o", option]))
458487
.args(sandbox_ssh_args(&proxy_command, "ERROR"))
459488
.args(["sandbox", COMMAND]);
460-
finished(ssh, config).await
489+
finished(ssh, config, false).await
461490
}
462491

463492
/// Runs [`COMMAND`] through the config entry `sandbox ssh-config`
464-
/// prints, with no other configuration and no options of its own.
493+
/// prints, with no other configuration and no options of its own, for
494+
/// a user who requires a verified host key.
465495
async fn ssh_through_config_entry(gateway: SocketAddr, config: &Path) -> Output {
466496
let gateway_dir = config.join("openshell/gateways").join(GATEWAY);
467497
std::fs::create_dir_all(&gateway_dir).unwrap();
@@ -476,7 +506,7 @@ mod openssh {
476506

477507
let print_entry =
478508
format!("--gateway {GATEWAY} --workspace {WORKSPACE} sandbox ssh-config {SANDBOX}");
479-
let printed = openshell(&print_entry, config).await;
509+
let printed = openshell(&print_entry, config, false).await;
480510
assert!(
481511
printed.status.success(),
482512
"{}",
@@ -490,7 +520,7 @@ mod openssh {
490520
.arg(entry)
491521
.args(["-o", "BatchMode=yes"])
492522
.args([format!("openshell-{SANDBOX}.{WORKSPACE}").as_str(), COMMAND]);
493-
finished(ssh, config).await
523+
finished(ssh, config, true).await
494524
}
495525

496526
/// The proxy accepts and forwards any key here, so the refusal is `ssh`'s

‎crates/openshell-core/src/ssh_host_key.rs‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
//! fingerprint format, the pin location and file format, the `ssh` options,
1010
//! the `ssh-proxy` flags, and the scan of the server's key exchange reply.
1111
12+
use std::ffi::OsStr;
1213
use std::fmt;
1314
use std::fs;
1415
use std::io::{self, Write as _};
@@ -21,7 +22,11 @@ use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD};
2122

2223
use crate::forward::shell_escape;
2324
use crate::proto::CreateSshSessionResponse;
25+
use crate::settings::parse_bool_like;
2426

27+
/// Set to refuse every SSH connection whose host key is not verified. Unset,
28+
/// such a connection goes ahead with a warning.
29+
pub const REQUIRE_HOST_KEY_ENV: &str = "OPENSHELL_SSH_REQUIRE_HOST_KEY";
2530
const FINGERPRINT_PREFIX: &str = "SHA256:";
2631
const UNVERIFIED: &str = "unverified";
2732
const HOST_KEY_ALGORITHM: &str = "ssh-ed25519";
@@ -122,6 +127,28 @@ impl HostKeyExpectation {
122127
}
123128
}
124129

130+
/// Whether the user set [`REQUIRE_HOST_KEY_ENV`]. Only a value that reads as
131+
/// "no" turns it back off.
132+
fn host_key_required() -> bool {
133+
requires_host_key(std::env::var_os(REQUIRE_HOST_KEY_ENV).as_deref())
134+
}
135+
136+
fn requires_host_key(value: Option<&OsStr>) -> bool {
137+
value.is_some_and(|value| {
138+
!value.is_empty() && value.to_str().and_then(parse_bool_like) != Some(false)
139+
})
140+
}
141+
142+
/// For a caller that just warned that nothing verifies the host key of its
143+
/// connection.
144+
pub fn permit_unverified() -> Result<(), HostKeyError> {
145+
if host_key_required() {
146+
Err(HostKeyError::Required)
147+
} else {
148+
Ok(())
149+
}
150+
}
151+
125152
#[derive(Debug, thiserror::Error)]
126153
pub enum HostKeyError {
127154
#[error("SSH host key fingerprint is not 'SHA256:' followed by 43 unpadded base64 characters")]
@@ -142,6 +169,17 @@ pub enum HostKeyError {
142169
expected: HostKeyFingerprint,
143170
presented: HostKeyFingerprint,
144171
},
172+
#[error(
173+
"SSH connection to sandbox '{sandbox}' (workspace '{workspace}') refused: {} is set and the gateway published no host key fingerprint.\n\
174+
Upgrade a gateway that predates sandbox SSH identities; otherwise stop and start the sandbox.",
175+
REQUIRE_HOST_KEY_ENV
176+
)]
177+
Unpublished { sandbox: String, workspace: String },
178+
#[error(
179+
"the SSH connection is refused because {} is set and its host key is not verified",
180+
REQUIRE_HOST_KEY_ENV
181+
)]
182+
Required,
145183
#[error("malformed SSH stream from the sandbox: {0}")]
146184
Malformed(&'static str),
147185
#[error(
@@ -382,6 +420,12 @@ impl HostKeyCheck {
382420
HostKeyExpectation::Fingerprint(fingerprint) => Some(fingerprint),
383421
HostKeyExpectation::AcceptAny => None,
384422
})?;
423+
if matches!(expectation, HostKeyExpectation::AcceptAny) && host_key_required() {
424+
return Err(HostKeyError::Unpublished {
425+
sandbox: pin.sandbox,
426+
workspace: pin.workspace,
427+
});
428+
}
385429
Ok(Self { expectation, pin })
386430
}
387431

@@ -927,6 +971,25 @@ mod tests {
927971
}
928972
}
929973

974+
#[test]
975+
fn host_key_is_required_by_any_value_but_a_no() {
976+
for (value, required) in [
977+
(None, false),
978+
(Some(""), false),
979+
(Some("0"), false),
980+
(Some("False"), false),
981+
(Some("1"), true),
982+
(Some("true"), true),
983+
(Some("strict"), true),
984+
] {
985+
assert_eq!(
986+
requires_host_key(value.map(OsStr::new)),
987+
required,
988+
"{value:?}"
989+
);
990+
}
991+
}
992+
930993
/// Before `ssh` can read the pin, it holds the published key or no key.
931994
#[test]
932995
fn check_for_session_keeps_only_the_published_key() {

‎docs/how-it-works/sandboxes/overview.mdx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -922,6 +922,10 @@ They keep working and print a warning on every connection. Replace each pasted
922922
entry with new `openshell sandbox ssh-config` output, or use `--editor` on
923923
`sandbox connect` again for that sandbox.
924924
925+
Set `OPENSHELL_SSH_REQUIRE_HOST_KEY=1` to refuse every unverified connection,
926+
to a sandbox with no published fingerprint or through such an entry, instead
927+
of connecting with a warning.
928+
925929
## Transfer Files
926930
927931
Upload files from your host into the sandbox:

‎skills/openshell-cli/SKILL.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -586,7 +586,8 @@ The CLI, the TUI, and generated SSH config entries verify the host key against
586586
that fingerprint on every SSH connection they open, and refuse a different key
587587
with `SSH host key mismatch`. A `NOT verified` warning means the gateway
588588
published no fingerprint, or the SSH config entry predates host-key
589-
verification; the warning prints its fix.
589+
verification; the warning prints its fix. Set
590+
`OPENSHELL_SSH_REQUIRE_HOST_KEY=1` to refuse such connections instead.
590591

591592
For an infrastructure `Error` on a backend that supports restarting stopped sandboxes, fix the reported cause, run `sandbox stop`, and wait for it to succeed before running `sandbox start`. This retains the sandbox and persistent workspace but cannot recover deleted resources or storage. For a provisioning timeout, wait for cleanup to finish, then run `sandbox start` directly.
592593

0 commit comments

Comments
 (0)