Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions rust/crates/git-host/src/authentication/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ const CREATE_ATTEMPTS: usize = 4;
/// How long the helper waits for a free pipe instance.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);

/// Creates a directory with the same protected owner-only DACL as AskPass.
/// Creates a directory with a protected owner-only DACL inherited by files created inside it.
pub(crate) fn private_directory(path: &std::path::Path) -> io::Result<()> {
use windows_sys::Win32::Storage::FileSystem::CreateDirectoryW;
let descriptor = Descriptor::owner_only(&CurrentUser::query()?)?;
let descriptor = Descriptor::owner_only_directory(&CurrentUser::query()?)?;
let attributes = SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: descriptor.0 .0,
Expand Down Expand Up @@ -371,10 +371,18 @@ struct Descriptor(Local);
impl Descriptor {
fn owner_only(user: &CurrentUser) -> io::Result<Self> {
let sid = user.sid_string()?;
let sddl: Vec<u16> = format!("O:{sid}D:P(A;;GA;;;{sid})")
.encode_utf16()
.chain([0])
.collect();
Self::from_sddl(&format!("O:{sid}D:P(A;;GA;;;{sid})"))
}

fn owner_only_directory(user: &CurrentUser) -> io::Result<Self> {
let sid = user.sid_string()?;
// OICI ensures files and subdirectories created inside inherit the
// owner-only protected DACL instead of falling back to the default DACL.
Self::from_sddl(&format!("O:{sid}D:P(A;OICI;GA;;;{sid})"))
}

fn from_sddl(text: &str) -> io::Result<Self> {
let sddl: Vec<u16> = text.encode_utf16().chain([0]).collect();
let mut descriptor: PSECURITY_DESCRIPTOR = null_mut();
// SAFETY: the SDDL string is NUL-terminated and the out-pointer
// references a live local.
Expand Down
36 changes: 36 additions & 0 deletions rust/crates/platform-tests/tests/platform/permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,12 @@ mod unix {
#[cfg(windows)]
mod windows {
use crate::support::TempDir;
use lithe_git_host::private_directory::PrivateDirectory;
use lithe_platform::fs::{add_execute_bits, has_execute_bit, is_launchable_file, unix_mode};
use std::fs::OpenOptions;
use std::io::{Read, Write};
use std::os::windows::fs::OpenOptionsExt;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;

#[test]
fn windows_stores_no_mode_and_launches_any_regular_file() {
Expand All @@ -86,4 +91,35 @@ mod windows {
let folder = std::fs::metadata(directory.path()).expect("metadata");
assert!(!is_launchable_file(&folder));
}

// Mirrors Win32-OpenSSH opening `-E <path>` without FILE_SHARE_WRITE while
// the host reads the evidence log concurrently after closing its create handle.
#[test]
fn private_directory_evidence_log_allows_read_only_sharing_with_single_writer() {
let directory = PrivateDirectory::new().expect("private directory");
let path = directory.path().join("ssh.log");
drop(
OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
.expect("pre-create evidence log"),
);

let mut writer = OpenOptions::new()
.append(true)
.share_mode(FILE_SHARE_READ)
.open(&path)
.expect("open log without FILE_SHARE_WRITE");
writer.write_all(b"debug1: connected\n").expect("write log");
writer.flush().expect("flush log");

let mut reader = OpenOptions::new()
.read(true)
.open(&path)
.expect("read log while writer is open");
let mut text = String::new();
reader.read_to_string(&mut text).expect("read contents");
assert_eq!(text, "debug1: connected\n");
}
}
43 changes: 28 additions & 15 deletions rust/crates/workspace/src/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,9 @@ pub(crate) enum ConnectionTransport {
Process {
child: Mutex<Child>,
tree: ProcessTree,
/// Private SSH evidence directory, kept until `end_transport` has
/// stopped the client so Windows does not fail to delete an open log.
evidence: Mutex<Option<Arc<crate::ssh_evidence::Evidence>>>,
},
#[cfg(feature = "test-support")]
InProcess,
Expand Down Expand Up @@ -314,7 +317,11 @@ impl Connection {
/// host outlives it.
fn end_transport(&self) {
match &self.transport {
ConnectionTransport::Process { child, tree } => {
ConnectionTransport::Process {
child,
tree,
evidence,
} => {
let mut child = child
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
Expand All @@ -336,6 +343,12 @@ impl Connection {
if let Err(error) = tree.terminate(EXIT_GRACE) {
record_cleanup_io("tree-terminate", &error);
}
// Drop the private evidence directory after the SSH process has
// exited so Windows can remove the `-E` log file cleanly.
evidence
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.take();
}
#[cfg(feature = "test-support")]
ConnectionTransport::InProcess => {}
Expand Down Expand Up @@ -737,24 +750,25 @@ fn connect_logged(

let chain = TransportChain::new(chain_hops(request, program)?);
let evidence = if client == Client::Ssh {
Some(crate::ssh_evidence::Evidence::new().map_err(|error| {
CoreError::new(
ErrorCode::ProcessStartFailed,
"Could not prepare SSH identity evidence",
)
.with_details(error.to_string())
})?)
Some(Arc::new(crate::ssh_evidence::Evidence::new().map_err(
|error| {
CoreError::new(
ErrorCode::ProcessStartFailed,
"Could not prepare SSH identity evidence",
)
.with_details(error.to_string())
},
)?))
} else {
None
};
let evidence = Arc::new(Mutex::new(evidence));
let mut argv = chain
.command(&bound_launch_command(request.install_root.as_deref()))
.map_err(|error| {
CoreError::new(ErrorCode::InvalidRequest, client.invalid())
.with_details(error.to_string())
})?;
if let Some(evidence) = evidence.lock().unwrap_or_else(|p| p.into_inner()).as_ref() {
if let Some(evidence) = evidence.as_ref() {
argv.splice(1..1, evidence.arguments());
}
let (program, arguments) = argv.split_first().expect("a hop always produces a command");
Expand Down Expand Up @@ -820,7 +834,7 @@ fn connect_logged(
let launch_log = log.clone();
let resume_for_launch = resume.cloned();
let chain_target = Target::new(&chain, None);
let evidence_for_launch = Arc::clone(&evidence);
let evidence_for_launch = evidence.clone();
std::thread::spawn(move || {
let artifact_for = |report: &lithe_remote::client::bootstrap::ProbeReport| {
let target = report.target()?;
Expand Down Expand Up @@ -852,9 +866,7 @@ fn connect_logged(
},
|server_identity| {
let actual = evidence_for_launch
.lock()
.unwrap_or_else(|p| p.into_inner())
.as_mut()
.as_ref()
.and_then(|evidence| evidence.identity(ssh_pid));
let binding = if client == Client::Ssh && actual.is_none() {
None
Expand Down Expand Up @@ -958,7 +970,7 @@ fn connect_logged(
.iter()
.copied()
.collect();
if let Some(evidence) = evidence.lock().unwrap_or_else(|p| p.into_inner()).as_mut() {
if let Some(evidence) = evidence.as_ref() {
bytes.extend(evidence.diagnostics());
}
bytes
Expand Down Expand Up @@ -1148,6 +1160,7 @@ fn connect_logged(
ConnectionTransport::Process {
child: Mutex::new(child),
tree,
evidence: Mutex::new(evidence),
},
History {
resumed: info.resumed,
Expand Down
89 changes: 59 additions & 30 deletions rust/crates/workspace/src/ssh_evidence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@

use lithe_git_host::private_directory::PrivateDirectory;
use lithe_remote::client::ssh_identity::{self, Identity};
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Seek};
use std::fs::OpenOptions;
use std::io::{self, Read};
use std::path::PathBuf;

/// The helper only writes a private log; it is never parsed as shell code.
///
/// No open write handle is retained after creation: Win32-OpenSSH opens its
/// `-E` log file without `FILE_SHARE_WRITE`, so holding a writable handle in
/// the parent causes `ssh.exe` to fail with `ERROR_SHARING_VIOLATION` (32,
/// reported by the CRT as `Broken pipe`).
pub(crate) struct Evidence {
file: File,
path: PathBuf,
_directory: PrivateDirectory,
}
Expand All @@ -17,12 +21,13 @@ impl Evidence {
pub(crate) fn new() -> io::Result<Self> {
let directory = PrivateDirectory::new()?;
let path = directory.path().join("ssh.log");
let file = lithe_platform::fs::owner_only_file(
OpenOptions::new().read(true).write(true).create_new(true),
)
.open(&path)?;
// Pre-create with owner-only permissions and close immediately so the
// child OpenSSH process is the sole writer.
drop(
lithe_platform::fs::owner_only_file(OpenOptions::new().write(true).create_new(true))
.open(&path)?,
);
Ok(Self {
file,
path,
_directory: directory,
})
Expand All @@ -38,17 +43,20 @@ impl Evidence {
arguments
}

pub(crate) fn identity(&mut self, pid: u32) -> Option<Identity> {
let read = (|| -> io::Result<Vec<u8>> {
self.file.rewind()?;
let mut bytes = Vec::new();
self.file
.by_ref()
.take(ssh_identity::MAX_BYTES as u64 + 1)
.read_to_end(&mut bytes)?;
Ok(bytes)
})();
match read {
/// Opens the evidence log read-only and reads at most `limit` bytes.
///
/// On Windows, `OpenOptions::new().read(true)` defaults to
/// `FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE`, which allows
/// reading while `ssh.exe` still holds the log open for writing.
fn read_bounded(&self, limit: u64) -> io::Result<Vec<u8>> {
let mut file = OpenOptions::new().read(true).open(&self.path)?;
let mut bytes = Vec::new();
file.by_ref().take(limit).read_to_end(&mut bytes)?;
Ok(bytes)
}

pub(crate) fn identity(&self, pid: u32) -> Option<Identity> {
match self.read_bounded(ssh_identity::MAX_BYTES as u64 + 1) {
Ok(bytes) => ssh_identity::parse(&bytes, pid),
Err(error) => {
lithe_diagnostics::core_events::recovery_failed(
Expand All @@ -62,17 +70,8 @@ impl Evidence {
}
}

pub(crate) fn diagnostics(&mut self) -> Vec<u8> {
let result = (|| -> io::Result<Vec<u8>> {
self.file.rewind()?;
let mut bytes = Vec::new();
self.file
.by_ref()
.take(ssh_identity::MAX_BYTES as u64)
.read_to_end(&mut bytes)?;
Ok(bytes)
})();
match result {
pub(crate) fn diagnostics(&self) -> Vec<u8> {
match self.read_bounded(ssh_identity::MAX_BYTES as u64) {
Ok(bytes) => bytes,
Err(error) => {
lithe_diagnostics::core_events::recovery_failed(
Expand All @@ -86,3 +85,33 @@ impl Evidence {
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;

#[test]
fn evidence_reads_diagnostics_and_identity_written_by_another_handle() {
let evidence = Evidence::new().expect("evidence");
let log_line = format!(
"debug1: sshconnect.c:ssh_connect_direct():10 (pid=42): Connecting to box [127.0.0.1] port 22.\n\
debug1: sshconnect.c:ssh_login():20 (pid=42): Authenticating to box:22 as 'dev'\n\
debug1: sshconnect.c:verify_host_key():30 (pid=42): Server host key: ssh-ed25519 SHA256:{}\n\
sshconnect2.c:ssh_userauth2():40 (pid=42): Authenticated to box ([127.0.0.1]:22) using \"publickey\".\n",
"a".repeat(43)
);
let mut writer = OpenOptions::new()
.append(true)
.open(&evidence.path)
.expect("open evidence log for append");
writer
.write_all(log_line.as_bytes())
.expect("write evidence");
writer.flush().expect("flush evidence");

// Read while the writer handle is still open, matching a live ssh.exe.
assert!(evidence.identity(42).is_some());
assert_eq!(evidence.diagnostics(), log_line.as_bytes());
}
}
Loading