diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 6d33e415..c94b4ff7 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1082,6 +1082,7 @@ dependencies = [ "serde", "serde_json", "windows-sys", + "zeroize", ] [[package]] @@ -1201,6 +1202,7 @@ dependencies = [ "lithe-git-host", "lithe-lsp-transport", "lithe-platform", + "windows-sys", ] [[package]] @@ -2898,6 +2900,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + [[package]] name = "zerotrie" version = "0.2.4" diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 6b9a8740..90b5fbc1 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -1257,6 +1257,23 @@ answer `"retry"` to repeat the failed transfer with helper bypass, at most three total attempts. The AskPass C ABI is called only in the child app's early helper mode. Credential answers are never copied into events or settings. +The helper reaches its invocation's session over a channel that only the same +account can open: on Unix, a socket (mode 0600) in a fresh owner-only directory, +with both ends also checking the peer's user ID; on Windows, a named pipe that +refuses remote clients, whose protected DACL admits only the current user, and +whose owner the helper verifies before writing. Each request also carries a +256-bit session token taken from the child's environment. Core drops a request +before any prompt reaches the host when it comes from another account, carries +another token, is malformed or longer than 16 KiB, asks a prompt longer than +8 KiB, does not arrive within 10 seconds of connecting, would be the session's +seventeenth distinct prompt, or repeats one prompt a fourth time. Each such +drop is logged as `vcs.authentication.request_rejected` with only its `reason`. +A session serves four helpers at a time; later ones wait to be accepted. A +prompt the host leaves unanswered for 180 seconds expires and its helper exits +with status 1, as after a cancel. Core zeroes the token, request frames and +answers when it drops them; copies outside Core, such as the child environment, +the host's JSON strings and operating system buffers, are not covered. + See `rust/fixtures/git/{fetch-plan,execution-events,execution-policy}-v1.json` and [Git execution and project console](https://github.com/1lck/Lithe-IDEA/blob/main/.agents/notes/implemented/architecture/2026-09-12-git-execution-and-project-console.md). diff --git a/rust/crates/core/src/runtime/helper_failures.rs b/rust/crates/core/src/runtime/helper_failures.rs index 7c4b9dda..5daa3915 100644 --- a/rust/crates/core/src/runtime/helper_failures.rs +++ b/rust/crates/core/src/runtime/helper_failures.rs @@ -60,12 +60,14 @@ mod tests { fn helper_events_have_core_ownership_and_expected_channels() { install(); install(); - let input = [ + let failure = [ ("stage", json!("test")), ("error", json!("Helper operation failed")), ("error_code", json!("PermissionDenied")), ("error_domain", json!("io")), ]; + // Rejections carry only their reason; every other helper event is a failure. + let rejection = [("reason", json!("token"))]; for (events, channel) in [ (lithe_git_host::failure_log::EVENTS, "vcs/git"), (lithe_ide_host::failure_log::EVENTS, "app"), @@ -73,12 +75,18 @@ mod tests { ] { for id in events { assert_eq!(catalog::event_by_id(id).unwrap().owner, "lithe-core"); + let input: &[(&'static str, Value)] = + if *id == "vcs.authentication.request_rejected" { + &rejection + } else { + &failure + }; // Exercise the exact sink conversion/validation into an owned // queue, so parallel host drains cannot steal this assertion. let queue = RefCell::new(Vec::new()); dispatch( id, - &input, + input, |event, map| { let prepared = core_events::prepare(event, map, None)?; queue.borrow_mut().push(prepared); diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index d79abe9c..aca8183d 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -1616,6 +1616,18 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "Lithe", }, + EventMetadata { + id: "vcs.authentication.request_rejected", + channel: "vcs/git", + level: LogLevel::Warn, + message: "Git authentication request rejected", + fields: &[ + FieldMetadata { name: "reason", field_type: FieldType::Token, required: true, description: "Why the AskPass channel refused a request: peer-identity (another account or unverifiable peer), token, malformed, oversized, timeout (no complete request before the deadline), prompt-limit or attempt-limit; never the prompt, token or peer input", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "vcs.authentication.response_failed", channel: "vcs/git", diff --git a/rust/crates/git-host/Cargo.toml b/rust/crates/git-host/Cargo.toml index 408a76d5..b939d525 100644 --- a/rust/crates/git-host/Cargo.toml +++ b/rust/crates/git-host/Cargo.toml @@ -9,10 +9,11 @@ description = "Native Git process adapter for Lithe hosts" libc = "0.2" [target.'cfg(windows)'.dependencies] -windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Pipes", "Win32_System_JobObjects", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Threading", "Win32_Security"] } +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Pipes", "Win32_System_JobObjects", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Threading", "Win32_System_IO", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem"] } [dependencies] lithe-platform = { path = "../platform" } rand = "0.8" serde = { version = "1", features = ["derive"] } serde_json = "1" +zeroize = "1.9" diff --git a/rust/crates/git-host/src/authentication.rs b/rust/crates/git-host/src/authentication.rs index 3fc48fa4..0348f3d6 100644 --- a/rust/crates/git-host/src/authentication.rs +++ b/rust/crates/git-host/src/authentication.rs @@ -1,26 +1,111 @@ -//! Owned AskPass transport. Secrets travel only over a token-authenticated loopback socket. +//! AskPass transport between Git or SSH and the host that shows prompts. +//! +//! Git and SSH run this executable in helper mode ([`helper_main`]) when they +//! need a credential. The helper sends the prompt to the [`Session`] that +//! started the command over a channel that only the same account can open: a +//! socket in an owner-only directory on Unix, or a named pipe whose security +//! descriptor admits only the current user on Windows. Each request also +//! carries the session token from the child's environment, so another process +//! of the same account that finds the channel still cannot inject prompts. +//! +//! The token, request frames, and answers live in buffers that are sized up +//! front, so they never reallocate, and are zeroed when dropped. Copies made +//! outside this module are not covered: the child's environment, the host +//! caller's JSON values, and operating system buffers. + +#[cfg(unix)] +mod unix; +#[cfg(unix)] +use unix as channel; +#[cfg(windows)] +mod windows; +#[cfg(windows)] +use windows as channel; +#[cfg(test)] +mod tests; + +use crate::failure_log::{self, FailureSink}; use rand::RngCore; use serde::{Deserialize, Serialize}; +use serde_json::json; +use std::borrow::Cow; use std::collections::HashMap; +use std::ffi::OsStr; use std::io::{self, Read, Write}; -use std::net::{TcpListener, TcpStream}; +use std::path::PathBuf; use std::process::Command; -use std::sync::{mpsc, Mutex, OnceLock}; +use std::sync::{mpsc, Mutex, MutexGuard, OnceLock, PoisonError}; use std::time::{Duration, Instant}; +use zeroize::Zeroizing; +/// Largest request frame, newline excluded. const MAX_FRAME: usize = 16 * 1024; +/// Longest prompt the session forwards to the host. +const MAX_PROMPT: usize = 8192; +/// Longest answer the host may send back. +const MAX_ANSWER: usize = 8192; +/// How long a prompt waits for the user to answer. const PROMPT_TIMEOUT: Duration = Duration::from_secs(180); -type Answer = Option; -static ANSWERS: OnceLock>>> = OnceLock::new(); -fn answers() -> &'static Mutex>> { - ANSWERS.get_or_init(Mutex::default) +/// How long a connected helper has to send its request. +const REQUEST_TIMEOUT: Duration = Duration::from_secs(10); +/// How long delivering an answer, and then seeing the helper close, may take. +const WRITE_TIMEOUT: Duration = Duration::from_secs(5); +/// How often [`Confirmation::wait`] checks for cancellation. +const CANCEL_CHECK: Duration = Duration::from_millis(10); +/// Connections the session serves at once; later ones wait to be accepted. +const MAX_PENDING: usize = 4; +/// Connections one [`Session::poll`] accepts, so a flood of rejected +/// connections cannot hold the caller's loop. +const MAX_ACCEPTS: usize = 16; +/// Distinct prompts one session forwards. +const MAX_PROMPTS: usize = 16; +/// Times one session forwards the same prompt. +const MAX_ATTEMPTS: usize = 3; +/// The channel address the helper connects to. +const ADDRESS_VARIABLE: &str = "LITHE_GIT_ASKPASS_ADDRESS"; +/// The session token the helper must present. +const TOKEN_VARIABLE: &str = "LITHE_GIT_ASKPASS_TOKEN"; + +/// The host's answer; `None` cancels the prompt. +type Answer = Option>; +type Registry = HashMap>; +static ANSWERS: OnceLock> = OnceLock::new(); + +/// Prompts and decisions that wait for [`respond`]. The map has no invariant +/// that a panicking holder could break, so a poisoned lock is used as is. +fn registry() -> MutexGuard<'static, Registry> { + ANSWERS + .get_or_init(Mutex::default) + .lock() + .unwrap_or_else(PoisonError::into_inner) } -fn nonce() -> io::Result { - let mut bytes = [0u8; 32]; + +/// Lowercase hex of `N` random bytes from the operating system. +fn random_hex() -> io::Result { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut bytes = Zeroizing::new([0u8; N]); rand::rngs::OsRng - .try_fill_bytes(&mut bytes) + .try_fill_bytes(bytes.as_mut()) .map_err(io::Error::other)?; - Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect()) + let mut text = String::with_capacity(N * 2); + for byte in bytes.iter() { + text.push(char::from(DIGITS[usize::from(byte >> 4)])); + text.push(char::from(DIGITS[usize::from(byte & 0x0f)])); + } + Ok(text) +} + +/// What one nonblocking accept on the channel produced. +enum Accept { + /// A connection from the session's own account. + Peer(S), + /// A connection that was closed, and why. + // The Windows pipe's descriptor keeps other accounts out before a + // connection exists, so only Unix rejects at accept time. + #[cfg_attr(windows, allow(dead_code))] + Rejected(&'static str), + /// Nothing is waiting. + Empty, } /// A credential prompt from Git or SSH that the host must show to the user. @@ -36,212 +121,496 @@ pub struct Challenge { /// How many times this prompt has been asked in the session, starting at 1. pub attempt: usize, } -#[derive(Deserialize, Serialize)] -struct WireRequest { - token: String, - prompt: String, -} -struct Pending { - stream: TcpStream, - input: Vec, - request_id: Option, - response: Option>, - deadline: Instant, -} -impl Drop for Pending { - fn drop(&mut self) { - if let Some(id) = &self.request_id { - if let Ok(mut map) = answers().lock() { - map.remove(id); - } - } - self.input.fill(0); - } +/// One request frame. Fields borrow from the zeroed input buffer when they +/// contain no escapes, which a hex token never does. +#[derive(Deserialize, Serialize)] +struct WireRequest<'a> { + #[serde(borrow)] + token: Cow<'a, str>, + #[serde(borrow)] + prompt: Cow<'a, str>, } -/// One invocation owns its listener, outstanding prompts, and reply registrations. +/// One invocation owns its channel, outstanding prompts, and reply +/// registrations. Dropping it closes the channel and fails every prompt that +/// has not been answered yet. pub struct Session { - listener: TcpListener, - token: String, + listener: channel::Listener, + token: Zeroizing, pending: Vec, attempts: HashMap, - helper: std::path::PathBuf, + helper: PathBuf, + sink: FailureSink, } + impl Session { - /// Opens a loopback listener with a fresh token for one Git invocation. + /// Opens a private channel with a fresh token for one Git invocation. pub fn new() -> io::Result { - let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))?; - listener.set_nonblocking(true)?; - let executable = std::env::current_exe()?; - // AskPass is an executable path, including spaces. The child environment - // selects the early helper mode without requiring shell interpretation. Ok(Self { - listener, - token: nonce()?, + listener: channel::Listener::bind()?, + token: Zeroizing::new(random_hex::<32>()?), pending: Vec::new(), attempts: HashMap::new(), - helper: executable, + helper: std::env::current_exe()?, + sink: failure_log::emit, }) } + /// Points the command's Git and SSH askpass at this executable and session. pub fn configure(&self, command: &mut Command) -> io::Result<()> { + // AskPass is an executable path, including spaces. The child + // environment selects the early helper mode without a shell. command .env("GIT_ASKPASS", &self.helper) .env("SSH_ASKPASS", &self.helper) .env("LITHE_GIT_ASKPASS_MODE", "1") .env("SSH_ASKPASS_REQUIRE", "force") .env("DISPLAY", "lithe-askpass") - .env( - "LITHE_GIT_ASKPASS_ADDRESS", - self.listener.local_addr()?.to_string(), - ) - .env("LITHE_GIT_ASKPASS_TOKEN", &self.token); + .env(ADDRESS_VARIABLE, self.listener.address()) + .env(TOKEN_VARIABLE, self.token.as_str()); Ok(()) } - /// Nonblocking polling shares the process cancellation loop; no detached worker survives it. + + /// Accepts and advances helper connections without blocking, and returns + /// the prompts that became ready. The caller's process loop drives it, so + /// no detached worker outlives the command. pub fn poll(&mut self) -> io::Result> { - while self.pending.len() < 4 { + let now = Instant::now(); + for _ in 0..MAX_ACCEPTS { + if self.pending.len() >= MAX_PENDING { + break; + } match self.listener.accept() { - Ok((stream, _)) => { - stream.set_nonblocking(true)?; - self.pending.push(Pending { - stream, - input: Vec::new(), - request_id: None, - response: None, - deadline: Instant::now() + Duration::from_secs(10), - }); - } - Err(error) if error.kind() == io::ErrorKind::WouldBlock => break, + Ok(Accept::Peer(stream)) => self.pending.push(Pending::new(stream, now)), + Ok(Accept::Rejected(reason)) => rejected(self.sink, reason), + Ok(Accept::Empty) => break, + Err(error) if is_retry(&error) => break, + // log-exempt: Expected absence: the client left before it was accepted, so nothing is left to serve. + Err(error) if is_gone(&error) => {} Err(error) => return Err(error), } } - let mut prompts = Vec::new(); - let token = &self.token; - let attempts = &mut self.attempts; - self.pending.retain_mut(|pending| { - if Instant::now() >= pending.deadline { - return false; - } - if let Some(receiver) = &pending.response { - match receiver.try_recv() { - Ok(answer) => { - // A bounded credential frame fits in a fresh loopback send buffer. - // Failure closes the connection; it never logs or retries the secret. - if let Some(answer) = answer { - write_response(&mut pending.stream, answer, crate::failure_log::emit); - } - return false; - } - Err(mpsc::TryRecvError::Disconnected) => return false, - Err(mpsc::TryRecvError::Empty) => return true, + let mut context = Context { + token: self.token.as_bytes(), + attempts: &mut self.attempts, + sink: self.sink, + challenges: Vec::new(), + }; + self.pending + .retain_mut(|pending| pending.advance(&mut context, now)); + Ok(context.challenges) + } +} + +/// Session state that every connection consults. +struct Context<'a> { + token: &'a [u8], + attempts: &'a mut HashMap, + sink: FailureSink, + challenges: Vec, +} + +impl Context<'_> { + /// Applies the token and the session's limits. Returns the prompt and its + /// attempt number, or the rejection reason. + fn admit(&mut self, request: WireRequest<'_>) -> Result<(String, usize), &'static str> { + if !same_secret(request.token.as_bytes(), self.token) { + return Err("token"); + } + if request.prompt.len() > MAX_PROMPT { + return Err("oversized"); + } + let prompt = request.prompt.into_owned(); + if !self.attempts.contains_key(&prompt) && self.attempts.len() >= MAX_PROMPTS { + return Err("prompt-limit"); + } + let count = self.attempts.entry(prompt.clone()).or_insert(0); + if *count >= MAX_ATTEMPTS { + return Err("attempt-limit"); + } + *count += 1; + Ok((prompt, *count)) + } +} + +/// One accepted helper connection. +struct Pending { + stream: channel::Stream, + /// The request frame; released as soon as it is parsed. + input: Zeroizing>, + filled: usize, + stage: Stage, + deadline: Instant, +} + +enum Stage { + /// Reading the helper's request frame. + Request, + /// Waiting for the host to answer through [`respond`]. + Answer { + _registration: Registration, + receiver: mpsc::Receiver, + }, + /// Writing the answer back to the helper. + Reply { + frame: Zeroizing>, + written: usize, + }, + /// The answer is written; waiting for the helper to close its end, so that + /// closing ours can never discard bytes it has not read yet. + Drain, +} + +impl Pending { + fn new(stream: channel::Stream, now: Instant) -> Self { + Self { + stream, + input: Zeroizing::new(vec![0; MAX_FRAME + 1]), + filled: 0, + stage: Stage::Request, + deadline: now + REQUEST_TIMEOUT, + } + } + + /// Moves the connection forward without blocking. Returns whether it + /// stays open. + fn advance(&mut self, context: &mut Context<'_>, now: Instant) -> bool { + if now >= self.deadline { + let stage = match self.stage { + Stage::Request => { + rejected(context.sink, "timeout"); + return false; } - } - let mut bytes = [0u8; 2048]; - match pending.stream.read(&mut bytes) { - Ok(0) => return false, - Ok(count) => pending.input.extend_from_slice(&bytes[..count]), - Err(error) if error.kind() == io::ErrorKind::WouldBlock => return true, - Err(_) => return false, - } - if pending.input.len() > MAX_FRAME { - return false; - } - if !pending.input.ends_with(b"\n") { - return true; - } - let Ok(request) = serde_json::from_slice::(&pending.input) else { - return false; + // The user did not answer before the prompt timeout. + Stage::Answer { .. } => "wait_answer", + Stage::Reply { .. } => "write_response", + // The helper stayed connected after reading its answer. + Stage::Drain => "drain_helper", }; - if request.token != *token || request.prompt.len() > 8192 { + response_failed(context.sink, stage, &io::ErrorKind::TimedOut.into()); + return false; + } + match &mut self.stage { + Stage::Request => self.read_request(context, now), + Stage::Answer { receiver, .. } => match receiver.try_recv() { + Ok(Some(answer)) => { + self.stage = Stage::Reply { + frame: reply_frame(&answer), + written: 0, + }; + self.deadline = now + WRITE_TIMEOUT; + self.advance(context, now) + } + // log-exempt: User cancellation: the host cancelled the prompt; the helper sees the channel close and fails. + Ok(None) | Err(mpsc::TryRecvError::Disconnected) => false, + Err(mpsc::TryRecvError::Empty) => self.helper_waiting(context.sink), + }, + Stage::Reply { frame, written } => match deliver(&mut self.stream, frame, written) { + Ok(false) => true, + Ok(true) => { + self.stage = Stage::Drain; + self.deadline = now + WRITE_TIMEOUT; + true + } + Err(error) => { + response_failed(context.sink, "write_response", &error); + false + } + }, + Stage::Drain => self.drain(context.sink), + } + } + + /// Reads what has arrived of the request frame, and registers the prompt + /// once the whole frame is there. + fn read_request(&mut self, context: &mut Context<'_>, now: Instant) -> bool { + let start = self.filled; + let count = match self.stream.read(&mut self.input[start..]) { + Ok(0) => { + if start > 0 { + rejected(context.sink, "malformed"); + } return false; } - if attempts.len() >= 16 && !attempts.contains_key(&request.prompt) { + Ok(count) => count, + Err(error) if is_retry(&error) => return true, + Err(error) => { + read_failed(context.sink, "read_request", &error); return false; } - let attempt = attempts.entry(request.prompt.clone()).or_default(); - *attempt += 1; - if *attempt > 3 { + }; + self.filled += count; + let newline = self.input[start..self.filled] + .iter() + .position(|&byte| byte == b'\n'); + let Some(end) = newline.map(|offset| start + offset) else { + if self.filled == self.input.len() { + rejected(context.sink, "oversized"); return false; } - let Ok(id) = nonce() else { + return true; + }; + // One request per connection: nothing may follow the frame. + let admitted = if end + 1 == self.filled { + serde_json::from_slice::>(&self.input[..end]) + .map_err(|_| "malformed") + .and_then(|request| context.admit(request)) + } else { + Err("malformed") + }; + // The frame held the token; zero and release it before going on. + self.input = Zeroizing::new(Vec::new()); + self.filled = 0; + let (prompt, attempt) = match admitted { + Ok(admitted) => admitted, + Err(reason) => { + rejected(context.sink, reason); return false; - }; - let (sender, receiver) = mpsc::sync_channel(1); - let Ok(mut registry) = answers().lock() else { + } + }; + let request_id = match random_hex::<16>() { + Ok(id) => id, + Err(error) => { + response_failed(context.sink, "register_request", &error); return false; - }; - registry.insert(id.clone(), sender); - pending.request_id = Some(id.clone()); - pending.response = Some(receiver); - pending.deadline = Instant::now() + PROMPT_TIMEOUT; - let lower = request.prompt.to_ascii_lowercase(); - let secret = !lower.contains("username") - && !lower.contains("yes/no") - && !lower.contains("(yes/"); - prompts.push(Challenge { - request_id: id, - prompt: request.prompt, - secret, - attempt: *attempt, - }); - true + } + }; + let (sender, receiver) = mpsc::sync_channel(1); + registry().insert(request_id.clone(), sender); + self.stage = Stage::Answer { + _registration: Registration(request_id.clone()), + receiver, + }; + self.deadline = now + PROMPT_TIMEOUT; + context.challenges.push(Challenge { + request_id, + secret: is_secret(&prompt), + prompt, + attempt, }); - Ok(prompts) + true + } + + /// Checks on the helper while its prompt waits for the user, so a helper + /// that already left does not keep a prompt the host can still answer. + fn helper_waiting(&mut self, sink: FailureSink) -> bool { + match self.stream.read(&mut [0u8; 1]) { + Err(error) if is_retry(&error) => true, + Ok(0) => false, + Ok(_) => { + // One request per connection: nothing may follow the frame. + rejected(sink, "malformed"); + false + } + Err(error) => { + read_failed(sink, "watch_helper", &error); + false + } + } + } + + /// Discards anything the helper still sends until it closes. + fn drain(&mut self, sink: FailureSink) -> bool { + match self.stream.read(&mut [0u8; 64]) { + Ok(0) => false, + Ok(_) => true, + Err(error) if is_retry(&error) => true, + Err(error) => { + read_failed(sink, "drain_helper", &error); + false + } + } + } +} + +/// An entry in the answer registry, removed when dropped so that answers to +/// prompts that already ended fail instead of reaching a later prompt. +struct Registration(String); + +impl Drop for Registration { + fn drop(&mut self) { + registry().remove(&self.0); } } -/// Replies once to a currently owned prompt. Null means cancel; stale replies fail. -pub fn respond(request_id: &str, answer: Answer) -> bool { +fn is_retry(error: &io::Error) -> bool { + matches!( + error.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted + ) +} + +/// The helper closed or reset its end of the channel. +fn is_gone(error: &io::Error) -> bool { + matches!( + error.kind(), + io::ErrorKind::ConnectionReset + | io::ErrorKind::ConnectionAborted + | io::ErrorKind::BrokenPipe + | io::ErrorKind::NotConnected + | io::ErrorKind::UnexpectedEof + ) +} + +/// Ends a connection whose read failed. A helper that left is the normal end +/// of its prompt; any other failure is recorded under `stage`. +fn read_failed(sink: FailureSink, stage: &'static str, error: &io::Error) { + // log-exempt: Expected absence: the helper already closed or reset its end, so nobody is left to serve. + if !is_gone(error) { + response_failed(sink, stage, error); + } +} + +/// Usernames and host-key confirmations are shown; everything else is masked. +fn is_secret(prompt: &str) -> bool { + let lower = prompt.to_ascii_lowercase(); + !lower.contains("username") && !lower.contains("yes/no") && !lower.contains("(yes/") +} + +/// Compares without stopping at the first difference, so timing does not +/// reveal how much of a guessed token matched. +fn same_secret(left: &[u8], right: &[u8]) -> bool { + let difference = left + .iter() + .zip(right) + .fold(0u8, |difference, (left, right)| difference | (left ^ right)); + left.len() == right.len() && std::hint::black_box(difference) == 0 +} + +/// The answer followed by a newline, in a buffer that holds it exactly. +fn reply_frame(answer: &str) -> Zeroizing> { + let mut frame = Zeroizing::new(Vec::with_capacity(answer.len() + 1)); + frame.extend_from_slice(answer.as_bytes()); + frame.push(b'\n'); + frame +} + +/// Writes as much of the frame as the channel takes now. Returns whether the +/// whole frame has been written. +fn deliver(writer: &mut impl Write, frame: &[u8], written: &mut usize) -> io::Result { + while *written < frame.len() { + match writer.write(&frame[*written..]) { + Ok(0) => return Err(io::ErrorKind::WriteZero.into()), + Ok(count) => *written += count, + Err(error) if error.kind() == io::ErrorKind::WouldBlock => return Ok(false), + Err(error) if error.kind() == io::ErrorKind::Interrupted => {} + Err(error) => return Err(error), + } + } + Ok(true) +} + +fn rejected(sink: FailureSink, reason: &'static str) { + sink( + "vcs.authentication.request_rejected", + &[("reason", json!(reason))], + ); +} + +/// Records only the stage and the stable I/O category, never the answer or +/// the error's display text. +fn response_failed(sink: FailureSink, stage: &'static str, error: &io::Error) { + sink( + "vcs.authentication.response_failed", + &[ + ("stage", json!(stage)), + ("error", json!("Git authentication response failed")), + ("error_code", json!(format!("{:?}", error.kind()))), + ("error_domain", json!("io")), + ], + ); +} + +/// Replies once to a currently owned prompt. Null means cancel; stale replies +/// and answers longer than 8192 bytes or containing NUL, CR, or LF fail. +pub fn respond(request_id: &str, answer: Option) -> bool { + let answer = answer.map(Zeroizing::new); if answer .as_ref() - .is_some_and(|value| value.len() > 8192 || value.contains(['\0', '\r', '\n'])) + .is_some_and(|value| value.len() > MAX_ANSWER || value.contains(['\0', '\r', '\n'])) { return false; } - let sender = answers() - .lock() - .ok() - .and_then(|mut map| map.remove(request_id)); + let sender = registry().remove(request_id); sender.is_some_and(|sender| sender.send(answer).is_ok()) } /// Early application mode invoked by Git, before GUI/runtime initialization. +/// Prints the answer and returns 0, or returns 1 when there is none. pub fn helper_main(prompt: &str) -> i32 { - fn run(prompt: &str) -> io::Result<()> { - let address = std::env::var("LITHE_GIT_ASKPASS_ADDRESS").map_err(io::Error::other)?; - let address: std::net::SocketAddr = address.parse().map_err(io::Error::other)?; - if !address.ip().is_loopback() { - return Err(io::ErrorKind::PermissionDenied.into()); + // The helper runs before any log writer exists; the session that owns the + // channel records every rejection it sees. + if helper(prompt).is_ok() { + 0 + } else { + 1 + } +} + +fn helper(prompt: &str) -> io::Result<()> { + let address = std::env::var_os(ADDRESS_VARIABLE).ok_or(io::ErrorKind::NotFound)?; + let token = Zeroizing::new(std::env::var(TOKEN_VARIABLE).map_err(io::Error::other)?); + ask(&address, &token, prompt, &mut io::stdout().lock()) +} + +/// Sends one prompt to the session at `address` and copies its answer line to +/// `out`. Fails when the session cancels, closes, or answers out of protocol. +fn ask(address: &OsStr, token: &str, prompt: &str, out: &mut impl Write) -> io::Result<()> { + let mut request = Zeroizing::new(Vec::with_capacity(MAX_FRAME + 1)); + serde_json::to_writer( + Bounded(&mut request), + &WireRequest { + token: Cow::Borrowed(token), + prompt: Cow::Borrowed(prompt), + }, + )?; + request.push(b'\n'); + let mut stream = channel::connect(address)?; + stream.write_all(&request)?; + drop(request); + let mut answer = Zeroizing::new(vec![0u8; MAX_ANSWER + 1]); + let mut filled = 0; + loop { + if filled == answer.len() { + return Err(io::ErrorKind::InvalidData.into()); } - let token = std::env::var("LITHE_GIT_ASKPASS_TOKEN").map_err(io::Error::other)?; - let mut stream = TcpStream::connect_timeout(&address, Duration::from_secs(5))?; - stream.set_read_timeout(Some(PROMPT_TIMEOUT))?; - stream.set_write_timeout(Some(Duration::from_secs(5)))?; - let mut request = serde_json::to_vec(&WireRequest { - token, - prompt: prompt.to_string(), - })?; - if request.len() > MAX_FRAME { - return Err(io::ErrorKind::InvalidInput.into()); + let count = match stream.read(&mut answer[filled..]) { + Ok(0) => return Err(io::ErrorKind::UnexpectedEof.into()), + Ok(count) => count, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => return Err(error), + }; + let start = filled; + filled += count; + if let Some(offset) = answer[start..filled].iter().position(|&byte| byte == b'\n') { + // The session sends one line and nothing after it. + if start + offset + 1 != filled { + return Err(io::ErrorKind::InvalidData.into()); + } + break; } - request.push(b'\n'); - stream.write_all(&request)?; - let mut answer = Vec::new(); - stream.take(MAX_FRAME as u64).read_to_end(&mut answer)?; - if !answer.ends_with(b"\n") { - answer.fill(0); - return Err(io::ErrorKind::Interrupted.into()); + } + out.write_all(&answer[..filled])?; + out.flush() +} + +/// Appends to a buffer whose capacity already holds a whole frame, and fails +/// instead of growing it, so serialization never leaves a reallocated copy +/// of the token behind. +struct Bounded<'a>(&'a mut Vec); + +impl Write for Bounded<'_> { + fn write(&mut self, bytes: &[u8]) -> io::Result { + if self.0.len() + bytes.len() > MAX_FRAME { + return Err(io::ErrorKind::InvalidInput.into()); } - let result = io::stdout().write_all(&answer); - answer.fill(0); - result + self.0.extend_from_slice(bytes); + Ok(bytes.len()) } - if run(prompt).is_ok() { - 0 - } else { - 1 + + fn flush(&mut self) -> io::Result<()> { + Ok(()) } } @@ -250,94 +619,40 @@ pub struct Confirmation { /// Identifies the decision when the host replies through [`respond`]. pub request_id: String, receiver: mpsc::Receiver, + _registration: Registration, } + impl Confirmation { /// Registers a new decision that the host answers through [`respond`]. pub fn new() -> io::Result { - let request_id = nonce()?; + let request_id = random_hex::<16>()?; let (sender, receiver) = mpsc::sync_channel(1); - answers() - .lock() - .map_err(|_| io::Error::other("Authentication registry unavailable"))? - .insert(request_id.clone(), sender); + registry().insert(request_id.clone(), sender); Ok(Self { + _registration: Registration(request_id.clone()), request_id, receiver, }) } - /// A worker-thread wait observes both its own deadline and the owning request cancellation. + + /// Waits on a worker thread until the host decides, the owning request is + /// cancelled, or the prompt deadline passes. Only the answer `retry` + /// means yes. pub fn wait(&self, mut cancelled: impl FnMut() -> bool) -> io::Result { let deadline = Instant::now() + PROMPT_TIMEOUT; - while Instant::now() < deadline { + loop { if cancelled() { return Ok(false); } - match self.receiver.try_recv() { - Ok(value) => return Ok(value.as_deref() == Some("retry")), - Err(mpsc::TryRecvError::Disconnected) => return Ok(false), - Err(mpsc::TryRecvError::Empty) => std::thread::sleep(Duration::from_millis(10)), + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return Err(io::ErrorKind::TimedOut.into()); + } + match self.receiver.recv_timeout(remaining.min(CANCEL_CHECK)) { + Ok(answer) => return Ok(answer.is_some_and(|value| value.as_str() == "retry")), + Err(mpsc::RecvTimeoutError::Timeout) => {} + Err(mpsc::RecvTimeoutError::Disconnected) => return Ok(false), } } - Err(io::ErrorKind::TimedOut.into()) - } -} -impl Drop for Confirmation { - fn drop(&mut self) { - if let Ok(mut map) = answers().lock() { - map.remove(&self.request_id); - } - } -} - -/// Zero the credential frame before emitting only the stable write category. -fn write_response( - mut writer: impl std::io::Write, - answer: String, - emit: impl FnOnce(&str, crate::failure_log::Fields<'_>), -) { - let mut bytes = answer.into_bytes(); - bytes.push(b'\n'); - let result = writer.write_all(&bytes); - bytes.fill(0); - if let Err(error) = result { - emit( - "vcs.authentication.response_failed", - &[ - ("stage", serde_json::json!("write_response")), - ( - "error", - serde_json::json!("Git authentication response failed"), - ), - ( - "error_code", - serde_json::json!(format!("{:?}", error.kind())), - ), - ("error_domain", serde_json::json!("io")), - ], - ); - } -} - -#[cfg(test)] -mod failure_tests { - #[test] - fn credential_write_failure_never_emits_credentials_or_io_message() { - // A real read-only file descriptor rejects writes on every platform. - let file = std::fs::File::open( - std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/authentication.rs"), - ) - .unwrap(); - let credential = "test-only-private-credential"; - let called = std::cell::Cell::new(false); - super::write_response(file, credential.into(), |event, fields| { - called.set(true); - assert_eq!(event, "vcs.authentication.response_failed"); - assert_eq!(fields.len(), 4); - assert_eq!(fields[0].1, "write_response"); - assert_eq!(fields[1].1, "Git authentication response failed"); - assert_eq!(fields[3].1, "io"); - assert!(!serde_json::to_string(fields).unwrap().contains(credential)); - }); - assert!(called.get()); } } diff --git a/rust/crates/git-host/src/authentication/tests.rs b/rust/crates/git-host/src/authentication/tests.rs new file mode 100644 index 00000000..6c8842c9 --- /dev/null +++ b/rust/crates/git-host/src/authentication/tests.rs @@ -0,0 +1,519 @@ +//! In-process AskPass tests: the helper side runs on a thread against a real +//! channel while the test thread polls the session, with explicit deadlines. + +use super::*; +use std::cell::RefCell; +use std::ffi::OsString; +use std::thread::{self, JoinHandle}; + +const DEADLINE: Duration = Duration::from_secs(10); +const CREDENTIAL: &str = "test-only-private-credential"; + +thread_local! { + static RECORDED: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// Sink for sessions polled on the test thread. +fn record(event: &str, fields: failure_log::Fields<'_>) { + let fields = serde_json::to_string(fields).unwrap(); + RECORDED.with(|recorded| recorded.borrow_mut().push((event.to_owned(), fields))); +} + +fn recorded() -> Vec<(String, String)> { + RECORDED.with(RefCell::take) +} + +fn rejection(reason: &str) -> (String, String) { + ( + "vcs.authentication.request_rejected".into(), + json!([["reason", reason]]).to_string(), + ) +} + +fn failure(stage: &str, code: &str) -> (String, String) { + ( + "vcs.authentication.response_failed".into(), + json!([ + ["stage", stage], + ["error", "Git authentication response failed"], + ["error_code", code], + ["error_domain", "io"] + ]) + .to_string(), + ) +} + +struct Fixture { + session: Session, + address: OsString, + token: String, +} + +fn fixture() -> Fixture { + let mut session = Session::new().unwrap(); + session.sink = record; + Fixture { + address: session.listener.address().to_owned(), + token: session.token.to_string(), + session, + } +} + +fn frame(token: &str, prompt: &str) -> Vec { + let mut frame = json!({"token": token, "prompt": prompt}) + .to_string() + .into_bytes(); + frame.push(b'\n'); + frame +} + +/// Runs the helper side of one prompt on a thread. +fn spawn_ask(address: &OsStr, token: &str, prompt: &str) -> JoinHandle>> { + let (address, token, prompt) = (address.to_owned(), token.to_owned(), prompt.to_owned()); + thread::spawn(move || { + let mut out = Vec::new(); + ask(&address, &token, &prompt, &mut out).map(|()| out) + }) +} + +/// Sends raw bytes as a helper would. Unless `close` is set, it then returns +/// what came back before the session closed the channel. +fn spawn_raw(address: &OsStr, bytes: Vec, close: bool) -> JoinHandle>> { + let address = address.to_owned(); + thread::spawn(move || { + let mut stream = channel::connect(&address)?; + stream.write_all(&bytes)?; + let mut received = Vec::new(); + if !close { + stream.read_to_end(&mut received)?; + } + Ok(received) + }) +} + +fn next_challenge(session: &mut Session) -> Challenge { + let deadline = Instant::now() + DEADLINE; + loop { + let mut ready = session.poll().unwrap(); + if let Some(challenge) = ready.pop() { + assert!(ready.is_empty(), "unexpected second AskPass prompt"); + return challenge; + } + assert!( + Instant::now() < deadline, + "no AskPass prompt before the deadline" + ); + thread::yield_now(); + } +} + +/// Polls until the helper thread ends; no prompt may appear meanwhile. +fn finish(session: &mut Session, helper: JoinHandle) -> T { + let deadline = Instant::now() + DEADLINE; + while !helper.is_finished() { + assert!( + session.poll().unwrap().is_empty(), + "unexpected AskPass prompt" + ); + assert!( + Instant::now() < deadline, + "AskPass helper did not finish before the deadline" + ); + thread::yield_now(); + } + helper.join().unwrap() +} + +/// Polls until the session has recorded something about a helper that +/// already left. +fn settle(session: &mut Session) { + let deadline = Instant::now() + DEADLINE; + while RECORDED.with(|recorded| recorded.borrow().is_empty()) { + assert!( + session.poll().unwrap().is_empty(), + "unexpected AskPass prompt" + ); + assert!( + Instant::now() < deadline, + "the session recorded nothing before the deadline" + ); + thread::yield_now(); + } +} + +/// Joins a helper whose channel no longer needs polling. +fn join(helper: JoinHandle) -> T { + let deadline = Instant::now() + DEADLINE; + while !helper.is_finished() { + assert!( + Instant::now() < deadline, + "AskPass helper did not finish before the deadline" + ); + thread::yield_now(); + } + helper.join().unwrap() +} + +/// The helper saw the channel close without an answer. +fn assert_no_answer(result: io::Result>) { + match result { + Ok(received) => assert!(received.is_empty(), "the helper received bytes"), + Err(error) => assert!( + matches!( + error.kind(), + io::ErrorKind::UnexpectedEof | io::ErrorKind::ConnectionReset + ), + "unexpected helper error {error:?}" + ), + } +} + +#[test] +fn configure_points_git_and_ssh_at_this_session() { + let fixture = fixture(); + let mut command = Command::new("unused-fixture"); + fixture.session.configure(&mut command).unwrap(); + let env: HashMap = command + .get_envs() + .map(|(key, value)| (key.to_owned(), value.unwrap().to_owned())) + .collect(); + let value = |key: &str| env[OsStr::new(key)].clone(); + assert_eq!(value("GIT_ASKPASS"), std::env::current_exe().unwrap()); + assert_eq!(value("SSH_ASKPASS"), value("GIT_ASKPASS")); + assert_eq!(value("LITHE_GIT_ASKPASS_MODE"), "1"); + assert_eq!(value("SSH_ASKPASS_REQUIRE"), "force"); + assert_eq!(value(ADDRESS_VARIABLE), fixture.address); + assert_eq!(value(TOKEN_VARIABLE), OsStr::new(&fixture.token)); + assert_eq!(fixture.token.len(), 64); +} + +#[test] +fn answer_reaches_the_helper_exactly_once() { + let mut fixture = fixture(); + let prompt = "Password for 'https://fixture.invalid':"; + let helper = spawn_ask(&fixture.address, &fixture.token, prompt); + let challenge = next_challenge(&mut fixture.session); + assert_eq!(challenge.prompt, prompt); + assert!(challenge.secret); + assert_eq!(challenge.attempt, 1); + let id = challenge.request_id; + assert!(!respond(&id, Some("invalid\nresponse".into()))); + assert!(!respond(&id, Some("invalid\rresponse".into()))); + assert!(!respond(&id, Some("invalid\0response".into()))); + assert!(!respond(&id, Some("x".repeat(MAX_ANSWER + 1)))); + assert!(respond(&id, Some(CREDENTIAL.into()))); + assert!(!respond(&id, Some("replayed".into()))); + let answer = finish(&mut fixture.session, helper).unwrap(); + assert_eq!(answer, format!("{CREDENTIAL}\n").into_bytes()); + assert!(recorded().is_empty()); +} + +#[test] +fn longest_answer_fits_the_helper_buffer() { + let mut fixture = fixture(); + let helper = spawn_ask(&fixture.address, &fixture.token, "Password:"); + let challenge = next_challenge(&mut fixture.session); + let longest = "a".repeat(MAX_ANSWER); + assert!(respond(&challenge.request_id, Some(longest.clone()))); + let answer = finish(&mut fixture.session, helper).unwrap(); + assert_eq!(answer.len(), MAX_ANSWER + 1); + assert!(answer.starts_with(longest.as_bytes()) && answer.ends_with(b"\n")); +} + +#[test] +fn cancelled_prompt_fails_the_helper() { + let mut fixture = fixture(); + let helper = spawn_ask(&fixture.address, &fixture.token, "Password:"); + let challenge = next_challenge(&mut fixture.session); + assert!(respond(&challenge.request_id, None)); + let error = finish(&mut fixture.session, helper).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof); + assert!(!registry().contains_key(&challenge.request_id)); + assert!(recorded().is_empty()); +} + +#[test] +fn wrong_token_is_rejected_without_a_prompt() { + let mut fixture = fixture(); + let guess = "0".repeat(fixture.token.len()); + let helper = spawn_ask(&fixture.address, &guess, "Password for intruder:"); + assert_no_answer(finish(&mut fixture.session, helper)); + let recorded = recorded(); + assert_eq!(recorded, [rejection("token")]); + assert!(!recorded[0].1.contains(&guess) && !recorded[0].1.contains("intruder")); +} + +#[test] +fn frames_outside_the_protocol_are_rejected() { + let mut fixture = fixture(); + let mut trailing = frame(&fixture.token, "Password:"); + trailing.extend_from_slice(b"extra"); + // (bytes, whether the helper closes right after sending, reason) + let cases = [ + (b"not json\n".to_vec(), false, "malformed"), + (b"{\"token\"".to_vec(), true, "malformed"), + (trailing, false, "malformed"), + (vec![b'x'; MAX_FRAME + 1], false, "oversized"), + ( + frame(&fixture.token, &"p".repeat(MAX_PROMPT + 1)), + false, + "oversized", + ), + ]; + for (bytes, close, reason) in cases { + let helper = spawn_raw(&fixture.address, bytes, close); + assert_no_answer(finish(&mut fixture.session, helper)); + if close { + // The helper left before the session read its bytes. + settle(&mut fixture.session); + } + assert_eq!(recorded(), [rejection(reason)]); + } + assert!(fixture.session.attempts.is_empty()); +} + +#[test] +fn longest_prompt_is_forwarded() { + let mut fixture = fixture(); + let prompt = "p".repeat(MAX_PROMPT); + let helper = spawn_ask(&fixture.address, &fixture.token, &prompt); + let challenge = next_challenge(&mut fixture.session); + assert_eq!(challenge.prompt, prompt); + assert!(respond(&challenge.request_id, None)); + assert_no_answer(finish(&mut fixture.session, helper)); +} + +#[test] +fn request_larger_than_a_frame_never_leaves_the_helper() { + let fixture = fixture(); + let mut out = Vec::new(); + let error = ask( + &fixture.address, + &fixture.token, + &"p".repeat(MAX_FRAME), + &mut out, + ) + .unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidInput); + assert!(out.is_empty()); +} + +#[test] +fn attempts_per_prompt_are_bounded() { + let mut fixture = fixture(); + for attempt in 1..=MAX_ATTEMPTS { + let helper = spawn_ask(&fixture.address, &fixture.token, "Password:"); + let challenge = next_challenge(&mut fixture.session); + assert_eq!(challenge.attempt, attempt); + assert!(respond(&challenge.request_id, None)); + assert_no_answer(finish(&mut fixture.session, helper)); + } + let helper = spawn_ask(&fixture.address, &fixture.token, "Password:"); + assert_no_answer(finish(&mut fixture.session, helper)); + assert_eq!(recorded(), [rejection("attempt-limit")]); +} + +#[test] +fn distinct_prompts_are_bounded() { + let mut fixture = fixture(); + let mut ask_once = |prompt: &str| { + let helper = spawn_ask(&fixture.address, &fixture.token, prompt); + let challenge = next_challenge(&mut fixture.session); + assert!(respond(&challenge.request_id, None)); + assert_no_answer(finish(&mut fixture.session, helper)); + challenge.attempt + }; + for index in 0..MAX_PROMPTS { + assert_eq!(ask_once(&format!("Password {index}:")), 1); + } + // A prompt already seen is still forwarded once the limit is reached. + assert_eq!(ask_once("Password 0:"), 2); + let helper = spawn_ask(&fixture.address, &fixture.token, "One prompt too many:"); + assert_no_answer(finish(&mut fixture.session, helper)); + assert_eq!(recorded(), [rejection("prompt-limit")]); +} + +#[test] +fn helper_that_leaves_ends_its_prompt() { + let mut fixture = fixture(); + let address = fixture.address.clone(); + let request = frame(&fixture.token, "Password:"); + let (leave, left) = mpsc::channel::<()>(); + let helper = thread::spawn(move || { + let mut stream = channel::connect(&address)?; + stream.write_all(&request)?; + left.recv_timeout(DEADLINE).map_err(io::Error::other)?; + Ok::<_, io::Error>(()) + }); + let challenge = next_challenge(&mut fixture.session); + leave.send(()).unwrap(); + join(helper).unwrap(); + let deadline = Instant::now() + DEADLINE; + while registry().contains_key(&challenge.request_id) { + assert!(fixture.session.poll().unwrap().is_empty()); + assert!(Instant::now() < deadline, "the prompt outlived its helper"); + thread::yield_now(); + } + assert!(!respond(&challenge.request_id, Some(CREDENTIAL.into()))); + assert!(fixture.session.pending.is_empty()); + assert!(recorded().is_empty()); +} + +#[test] +fn bytes_after_the_request_end_its_prompt() { + let mut fixture = fixture(); + let address = fixture.address.clone(); + let request = frame(&fixture.token, "Password:"); + let (send_more, more) = mpsc::channel::<()>(); + let helper = thread::spawn(move || { + let mut stream = channel::connect(&address)?; + stream.write_all(&request)?; + more.recv_timeout(DEADLINE).map_err(io::Error::other)?; + stream.write_all(b"second request")?; + let mut received = Vec::new(); + stream.read_to_end(&mut received)?; + Ok(received) + }); + let challenge = next_challenge(&mut fixture.session); + send_more.send(()).unwrap(); + assert_no_answer(finish(&mut fixture.session, helper)); + assert!(!respond(&challenge.request_id, Some(CREDENTIAL.into()))); + assert_eq!(recorded(), [rejection("malformed")]); +} + +#[test] +fn silent_helper_is_dropped_at_the_request_deadline() { + let mut fixture = fixture(); + let helper = spawn_raw(&fixture.address, Vec::new(), false); + let deadline = Instant::now() + DEADLINE; + while fixture.session.pending.is_empty() { + assert!(fixture.session.poll().unwrap().is_empty()); + assert!(Instant::now() < deadline, "the helper was never accepted"); + thread::yield_now(); + } + // Expire the deadline instead of waiting for it. + fixture.session.pending[0].deadline = Instant::now(); + assert!(fixture.session.poll().unwrap().is_empty()); + assert!(fixture.session.pending.is_empty()); + assert_no_answer(join(helper)); + assert_eq!(recorded(), [rejection("timeout")]); +} + +#[test] +fn unanswered_prompt_is_recorded_at_its_deadline() { + let mut fixture = fixture(); + let helper = spawn_ask(&fixture.address, &fixture.token, "Password:"); + let challenge = next_challenge(&mut fixture.session); + // Expire the prompt timeout instead of waiting for it. + fixture.session.pending[0].deadline = Instant::now(); + assert!(fixture.session.poll().unwrap().is_empty()); + assert!(fixture.session.pending.is_empty()); + assert_no_answer(join(helper)); + assert!(!respond(&challenge.request_id, Some(CREDENTIAL.into()))); + assert_eq!(recorded(), [failure("wait_answer", "TimedOut")]); +} + +#[test] +fn read_failures_are_recorded_unless_the_helper_left() { + for kind in [ + io::ErrorKind::ConnectionReset, + io::ErrorKind::ConnectionAborted, + io::ErrorKind::BrokenPipe, + io::ErrorKind::NotConnected, + io::ErrorKind::UnexpectedEof, + ] { + read_failed(record, "read_request", &kind.into()); + } + assert!(recorded().is_empty()); + read_failed( + record, + "watch_helper", + &io::ErrorKind::PermissionDenied.into(), + ); + assert_eq!(recorded(), [failure("watch_helper", "PermissionDenied")]); +} + +#[test] +fn dropping_the_session_fails_waiting_helpers() { + let mut fixture = fixture(); + let helper = spawn_ask(&fixture.address, &fixture.token, "Password:"); + let challenge = next_challenge(&mut fixture.session); + drop(fixture.session); + assert_no_answer(join(helper)); + assert!(!respond(&challenge.request_id, Some(CREDENTIAL.into()))); +} + +#[cfg(unix)] +#[test] +fn unix_channel_is_private_and_removed_with_the_session() { + use std::os::unix::fs::PermissionsExt; + let fixture = fixture(); + let socket = std::path::PathBuf::from(&fixture.address); + let directory = socket.parent().unwrap().to_path_buf(); + let mode = |path: &std::path::Path| { + std::fs::symlink_metadata(path) + .unwrap() + .permissions() + .mode() + & 0o777 + }; + assert_eq!(mode(&directory), 0o700); + assert_eq!(mode(&socket), 0o600); + drop(fixture.session); + assert!(!socket.exists() && !directory.exists()); +} + +#[test] +fn reply_write_failure_never_logs_the_answer() { + // A real read-only file rejects writes on every platform. + let mut file = + std::fs::File::open(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml")) + .unwrap(); + let frame = reply_frame(CREDENTIAL); + let mut written = 0; + let error = deliver(&mut file, &frame, &mut written).unwrap_err(); + response_failed(record, "write_response", &error); + let recorded = recorded(); + assert_eq!(recorded.len(), 1); + assert_eq!(recorded[0].0, "vcs.authentication.response_failed"); + let fields: serde_json::Value = serde_json::from_str(&recorded[0].1).unwrap(); + assert_eq!(fields[0], json!(["stage", "write_response"])); + assert_eq!( + fields[1], + json!(["error", "Git authentication response failed"]) + ); + assert_eq!(fields[3], json!(["error_domain", "io"])); + assert!(!recorded[0].1.contains(CREDENTIAL)); +} + +#[test] +fn confirmation_unregisters_when_dropped() { + let confirmation = Confirmation::new().unwrap(); + let id = confirmation.request_id.clone(); + assert!(registry().contains_key(&id)); + drop(confirmation); + assert!(!registry().contains_key(&id)); +} + +#[test] +fn prompts_for_names_and_host_keys_are_not_masked() { + assert!(!is_secret("Username for 'https://fixture.invalid':")); + assert!(!is_secret( + "Are you sure you want to continue connecting (yes/no/[fingerprint])?" + )); + assert!(is_secret("Enter passphrase for key '/fixture/id':")); +} + +#[test] +fn random_hex_and_secret_comparison() { + let first = random_hex::<16>().unwrap(); + assert_eq!(first.len(), 32); + assert!(first + .bytes() + .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())); + assert_ne!(first, random_hex::<16>().unwrap()); + assert!(same_secret(b"abcd", b"abcd")); + assert!(!same_secret(b"abcd", b"abce")); + assert!(!same_secret(b"abcd", b"abc")); + assert!(!same_secret(b"", b"a")); +} diff --git a/rust/crates/git-host/src/authentication/unix.rs b/rust/crates/git-host/src/authentication/unix.rs new file mode 100644 index 00000000..f8fa8b39 --- /dev/null +++ b/rust/crates/git-host/src/authentication/unix.rs @@ -0,0 +1,227 @@ +//! Unix AskPass channel: a socket inside a fresh owner-only directory. +//! +//! Both ends check the account on the other side of the socket, so the +//! directory permissions are a second layer rather than the only one. A +//! process of another account that swaps or guesses the path can at most +//! make the prompt fail; it never receives the session token or an answer. + +use super::{random_hex, Accept, PROMPT_TIMEOUT, WRITE_TIMEOUT}; +use crate::failure_log; +use lithe_platform::fs::{ + restrict_directory_to_owner, OWNER_ONLY_DIRECTORY_MODE, OWNER_ONLY_FILE_MODE, +}; +use std::ffi::OsStr; +use std::fs::{self, DirBuilder, Permissions}; +use std::io; +use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt}; +use std::os::unix::io::{AsRawFd, RawFd}; +use std::os::unix::net::{UnixListener, UnixStream}; +use std::path::{Path, PathBuf}; + +/// The socket's file name inside the private directory. +const SOCKET_NAME: &str = "askpass.sock"; +/// `sun_path` holds 104 bytes on macOS and 108 on Linux, terminator included; +/// longer candidate paths are skipped rather than truncated. +const MAX_SOCKET_PATH: usize = 100; +/// Name collisions are retried with a fresh random suffix this many times. +const CREATE_ATTEMPTS: usize = 4; + +/// The server end the session reads requests from and writes answers to. +pub(super) type Stream = UnixStream; + +/// Listening socket for one session. Dropping it closes the socket, then +/// removes the socket file and the private directory. +pub(super) struct Listener { + listener: UnixListener, + socket: Entry, + _directory: Entry, +} + +impl Listener { + /// Binds a socket in the first usable temporary directory. + pub(super) fn bind() -> io::Result { + let mut last = io::Error::new( + io::ErrorKind::NotFound, + "No temporary directory can hold the AskPass socket", + ); + for parent in candidates() { + match bind_in(&parent) { + Ok(listener) => return Ok(listener), + Err(error) => last = error, + } + } + Err(last) + } + + /// The socket path the helper connects to. + pub(super) fn address(&self) -> &OsStr { + self.socket.path.as_os_str() + } + + /// Takes one waiting connection without blocking. + pub(super) fn accept(&mut self) -> io::Result> { + let stream = match self.listener.accept() { + Ok((stream, _)) => stream, + Err(error) if error.kind() == io::ErrorKind::WouldBlock => return Ok(Accept::Empty), + Err(error) => return Err(error), + }; + // A peer whose account cannot be read is treated like another account. + if peer_uid(stream.as_raw_fd()).ok() != Some(effective_uid()) { + return Ok(Accept::Rejected("peer-identity")); + } + // Linux does not carry O_NONBLOCK from the listener to accepted sockets. + stream.set_nonblocking(true)?; + Ok(Accept::Peer(stream)) + } +} + +/// Opens the helper's end of the channel and checks that the session's own +/// account owns the socket before any byte is sent. +pub(super) fn connect(address: &OsStr) -> io::Result { + let path = Path::new(address); + if !path.is_absolute() { + return Err(io::ErrorKind::InvalidInput.into()); + } + let stream = UnixStream::connect(path)?; + if peer_uid(stream.as_raw_fd())? != effective_uid() { + return Err(io::ErrorKind::PermissionDenied.into()); + } + // The session's own prompt and write deadlines end first and close the + // socket; this timeout only covers a session that stopped polling. + stream.set_read_timeout(Some(PROMPT_TIMEOUT + WRITE_TIMEOUT))?; + stream.set_write_timeout(Some(WRITE_TIMEOUT))?; + Ok(stream) +} + +/// A path the listener created and removes when dropped. +struct Entry { + path: PathBuf, + stage: &'static str, + remove: fn(&Path) -> io::Result<()>, +} + +impl Drop for Entry { + fn drop(&mut self) { + failure_log::cleanup( + "vcs.host.cleanup_failed", + self.stage, + (self.remove)(&self.path), + ); + } +} + +/// Per-user runtime directory first, then the temporary directory. Relative +/// values are ignored because they would depend on the working directory. +fn candidates() -> Vec { + let mut list: Vec = std::env::var_os("XDG_RUNTIME_DIR") + .map(PathBuf::from) + .into_iter() + .chain([std::env::temp_dir(), PathBuf::from("/tmp")]) + .filter(|path| path.is_absolute()) + .collect(); + list.dedup(); + list +} + +fn bind_in(parent: &Path) -> io::Result { + let mut last = io::Error::from(io::ErrorKind::AlreadyExists); + for _ in 0..CREATE_ATTEMPTS { + let directory = parent.join(format!("lithe-askpass-{}", random_hex::<8>()?)); + let socket = directory.join(SOCKET_NAME); + if socket.as_os_str().len() > MAX_SOCKET_PATH { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "The AskPass socket path is too long", + )); + } + match DirBuilder::new() + .mode(OWNER_ONLY_DIRECTORY_MODE) + .create(&directory) + { + Ok(()) => {} + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => { + last = error; + continue; + } + Err(error) => return Err(error), + } + // Created by this call, so removal on every later failure is safe. + let directory = Entry { + path: directory, + stage: "askpass_directory", + remove: |path| fs::remove_dir(path), + }; + verify_private(&directory.path)?; + let listener = UnixListener::bind(&socket)?; + let socket = Entry { + path: socket, + stage: "askpass_socket", + remove: |path| fs::remove_file(path), + }; + fs::set_permissions(&socket.path, Permissions::from_mode(OWNER_ONLY_FILE_MODE))?; + listener.set_nonblocking(true)?; + return Ok(Listener { + listener, + socket, + _directory: directory, + }); + } + Err(last) +} + +/// The umask can clear owner bits and a racing process can replace the entry, +/// so the directory is restricted explicitly and checked without following +/// links. +fn verify_private(directory: &Path) -> io::Result<()> { + restrict_directory_to_owner(directory)?; + let metadata = fs::symlink_metadata(directory)?; + if metadata.is_dir() && metadata.uid() == effective_uid() && metadata.mode() & 0o077 == 0 { + Ok(()) + } else { + Err(io::ErrorKind::PermissionDenied.into()) + } +} + +fn effective_uid() -> u32 { + // SAFETY: geteuid has no preconditions and cannot fail. + unsafe { libc::geteuid() } +} + +/// Account of the process on the other end of a connected Unix socket. For a +/// client this is the account that created the listening socket. +#[cfg(any(target_os = "linux", target_os = "android"))] +fn peer_uid(socket: RawFd) -> io::Result { + let mut credentials = libc::ucred { + pid: 0, + uid: 0, + gid: 0, + }; + let mut length = std::mem::size_of::() as libc::socklen_t; + // SAFETY: the out-pointers reference live locals of the declared size. + let status = unsafe { + libc::getsockopt( + socket, + libc::SOL_SOCKET, + libc::SO_PEERCRED, + (&mut credentials as *mut libc::ucred).cast(), + &mut length, + ) + }; + if status == -1 { + return Err(io::Error::last_os_error()); + } + Ok(credentials.uid) +} + +/// Account of the process on the other end of a connected Unix socket. For a +/// client this is the account that created the listening socket. +#[cfg(not(any(target_os = "linux", target_os = "android")))] +fn peer_uid(socket: RawFd) -> io::Result { + let mut uid: libc::uid_t = 0; + let mut gid: libc::gid_t = 0; + // SAFETY: the out-pointers reference live locals. + if unsafe { libc::getpeereid(socket, &mut uid, &mut gid) } == -1 { + return Err(io::Error::last_os_error()); + } + Ok(uid) +} diff --git a/rust/crates/git-host/src/authentication/windows.rs b/rust/crates/git-host/src/authentication/windows.rs new file mode 100644 index 00000000..61f5c614 --- /dev/null +++ b/rust/crates/git-host/src/authentication/windows.rs @@ -0,0 +1,385 @@ +//! Windows AskPass channel: a local named pipe that only the current user can +//! open. +//! +//! The pipe's security descriptor makes the current user its owner and +//! grants access to nobody else, and the kernel refuses clients on other +//! machines. Names are random and the first instance is created exclusively, +//! so a name that another process already holds is skipped rather than +//! shared. The helper checks the pipe's owner before it sends the session +//! token, so a pipe that another account created never receives it. + +use super::{random_hex, Accept}; +use std::ffi::{OsStr, OsString}; +use std::fs::{File, OpenOptions}; +use std::io::{self, Read, Write}; +use std::os::windows::ffi::OsStrExt; +use std::os::windows::fs::OpenOptionsExt; +use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; +use std::ptr::null_mut; +use std::time::{Duration, Instant}; +use windows_sys::Win32::Foundation::{ + LocalFree, ERROR_ACCESS_DENIED, ERROR_BROKEN_PIPE, ERROR_NO_DATA, ERROR_PIPE_BUSY, + ERROR_PIPE_CONNECTED, ERROR_PIPE_LISTENING, ERROR_PIPE_NOT_CONNECTED, ERROR_SUCCESS, + GENERIC_READ, GENERIC_WRITE, HANDLE, INVALID_HANDLE_VALUE, +}; +use windows_sys::Win32::Security::Authorization::{ + ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, GetSecurityInfo, + SDDL_REVISION_1, SE_KERNEL_OBJECT, +}; +use windows_sys::Win32::Security::{ + EqualSid, GetTokenInformation, TokenUser, OWNER_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, + PSID, SECURITY_ATTRIBUTES, TOKEN_QUERY, TOKEN_USER, +}; +use windows_sys::Win32::Storage::FileSystem::{ + FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_ACCESS_DUPLEX, READ_CONTROL, SECURITY_IDENTIFICATION, +}; +use windows_sys::Win32::System::Pipes::{ + ConnectNamedPipe, CreateNamedPipeW, PeekNamedPipe, WaitNamedPipeW, PIPE_NOWAIT, + PIPE_READMODE_BYTE, PIPE_REJECT_REMOTE_CLIENTS, PIPE_TYPE_BYTE, +}; +use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + +/// Every local named pipe lives under this prefix. +const PREFIX: &str = r"\\.\pipe\"; +/// Each direction buffers one maximum-size frame. +const BUFFER_SIZE: u32 = 16 * 1024; +/// Accepted prompts, the listening instance, and the replacement that is +/// created before a connected instance is handed over. +const MAX_INSTANCES: u32 = 8; +/// Name collisions are retried with a fresh random suffix this many times. +const CREATE_ATTEMPTS: usize = 4; +/// How long the helper waits for a free pipe instance. +const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); + +/// Listening pipe for one session. Dropping it closes the last listening +/// instance, which removes the pipe name once accepted instances close too. +pub(super) struct Listener { + listening: OwnedHandle, + name: Vec, + address: OsString, + descriptor: Descriptor, +} + +impl Listener { + /// Creates the first instance of a pipe with a fresh random name. + pub(super) fn bind() -> io::Result { + let descriptor = Descriptor::owner_only(&CurrentUser::query()?)?; + let mut last = io::Error::from(io::ErrorKind::AlreadyExists); + for _ in 0..CREATE_ATTEMPTS { + let address = OsString::from(format!("{PREFIX}lithe-askpass-{}", random_hex::<8>()?)); + let name = wide(&address); + match instance(&name, &descriptor, true) { + Ok(listening) => { + return Ok(Self { + listening, + name, + address, + descriptor, + }) + } + // The first-instance flag reports a name in use as access denied. + Err(error) if error.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) => { + last = error + } + Err(error) => return Err(error), + } + } + Err(last) + } + + /// The pipe name the helper connects to. + pub(super) fn address(&self) -> &OsStr { + &self.address + } + + /// Takes the connected instance, if any, without blocking. + pub(super) fn accept(&mut self) -> io::Result> { + // SAFETY: the handle is a live pipe instance; nonblocking mode never + // uses the overlapped structure. + if unsafe { ConnectNamedPipe(self.listening.as_raw_handle(), null_mut()) } != 0 { + // Nonzero only reports that the instance is ready for a client. + return Ok(Accept::Empty); + } + let error = io::Error::last_os_error(); + match error.raw_os_error().map(|code| code as u32) { + Some(ERROR_PIPE_LISTENING) => Ok(Accept::Empty), + Some(ERROR_PIPE_CONNECTED) => { + // Create the replacement first so the name keeps listening. + let next = instance(&self.name, &self.descriptor, false)?; + let connected = std::mem::replace(&mut self.listening, next); + Ok(Accept::Peer(Stream(File::from(connected)))) + } + Some(ERROR_NO_DATA) => { + // A client connected and left before it was accepted; this + // instance cannot serve another one. + self.listening = instance(&self.name, &self.descriptor, false)?; + Ok(Accept::Empty) + } + _ => Err(error), + } + } +} + +/// The server end of one accepted connection, in nonblocking mode. +pub(super) struct Stream(File); + +impl Read for Stream { + /// Reads only what is already in the pipe, so the call never waits. + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + let mut available = 0u32; + // SAFETY: only the count out-pointer is supplied and it references a + // live local. + let peeked = unsafe { + PeekNamedPipe( + self.0.as_raw_handle(), + null_mut(), + 0, + null_mut(), + &mut available, + null_mut(), + ) + }; + if peeked == 0 { + let error = io::Error::last_os_error(); + return match error.raw_os_error().map(|code| code as u32) { + Some(ERROR_BROKEN_PIPE | ERROR_PIPE_NOT_CONNECTED | ERROR_NO_DATA) => Ok(0), + _ => Err(error), + }; + } + if available == 0 { + return Err(io::ErrorKind::WouldBlock.into()); + } + let limit = buffer.len().min(available as usize); + self.0.read(&mut buffer[..limit]) + } +} + +impl Write for Stream { + /// Writes what fits in the pipe buffer; a full buffer reports + /// `WouldBlock` like a nonblocking socket. + fn write(&mut self, buffer: &[u8]) -> io::Result { + match self.0.write(buffer)? { + 0 if !buffer.is_empty() => Err(io::ErrorKind::WouldBlock.into()), + written => Ok(written), + } + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +/// Opens the helper's end of the pipe and checks that the current user owns +/// it before any byte is sent. Reads then wait until the session answers or +/// closes the pipe. +pub(super) fn connect(address: &OsStr) -> io::Result { + let local = address + .to_str() + .and_then(|text| text.strip_prefix(PREFIX)) + .is_some_and(|name| !name.is_empty() && !name.contains(['\\', '/'])); + if !local { + return Err(io::ErrorKind::InvalidInput.into()); + } + let name = wide(address); + let deadline = Instant::now() + CONNECT_TIMEOUT; + let pipe = loop { + let opened = OpenOptions::new() + .access_mode(GENERIC_READ | GENERIC_WRITE | READ_CONTROL) + // The server may identify this process but never act as it. + .security_qos_flags(SECURITY_IDENTIFICATION) + .open(address); + match opened { + Ok(pipe) => break pipe, + Err(error) if error.raw_os_error() == Some(ERROR_PIPE_BUSY as i32) => { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return Err(io::ErrorKind::TimedOut.into()); + } + let wait = u32::try_from(remaining.as_millis()) + .unwrap_or(u32::MAX) + .max(1); + // SAFETY: the name is NUL-terminated. The next open reports + // whatever made the wait fail. + unsafe { WaitNamedPipeW(name.as_ptr(), wait) }; + } + Err(error) => return Err(error), + } + }; + verify_owner(&pipe)?; + Ok(pipe) +} + +fn verify_owner(pipe: &File) -> io::Result<()> { + let user = CurrentUser::query()?; + let mut owner: PSID = null_mut(); + let mut descriptor: PSECURITY_DESCRIPTOR = null_mut(); + // SAFETY: the handle is live and every out-pointer references a live + // local; `owner` points into `descriptor`. + let status = unsafe { + GetSecurityInfo( + pipe.as_raw_handle(), + SE_KERNEL_OBJECT, + OWNER_SECURITY_INFORMATION, + &mut owner, + null_mut(), + null_mut(), + null_mut(), + &mut descriptor, + ) + }; + if status != ERROR_SUCCESS { + return Err(io::Error::from_raw_os_error(status as i32)); + } + let descriptor = Local(descriptor); + // SAFETY: both SIDs stay valid while their buffers live. + let same = !owner.is_null() && unsafe { EqualSid(owner, user.sid()) } != 0; + drop(descriptor); + if same { + Ok(()) + } else { + Err(io::ErrorKind::PermissionDenied.into()) + } +} + +fn instance(name: &[u16], descriptor: &Descriptor, first: bool) -> io::Result { + let attributes = SECURITY_ATTRIBUTES { + nLength: std::mem::size_of::() as u32, + lpSecurityDescriptor: descriptor.0 .0, + bInheritHandle: 0, + }; + let open_mode = if first { + PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE + } else { + PIPE_ACCESS_DUPLEX + }; + // SAFETY: the name is NUL-terminated and the attributes and descriptor + // outlive the call. + let handle = unsafe { + CreateNamedPipeW( + name.as_ptr(), + open_mode, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_NOWAIT | PIPE_REJECT_REMOTE_CLIENTS, + MAX_INSTANCES, + BUFFER_SIZE, + BUFFER_SIZE, + 0, + &attributes, + ) + }; + if handle == INVALID_HANDLE_VALUE { + return Err(io::Error::last_os_error()); + } + // SAFETY: CreateNamedPipeW returned a new handle that nothing else owns. + Ok(unsafe { OwnedHandle::from_raw_handle(handle) }) +} + +fn wide(value: &OsStr) -> Vec { + value.encode_wide().chain([0]).collect() +} + +/// The process token's user, kept in the buffer that `GetTokenInformation` +/// filled, because the SID points into it. +struct CurrentUser { + buffer: Vec, +} + +impl CurrentUser { + fn query() -> io::Result { + let mut token: HANDLE = null_mut(); + // SAFETY: the pseudo handle needs no closing and the out-pointer + // references a live local. + if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: OpenProcessToken returned a new handle that nothing else owns. + let token = unsafe { OwnedHandle::from_raw_handle(token) }; + let mut length = 0u32; + // SAFETY: a null buffer of size zero only asks for the needed length; + // the expected insufficient-buffer failure leaves `length` set. + unsafe { + GetTokenInformation(token.as_raw_handle(), TokenUser, null_mut(), 0, &mut length) + }; + if length == 0 { + return Err(io::Error::last_os_error()); + } + let word = std::mem::size_of::(); + let mut buffer = vec![0usize; (length as usize).div_ceil(word)]; + // SAFETY: the buffer is pointer-aligned and at least `length` bytes. + let filled = unsafe { + GetTokenInformation( + token.as_raw_handle(), + TokenUser, + buffer.as_mut_ptr().cast(), + (buffer.len() * word) as u32, + &mut length, + ) + }; + if filled == 0 { + return Err(io::Error::last_os_error()); + } + Ok(Self { buffer }) + } + + fn sid(&self) -> PSID { + // SAFETY: the buffer holds the TOKEN_USER that query() read. + unsafe { (*self.buffer.as_ptr().cast::()).User.Sid } + } + + fn sid_string(&self) -> io::Result { + let mut text = null_mut(); + // SAFETY: the SID is valid while `self` lives and the out-pointer + // references a live local. + if unsafe { ConvertSidToStringSidW(self.sid(), &mut text) } == 0 { + return Err(io::Error::last_os_error()); + } + let allocation = Local(text.cast()); + // SAFETY: the system returned a NUL-terminated string. + let length = (0..) + .take_while(|&index| unsafe { *text.add(index) } != 0) + .count(); + // SAFETY: `length` characters precede the terminator. + let value = String::from_utf16(unsafe { std::slice::from_raw_parts(text, length) }) + .map_err(io::Error::other); + drop(allocation); + value + } +} + +/// A security descriptor whose owner is the current user and whose protected +/// DACL grants that user full access and nobody else any. +struct Descriptor(Local); + +impl Descriptor { + fn owner_only(user: &CurrentUser) -> io::Result { + let sid = user.sid_string()?; + let sddl: Vec = format!("O:{sid}D:P(A;;GA;;;{sid})") + .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. + let converted = unsafe { + ConvertStringSecurityDescriptorToSecurityDescriptorW( + sddl.as_ptr(), + SDDL_REVISION_1, + &mut descriptor, + null_mut(), + ) + }; + if converted == 0 { + return Err(io::Error::last_os_error()); + } + Ok(Self(Local(descriptor))) + } +} + +/// Memory the system allocated with `LocalAlloc`, freed once when dropped. +struct Local(*mut core::ffi::c_void); + +impl Drop for Local { + fn drop(&mut self) { + // SAFETY: the pointer came from a system allocation owned only here. + unsafe { LocalFree(self.0) }; + } +} diff --git a/rust/crates/git-host/src/failure_log.rs b/rust/crates/git-host/src/failure_log.rs index 9b583642..8fefd274 100644 --- a/rust/crates/git-host/src/failure_log.rs +++ b/rust/crates/git-host/src/failure_log.rs @@ -7,6 +7,7 @@ use std::sync::OnceLock; /// Complete catalog surface emitted by this adapter. pub const EVENTS: &[&str] = &[ "vcs.authentication.response_failed", + "vcs.authentication.request_rejected", "vcs.host.cleanup_failed", ]; diff --git a/rust/crates/git-host/tests/authentication.rs b/rust/crates/git-host/tests/authentication.rs index fbab62a7..546b8244 100644 --- a/rust/crates/git-host/tests/authentication.rs +++ b/rust/crates/git-host/tests/authentication.rs @@ -1,90 +1,6 @@ -//! Loopback transport tests own their sockets and require no Git, GUI, or network service. -use lithe_git_host::authentication::{respond, Confirmation, Session}; -use std::io::{Read, Write}; -use std::net::TcpStream; -use std::process::Command; -use std::time::{Duration, Instant}; - -#[test] -fn prompt_response_is_single_use_and_cancellation_drops_pending_challenges() { - let mut session = Session::new().unwrap(); - let mut command = Command::new("unused-fixture"); - session.configure(&mut command).unwrap(); - let env = command - .get_envs() - .map(|(key, value)| { - ( - key.to_string_lossy().into_owned(), - value.unwrap().to_string_lossy().into_owned(), - ) - }) - .collect::>(); - assert_eq!( - env["GIT_ASKPASS"], - std::env::current_exe().unwrap().to_string_lossy() - ); - assert_eq!(env["SSH_ASKPASS"], env["GIT_ASKPASS"]); - assert_eq!(env["LITHE_GIT_ASKPASS_MODE"], "1"); - let mut untrusted = TcpStream::connect(&env["LITHE_GIT_ASKPASS_ADDRESS"]).unwrap(); - untrusted - .set_write_timeout(Some(Duration::from_secs(1))) - .unwrap(); - writeln!( - untrusted, - "{}", - serde_json::json!({"token": "wrong-fixture-token", "prompt": "untrusted"}) - ) - .unwrap(); - untrusted.set_nonblocking(true).unwrap(); - let mut peer = TcpStream::connect(&env["LITHE_GIT_ASKPASS_ADDRESS"]).unwrap(); - peer.set_read_timeout(Some(Duration::from_secs(1))).unwrap(); - peer.set_write_timeout(Some(Duration::from_secs(1))) - .unwrap(); - writeln!(peer, "{}", serde_json::json!({"token": env["LITHE_GIT_ASKPASS_TOKEN"], "prompt": "Password for fixture:"})).unwrap(); - let deadline = Instant::now() + Duration::from_secs(3); - let mut challenge = None; - let mut rejection_observed = false; - // The two TCP frames may arrive in either order or in fragments. Continue - // pumping the owned session until both the prompt and rejection complete; - // blocking on the rejected peer early would stop the only transport driver. - while challenge.is_none() || !rejection_observed { - for received in session.poll().unwrap() { - assert!(challenge.is_none(), "Unexpected additional AskPass prompt"); - challenge = Some(received); - } - if !rejection_observed { - match untrusted.read(&mut [0u8; 1]) { - Ok(0) => rejection_observed = true, - Ok(_) => panic!("Untrusted peer received a response"), - Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {} - Err(error) => panic!("Could not observe untrusted peer rejection: {error}"), - } - } - assert!( - Instant::now() < deadline, - "AskPass prompt and peer rejection did not complete before deadline" - ); - std::thread::yield_now(); - } - let challenge = challenge.unwrap(); - assert!(challenge.secret); - assert!(!respond( - &challenge.request_id, - Some("invalid\nresponse".into()) - )); - assert!(!respond(&challenge.request_id, Some("x".repeat(8193)))); - assert!(respond( - &challenge.request_id, - Some("fixture-answer".into()) - )); - assert!(!respond(&challenge.request_id, Some("replayed".into()))); - session.poll().unwrap(); - let mut answer = String::new(); - peer.read_to_string(&mut answer).unwrap(); - assert_eq!(answer, "fixture-answer\n"); - drop(session); - assert!(!respond(&challenge.request_id, None)); -} +//! Public AskPass decision API. Channel behaviour is covered by the unit tests +//! next to the transport and by the platform tests that run the real helper. +use lithe_git_host::authentication::{respond, Confirmation}; #[test] fn retry_decisions_and_stale_responses_are_bounded() { @@ -92,8 +8,17 @@ fn retry_decisions_and_stale_responses_are_bounded() { assert!(respond(&confirmation.request_id, Some("retry".into()))); assert!(confirmation.wait(|| false).unwrap()); let confirmation = Confirmation::new().unwrap(); + assert!(respond(&confirmation.request_id, Some("skip".into()))); + assert!(!confirmation.wait(|| false).unwrap()); + let confirmation = Confirmation::new().unwrap(); let id = confirmation.request_id.clone(); assert!(!confirmation.wait(|| true).unwrap()); drop(confirmation); assert!(!respond(&id, Some("retry".into()))); } + +#[test] +fn unknown_requests_are_refused() { + assert!(!respond("not-a-registered-request", None)); + assert!(!respond("not-a-registered-request", Some("answer".into()))); +} diff --git a/rust/crates/platform-tests/Cargo.toml b/rust/crates/platform-tests/Cargo.toml index eff76995..c9ce4255 100644 --- a/rust/crates/platform-tests/Cargo.toml +++ b/rust/crates/platform-tests/Cargo.toml @@ -11,10 +11,16 @@ description = "Tests that need a real Windows or Unix host, and the fixture prog [package.metadata.lithe-ci] hosts = ["macos", "windows"] -[dev-dependencies] +[dependencies] +# The fixture program runs the real AskPass helper. lithe-git-host = { path = "../git-host" } + +[dev-dependencies] lithe-lsp-transport = { path = "../lsp-transport" } lithe-platform = { path = "../platform" } [target.'cfg(unix)'.dev-dependencies] libc = "0.2" + +[target.'cfg(windows)'.dev-dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_SystemServices", "Win32_System_Threading"] } diff --git a/rust/crates/platform-tests/src/bin/lithe-platform-fixture.rs b/rust/crates/platform-tests/src/bin/lithe-platform-fixture.rs index c52d1485..d78c23fd 100644 --- a/rust/crates/platform-tests/src/bin/lithe-platform-fixture.rs +++ b/rust/crates/platform-tests/src/bin/lithe-platform-fixture.rs @@ -36,6 +36,7 @@ fn main() -> ExitCode { Ok(()) } Mode::EchoArguments => echo(arguments), + Mode::AskPass => askpass(arguments), }; match result { Ok(()) => ExitCode::SUCCESS, @@ -92,3 +93,11 @@ fn echo(arguments: impl Iterator) -> io::Result<()> { .collect(); std::fs::write(file, lines.join("\n")) } + +fn askpass(mut arguments: impl Iterator) -> ! { + let prompt = arguments + .next() + .map(|prompt| prompt.to_string_lossy().into_owned()) + .unwrap_or_default(); + std::process::exit(lithe_git_host::authentication::helper_main(&prompt)); +} diff --git a/rust/crates/platform-tests/src/lib.rs b/rust/crates/platform-tests/src/lib.rs index e91ad613..0447be99 100644 --- a/rust/crates/platform-tests/src/lib.rs +++ b/rust/crates/platform-tests/src/lib.rs @@ -33,16 +33,20 @@ pub enum Mode { /// Writes its remaining arguments, one per line, to the file named by /// [`ECHO_FILE_ENV`], exactly as the platform passed them. EchoArguments, + /// Runs the Git AskPass helper for the prompt in its next argument, as + /// Git or SSH would, and exits with the helper's exit code. + AskPass, } impl Mode { /// Every mode, in declaration order. - pub const ALL: [Self; 5] = [ + pub const ALL: [Self; 6] = [ Self::Hold, Self::Parent, Self::Failure, Self::Stream, Self::EchoArguments, + Self::AskPass, ]; /// The argument that selects this mode. @@ -53,6 +57,7 @@ impl Mode { Self::Failure => "failure", Self::Stream => "stream", Self::EchoArguments => "echo-arguments", + Self::AskPass => "askpass", } } diff --git a/rust/crates/platform-tests/tests/platform/askpass.rs b/rust/crates/platform-tests/tests/platform/askpass.rs new file mode 100644 index 00000000..3775a8bb --- /dev/null +++ b/rust/crates/platform-tests/tests/platform/askpass.rs @@ -0,0 +1,308 @@ +//! The Git AskPass helper as Git and SSH start it: a separate process that +//! finds its session through the environment the session put on the command, +//! and prints the answer on its standard output. + +use crate::support::{fixture, DEADLINE}; +use lithe_git_host::authentication::{respond, Challenge, Session}; +use lithe_platform_tests::Mode; +use std::ffi::OsString; +use std::io::Read; +use std::process::{Child, Command, Stdio}; +use std::time::Instant; + +/// The prompt Git shows for an HTTPS password. +const PROMPT: &str = "Password for 'https://example.invalid': "; +const CREDENTIAL: &str = "test-only-private-credential"; +/// Variables that `Session::configure` sets for the helper. +const ADDRESS_VARIABLE: &str = "LITHE_GIT_ASKPASS_ADDRESS"; +const TOKEN_VARIABLE: &str = "LITHE_GIT_ASKPASS_TOKEN"; + +/// The value `session` gives `variable` in a configured command. +fn configured(session: &Session, variable: &str) -> OsString { + let mut command = fixture(Mode::AskPass); + session.configure(&mut command).expect("configure"); + command + .get_envs() + .find(|(name, _)| *name == variable) + .and_then(|(_, value)| value) + .expect("configured variable") + .to_owned() +} + +/// A running helper process, killed and reaped when dropped, so a failed +/// assertion leaves no process behind. +struct Helper(Child); + +impl Helper { + /// Starts the helper with the environment `session` gives Git, changed + /// by `adjust`. + fn start(session: &Session, adjust: impl FnOnce(&mut Command)) -> Self { + let mut command = fixture(Mode::AskPass); + command + .arg(PROMPT) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + session.configure(&mut command).expect("configure"); + adjust(&mut command); + Self(command.spawn().expect("start the helper")) + } + + /// Polls `session` until the helper's prompt arrives. + fn challenge(&mut self, session: &mut Session) -> Challenge { + let deadline = Instant::now() + DEADLINE; + loop { + let mut ready = session.poll().expect("poll"); + if let Some(challenge) = ready.pop() { + assert!(ready.is_empty(), "unexpected second prompt"); + return challenge; + } + if let Some(status) = self.0.try_wait().expect("helper status") { + panic!("the helper ended with {status} before it prompted"); + } + assert!(Instant::now() < deadline, "no prompt before the deadline"); + std::thread::yield_now(); + } + } + + /// Runs `poll` until the helper exits, then returns its exit code and + /// everything it printed. + fn exit(&mut self, mut poll: impl FnMut()) -> (Option, Vec) { + let deadline = Instant::now() + DEADLINE; + let status = loop { + if let Some(status) = self.0.try_wait().expect("helper status") { + break status; + } + assert!( + Instant::now() < deadline, + "the helper did not exit before the deadline" + ); + poll(); + std::thread::yield_now(); + }; + let mut output = Vec::new(); + self.0 + .stdout + .take() + .expect("helper output") + .read_to_end(&mut output) + .expect("read helper output"); + (status.code(), output) + } +} + +impl Drop for Helper { + fn drop(&mut self) { + // Both fail harmlessly once the helper has exited and been reaped. + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +#[test] +fn answer_reaches_git_through_the_helper_process() { + let mut session = Session::new().expect("session"); + let mut helper = Helper::start(&session, |_| {}); + + let challenge = helper.challenge(&mut session); + assert_eq!(challenge.prompt, PROMPT); + assert!(challenge.secret); + assert_eq!(challenge.attempt, 1); + assert!(respond(&challenge.request_id, Some(CREDENTIAL.into()))); + + let (code, output) = helper.exit(|| { + session.poll().expect("poll"); + }); + assert_eq!(code, Some(0)); + assert_eq!(output, format!("{CREDENTIAL}\n").into_bytes()); +} + +#[test] +fn cancelled_prompt_fails_the_helper_process() { + let mut session = Session::new().expect("session"); + let mut helper = Helper::start(&session, |_| {}); + + let challenge = helper.challenge(&mut session); + assert!(respond(&challenge.request_id, None)); + + let (code, output) = helper.exit(|| { + session.poll().expect("poll"); + }); + assert_eq!(code, Some(1)); + assert!(output.is_empty()); +} + +#[test] +fn helper_with_another_token_never_reaches_the_user() { + let mut session = Session::new().expect("session"); + let mut helper = Helper::start(&session, |command| { + command.env(TOKEN_VARIABLE, "0".repeat(64)); + }); + + let (code, output) = helper.exit(|| { + assert!( + session.poll().expect("poll").is_empty(), + "a request with another token reached the user" + ); + }); + assert_eq!(code, Some(1)); + assert!(output.is_empty()); +} + +#[test] +fn helper_fails_once_its_session_is_gone() { + let mut session = Session::new().expect("session"); + let mut helper = Helper::start(&session, |_| {}); + let challenge = helper.challenge(&mut session); + + drop(session); + + let (code, output) = helper.exit(|| {}); + assert_eq!(code, Some(1)); + assert!(output.is_empty()); + assert!(!respond(&challenge.request_id, Some(CREDENTIAL.into()))); +} + +#[test] +fn helper_without_a_live_session_fails() { + let stale = configured(&Session::new().expect("session"), ADDRESS_VARIABLE); + let mut session = Session::new().expect("session"); + // No address at all, then the address of a session that has closed. + for (case, address) in [("no address", None), ("closed session", Some(stale))] { + let mut helper = Helper::start(&session, |command| match address { + Some(address) => { + command.env(ADDRESS_VARIABLE, address); + } + None => { + command.env_remove(ADDRESS_VARIABLE); + } + }); + let (code, output) = helper.exit(|| { + assert!(session.poll().expect("poll").is_empty(), "{case}: prompt"); + }); + assert_eq!(code, Some(1), "{case}"); + assert!(output.is_empty(), "{case}"); + } +} + +#[cfg(windows)] +mod windows { + //! What the kernel enforces on the session's named pipe. + + use super::{configured, ADDRESS_VARIABLE}; + use lithe_git_host::authentication::Session; + use std::ffi::c_void; + use std::fs::OpenOptions; + use std::os::windows::fs::OpenOptionsExt; + use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; + use std::ptr::{addr_of_mut, null_mut}; + use windows_sys::Win32::Foundation::{LocalFree, ERROR_SUCCESS, HANDLE}; + use windows_sys::Win32::Security::Authorization::{GetSecurityInfo, SE_KERNEL_OBJECT}; + use windows_sys::Win32::Security::{ + AclSizeInformation, EqualSid, GetAce, GetAclInformation, GetSecurityDescriptorControl, + GetTokenInformation, TokenUser, ACCESS_ALLOWED_ACE, ACL, ACL_SIZE_INFORMATION, + DACL_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID, + SE_DACL_PROTECTED, TOKEN_QUERY, TOKEN_USER, + }; + use windows_sys::Win32::Storage::FileSystem::READ_CONTROL; + use windows_sys::Win32::System::SystemServices::ACCESS_ALLOWED_ACE_TYPE; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + + /// This process's `TOKEN_USER`, in a pointer-aligned buffer the SID + /// points into. + fn current_user() -> Vec { + let mut token: HANDLE = null_mut(); + // SAFETY: the pseudo handle needs no closing and the out-pointer + // references a live local. + assert_ne!( + unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) }, + 0 + ); + // SAFETY: OpenProcessToken returned a new handle that nothing else owns. + let token = unsafe { OwnedHandle::from_raw_handle(token) }; + let mut buffer = vec![0usize; 64]; + let mut length = 0u32; + // SAFETY: the buffer is pointer-aligned and as long as the size passed. + let filled = unsafe { + GetTokenInformation( + token.as_raw_handle(), + TokenUser, + buffer.as_mut_ptr().cast(), + (buffer.len() * size_of::()) as u32, + &mut length, + ) + }; + assert_ne!(filled, 0, "token user"); + buffer + } + + #[test] + fn pipe_belongs_to_the_current_user_and_admits_nobody_else() { + let session = Session::new().expect("session"); + let pipe = OpenOptions::new() + .access_mode(READ_CONTROL) + .open(configured(&session, ADDRESS_VARIABLE)) + .expect("open the pipe"); + let user = current_user(); + // SAFETY: the buffer holds the TOKEN_USER that current_user() read. + let user_sid = unsafe { (*user.as_ptr().cast::()).User.Sid }; + + let mut owner: PSID = null_mut(); + let mut dacl: *mut ACL = null_mut(); + let mut descriptor: PSECURITY_DESCRIPTOR = null_mut(); + // SAFETY: the handle is live and every out-pointer references a live + // local; `owner` and `dacl` point into `descriptor`. + let status = unsafe { + GetSecurityInfo( + pipe.as_raw_handle(), + SE_KERNEL_OBJECT, + OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, + &mut owner, + null_mut(), + &mut dacl, + null_mut(), + &mut descriptor, + ) + }; + assert_eq!(status, ERROR_SUCCESS); + let mut control = 0u16; + let mut revision = 0u32; + let mut size = ACL_SIZE_INFORMATION { + AceCount: 0, + AclBytesInUse: 0, + AclBytesFree: 0, + }; + let mut ace: *mut c_void = null_mut(); + // SAFETY: the descriptor and everything pointing into it stay valid + // until LocalFree below; every out-pointer references a live local. + unsafe { + assert_ne!(EqualSid(owner, user_sid), 0, "the owner is the user"); + assert_ne!( + GetSecurityDescriptorControl(descriptor, &mut control, &mut revision), + 0 + ); + assert!(!dacl.is_null(), "a null DACL admits everyone"); + assert_ne!( + GetAclInformation( + dacl, + addr_of_mut!(size).cast(), + size_of::() as u32, + AclSizeInformation, + ), + 0 + ); + assert_eq!(size.AceCount, 1, "one entry, for the user"); + assert_ne!(GetAce(dacl, 0, &mut ace), 0); + let ace = ace.cast::(); + assert_eq!(u32::from((*ace).Header.AceType), ACCESS_ALLOWED_ACE_TYPE); + let ace_sid: PSID = addr_of_mut!((*ace).SidStart).cast(); + assert_ne!(EqualSid(ace_sid, user_sid), 0, "the entry is the user's"); + LocalFree(descriptor); + } + assert_ne!( + control & SE_DACL_PROTECTED, + 0, + "inherited entries could widen the DACL" + ); + } +} diff --git a/rust/crates/platform-tests/tests/platform/main.rs b/rust/crates/platform-tests/tests/platform/main.rs index ef052e22..3857cf5e 100644 --- a/rust/crates/platform-tests/tests/platform/main.rs +++ b/rust/crates/platform-tests/tests/platform/main.rs @@ -3,6 +3,7 @@ //! Every module shares one test binary, so the helpers in `support` and the //! dependencies are built once. +mod askpass; mod git_executable; mod lsp_process; mod permissions; diff --git a/rust/logging/events/vcs.json b/rust/logging/events/vcs.json index ad3e6c91..4e5ecbb2 100644 --- a/rust/logging/events/vcs.json +++ b/rust/logging/events/vcs.json @@ -370,6 +370,21 @@ "rate": 60, "owner": "lithe-core" }, + { + "id": "vcs.authentication.request_rejected", + "channel": "vcs/git", + "level": "warn", + "message": "Git authentication request rejected", + "fields": { + "reason": { + "type": "token", + "required": true, + "description": "Why the AskPass channel refused a request: peer-identity (another account or unverifiable peer), token, malformed, oversized, timeout (no complete request before the deadline), prompt-limit or attempt-limit; never the prompt, token or peer input" + } + }, + "rate": 60, + "owner": "lithe-core" + }, { "id": "vcs.host.cleanup_failed", "channel": "vcs/git",