diff --git a/Cargo.toml b/Cargo.toml index 5a353ac..c6ff426 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -240,6 +240,15 @@ windows-sys = { version = "0.61", features = [ # Win32_System_Threading (already on). Each was confirmed present in the # cached 0.61.2 manifest before being written here. "Win32_Security_Authorization", + # permissions::managed — the ProgramData folder from the OS + # (SHGetKnownFolderPath, FOLDERID_ProgramData), never from `%ProgramData%`, + # which the person the managed file constrains can point anywhere. + # mcp_oauth::open_browser — ShellExecuteW, so a login URL is never parsed + # by cmd. CoTaskMemFree and CoInitializeEx are in Win32_System_Com. NO NEW + # PACKAGE: features of windows-sys 0.61.2 only, each item confirmed in the + # cached source before being written here. + "Win32_UI_Shell", + "Win32_System_Com", ] } # agent::process_tree on Linux and macOS: `killpg` for the process group the diff --git a/README.md b/README.md index 53d516a..460d536 100644 --- a/README.md +++ b/README.md @@ -1140,7 +1140,8 @@ careful, never less. `/permissions` lists the rules in force. **Managed settings.** An administrator can put a file at `/etc/incode/managed.toml` (macOS `/Library/Application Support/incode/managed.toml`, -Windows `%ProgramData%\incode\managed.toml`): +Windows `C:\ProgramData\incode\managed.toml` — the ProgramData folder Windows +records, whatever a user sets `%ProgramData%` to): ```toml [permissions] diff --git a/TESTING.md b/TESTING.md index 5daf542..101c329 100644 --- a/TESTING.md +++ b/TESTING.md @@ -74,6 +74,7 @@ with `cargo test --lib -- --ignored --nocapture`. | `desktop::thread` (moves the cursor) | A desktop session you are not using | Moves the real mouse and puts it back | | `desktop::capture::tests::live::report_real_capture` | A display | Captures the real screen and prints the coordinate mapping | | `desktop::win32`, `desktop::uia` reports | Windows | Print the display table and the focused window's accessibility tree | +| `mcp_oauth::tests::open_browser_runs_nothing_from_the_address` | Windows with a default browser | Opens a browser tab on a loopback listener and checks the address reached it, while a `\|mkdir,…` in the address ran nothing | | `toolbox::code_edits_tests::live_an_unseen_change_is_refused_by_the_engine` | `INCODE_LIVE_MEMORY_URL` (a throwaway Incord Memory engine) and `INCODE_LIVE_REPO` | Checks the engine refuses an edit to code it has not seen | ## By hand diff --git a/src/ansi_c.rs b/src/ansi_c.rs new file mode 100644 index 0000000..8482840 --- /dev/null +++ b/src/ansi_c.rs @@ -0,0 +1,204 @@ +//! Bash's ANSI-C quoting, `$'…'`, read the way bash reads it. +//! +//! Inside `$'…'` a backslash escapes the next character, a quote included, so +//! `$'\''` is ONE quote character and whatever follows the closing quote is +//! shell syntax again. Read as a plain `'…'`, where a backslash is just a +//! character, the same text looks like a quote that runs on: a `;` and the +//! command after it are taken for one quoted argument. +//! +//! But a POSIX `sh` such as dash — what `sh -c` runs on Debian and Ubuntu — +//! DOES read `$'` as a `$` and a plain quote. So each reader of a command line +//! that decides what runs reads a line with `$'` both ways, and a command +//! either reading finds counts. +//! +//! Used by the two such readers: +//! - `permissions::rules` — `split_into`, `substitution`, `words` and +//! `unquote`: which commands a line holds, for the allow / ask / deny rules. +//! - `guards::shell` — `lex` and `Lexer::substitution`: which files a command +//! writes, for the protected-path guard. +//! +//! `$"…"` (a double-quoted string translated by the locale) needs nothing +//! here: past its `$` it is read exactly as `"…"`. + +/// The text of the `$'…'` whose body starts at `start` (just past `$'`), +/// decoded as bash decodes it (`man bash`, QUOTING), and the index just past +/// its closing quote. Unterminated: the rest of `chars`, decoded. +/// +/// The end is found FIRST, as bash's lexer finds it — a backslash pairs with +/// the one character after it, whatever escape that makes — and only the body +/// is decoded, so no escape (`\c'`, say) can move the closing quote. +#[must_use] +pub fn quoted(chars: &[char], start: usize) -> (String, usize) { + let start = start.min(chars.len()); + let mut close = start; + while close < chars.len() && chars[close] != '\'' { + close += if chars[close] == '\\' { 2 } else { 1 }; + } + let close = close.min(chars.len()); + (decode(&chars[start..close]), (close + 1).min(chars.len())) +} + +/// A `$'…'` body, decoded. A NUL ends the text, as in bash: `$'rm\0x'` is +/// `rm`. +fn decode(body: &[char]) -> String { + let mut out = String::new(); + let mut i = 0; + while i < body.len() { + let c = body[i]; + i += 1; + if c != '\\' { + out.push(c); + continue; + } + let Some(&escaped) = body.get(i) else { + out.push('\\'); + break; + }; + i += 1; + let code = match escaped { + 'a' => 0x07, + 'b' => 0x08, + 'e' | 'E' => 0x1b, + 'f' => 0x0c, + 'n' => u32::from('\n'), + 'r' => u32::from('\r'), + 't' => u32::from('\t'), + 'v' => 0x0b, + '\\' | '\'' | '"' | '?' => u32::from(escaped), + // `\nnn`: one to three octal digits, the first already read. + '0'..='7' => { + let (rest, used) = digits(body, i, 8, 2); + i += used; + let first = escaped.to_digit(8).unwrap_or(0); + (first * 8u32.pow(used as u32) + rest) & 0xff + } + 'x' | 'u' | 'U' => { + let most = match escaped { + 'x' => 2, + 'u' => 4, + _ => 8, + }; + let (value, used) = digits(body, i, 16, most); + if used == 0 { + // No digits: bash keeps the escape as written. + out.push('\\'); + out.push(escaped); + continue; + } + i += used; + value + } + // `\cx`: the control character of the next character, whatever + // it is (`\c\` is 0x1c). + 'c' => match body.get(i) { + Some(&x) => { + i += 1; + u32::from(x) & 0x1f + } + None => { + out.push_str("\\c"); + continue; + } + }, + other => { + out.push('\\'); + out.push(other); + continue; + } + }; + if code == 0 { + break; + } + out.push(char::from_u32(code).unwrap_or(char::REPLACEMENT_CHARACTER)); + } + out +} + +/// Up to `most` digits in `radix` from `start`: their value and how many. +fn digits(chars: &[char], start: usize, radix: u32, most: usize) -> (u32, usize) { + let mut value = 0u32; + let mut used = 0; + while used < most { + let Some(digit) = chars.get(start + used).and_then(|c| c.to_digit(radix)) else { + break; + }; + value = value.saturating_mul(radix).saturating_add(digit); + used += 1; + } + (value, used) +} + +#[cfg(test)] +mod tests { + use super::quoted; + + fn decode(body: &str) -> (String, usize) { + let chars: Vec = body.chars().collect(); + quoted(&chars, 0) + } + + #[test] + fn an_escaped_quote_does_not_close_the_string() { + assert_eq!(decode(r"\'' ; rm"), ("'".to_string(), 3)); + assert_eq!(decode(r"it\'s' tail"), ("it's".to_string(), 6)); + } + + /// **NO ESCAPE MOVES THE CLOSING QUOTE.** bash finds the end first — a + /// backslash pairs with one character — and decodes after. `\c` takes + /// the next character as its operand, but that is decoding: `$'\c'` + /// still ends at its quote (checked with bash: `\c`, then the command + /// after it runs), and `$'\c\''` is 0x1c and `'`. + #[test] + fn the_end_is_found_before_any_escape_is_decoded() { + assert_eq!(decode(r"\c' ; rm"), (r"\c".to_string(), 3)); + assert_eq!(decode(r"\c\'' ; rm"), ("\u{1c}'".to_string(), 5)); + assert_eq!(decode(r"\x' ; rm").1, 3); + assert_eq!(decode(r"\1' ; rm").1, 3); + } + + /// A NUL ends the text, whichever escape spells it, as in bash + /// (`> $'a.txt\0junk'` writes `a.txt`); the end is still the quote. + #[test] + fn a_nul_ends_the_text_but_not_the_string() { + for body in [ + r"rm\0x' tail", + r"rm\x00x' tail", + r"rm\000x' tail", + r"rm\c@x' tail", + concat!("rm", "\\", "u0000x' tail"), + ] { + assert_eq!( + decode(body), + ("rm".to_string(), body.find('\'').unwrap() + 1), + "{body}" + ); + } + } + + #[test] + fn escapes_decode_as_bash_does() { + for (body, meant) in [ + (r"a\tb'", "a\tb"), + (r"\x72m'", "rm"), + (r"\x7'", "\u{7}"), + (r"\162m'", "rm"), + (r"\0'", ""), + (concat!("\\", "u0072m'"), "rm"), + (r"\U00000072m'", "rm"), + (r"\cA'", "\u{1}"), + (r"\\'", "\\"), + (r#"\"\?'"#, "\"?"), + (r"\e\E'", "\u{1b}\u{1b}"), + (r"\z'", "\\z"), + (r"\xg'", "\\xg"), + ] { + assert_eq!(decode(body).0, meant, "`$'{body}`"); + } + } + + #[test] + fn an_unterminated_string_runs_to_the_end() { + assert_eq!(decode(r"abc\"), ("abc\\".to_string(), 4)); + assert_eq!(decode("abc"), ("abc".to_string(), 3)); + } +} diff --git a/src/guards/shell.rs b/src/guards/shell.rs index 2943747..de32b68 100644 --- a/src/guards/shell.rs +++ b/src/guards/shell.rs @@ -139,13 +139,29 @@ enum Program { /// not be read from the text, so a command wrapping this one — `bash -c`, a /// `$(...)` — must count its own words too: `bash -c 'rm "$1"' _ tests/x` /// names its target OUTSIDE the inner command. +/// +/// A command with `$'` is read twice: as bash reads it (ANSI-C quoting) and as +/// a POSIX `sh` such as dash does (a `$` and a plain quote). incode runs +/// `sh -c`, which is dash on Debian and Ubuntu, and the two readings can end +/// the quote in different places; a write either one sees is a target. +/// `permissions::rules::split_into` does the same. #[must_use] fn collect(command: &str, depth: usize, out: &mut Vec) -> bool { if depth > MAX_DEPTH { out.extend(pieces(command)); return true; } - let lexed = lex(command); + let mut unresolved = collect_reading(command, depth, out, true); + if command.contains("$'") { + unresolved |= collect_reading(command, depth, out, false); + } + unresolved +} + +/// [`collect`] for one reading: with `ansi_c`, `$'…'` as bash reads it. +#[must_use] +fn collect_reading(command: &str, depth: usize, out: &mut Vec, ansi_c: bool) -> bool { + let lexed = lex(command, ansi_c); let mut unresolved = false; for inner in &lexed.substitutions { unresolved |= collect(inner, depth + 1, out); @@ -446,9 +462,12 @@ fn pieces(text: &str) -> Vec { /// Read a command roughly as the shell does: quotes, operators, comments, /// command substitutions and heredoc bodies. -fn lex(text: &str) -> Lexed { +fn lex(text: &str, ansi_c: bool) -> Lexed { let chars: Vec = text.chars().collect(); - let mut lexer = Lexer::default(); + let mut lexer = Lexer { + ansi_c, + ..Lexer::default() + }; let mut index = 0; while index < chars.len() { let c = chars[index]; @@ -498,6 +517,23 @@ fn lex(text: &str) -> Lexed { } '`' => index = lexer.substitution(&chars, index), '$' if matches!(next, Some('(' | '{')) => index = lexer.substitution(&chars, index), + // `$$`, the shell's pid: a quote after it is an ordinary one. + '$' if next == Some('$') => { + lexer.word.push_str("$$"); + lexer.started = true; + index += 2; + } + // `$'…'`: escapes decoded, ending where bash ends it + // (`crate::ansi_c`) — a backslash escapes the quote. + '$' if lexer.ansi_c && next == Some('\'') => { + let (text, end) = crate::ansi_c::quoted(&chars, index + 2); + lexer.word.push_str(&text); + lexer.started = true; + lexer.quoted = true; + index = end; + } + // `$"…"` is read as `"…"`. + '$' if next == Some('"') => index += 1, '#' if !lexer.started => { while index < chars.len() && chars[index] != '\n' { index += 1; @@ -590,6 +626,8 @@ fn lex(text: &str) -> Lexed { #[derive(Default)] struct Lexer { lexed: Lexed, + /// `$'…'` read as bash reads it, not as a POSIX `sh` does ([`collect`]). + ansi_c: bool, word: String, /// A word has begun, even if it is empty so far (`""`). started: bool, @@ -647,6 +685,14 @@ impl Lexer { index += 2; continue; } + if c == '$' && chars.get(index + 1) == Some(&'$') { + index += 2; + continue; + } + if self.ansi_c && c == '$' && chars.get(index + 1) == Some(&'\'') { + index = crate::ansi_c::quoted(chars, index + 2).1; + continue; + } // A quoted `)` does not close `$(...)`: a quoted span is skipped // whole, or the rest of the command would be read off by one. if matches!(c, '\'' | '"') && c != close { @@ -756,6 +802,67 @@ mod tests { ); } + /// **`$'…'` ENDS WHERE BASH SAYS.** A backslash escapes its quote, so + /// `$'\''` is one character and the redirect after the `;` is real. Read + /// as a plain `'…'`, the rest of the line looked quoted and the write to a + /// protected file went unseen. + #[test] + fn an_ansi_c_quote_does_not_hide_a_redirect_after_it() { + for command in [ + r"echo $'\'' ; echo x > tests/a.rs #'", + r"echo $'it\'s' && echo x >tests/a.rs #'", + r"echo $(echo $'\'') ; echo x > tests/a.rs #'", + ] { + // Each reading of `$'` may find it; the caller asks only whether + // any target is protected. + assert!( + targets(command).contains(&"tests/a.rs".to_string()), + "{command}: {:?}", + targets(command) + ); + } + assert!( + targets(r"echo $'a > tests/a.rs'").is_empty(), + "a `>` inside `$'…'` is text" + ); + } + + /// A target spelled with `$'…'` or `$"…"` is the file bash writes; a NUL + /// ends it (`> $'a.txt\0junk'` writes `a.txt`). + #[test] + fn a_target_in_ansi_c_or_locale_quotes_is_the_file_written() { + for command in [ + r"echo x > $'tests/a.rs'", + r"echo x > $'tests\x2fa.rs'", + r#"echo x > $"tests/a.rs""#, + r"echo x > $'tests/a.rs\0junk'", + ] { + assert!( + targets(command).contains(&"tests/a.rs".to_string()), + "{command}: {:?}", + targets(command) + ); + } + } + + /// **TWO SHELLS, TWO READINGS.** dash — what `sh -c` runs on Debian and + /// Ubuntu — reads `$'` as a `$` and a plain quote, and bash ends `$'\c'` + /// at its quote. A write hidden from either reading is still seen. + #[test] + fn a_redirect_hidden_from_either_reading_of_dollar_quote_is_seen() { + for command in [ + r"echo $'\' ; echo x > tests/a.rs # '", + r"echo $'\c' ; echo x > tests/a.rs #'", + r"echo $'\c\'' ; echo x > tests/a.rs #'", + ] { + assert!( + targets(command).contains(&"tests/a.rs".to_string()), + "{command}: {:?}", + targets(command) + ); + } + } + /// The body of a heredoc given to `cat` is what is written, not where. #[test] fn heredoc_data_is_not_a_target() { diff --git a/src/lib.rs b/src/lib.rs index cd0341a..2f136cd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,7 @@ pub mod acp_agent; pub mod admin; pub mod agent; +pub mod ansi_c; pub mod ask; pub mod auditor; pub mod brief; diff --git a/src/mcp_oauth.rs b/src/mcp_oauth.rs index a4de252..fc94c4d 100644 --- a/src/mcp_oauth.rs +++ b/src/mcp_oauth.rs @@ -793,32 +793,83 @@ fn reply(stream: &mut TcpStream, status: u16, said: &str) { /// Open `url` in the user's browser; whether a browser was started is not /// known, so the address is always printed as well. +/// +/// The address is built from a remote server's metadata +/// ([`authorization_url`]), which can put `|`, `&` or `%NAME%` in it. So it +/// goes to the OS as one argument no shell reads — on Windows through +/// `ShellExecuteW`, never `cmd /c start`, where the text after a `|` ran as a +/// command — and only when it is an http(s) URL ([`web_address`]). +/// +/// Called by `mcp_config.rs` (`incode mcp login`) as the login's opener. pub fn open_browser(url: &str) { - let mut command = if cfg!(target_os = "macos") { - let mut c = std::process::Command::new("open"); - c.arg(url); - c - } else if cfg!(windows) { - // `start` is a cmd built-in; `&` would end the command there, so it - // is escaped. The empty argument, which reaches cmd as `""`, is the window - // title `start` takes first. - let mut c = std::process::Command::new("cmd"); - c.args(["/c", "start", "", &url.replace('&', "^&")]); - c - } else { - let mut c = std::process::Command::new("xdg-open"); - c.arg(url); - c + let Some(address) = web_address(url) else { + return; }; - command - .stdin(std::process::Stdio::null()) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()); - if let Ok(mut child) = command.spawn() { - std::thread::spawn(move || child.wait()); + #[cfg(windows)] + shell_open(address); + #[cfg(not(windows))] + { + let program = if cfg!(target_os = "macos") { + "open" + } else { + "xdg-open" + }; + let mut command = std::process::Command::new(program); + command + .arg(address) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()); + if let Ok(mut child) = command.spawn() { + std::thread::spawn(move || child.wait()); + } } } +/// `url` as an http or https address, or `None`. A path, a `file:` URL or +/// another scheme would be run or opened as a document by the OS's handler. +fn web_address(url: &str) -> Option { + let parsed = Url::parse(url).ok()?; + matches!(parsed.scheme(), "https" | "http").then(|| parsed.into()) +} + +/// Hand `address` to the handler Windows has for its scheme. On a thread of +/// its own, with COM set up as `ShellExecuteW` asks, so a slow handler does +/// not hold up the login waiting for the redirect. +#[cfg(windows)] +fn shell_open(address: String) { + use windows_sys::Win32::System::Com::{ + CoInitializeEx, CoUninitialize, COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE, + }; + use windows_sys::Win32::UI::Shell::ShellExecuteW; + use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL; + + std::thread::spawn(move || { + let wide = |s: &str| s.encode_utf16().chain([0]).collect::>(); + let (verb, file) = (wide("open"), wide(&address)); + // SAFETY: COM is set up for this thread only, and undone below when it + // was. The two strings are NUL-terminated and outlive the call; the + // window, parameters and directory may be null. + unsafe { + let com = CoInitializeEx( + std::ptr::null(), + (COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE) as u32, + ); + ShellExecuteW( + std::ptr::null_mut(), + verb.as_ptr(), + file.as_ptr(), + std::ptr::null(), + std::ptr::null(), + SW_SHOWNORMAL, + ); + if com >= 0 { + CoUninitialize(); + } + } + }); +} + // --------------------------------------------------------------------------- // Registration and tokens // --------------------------------------------------------------------------- diff --git a/src/mcp_oauth_tests.rs b/src/mcp_oauth_tests.rs index d4472fc..8eecd81 100644 --- a/src/mcp_oauth_tests.rs +++ b/src/mcp_oauth_tests.rs @@ -180,6 +180,84 @@ fn the_authorization_url_carries_every_parameter() { assert!(authorization_url(&clear).is_err()); } +/// **A SERVER'S ENDPOINT IS NOT A COMMAND LINE.** Its metadata can put `|`, +/// `&` or `%NAME%` in the authorization URL, and they reach the address the +/// browser is sent to unchanged — which is why no shell may read it. +#[test] +fn an_endpoint_can_carry_shell_text_into_the_browser_address() { + let url = authorization_url(&AuthRequest { + endpoint: "https://auth.example/a|b?x=%PATH%|calc", + client_id: "c", + redirect_uri: "http://127.0.0.1:1/callback", + scopes: &[], + state: "s", + challenge: "c", + resource: "r", + }) + .expect("url"); + assert!(url.contains("/a|b?x=%PATH%|calc&"), "{url}"); + assert_eq!(web_address(&url).as_deref(), Some(url.as_str())); +} + +/// Only an http(s) address is opened: a path or another scheme would be run, +/// or opened as a document, by the OS's handler for it. +#[test] +fn only_a_web_address_is_handed_to_the_browser() { + for address in [ + r"C:\Windows\System32\calc.exe", + "calc.exe", + "file:///C:/Windows/System32/calc.exe", + r"\\host\share\run.exe", + "javascript:alert(1)", + "ms-settings:privacy", + "", + ] { + assert_eq!(web_address(address), None, "`{address}`"); + } + assert!(web_address("http://127.0.0.1:5555/callback").is_some()); + assert!(web_address("https://auth.example/authorize?a=1").is_some()); +} + +/// **THE BROWSER IS OPENED WITHOUT A SHELL.** Under `cmd /c start`, the text +/// after a `|` in the address ran as a command. The address must still reach +/// a browser: it calls back to a listener here. It opens a browser tab, so it +/// is run by hand: `cargo test --lib open_browser_runs_nothing -- --ignored`. +#[cfg(windows)] +#[test] +#[ignore = "opens a browser tab"] +fn open_browser_runs_nothing_from_the_address() { + let probe = + std::env::temp_dir().join(format!("incode-open-browser-probe-{}", std::process::id())); + let _ = std::fs::remove_dir(&probe); + let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); + listener.set_nonblocking(true).expect("nonblocking"); + let port = listener.local_addr().expect("addr").port(); + let address = format!("http://127.0.0.1:{port}/?q=|mkdir,{}", probe.display()); + open_browser(&address); + let deadline = Instant::now() + Duration::from_secs(20); + let mut reached = false; + while Instant::now() < deadline { + if let Ok((mut stream, _)) = listener.accept() { + reached = true; + let _ = stream.write_all(b"HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n"); + } + if reached { + // Time for a command started beside the browser to have run. + std::thread::sleep(Duration::from_secs(2)); + break; + } + std::thread::sleep(Duration::from_millis(100)); + } + let ran = probe.exists(); + let _ = std::fs::remove_dir(&probe); + assert!( + !ran, + "text from the address ran as a command: it made {}", + probe.display() + ); + assert!(reached, "no browser asked for the address within 20 s"); +} + #[test] fn the_callback_is_parsed_and_its_state_checked() { assert_eq!( diff --git a/src/permissions/managed.rs b/src/permissions/managed.rs index 4b5ddd5..619eb87 100644 --- a/src/permissions/managed.rs +++ b/src/permissions/managed.rs @@ -5,7 +5,9 @@ //! //! - Linux and other Unix: `/etc/incode/managed.toml` //! - macOS: `/Library/Application Support/incode/managed.toml` -//! - Windows: `%ProgramData%\incode\managed.toml` +//! - Windows: `\incode\managed.toml`, where `` is +//! the folder Windows records (`C:\ProgramData` as installed) — asked of the +//! OS, never read from the `%ProgramData%` variable //! //! Written by an administrator and readable by everyone; incode never writes //! it. Its location is fixed in code, deliberately: an environment variable @@ -51,9 +53,7 @@ pub const MANAGED_FILE: &str = "managed.toml"; #[must_use] pub fn managed_dir() -> PathBuf { if cfg!(windows) { - let base = std::env::var_os("ProgramData") - .map_or_else(|| PathBuf::from(r"C:\ProgramData"), PathBuf::from); - base.join("incode") + program_data().join("incode") } else if cfg!(target_os = "macos") { PathBuf::from("/Library/Application Support/incode") } else { @@ -61,6 +61,45 @@ pub fn managed_dir() -> PathBuf { } } +/// Windows' ProgramData folder as the OS records it. NOT `%ProgramData%`: the +/// person the managed file constrains sets their own environment, and one +/// pointing it at an empty folder would leave no policy at all. +fn program_data() -> PathBuf { + #[cfg(windows)] + if let Some(path) = known_program_data() { + return path; + } + // The OS always answers; were it not to, its own default, still never + // a value from the environment. + PathBuf::from(r"C:\ProgramData") +} + +/// `FOLDERID_ProgramData`, from `SHGetKnownFolderPath`. +#[cfg(windows)] +fn known_program_data() -> Option { + use std::os::windows::ffi::OsStringExt; + use windows_sys::Win32::System::Com::CoTaskMemFree; + use windows_sys::Win32::UI::Shell::{FOLDERID_ProgramData, SHGetKnownFolderPath}; + + let mut raw: windows_sys::core::PWSTR = std::ptr::null_mut(); + // SAFETY: a known-folder id, no flags, no token (this user), and an out + // pointer the call fills with a string for CoTaskMemFree. + let status = + unsafe { SHGetKnownFolderPath(&FOLDERID_ProgramData, 0, std::ptr::null_mut(), &mut raw) }; + let path = (status >= 0 && !raw.is_null()).then(|| { + // SAFETY: on success `raw` is a NUL-terminated wide string. + let wide = unsafe { + let len = (0..).take_while(|&i| *raw.add(i) != 0).count(); + std::slice::from_raw_parts(raw, len) + }; + PathBuf::from(std::ffi::OsString::from_wide(wide)) + }); + // SAFETY: frees what the call allocated, on success or failure (null is + // allowed). + unsafe { CoTaskMemFree(raw.cast()) }; + path +} + /// The managed file, on this OS. #[must_use] pub fn managed_path() -> PathBuf { @@ -278,4 +317,40 @@ mod tests { fn a_test_never_reads_the_machines_managed_file() { assert_eq!(load(), Managed::Absent); } + + /// **THE PERSON THE FILE CONSTRAINS SETS THEIR OWN ENVIRONMENT.** Pointing + /// `%ProgramData%`, or the variables Windows builds it from, at an empty + /// folder must not move the managed file there. + #[cfg(windows)] + #[test] + fn the_managed_folder_does_not_follow_the_environment() { + let _guard = crate::brief::ENV_LOCK + .lock() + .unwrap_or_else(|e| e.into_inner()); + let real = managed_dir(); + let decoy = tempfile::tempdir().expect("temp dir"); + let names = ["ProgramData", "ALLUSERSPROFILE", "SystemDrive"]; + let saved: Vec<_> = names.iter().map(std::env::var_os).collect(); + for name in names { + std::env::set_var(name, decoy.path()); + } + let moved = managed_dir(); + for (name, value) in names.iter().zip(saved) { + match value { + Some(value) => std::env::set_var(name, value), + None => std::env::remove_var(name), + } + } + assert!( + !moved.starts_with(decoy.path()), + "the environment moved the managed folder to {}", + moved.display() + ); + assert_eq!(moved, real); + assert!( + real.is_absolute() && real.ends_with("incode"), + "{}", + real.display() + ); + } } diff --git a/src/permissions/rules.rs b/src/permissions/rules.rs index 2d6bd68..cce01c5 100644 --- a/src/permissions/rules.rs +++ b/src/permissions/rules.rs @@ -320,7 +320,8 @@ pub struct Segment { /// As written, whitespace-collapsed. What an allow rule is matched with. pub text: String, /// The forms a deny or ask rule is matched with: `text`, and `text` with - /// leading assignments and wrapper commands peeled off, one at a time. + /// leading assignments and wrapper commands peeled off, one at a time; + /// each as written and unquoted. pub peeled: Vec, /// A part no allow rule may pass: it substitutes a command, redirects, /// or hands a string to a shell. @@ -342,6 +343,15 @@ pub fn split_command(line: &str) -> Vec { /// How deep `sh -c "sh -c '…'"` is followed before the rest is simply opaque. const MAX_DEPTH: usize = 8; +/// `line`'s parts, appended to `out`. +/// +/// `$'…'` is ANSI-C quoting to bash, zsh and ksh, but a `$` and a plain +/// quote to a POSIX `sh` such as dash — the `sh` of Debian and Ubuntu, and +/// incode runs `sh -c` (`tools::shell_choice`). The two readings can end the +/// quote in different places, so a command can hide from one of them. Which +/// shell runs is not known here, so a line with `$'` is read BOTH ways: a deny +/// or ask rule meets the parts of either, and every part is opaque, so no +/// allow rule passes it. `guards::shell::write_targets` does the same. fn split_into(line: &str, out: &mut Vec, depth: usize) { if depth > MAX_DEPTH { out.push(Segment { @@ -351,6 +361,19 @@ fn split_into(line: &str, out: &mut Vec, depth: usize) { }); return; } + let first = out.len(); + split_reading(line, out, depth, true); + if line.contains("$'") { + split_reading(line, out, depth, false); + for segment in &mut out[first..] { + segment.opaque = true; + } + } +} + +/// One reading of `line`: with `ansi_c`, `$'…'` as bash reads it; without, +/// as a POSIX `sh` does. +fn split_reading(line: &str, out: &mut Vec, depth: usize, ansi_c: bool) { let chars: Vec = line.chars().collect(); let mut i = 0; // The current part, as written; and with quoted text blanked, to look @@ -407,7 +430,7 @@ fn split_into(line: &str, out: &mut Vec, depth: usize) { } // Substitution happens inside double quotes too. if (c == '$' && next == Some('(')) || c == '`' { - let (body, end) = substitution(&chars, i); + let (body, end) = substitution(&chars, i, ansi_c); raw.extend(&chars[i..end]); bare.push('_'); inner.push(body); @@ -431,6 +454,30 @@ fn split_into(line: &str, out: &mut Vec, depth: usize) { bare.push_str("__"); i += 2; } + // `$$`, the shell's pid: a quote after it is an ordinary one. + '$' if next == Some('$') => { + raw.push_str("$$"); + bare.push_str("$$"); + i += 2; + } + // `$'…'`: a backslash escapes the quote, so it ends where bash + // says (`crate::ansi_c`). What it spells is decided by escapes, + // so no allow rule passes the part. + '$' if ansi_c && next == Some('\'') => { + let (_, end) = crate::ansi_c::quoted(&chars, i + 2); + raw.extend(&chars[i..end]); + bare.extend(std::iter::repeat_n('_', end - i)); + opaque = true; + i = end; + } + // `$"…"`: a double-quoted string the locale may translate into + // other text; past the `$` it is read as `"…"`. + '$' if next == Some('"') => { + raw.push(c); + bare.push('_'); + opaque = true; + i += 1; + } '\'' | '"' => { quote = Some(c); raw.push(c); @@ -438,7 +485,7 @@ fn split_into(line: &str, out: &mut Vec, depth: usize) { i += 1; } '$' if next == Some('(') => { - let (body, end) = substitution(&chars, i); + let (body, end) = substitution(&chars, i, ansi_c); raw.extend(&chars[i..end]); bare.push('_'); inner.push(body); @@ -446,7 +493,7 @@ fn split_into(line: &str, out: &mut Vec, depth: usize) { i = end; } '`' => { - let (body, end) = substitution(&chars, i); + let (body, end) = substitution(&chars, i, ansi_c); raw.extend(&chars[i..end]); bare.push('_'); inner.push(body); @@ -454,7 +501,7 @@ fn split_into(line: &str, out: &mut Vec, depth: usize) { i = end; } '<' | '>' if next == Some('(') => { - let (body, end) = substitution(&chars, i + 1); + let (body, end) = substitution(&chars, i + 1, ansi_c); raw.extend(&chars[i..end]); bare.push('_'); inner.push(body); @@ -499,7 +546,8 @@ fn split_into(line: &str, out: &mut Vec, depth: usize) { /// The body of the substitution that starts at `start` (`$(`, `(` or a /// backtick), and the index just past its end. Unterminated: the rest. -fn substitution(chars: &[char], start: usize) -> (String, usize) { +/// `ansi_c`: whether `$'…'` is read as bash reads it ([`split_into`]). +fn substitution(chars: &[char], start: usize, ansi_c: bool) -> (String, usize) { if chars[start] == '`' { let mut i = start + 1; let mut body = String::new(); @@ -540,6 +588,14 @@ fn substitution(chars: &[char], start: usize) -> (String, usize) { i += 2; continue; } + '$' if chars.get(i + 1) == Some(&'$') => { + i += 2; + continue; + } + '$' if ansi_c && chars.get(i + 1) == Some(&'\'') => { + i = crate::ansi_c::quoted(chars, i + 2).1; + continue; + } '\'' | '"' => quote = Some(c), '(' => depth += 1, ')' => { @@ -622,14 +678,18 @@ fn words(text: &str) -> Vec { let mut words = Vec::new(); let mut word = String::new(); let mut quote: Option = None; - let mut chars = text.chars().peekable(); - while let Some(c) = chars.next() { + let chars: Vec = text.chars().collect(); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + i += 1; match quote { Some(q) => { word.push(c); if c == '\\' && q == '"' { - if let Some(n) = chars.next() { + if let Some(&n) = chars.get(i) { word.push(n); + i += 1; } } else if c == q { quote = None; @@ -641,14 +701,25 @@ fn words(text: &str) -> Vec { words.push(std::mem::take(&mut word)); } } + '$' if chars.get(i) == Some(&'$') => { + word.push_str("$$"); + i += 1; + } + // `$'…'`, kept as written, to where bash ends it. + '$' if chars.get(i) == Some(&'\'') => { + let (_, end) = crate::ansi_c::quoted(&chars, i + 1); + word.extend(&chars[i - 1..end]); + i = end; + } '\'' | '"' => { quote = Some(c); word.push(c); } '\\' => { word.push(c); - if let Some(n) = chars.next() { + if let Some(&n) = chars.get(i) { word.push(n); + i += 1; } } _ => word.push(c), @@ -661,18 +732,35 @@ fn words(text: &str) -> Vec { words } -/// A word with its outer quotes and backslashes removed. +/// A word with its outer quotes and backslashes removed, and a `$'…'` in it +/// decoded (`crate::ansi_c`): `$'\x72m'` is `rm`. fn unquote(word: &str) -> String { let mut out = String::new(); let mut quote: Option = None; - let mut chars = word.chars(); - while let Some(c) = chars.next() { + let chars: Vec = word.chars().collect(); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + let next = chars.get(i + 1).copied(); + i += 1; match (quote, c) { + (None, '$') if next == Some('$') => { + out.push_str("$$"); + i += 1; + } + (None, '$') if next == Some('\'') => { + let (text, end) = crate::ansi_c::quoted(&chars, i + 1); + out.push_str(&text); + i = end; + } + // `$"…"` is `"…"`. + (None, '$') if next == Some('"') => {} (None, '\'' | '"') => quote = Some(c), (Some(q), _) if c == q => quote = None, (None | Some('"'), '\\') => { - if let Some(n) = chars.next() { + if let Some(n) = next { out.push(n); + i += 1; } } _ => out.push(c), @@ -722,10 +810,12 @@ fn flag_takes_value(wrapper: &str, flag: &str) -> bool { } /// `text`, then `text` with each leading assignment and wrapper peeled off in -/// turn; and the script, when the command hands one to a shell. +/// turn — each form also unquoted, since `'rm' -rf /` and `$'\x72m' -rf /` run +/// `rm` — and the script, when the command hands one to a shell. fn peel(text: &str) -> (Vec, Option) { let all = words(text); - let mut forms = vec![all.join(" ")]; + let plain: Vec = all.iter().map(|w| unquote(w)).collect(); + let mut forms = vec![all.join(" "), plain.join(" ")]; let mut at = 0; while at < all.len() { let word = &all[at]; @@ -748,6 +838,7 @@ fn peel(text: &str) -> (Vec, Option) { } if at < all.len() { forms.push(all[at..].join(" ")); + forms.push(plain[at..].join(" ")); } } // `sh -c '