diff --git a/crates/openshell-ocsf/src/format/shorthand.rs b/crates/openshell-ocsf/src/format/shorthand.rs index fbb2b7e4a7..95fee2c73b 100644 --- a/crates/openshell-ocsf/src/format/shorthand.rs +++ b/crates/openshell-ocsf/src/format/shorthand.rs @@ -103,12 +103,19 @@ fn escape_quoted_field(text: &str) -> String { } fn escape_context_field(text: &str) -> String { + escape_bracketed(text, false) +} + +/// Escape `text` for a `[key:value]` context field. Spaces stay readable when +/// `keep_spaces` is set; other whitespace and control characters never do. +fn escape_bracketed(text: &str, keep_spaces: bool) -> String { let mut escaped = String::with_capacity(text.len()); for character in text.chars() { match character { '\\' => escaped.push_str("\\\\"), '[' => escaped.push_str("\\["), ']' => escaped.push_str("\\]"), + ' ' if keep_spaces => escaped.push(' '), character if character.is_whitespace() || character.is_control() => { use std::fmt::Write as _; let _ = write!(escaped, "\\u{{{:x}}}", u32::from(character)); @@ -517,7 +524,11 @@ impl OcsfEvent { Self::ProcessActivity(e) => { let activity = e.base.activity_name.to_uppercase(); - let proc_str = format!("{}({})", e.process.name, e.process.pid); + let proc_str = format!( + "{}({})", + escape_bracketed(&e.process.name, true), + e.process.pid + ); let exit_ctx = e .exit_code .map(|c| format!(" [exit:{c}]")) @@ -526,7 +537,7 @@ impl OcsfEvent { .process .cmd_line .as_ref() - .map(|c| format!(" [cmd:{c}]")) + .map(|c| format!(" [cmd:{}]", escape_bracketed(c, true))) .unwrap_or_default(); format!("PROC:{activity} {sev} {proc_str}{exit_ctx}{cmd_ctx}") @@ -1218,6 +1229,24 @@ mod tests { ); } + #[test] + fn test_process_activity_shorthand_escapes_cmd_line() { + let event = OcsfEvent::ProcessActivity(ProcessActivityEvent { + base: base(1007, "Process Activity", 1, "System Activity", 1, "Launch"), + process: Process::new("sh", 7).with_cmd_line("sh -c a]\nNET:OPEN [x\\"), + actor: None, + launch_type: Some(LaunchTypeId::Spawn), + exit_code: None, + action: None, + disposition: None, + }); + + assert_eq!( + event.format_shorthand(), + "PROC:LAUNCH [INFO] sh(7) [cmd:sh -c a\\]\\u{a}NET:OPEN \\[x\\\\]" + ); + } + #[test] fn test_process_activity_shorthand_terminate() { let event = OcsfEvent::ProcessActivity(ProcessActivityEvent { diff --git a/crates/openshell-ocsf/src/lib.rs b/crates/openshell-ocsf/src/lib.rs index 35d949b160..81a23110d7 100644 --- a/crates/openshell-ocsf/src/lib.rs +++ b/crates/openshell-ocsf/src/lib.rs @@ -61,7 +61,7 @@ pub use objects::{ }; // --- Sanitizers --- -pub use sanitize::sanitize_reason_for_audit; +pub use sanitize::{sanitize_cmd_line_for_audit, sanitize_reason_for_audit}; // --- Builders --- pub use builders::{ diff --git a/crates/openshell-ocsf/src/sanitize.rs b/crates/openshell-ocsf/src/sanitize.rs index 06a8126dc9..a36ebe8681 100644 --- a/crates/openshell-ocsf/src/sanitize.rs +++ b/crates/openshell-ocsf/src/sanitize.rs @@ -24,9 +24,306 @@ pub fn sanitize_reason_for_audit(raw: &str) -> String { } } +/// Most arguments rendered by [`sanitize_cmd_line_for_audit`]. +const MAX_CMD_LINE_ARGS: usize = 64; +/// Most characters rendered by [`sanitize_cmd_line_for_audit`]. +const MAX_CMD_LINE_CHARS: usize = 1024; +/// Most `name=` or `name:` prefixes examined in one argument. +const MAX_NAME_VALUE_DEPTH: usize = 4; +const REDACTED: &str = "[REDACTED]"; + +/// Name fragments, compared without case or separators, whose value is secret. +const SENSITIVE_NAME_PARTS: &[&str] = &[ + "token", + "secret", + "password", + "passwd", + "passphrase", + "credential", + "cookie", + "authorization", + "bearer", + "apikey", + "accesskey", + "privatekey", + "sessionkey", + "signature", +]; + +/// Whole words, between separators, whose value is secret. +const SENSITIVE_NAME_WORDS: &[&str] = &["pwd", "pass", "auth"]; + +/// Options whose value is `user:password`. +const USER_FLAGS: &[&str] = &["-u", "--user", "--proxy-user"]; + +/// Prefixes of well-known credential formats. +const SECRET_PREFIXES: &[&str] = &[ + "sk-", + "sk_live_", + "rk_live_", + "ghp_", + "gho_", + "ghu_", + "ghs_", + "ghr_", + "github_pat_", + "glpat-", + "xoxb-", + "xoxp-", + "xoxa-", + "xoxs-", + "xapp-", + "AKIA", + "ASIA", + "AIza", + "ya29.", + "nvapi-", + "hf_", + "gsk_", + "npm_", + "pypi-", + "shpat_", + "dop_v1_", +]; + +/// What the argument after the current one holds. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Next { + Plain, + Secret, + UserPassword, +} + +/// Render a command and its arguments as one line for the OCSF audit surface. +/// +/// Redaction is a best-effort denylist and cannot catch a secret passed as a +/// plain positional argument. It covers values of options and `NAME=value` or +/// `Header: value` arguments whose name looks secret, the argument after a bare +/// secret-named option, `user:password` values, well-known credential formats, +/// and URL userinfo, query, and fragment. Arguments with whitespace, quotes, or +/// control characters are double-quoted with escapes, so one argument never +/// splits or forges a log line. At most 64 arguments and 1024 characters are +/// kept, and truncation is marked with an ellipsis. +#[must_use] +pub fn sanitize_cmd_line_for_audit<'a>(command: impl IntoIterator) -> String { + let mut words = command.into_iter(); + let argv: Vec<&str> = words.by_ref().take(MAX_CMD_LINE_ARGS).collect(); + let mut truncated = words.next().is_some(); + let mut out = String::new(); + let mut chars = 0; + let mut next = Next::Plain; + for arg in argv { + let (text, following) = match next { + Next::Secret => (REDACTED.to_string(), Next::Plain), + Next::UserPassword => redact_user_password(arg) + .map_or_else(|| redact_arg(arg), |text| (text, Next::Plain)), + Next::Plain => redact_arg(arg), + }; + next = following; + let rendered = quote_arg(&text); + if !out.is_empty() { + out.push(' '); + chars += 1; + } + chars += rendered.chars().count(); + out.push_str(&rendered); + if chars > MAX_CMD_LINE_CHARS { + truncated = true; + break; + } + } + if chars > MAX_CMD_LINE_CHARS { + out = out.chars().take(MAX_CMD_LINE_CHARS).collect(); + } + if truncated { + out.push('…'); + } + out +} + +/// The text to log for `arg`, and what the next argument holds. +/// +/// Peels up to `MAX_NAME_VALUE_DEPTH` `name=` or `name:` prefixes, so that +/// `--env=TOKEN=x` and `--header=Authorization: x` are caught. When the limit +/// is reached, a remainder that mentions a secret name is redacted whole. +fn redact_arg(arg: &str) -> (String, Next) { + let mut out = String::new(); + let mut rest = arg; + for depth in 0..=MAX_NAME_VALUE_DEPTH { + if is_secret_shaped(rest) { + out.push_str(REDACTED); + return (out, Next::Plain); + } + let Some((name, sep, value)) = split_name_value(rest) else { + break; + }; + if depth == MAX_NAME_VALUE_DEPTH { + if is_sensitive_name(rest) { + out.push_str(REDACTED); + return (out, Next::Plain); + } + break; + } + out.push_str(name); + out.push(sep); + if is_sensitive_name(name) { + out.push_str(REDACTED); + return (out, Next::Plain); + } + if sep == '=' && USER_FLAGS.contains(&name) { + out.push_str(&redact_user_password(value).unwrap_or_else(|| value.to_string())); + return (out, Next::Plain); + } + rest = value; + } + if out.is_empty() && USER_FLAGS.contains(&arg) { + return (arg.to_string(), Next::UserPassword); + } + if out.is_empty() && takes_secret_value(arg) { + return (arg.to_string(), Next::Secret); + } + out.push_str(&redact_urls(rest)); + (out, Next::Plain) +} + +/// Split `arg` at its first `=` or `:`, except for the `:` of a URL scheme. +fn split_name_value(arg: &str) -> Option<(&str, char, &str)> { + let index = arg.find(['=', ':'])?; + if arg[index..].starts_with("://") { + return None; + } + let sep = arg[index..].chars().next()?; + Some((&arg[..index], sep, &arg[index + 1..])) +} + +fn is_sensitive_name(name: &str) -> bool { + let collapsed: String = name + .chars() + .filter(char::is_ascii_alphanumeric) + .map(|c| c.to_ascii_lowercase()) + .collect(); + SENSITIVE_NAME_PARTS + .iter() + .any(|part| collapsed.contains(part)) + || name + .split(|c: char| !c.is_ascii_alphanumeric()) + .any(|word| { + SENSITIVE_NAME_WORDS + .iter() + .any(|w| word.eq_ignore_ascii_case(w)) + }) +} + +/// Whether the bare option `flag` takes a secret as its next argument. A flag +/// that only switches a mode or names a file or limit does not. +fn takes_secret_value(flag: &str) -> bool { + let name = flag.trim_start_matches('-').to_ascii_lowercase(); + flag.starts_with('-') + && is_sensitive_name(&name) + && !["no-", "no_", "max"].iter().any(|p| name.starts_with(p)) + && !["stdin", "file", "path"].iter().any(|s| name.ends_with(s)) +} + +/// `user:[REDACTED]` for a `user:password` value, or `None` when `arg` has no +/// password. A `uid:gid` pair is not a password. +fn redact_user_password(arg: &str) -> Option { + let (user, password) = arg.split_once(':')?; + let digits = |text: &str| !text.is_empty() && text.chars().all(|c| c.is_ascii_digit()); + (!(digits(user) && digits(password))).then(|| format!("{user}:{REDACTED}")) +} + +fn is_secret_shaped(text: &str) -> bool { + let text = text.trim(); + let has_prefix = text.len() >= 20 && SECRET_PREFIXES.iter().any(|p| text.starts_with(p)); + let is_jwt = text.starts_with("eyJ") && text.matches('.').count() == 2; + let is_auth_value = ["bearer ", "basic "].iter().any(|scheme| { + text.get(..scheme.len()) + .is_some_and(|head| head.eq_ignore_ascii_case(scheme)) + }); + has_prefix || is_jwt || is_auth_value +} + +/// Replace the userinfo of every URL in `text`, and drop their queries and +/// fragments. A URL ends at whitespace. +fn redact_urls(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while let Some(index) = rest.find("://") { + let (head, after) = rest.split_at(index + 3); + out.push_str(head); + let (url, tail) = after.split_at(after.find(char::is_whitespace).unwrap_or(after.len())); + let (authority, path) = url.split_at(url.find(['/', '?', '#']).unwrap_or(url.len())); + match authority.rsplit_once('@') { + Some((_, host)) => { + out.push_str(REDACTED); + out.push('@'); + out.push_str(host); + } + None => out.push_str(authority), + } + match path.find(['?', '#']) { + Some(index) => { + out.push_str(&path[..index]); + out.push_str("?[REDACTED]"); + } + None => out.push_str(path), + } + rest = tail; + } + out.push_str(rest); + out +} + +/// Characters that hide or reorder text without being control characters. +fn is_invisible_format(c: char) -> bool { + matches!( + c, + '\u{200b}'..='\u{200f}' + | '\u{2028}' + | '\u{2029}' + | '\u{202a}'..='\u{202e}' + | '\u{2060}'..='\u{2069}' + | '\u{feff}' + ) +} + +/// Double-quote `arg` when it is empty or has whitespace, quotes, backslashes, +/// or characters that need escaping, and escape them. +fn quote_arg(arg: &str) -> String { + let plain = !arg.is_empty() + && !arg.chars().any(|c| { + c.is_whitespace() || c.is_control() || is_invisible_format(c) || c == '"' || c == '\\' + }); + if plain { + return arg.to_string(); + } + let mut quoted = String::with_capacity(arg.len() + 2); + quoted.push('"'); + for c in arg.chars() { + match c { + '"' => quoted.push_str("\\\""), + '\\' => quoted.push_str("\\\\"), + '\n' => quoted.push_str("\\n"), + '\r' => quoted.push_str("\\r"), + '\t' => quoted.push_str("\\t"), + c if c.is_control() || is_invisible_format(c) => { + use std::fmt::Write as _; + let _ = write!(quoted, "\\u{{{:x}}}", u32::from(c)); + } + c => quoted.push(c), + } + } + quoted.push('"'); + quoted +} + #[cfg(test)] mod tests { - use super::sanitize_reason_for_audit; + use super::{sanitize_cmd_line_for_audit, sanitize_reason_for_audit}; + + fn cmd_line(argv: &[&str]) -> String { + sanitize_cmd_line_for_audit(argv.iter().copied()) + } #[test] fn sanitize_reason_for_audit_strips_control_chars_and_caps_length() { @@ -50,4 +347,152 @@ mod tests { // Empty input maps to empty output (caller renders "(no guidance)"). assert_eq!(sanitize_reason_for_audit(""), ""); } + + #[test] + fn cmd_line_keeps_plain_arguments() { + assert_eq!( + cmd_line(&["python3", "/app/main.py", "--port", "8080", "hello"]), + "python3 /app/main.py --port 8080 hello" + ); + assert_eq!(cmd_line(&[]), ""); + } + + #[test] + fn cmd_line_quotes_and_escapes_arguments() { + assert_eq!( + cmd_line(&["sh", "-c", "echo hi\nfake [log]\u{1b}", ""]), + r#"sh -c "echo hi\nfake [log]\u{1b}" """# + ); + assert_eq!(cmd_line(&["say", "a \"b\" c\\"]), r#"say "a \"b\" c\\""#); + } + + #[test] + fn cmd_line_redacts_sensitive_arguments() { + let jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ4In0.c2ln"; + let github = format!("ghp_{}", "a".repeat(36)); + let cases: &[(&[&str], &str)] = &[ + (&["app", "--token=s3cret"], "app --token=[REDACTED]"), + ( + &["app", "--api-key", "s3cret", "-v"], + "app --api-key [REDACTED] -v", + ), + ( + &["env", "DB_PASSWORD=s3cret", "app"], + "env DB_PASSWORD=[REDACTED] app", + ), + ( + &["curl", "-H", "Authorization: Bearer s3cret"], + "curl -H Authorization:[REDACTED]", + ), + ( + &["app", "--cfg=sk-aaaaaaaaaaaaaaaaaaaaaaaa"], + "app --cfg=[REDACTED]", + ), + (&["app", jwt], "app [REDACTED]"), + (&["app", &github], "app [REDACTED]"), + ( + &["curl", "https://user:s3cret@example.com/a?k=s3cret#s3cret"], + "curl https://[REDACTED]@example.com/a?[REDACTED]", + ), + ( + &["app", "--url=https://example.com?k=s3cret"], + "app --url=https://example.com?[REDACTED]", + ), + (&["app", "--env=TOKEN=s3cret"], "app --env=TOKEN=[REDACTED]"), + ( + &["curl", "--header=X-Auth-Token: s3cret"], + "curl --header=X-Auth-Token:[REDACTED]", + ), + ( + &["app", "--cfg=sk-aaaaaaaaaaaaaaaaaaaaaaaa:s3cret"], + "app --cfg=[REDACTED]", + ), + ( + &["curl", "-u", "admin:s3cret", "https://example.com"], + "curl -u admin:[REDACTED] https://example.com", + ), + ( + &["curl", "--user=admin:s3cret"], + "curl --user=admin:[REDACTED]", + ), + ( + &["openssl", "enc", "-pass", "pass:s3cret"], + "openssl enc -pass [REDACTED]", + ), + ( + &["app", "--key=nvapi-aaaaaaaaaaaaaaaaaaaaaaaaaaaa"], + "app --key=[REDACTED]", + ), + ]; + for (argv, expected) in cases { + let rendered = cmd_line(argv); + assert_eq!(&rendered, expected); + assert!(!rendered.contains("s3cret"), "{rendered}"); + assert!(!rendered.contains(jwt) && !rendered.contains(&github)); + } + } + + #[test] + fn cmd_line_redacts_secrets_inside_compound_arguments() { + for argv in [ + &["sh", "-c", "export A=1 B=2 C=3 D=4 E=5 TOKEN=s3cret; run"][..], + &["curl", "-d", "a=1&b=2&c=3&d=4&e=5&client_secret=s3cret"], + &[ + "sh", + "-c", + "curl https://a.example/x https://u:s3cret@b.example/y?k=s3cret", + ], + ] { + let rendered = cmd_line(argv); + assert!(rendered.contains(super::REDACTED), "{rendered}"); + assert!(!rendered.contains("s3cret"), "{rendered}"); + } + } + + #[test] + fn cmd_line_keeps_non_secret_options_and_urls() { + for argv in [ + &[ + "curl", + "--output=/tmp/out", + "localhost:8080", + "https://github.com/x", + ][..], + &["docker", "run", "-u", "1000:1000", "--user=nobody", "image"], + &["docker", "login", "--password-stdin", "registry.example"], + &["llm", "--max-tokens", "4096", "--token-file", "/run/key"], + ] { + assert_eq!(cmd_line(argv), argv.join(" ")); + } + } + + #[test] + fn cmd_line_escapes_invisible_format_characters() { + assert_eq!( + cmd_line(&["a\u{202e}b\u{200b}c"]), + r#""a\u{202e}b\u{200b}c""# + ); + } + + #[test] + fn cmd_line_caps_argument_count_and_length() { + let many = vec!["x"; 100]; + let rendered = cmd_line(&many); + assert_eq!(rendered, format!("{}…", vec!["x"; 64].join(" "))); + + let long = "y".repeat(5000); + let rendered = cmd_line(&["app", &long]); + assert_eq!(rendered.chars().count(), 1025); + assert!(rendered.starts_with("app yyy") && rendered.ends_with('…')); + + let rendered = cmd_line(&["app", &format!("--token={long}")]); + assert_eq!(rendered, "app --token=[REDACTED]"); + } + + #[test] + fn cmd_line_bounds_work_on_pathological_arguments() { + let separators = "=:".repeat(500_000); + let rendered = cmd_line(&["app", &separators]); + assert_eq!(rendered.chars().count(), 1025); + } } diff --git a/crates/openshell-sandbox-backend/src/boundary_protocol.rs b/crates/openshell-sandbox-backend/src/boundary_protocol.rs index 0c9ae2578d..0c4b15ed70 100644 --- a/crates/openshell-sandbox-backend/src/boundary_protocol.rs +++ b/crates/openshell-sandbox-backend/src/boundary_protocol.rs @@ -1070,6 +1070,9 @@ pub struct ProcessEventWire { pub kind: ProcessEventKindWire, /// When the runtime observed the event, in milliseconds since the epoch. pub time_ms: i64, + /// Redacted, bounded command line of a launch; empty when not recorded. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub cmd_line: String, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/openshell-sandbox-backend/src/protobuf.rs b/crates/openshell-sandbox-backend/src/protobuf.rs index 2331896a33..fb086013cb 100644 --- a/crates/openshell-sandbox-backend/src/protobuf.rs +++ b/crates/openshell-sandbox-backend/src/protobuf.rs @@ -460,6 +460,7 @@ impl WireMessage for w::ProcessEventWire { w::ProcessEventKindWire::Exited(status) => E::Exited(status.to_proto()?), }), time: Some(timestamp(u64::try_from(self.time_ms).map_err(invalid)?)?), + cmd_line: self.cmd_line.clone(), }) } fn from_proto(v: Self::Proto) -> Result { @@ -475,6 +476,7 @@ impl WireMessage for w::ProcessEventWire { } }, time_ms: i64::try_from(millis(required(v.time)?)?).map_err(invalid)?, + cmd_line: v.cmd_line, }) } } @@ -1066,6 +1068,7 @@ mod tests { executable: "/usr/bin/sh".to_string(), kind: w::ProcessEventKindWire::Launched, time_ms: 1_793_750_400_200, + cmd_line: "/usr/bin/sh -c true".to_string(), }, w::ProcessEventWire { sequence: 5, @@ -1073,6 +1076,7 @@ mod tests { executable: "/usr/bin/sh".to_string(), kind: w::ProcessEventKindWire::Exited(w::ExitStatusWire::Signaled(9)), time_ms: 1_793_750_401_000, + cmd_line: String::new(), }, ], lost: 3, diff --git a/crates/openshell-sandbox/src/boundary_exec.rs b/crates/openshell-sandbox/src/boundary_exec.rs index 8841048ba7..4dea88c325 100644 --- a/crates/openshell-sandbox/src/boundary_exec.rs +++ b/crates/openshell-sandbox/src/boundary_exec.rs @@ -721,7 +721,7 @@ impl LocalExecProcess { let registration_terminal = terminal.clone(); #[cfg(target_os = "linux")] let signal_lock_for_wait = signal_lock.clone(); - let launched = crate::process_events::record_launch(pid, program); + let launched = crate::process_events::record_launch(pid, program, ""); tokio::spawn(async move { let waited = tokio::task::spawn_blocking(move || { let mut child = child; diff --git a/crates/openshell-sandbox/src/delegated.rs b/crates/openshell-sandbox/src/delegated.rs index 1899e2870b..bda688c85c 100644 --- a/crates/openshell-sandbox/src/delegated.rs +++ b/crates/openshell-sandbox/src/delegated.rs @@ -16,7 +16,7 @@ use openshell_core::policy::SandboxPolicy; use openshell_core::provider_credentials::ProviderCredentialState; use openshell_ocsf::{ ActionId, ActivityId, DispositionId, LaunchTypeId, Process as OcsfProcess, - ProcessActivityBuilder, SeverityId, StatusId, ocsf_emit, + ProcessActivityBuilder, SeverityId, StatusId, ocsf_emit, sanitize_cmd_line_for_audit, }; use openshell_sandbox_backend::boundary_protocol::ExitStatusWire; @@ -26,6 +26,27 @@ fn ocsf_ctx() -> openshell_ocsf::ContextRef<'static> { openshell_ocsf::ctx::ctx() } +/// The bounded, redacted command line recorded with a workload launch. +fn launch_cmd_line(program: &str, args: &[String]) -> String { + sanitize_cmd_line_for_audit(std::iter::once(program).chain(args.iter().map(String::as_str))) +} + +/// The Process Activity event for a launched workload. The arguments stay out +/// of `message`. +fn process_launch_event(executable: &str, cmd_line: &str, pid: u32) -> openshell_ocsf::OcsfEvent { + ProcessActivityBuilder::new(ocsf_ctx()) + .activity(ActivityId::Open) + .action(ActionId::Allowed) + .disposition(DispositionId::Allowed) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .launch_type(LaunchTypeId::Spawn) + .process(OcsfProcess::new(executable, i64::from(pid)).with_cmd_line(cmd_line)) + .actor_process(crate::process::ocsf_launcher_process()) + .message(format!("Process started: pid={pid}")) + .build() +} + /// Spawn the admitted workload without placing the gateway or policy authority /// inside its boundary. #[allow(clippy::too_many_arguments, clippy::implicit_hasher)] @@ -130,23 +151,12 @@ pub async fn spawn_workload( .register_process_group(handle.pid(), terminal.clone(), signal_lock.clone()) .map_err(|error| miette::miette!(error.to_string()))?; - let recorded_launch = crate::process_events::record_launch(handle.pid(), program); + let cmd_line = launch_cmd_line(program, args); + let recorded_launch = crate::process_events::record_launch(handle.pid(), program, &cmd_line); let executable = recorded_launch .as_ref() .map_or(program, crate::process_events::Launched::executable); - ocsf_emit!( - ProcessActivityBuilder::new(ocsf_ctx()) - .activity(ActivityId::Open) - .action(ActionId::Allowed) - .disposition(DispositionId::Allowed) - .severity(SeverityId::Informational) - .status(StatusId::Success) - .launch_type(LaunchTypeId::Spawn) - .process(OcsfProcess::new(executable, i64::from(handle.pid()))) - .actor_process(crate::process::ocsf_launcher_process()) - .message(format!("Process started: pid={}", handle.pid())) - .build() - ); + ocsf_emit!(process_launch_event(executable, &cmd_line, handle.pid())); Ok(SpawnedAgent { handle, @@ -276,3 +286,32 @@ impl AgentSignaler { self.deliver(nix::sys::signal::Signal::SIGHUP) } } + +#[cfg(test)] +mod tests { + use super::{launch_cmd_line, process_launch_event}; + + #[test] + fn launch_event_carries_redacted_command_line() { + let args = [ + "--name".to_string(), + "two words".to_string(), + "--token=s3cret".to_string(), + ]; + let event = process_launch_event( + "/usr/bin/agent", + &launch_cmd_line("/usr/bin/agent", &args), + 42, + ); + let json = event.to_json().unwrap(); + + assert_eq!(json["process"]["name"], "/usr/bin/agent"); + assert_eq!(json["process"]["pid"], 42); + assert_eq!( + json["process"]["cmd_line"], + r#"/usr/bin/agent --name "two words" --token=[REDACTED]"# + ); + assert_eq!(json["message"], "Process started: pid=42"); + assert!(!json.to_string().contains("s3cret")); + } +} diff --git a/crates/openshell-sandbox/src/process_events.rs b/crates/openshell-sandbox/src/process_events.rs index 8fffe0c90c..b2e4480ab4 100644 --- a/crates/openshell-sandbox/src/process_events.rs +++ b/crates/openshell-sandbox/src/process_events.rs @@ -35,9 +35,10 @@ pub struct Launched { executable: String, } -/// Record the launch of a process the runtime just spawned from `program`. -/// `None` when procfs no longer reports it. -pub fn record_launch(pid: u32, program: &str) -> Option { +/// Record the launch of a process the runtime just spawned from `program`, +/// with its redacted `cmd_line` (empty when not recorded). `None` when procfs +/// no longer reports it. +pub fn record_launch(pid: u32, program: &str, cmd_line: &str) -> Option { let Some(process) = openshell_binary_identity::observe_process(pid) else { tracing::warn!( pid, @@ -48,7 +49,12 @@ pub fn record_launch(pid: u32, program: &str) -> Option { // A process that already exited has no readable executable link. let executable = std::fs::read_link(format!("/proc/{pid}/exe")) .map_or_else(|_| program.to_string(), |path| path.display().to_string()); - log().record(process, &executable, ProcessEventKindWire::Launched); + log().record( + process, + &executable, + cmd_line, + ProcessEventKindWire::Launched, + ); Some(Launched { process, executable, @@ -65,6 +71,7 @@ impl Launched { log().record( self.process, &self.executable, + "", ProcessEventKindWire::Exited(status), ); } @@ -98,7 +105,13 @@ impl ProcessEventLog { } } - pub fn record(&self, process: ProcessInstance, executable: &str, kind: ProcessEventKindWire) { + pub fn record( + &self, + process: ProcessInstance, + executable: &str, + cmd_line: &str, + kind: ProcessEventKindWire, + ) { let time_ms = SystemTime::now() .duration_since(UNIX_EPOCH) .ok() @@ -110,6 +123,7 @@ impl ProcessEventLog { executable: executable.to_string(), kind, time_ms, + cmd_line: cmd_line.to_string(), }; // An event the protocol cannot carry would fail every read after it. if let Err(error) = event.to_proto() { @@ -190,7 +204,7 @@ impl ProcessEventLog { /// An upper bound on one event's encoded size. fn encoded_size(event: &ProcessEventWire) -> usize { - event.executable.len() + 128 + event.executable.len() + event.cmd_line.len() + 128 } #[cfg(test)] @@ -210,13 +224,14 @@ mod tests { #[test] fn read_returns_events_after_the_cursor_in_order() { let log = ProcessEventLog::new(8); - log.record(process(10), "/bin/sh", ProcessEventKindWire::Launched); + log.record(process(10), "/bin/sh", "", ProcessEventKindWire::Launched); log.record( process(10), "/bin/sh", + "", ProcessEventKindWire::Exited(ExitStatusWire::Exited(3)), ); - log.record(process(11), "/bin/true", ProcessEventKindWire::Launched); + log.record(process(11), "/bin/true", "", ProcessEventKindWire::Launched); let (events, lost) = log.read(Some(1), MAX_READ, Duration::ZERO); assert_eq!(lost, 0); @@ -242,7 +257,12 @@ mod tests { fn evicted_events_after_the_cursor_are_counted_as_lost() { let log = ProcessEventLog::new(2); for pid in 1..=5 { - log.record(process(pid), "/bin/true", ProcessEventKindWire::Launched); + log.record( + process(pid), + "/bin/true", + "", + ProcessEventKindWire::Launched, + ); } let (events, lost) = log.read(Some(1), MAX_READ, Duration::ZERO); @@ -263,7 +283,7 @@ mod tests { let log = ProcessEventLog::new(MAX_READ); let path = format!("/{}", "a".repeat(4095)); for pid in 1..=u32::try_from(MAX_READ).unwrap() { - log.record(process(pid), &path, ProcessEventKindWire::Launched); + log.record(process(pid), &path, "", ProcessEventKindWire::Launched); } let (events, _) = log.read(Some(0), MAX_READ, Duration::ZERO); @@ -287,7 +307,7 @@ mod tests { fn an_event_records_when_it_happened() { let log = ProcessEventLog::new(8); let before = now_ms(); - log.record(process(7), "/bin/sh", ProcessEventKindWire::Launched); + log.record(process(7), "/bin/sh", "", ProcessEventKindWire::Launched); let (events, _) = log.read(Some(0), MAX_READ, Duration::ZERO); assert!(events[0].time_ms >= before); assert!(events[0].time_ms <= now_ms()); @@ -311,7 +331,12 @@ mod tests { fn a_read_without_a_cursor_resumes_after_the_last_acknowledged_sequence() { let log = ProcessEventLog::new(8); for pid in 1..=5 { - log.record(process(pid), "/bin/true", ProcessEventKindWire::Launched); + log.record( + process(pid), + "/bin/true", + "", + ProcessEventKindWire::Launched, + ); } let (events, _) = log.read(None, MAX_READ, Duration::ZERO); assert_eq!(sequences(&events), [1, 2, 3, 4, 5]); @@ -323,7 +348,7 @@ mod tests { log.read(Some(1), MAX_READ, Duration::ZERO); log.read(Some(99), MAX_READ, Duration::ZERO); - log.record(process(6), "/bin/true", ProcessEventKindWire::Launched); + log.record(process(6), "/bin/true", "", ProcessEventKindWire::Launched); let (events, _) = log.read(None, MAX_READ, Duration::ZERO); assert_eq!(sequences(&events), [6]); } @@ -348,8 +373,8 @@ mod tests { let log = ProcessEventLog::new(8); let mut unencodable = process(9); unencodable.start_time_ms = -1; - log.record(unencodable, "/bin/sh", ProcessEventKindWire::Launched); - log.record(process(10), "/bin/sh", ProcessEventKindWire::Launched); + log.record(unencodable, "/bin/sh", "", ProcessEventKindWire::Launched); + log.record(process(10), "/bin/sh", "", ProcessEventKindWire::Launched); let (events, lost) = log.read(Some(0), MAX_READ, Duration::ZERO); assert_eq!(lost, 0); @@ -369,7 +394,7 @@ mod tests { let writer = log.clone(); let recorder = std::thread::spawn(move || { std::thread::sleep(Duration::from_millis(20)); - writer.record(process(7), "/bin/sh", ProcessEventKindWire::Launched); + writer.record(process(7), "/bin/sh", "", ProcessEventKindWire::Launched); }); let (events, _) = log.read(Some(0), MAX_READ, Duration::from_secs(10)); recorder.join().unwrap(); diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 46709329b6..fa71b005c1 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -1156,8 +1156,8 @@ fn build_staged_transparent_denial_event( reason: &str, status_detail: &'static str, ) -> openshell_ocsf::OcsfEvent { - let (binary, ancestors, cmdline, process) = identity.as_ref().map_or_else( - |_| ("-".to_string(), "-".to_string(), "-".to_string(), None), + let (binary, ancestors, process) = identity.as_ref().map_or_else( + |_| ("-".to_string(), "-".to_string(), None), |identity| { ( identity.executable.path.display().to_string(), @@ -1167,12 +1167,6 @@ fn build_staged_transparent_denial_event( .map(|ancestor| ancestor.path.display().to_string()) .collect::>() .join(" -> "), - identity - .cmdline_paths - .iter() - .map(|path| path.display().to_string()) - .collect::>() - .join(", "), identity.process, ) }, @@ -1185,9 +1179,7 @@ fn build_staged_transparent_denial_event( .severity(SeverityId::Medium) .status(StatusId::Failure) .dst_endpoint(transparent_destination_endpoint(destination, mapped_host)) - .actor_process(egress::actor_process( - &binary, &pid, &ancestors, &cmdline, process, - )) + .actor_process(egress::actor_process(&binary, &pid, &ancestors, process)) .message(format!("Transparent TCP denied before relay: {reason}")) .status_detail(status_detail) .build() @@ -2512,7 +2504,6 @@ impl std::fmt::Display for DestinationCheckError { } } -#[allow(clippy::too_many_arguments)] fn build_connect_destination_deny_ocsf_event( denial: &DestinationDenial, peer_addr: SocketAddr, @@ -8049,8 +8040,7 @@ process: parent_pid: 77, start_time_ms: 1, }; - let actor = - egress::actor_process("/usr/bin/bash", "81", "/usr/bin/bash", "-", Some(process)); + let actor = egress::actor_process("/usr/bin/bash", "81", "/usr/bin/bash", Some(process)); let parent = actor.parent_process.expect("parent process"); assert_eq!(parent.name, "/usr/bin/bash"); assert_eq!(parent.pid, 77); @@ -10137,6 +10127,40 @@ process: { run_as_user: sandbox, run_as_group: sandbox } ); } + #[test] + fn network_events_do_not_present_cmdline_paths_as_cmd_line() { + let identity = Ok(ContractBinaryIdentity { + executable: ContractExecutableIdentity { + path: executable_path("/usr/bin/python3"), + digest: Some("44".repeat(32).parse().unwrap()), + }, + ancestors: Vec::new(), + cmdline_paths: vec![PathBuf::from("/app/main.py")], + process: None, + }); + let denied = build_staged_transparent_denial_event( + "203.0.113.7:443".parse().unwrap(), + None, + &identity, + "endpoint 203.0.113.7:443 is not allowed by any policy", + "transparent_tcp_policy_denied", + ); + let allowed = build_connect_allow_ocsf_event( + "127.0.0.1:45123".parse().unwrap(), + "example.com", + 443, + &Process::from_bypass("/usr/bin/python3", "42", "/usr/bin/bash"), + "allow_example", + false, + "opa", + ); + for event in [denied, allowed] { + let json = serde_json::to_value(event).unwrap(); + assert!(json["actor"]["process"].get("cmd_line").is_none(), "{json}"); + assert!(!json.to_string().contains("/app/main.py"), "{json}"); + } + } + #[tokio::test] async fn staged_policy_local_open_reaches_the_sandbox_scoped_api() { let addr = crate::policy_dns::POLICY_LOCAL_ADDRESS; @@ -12067,9 +12091,9 @@ network_policies: record["actor"]["process"]["name"], binary.to_string_lossy().as_ref() ); - assert_eq!( - record["actor"]["process"]["cmd_line"], - command.to_string_lossy().as_ref() + assert!( + record["actor"]["process"].get("cmd_line").is_none(), + "{record}" ); assert!( record["message"] @@ -13280,8 +13304,7 @@ network_policies: "api.example.com", 80, "/v1/models", - &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash") - .with_cmd_line("curl http://api.example.com/v1/models"), + &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash"), reason, "opa", ); @@ -13300,8 +13323,7 @@ network_policies: "api.example.com", 80, "/admin/x%2Fy", - &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash") - .with_cmd_line("curl http://api.example.com/admin/x%2Fy"), + &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash"), "allow_api", FORWARD_ENCODED_SLASH_REJECTION_DETAIL, ); @@ -13474,7 +13496,7 @@ network_policies: "api.example.com", 80, &path, - &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash").with_cmd_line("curl"), + &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash"), "allow_api", "opa", ) @@ -13486,7 +13508,7 @@ network_policies: "api.example.com", 80, &path, - &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash").with_cmd_line("curl"), + &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash"), "policy denied", "opa", ) @@ -13510,7 +13532,7 @@ network_policies: &host, port, &forward_telemetry_path(target), - &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash").with_cmd_line("curl"), + &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/bash"), "allow_api", "opa", ) diff --git a/crates/openshell-supervisor-network/src/proxy/egress.rs b/crates/openshell-supervisor-network/src/proxy/egress.rs index 2094953b52..eaa9acde2f 100644 --- a/crates/openshell-supervisor-network/src/proxy/egress.rs +++ b/crates/openshell-supervisor-network/src/proxy/egress.rs @@ -216,17 +216,12 @@ impl EgressDecision { join_paths(&self.ancestors, " -> ") } - pub(super) fn cmdline_display(&self) -> String { - join_paths(&self.cmdline_paths, ", ") - } - /// OCSF actor for the process that owns the connection. pub(super) fn actor_process(&self) -> Process { actor_process( &self.binary_display(), &self.pid_display(), &self.ancestors_display(), - &self.cmdline_display(), self.process, ) } @@ -236,10 +231,9 @@ pub(super) fn actor_process( binary: &str, pid: &str, ancestors: &str, - cmdline: &str, process: Option, ) -> Process { - let mut actor = Process::from_bypass(binary, pid, ancestors).with_cmd_line(cmdline); + let mut actor = Process::from_bypass(binary, pid, ancestors); let Some(process) = process else { return actor; }; diff --git a/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs b/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs index a06cf90b05..aa50ae6f1e 100644 --- a/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs +++ b/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs @@ -101,7 +101,7 @@ async fn destination_denials_preserve_adapter_specific_wire_contracts() { "target.example", 8443, "/usr/bin/curl", - &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/sh").with_cmd_line("curl"), + &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/sh"), &allowed_decision(EgressIntent::connect("target.example".to_string(), 8443)), &None, &None, @@ -146,7 +146,7 @@ async fn destination_denials_preserve_adapter_specific_wire_contracts() { 8080, "/v1/items", "/usr/bin/curl", - &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/sh").with_cmd_line("curl"), + &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/sh"), "proxy_compatibility", &allowed_decision(EgressIntent::forward_http( "target.example".to_string(), @@ -188,7 +188,7 @@ fn representative_adapter_denials_preserve_ocsf_fields() { peer, "target.example", 8443, - &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/sh").with_cmd_line("curl --proxy"), + &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/sh"), )) .unwrap(); assert_eq!(connect["class_name"], "Network Activity"); @@ -216,7 +216,7 @@ fn representative_adapter_denials_preserve_ocsf_fields() { "target.example", 8080, "/v1/items", - &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/sh").with_cmd_line("curl --proxy"), + &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/sh"), "proxy_compatibility", )) .unwrap(); @@ -245,7 +245,7 @@ fn representative_adapter_allows_preserve_ocsf_fields() { peer, "target.example", 8443, - &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/sh").with_cmd_line("curl --proxy"), + &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/sh"), "proxy_compatibility", true, "opa", @@ -270,7 +270,7 @@ fn representative_adapter_allows_preserve_ocsf_fields() { "target.example", 8080, "/v1/items", - &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/sh").with_cmd_line("curl --proxy"), + &Process::from_bypass("/usr/bin/curl", "42", "/usr/bin/sh"), "proxy_compatibility", "opa", )) diff --git a/crates/openshell-supervisor-network/src/proxy/trace_tests.rs b/crates/openshell-supervisor-network/src/proxy/trace_tests.rs index b3032894b9..9b087f9c88 100644 --- a/crates/openshell-supervisor-network/src/proxy/trace_tests.rs +++ b/crates/openshell-supervisor-network/src/proxy/trace_tests.rs @@ -130,7 +130,7 @@ async fn forward_denials_use_the_saved_connect_parent() { 443, "/", "curl", - &Process::from_bypass("curl", "42", "-").with_cmd_line("curl"), + &Process::from_bypass("curl", "42", "-"), "forward-policy", &decision, None, diff --git a/crates/openshell-supervisor/src/process_activity.rs b/crates/openshell-supervisor/src/process_activity.rs index 8f78ead2e9..cbd6d58fd3 100644 --- a/crates/openshell-supervisor/src/process_activity.rs +++ b/crates/openshell-supervisor/src/process_activity.rs @@ -142,9 +142,12 @@ fn process_activity(event: &ProcessEventWire) -> OcsfEvent { } else { event.executable.as_str() }; - let process = Process::new(name, i64::from(instance.pid)) + let mut process = Process::new(name, i64::from(instance.pid)) .with_parent(launcher()) .with_instance(instance.parent_pid, instance.start_time_ms); + if !event.cmd_line.is_empty() { + process = process.with_cmd_line(&event.cmd_line); + } let kind = match event.kind { ProcessEventKindWire::Launched => "launch", ProcessEventKindWire::Exited(_) => "exit", @@ -209,6 +212,7 @@ mod tests { executable: "/usr/bin/sh".to_string(), kind, time_ms: 1_793_750_400_200 + i64::try_from(sequence).unwrap(), + cmd_line: String::new(), } } @@ -234,6 +238,7 @@ mod tests { assert_eq!(launch["process"]["parent_process"]["pid"], 1); assert_eq!(launch["actor"]["process"]["name"], "openshell-sandbox"); assert_eq!(launch["actor"]["process"]["pid"], 1); + assert!(launch["process"].get("cmd_line").is_none()); let exit = serde_json::to_value(&emitted[1]).unwrap(); assert_eq!(exit["activity_name"], "Terminate"); @@ -256,6 +261,22 @@ mod tests { assert_eq!(clean["status"], "Success"); } + #[test] + fn launch_carries_the_recorded_command_line() { + let mut launch = event(1, ProcessEventKindWire::Launched); + launch.cmd_line = "/usr/bin/sh -c true".to_string(); + let launch = process_activity(&launch); + assert_eq!( + serde_json::to_value(&launch).unwrap()["process"]["cmd_line"], + "/usr/bin/sh -c true" + ); + assert!( + launch + .format_shorthand() + .contains("PROC:LAUNCH [INFO] /usr/bin/sh(57) [cmd:/usr/bin/sh -c true]") + ); + } + #[test] fn a_replayed_event_keeps_its_time_and_uid() { let launch = event(1, ProcessEventKindWire::Launched); diff --git a/docs/observability/logging.mdx b/docs/observability/logging.mdx index 3dfdc72635..5dc7b2a8f2 100644 --- a/docs/observability/logging.mdx +++ b/docs/observability/logging.mdx @@ -195,7 +195,7 @@ OCSF SSH:OPEN [INFO] ALLOWED A process launched inside the sandbox: ```text -OCSF PROC:LAUNCH [INFO] /usr/bin/sleep(49) +OCSF PROC:LAUNCH [INFO] /usr/bin/sleep(49) [cmd:sleep 60] ``` The same process exiting with status 3: diff --git a/docs/observability/ocsf-json-export.mdx b/docs/observability/ocsf-json-export.mdx index 46f541ebd3..38caebecb6 100644 --- a/docs/observability/ocsf-json-export.mdx +++ b/docs/observability/ocsf-json-export.mdx @@ -288,8 +288,7 @@ And a denied connection, produced when `curl https://github.com` runs in a sandb "actor": { "process": { "name": "/usr/bin/curl", - "pid": 2187, - "cmd_line": "curl https://github.com" + "pid": 2187 } }, "action_id": 2, @@ -442,6 +441,8 @@ Connection-error records include the known peer or listening endpoint. Policy configuration warnings use Device Config State Change. +Process Activity launch records for the sandbox entrypoint carry the launched command and its arguments in `process.cmd_line`. OpenShell quotes arguments that contain spaces, escapes control characters, and keeps at most 64 arguments and 1024 characters, marking truncation with `…`. It redacts values of options and variables whose names suggest a secret, such as `--token` or `API_KEY=`, well-known credential formats, and URL credentials, queries, and fragments. Redaction is best-effort and cannot catch a secret passed as a plain argument. Network and HTTP Activity records do not include `cmd_line`. + Unix socket relay and relay-control notifications, and proxy or mediation failures without an observed network endpoint, use Base Event (`class_uid: 0`). Include these classes when filtering supervisor operational events. Relay-control diff --git a/proto/sandbox_protocol.proto b/proto/sandbox_protocol.proto index 2e66118d5b..f8a7c7b368 100644 --- a/proto/sandbox_protocol.proto +++ b/proto/sandbox_protocol.proto @@ -256,6 +256,8 @@ message ProcessEvent { } // When the runtime observed the launch or exit. google.protobuf.Timestamp time = 6; + // Redacted, bounded command line of a launch; empty when not recorded. + string cmd_line = 7; } message ProcessLaunched {} message LoopbackConnected {}