Skip to content

Commit 024e0a4

Browse files
committed
feat(supervisor): record the command line of each process
Process Activity named each process by its executable only, so a record of /usr/bin/bash or /usr/bin/python3 did not say what it was asked to run. When the ocsf_process_cmdline_enabled setting is on, the runtime records each process's arguments with its launch: the argv it started the entrypoint or a session with, and the argv each exec in the workload passes, read from the caller's memory. It keeps up to 256 arguments and 4 KiB per process and marks a shortened list. The supervisor applies the setting through ReadProcessEvents alongside ocsf_process_exec_enabled, reports command lines only while the setting asks for them, and sets process.cmd_line on Launch records with the arguments quoted as a shell would read them, control characters ANSI-C quoted, and a trailing … when shortened. The shorthand log also escapes control characters and `]` in the command line so a workload cannot forge log lines. Arguments can hold secrets, so the setting is off by default and separate from exec recording. An exec's arguments are read before the kernel runs it, so another thread can change them first. Refs #4268 Signed-off-by: Kris Hicks <khicks@nvidia.com>
1 parent 5e43be6 commit 024e0a4

17 files changed

Lines changed: 639 additions & 78 deletions

File tree

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,13 @@ pub const REGISTERED_SETTINGS: &[RegisteredSetting] = &[
122122
kind: SettingValueKind::Bool,
123123
allowed_string_values: None,
124124
},
125+
// Whether the sandbox records the arguments of each process it reports
126+
// as OCSF Process Activity. Arguments can hold secrets. Defaults to false.
127+
RegisteredSetting {
128+
key: "ocsf_process_cmdline_enabled",
129+
kind: SettingValueKind::Bool,
130+
allowed_string_values: None,
131+
},
125132
// Deprecated and ignored: OpenShell emits OCSF 1.8.0 only. Still
126133
// registered so existing values load; the supervisor reports a set value.
127134
RegisteredSetting {

‎crates/openshell-ocsf/src/format/shorthand.rs‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
//!
66
//! Pattern: `<HH:MM:SS.mmm> <severity> <CLASS:ACTIVITY> <action> <key fields> [context]`
77
8+
use std::fmt::Write as _;
9+
810
use crate::enums::UserTypeId;
911
use crate::events::OcsfEvent;
1012
use crate::events::base_event::BaseEventData;
@@ -102,6 +104,30 @@ fn escape_quoted_field(text: &str) -> String {
102104
escaped
103105
}
104106

107+
/// A command line kept to one line that cannot end its context early:
108+
/// control and text-direction characters as `\uXXXX`, and `]` escaped.
109+
fn escape_command_line(text: &str) -> String {
110+
let mut escaped = String::with_capacity(text.len());
111+
for character in text.chars() {
112+
match character {
113+
']' => escaped.push_str("\\]"),
114+
c if c.is_control() || is_direction_control(c) => {
115+
let _ = write!(escaped, "\\u{:04x}", u32::from(c));
116+
}
117+
c => escaped.push(c),
118+
}
119+
}
120+
escaped
121+
}
122+
123+
/// Unicode characters that change how the text around them displays.
124+
pub fn is_direction_control(character: char) -> bool {
125+
matches!(
126+
character,
127+
'\u{200e}' | '\u{200f}' | '\u{2028}' | '\u{2029}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}'
128+
)
129+
}
130+
105131
fn escape_context_field(text: &str) -> String {
106132
let mut escaped = String::with_capacity(text.len());
107133
for character in text.chars() {
@@ -526,7 +552,7 @@ impl OcsfEvent {
526552
.process
527553
.cmd_line
528554
.as_ref()
529-
.map(|c| format!(" [cmd:{c}]"))
555+
.map(|c| format!(" [cmd:{}]", escape_command_line(c)))
530556
.unwrap_or_default();
531557
let count_ctx = e
532558
.base
@@ -1261,6 +1287,25 @@ mod tests {
12611287
);
12621288
}
12631289

1290+
#[test]
1291+
fn process_activity_shorthand_keeps_a_command_line_on_one_line() {
1292+
let event = OcsfEvent::ProcessActivity(ProcessActivityEvent {
1293+
base: base(1007, "Process Activity", 1, "System Activity", 1, "Launch"),
1294+
process: Process::new("/usr/bin/sh", 7)
1295+
.with_cmd_line("sh -c x\nOCSF NET:OPEN] \u{1b}[31m"),
1296+
actor: None,
1297+
launch_type: None,
1298+
exit_code: None,
1299+
action: None,
1300+
disposition: None,
1301+
});
1302+
1303+
assert_eq!(
1304+
event.format_shorthand(),
1305+
"PROC:LAUNCH [INFO] /usr/bin/sh(7) [cmd:sh -c x\\u000aOCSF NET:OPEN\\] \\u001b[31m]"
1306+
);
1307+
}
1308+
12641309
#[test]
12651310
fn test_detection_finding_shorthand() {
12661311
let event = OcsfEvent::DetectionFinding(DetectionFindingEvent {

‎crates/openshell-ocsf/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ pub use objects::{
5858
};
5959

6060
// --- Sanitizers ---
61+
pub use format::shorthand::is_direction_control;
6162
pub use sanitize::sanitize_reason_for_audit;
6263

6364
// --- Builders ---

‎crates/openshell-sandbox-backend/src/boundary_protocol.rs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -867,6 +867,9 @@ pub enum Request {
867867
/// Whether the runtime records each exec in the workload from now on.
868868
/// `None` keeps its current choice.
869869
executions: Option<bool>,
870+
/// Whether the runtime records each process's command line from now
871+
/// on. `None` keeps its current choice.
872+
command_lines: Option<bool>,
870873
},
871874
}
872875

@@ -984,10 +987,12 @@ impl fmt::Debug for Request {
984987
Self::ReadProcessEvents {
985988
after_sequence,
986989
executions,
990+
command_lines,
987991
} => formatter
988992
.debug_struct("ReadProcessEvents")
989993
.field("after_sequence", after_sequence)
990994
.field("executions", executions)
995+
.field("command_lines", command_lines)
991996
.finish(),
992997
}
993998
}
@@ -1071,6 +1076,17 @@ pub struct ProcessEventWire {
10711076
pub kind: ProcessEventKindWire,
10721077
/// When the runtime observed the event, in milliseconds since the epoch.
10731078
pub time_ms: i64,
1079+
/// The arguments of a launched or executed process, when recorded.
1080+
#[serde(default)]
1081+
pub command_line: Option<CommandLineWire>,
1082+
}
1083+
1084+
/// A process's arguments, `truncated` when only the first were kept.
1085+
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1086+
#[serde(deny_unknown_fields)]
1087+
pub struct CommandLineWire {
1088+
pub arguments: Vec<String>,
1089+
pub truncated: bool,
10741090
}
10751091

10761092
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]

‎crates/openshell-sandbox-backend/src/protobuf.rs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -476,6 +476,13 @@ impl WireMessage for w::ProcessEventWire {
476476
}),
477477
}),
478478
time: Some(timestamp(u64::try_from(self.time_ms).map_err(invalid)?)?),
479+
command_line: self
480+
.command_line
481+
.as_ref()
482+
.map(|command_line| p::CommandLine {
483+
arguments: command_line.arguments.clone(),
484+
truncated: command_line.truncated,
485+
}),
479486
})
480487
}
481488
fn from_proto(v: Self::Proto) -> Result<Self, FrameError> {
@@ -505,6 +512,10 @@ impl WireMessage for w::ProcessEventWire {
505512
executable: v.executable,
506513
kind,
507514
time_ms: i64::try_from(millis(required(v.time)?)?).map_err(invalid)?,
515+
command_line: v.command_line.map(|command_line| w::CommandLineWire {
516+
arguments: command_line.arguments,
517+
truncated: command_line.truncated,
518+
}),
508519
})
509520
}
510521
}
@@ -619,9 +630,11 @@ impl WireMessage for w::RequestEnvelope {
619630
W::ReadProcessEvents {
620631
after_sequence,
621632
executions,
633+
command_lines,
622634
} => P::ReadProcessEvents(p::ReadProcessEvents {
623635
after_sequence: *after_sequence,
624636
executions: *executions,
637+
command_lines: *command_lines,
625638
}),
626639
};
627640
Ok(p::RequestEnvelope {
@@ -694,6 +707,7 @@ impl WireMessage for w::RequestEnvelope {
694707
P::ReadProcessEvents(v) => W::ReadProcessEvents {
695708
after_sequence: v.after_sequence,
696709
executions: v.executions,
710+
command_lines: v.command_lines,
697711
},
698712
};
699713
// The server derives a fingerprint from decoded typed fields. Clients
@@ -1096,13 +1110,15 @@ mod tests {
10961110
executable: "/usr/bin/sh".to_string(),
10971111
kind: w::ProcessEventKindWire::Launched,
10981112
time_ms: 1_793_750_400_200,
1113+
command_line: None,
10991114
},
11001115
w::ProcessEventWire {
11011116
sequence: 5,
11021117
process,
11031118
executable: "/usr/bin/sh".to_string(),
11041119
kind: w::ProcessEventKindWire::Exited(w::ExitStatusWire::Signaled(9)),
11051120
time_ms: 1_793_750_401_000,
1121+
command_line: None,
11061122
},
11071123
],
11081124
lost: 3,
@@ -1116,6 +1132,7 @@ mod tests {
11161132
let request = w::Request::ReadProcessEvents {
11171133
after_sequence: 3,
11181134
executions: Some(true),
1135+
command_lines: Some(false),
11191136
};
11201137
let envelope = w::RequestEnvelope {
11211138
request_id: uuid::Uuid::new_v4().to_string(),
@@ -1146,6 +1163,10 @@ mod tests {
11461163
parent_executable: "/usr/bin/dash".to_string(),
11471164
},
11481165
time_ms: 1_793_750_400_310,
1166+
command_line: Some(w::CommandLineWire {
1167+
arguments: vec!["true".to_string(), "--version".to_string()],
1168+
truncated: true,
1169+
}),
11491170
},
11501171
w::ProcessEventWire {
11511172
sequence: 7,
@@ -1157,6 +1178,7 @@ mod tests {
11571178
executable: "/opt/openshell/bin/openshell-sandbox".to_string(),
11581179
kind: w::ProcessEventKindWire::Suppressed { count: 12 },
11591180
time_ms: 1_793_750_400_320,
1181+
command_line: None,
11601182
},
11611183
w::ProcessEventWire {
11621184
sequence: 8,
@@ -1168,6 +1190,7 @@ mod tests {
11681190
executable: "/usr/bin/true".to_string(),
11691191
kind: w::ProcessEventKindWire::Ended(Some(w::ExitStatusWire::Exited(3))),
11701192
time_ms: 1_793_750_400_330,
1193+
command_line: None,
11711194
},
11721195
w::ProcessEventWire {
11731196
sequence: 9,
@@ -1179,6 +1202,7 @@ mod tests {
11791202
executable: "/usr/bin/true".to_string(),
11801203
kind: w::ProcessEventKindWire::Ended(None),
11811204
time_ms: 1_793_750_400_340,
1205+
command_line: None,
11821206
},
11831207
],
11841208
lost: 0,

‎crates/openshell-sandbox-backend/src/runtime.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -927,17 +927,20 @@ impl ProcessEventSource {
927927
/// Events after `after_sequence` and how many of those the runtime no
928928
/// longer retains. Returns empty when none arrive within the runtime's
929929
/// read wait. `executions` sets whether the runtime records each exec
930-
/// from now on; it is ignored unless [`Self::records_executions`].
930+
/// from now on, and is ignored unless [`Self::records_executions`];
931+
/// `command_lines` sets whether it records each process's arguments.
931932
pub async fn read(
932933
&self,
933934
after_sequence: u64,
934935
executions: Option<bool>,
936+
command_lines: Option<bool>,
935937
) -> Result<(Vec<crate::boundary_protocol::ProcessEventWire>, u64), BackendError> {
936938
let response = self
937939
.client
938940
.call_wait(Request::ReadProcessEvents {
939941
after_sequence,
940942
executions: executions.filter(|_| self.records_executions()),
943+
command_lines,
941944
})
942945
.await?;
943946
let Response::ProcessEvents { events, lost } = response else {

‎crates/openshell-sandbox/src/boundary_exec.rs‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,10 @@ impl LocalBoundaryExec {
227227
self.runtime.ensure_active()?;
228228
let mut command = self.command(spec)?;
229229
let program = command.get_program().to_string_lossy().into_owned();
230+
let arguments: Vec<String> = command
231+
.get_args()
232+
.map(|argument| argument.to_string_lossy().into_owned())
233+
.collect();
230234
command
231235
.stdin(Stdio::piped())
232236
.stdout(Stdio::piped())
@@ -295,7 +299,7 @@ impl LocalBoundaryExec {
295299
let process = Arc::new(LocalExecProcess::new(
296300
child,
297301
pid,
298-
&program,
302+
crate::process_events::record_launch(pid, &program, &arguments),
299303
self.runtime.clone(),
300304
process_terminal,
301305
signal_lock,
@@ -342,6 +346,10 @@ impl LocalBoundaryExec {
342346
.map_err(|error| BackendError::Process(error.to_string()))?;
343347
let mut command = self.command(spec)?;
344348
let program = command.get_program().to_string_lossy().into_owned();
349+
let arguments: Vec<String> = command
350+
.get_args()
351+
.map(|argument| argument.to_string_lossy().into_owned())
352+
.collect();
345353
command.stdin(stdin).stdout(stdout).stderr(slave);
346354
let effective_workdir = spec.workdir.as_deref().or(self.base_workdir.as_deref());
347355
#[cfg(target_os = "linux")]
@@ -392,7 +400,7 @@ impl LocalBoundaryExec {
392400
let process = Arc::new(LocalExecProcess::new(
393401
child,
394402
pid,
395-
&program,
403+
crate::process_events::record_launch(pid, &program, &arguments),
396404
self.runtime.clone(),
397405
process_terminal,
398406
signal_lock,
@@ -576,7 +584,7 @@ impl LocalExecProcess {
576584
fn new(
577585
child: Child,
578586
pid: u32,
579-
program: &str,
587+
launched: Option<crate::process_events::Launched>,
580588
runtime: Arc<crate::boundary_io::BoundaryRuntimeState>,
581589
terminal: Arc<std::sync::atomic::AtomicBool>,
582590
signal_lock: Arc<std::sync::Mutex<()>>,
@@ -591,7 +599,6 @@ impl LocalExecProcess {
591599
let registration_terminal = terminal.clone();
592600
#[cfg(target_os = "linux")]
593601
let signal_lock_for_wait = signal_lock.clone();
594-
let launched = crate::process_events::record_launch(pid, program);
595602
tokio::spawn(async move {
596603
let waited = tokio::task::spawn_blocking(move || {
597604
let mut child = child;

‎crates/openshell-sandbox/src/boundary_server.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3421,10 +3421,14 @@ mod linux {
34213421
Request::ReadProcessEvents {
34223422
after_sequence,
34233423
executions,
3424+
command_lines,
34243425
} => {
34253426
if let Some(executions) = executions {
34263427
crate::process_events::set_record_executions(executions);
34273428
}
3429+
if let Some(command_lines) = command_lines {
3430+
crate::process_events::set_record_command_lines(command_lines);
3431+
}
34283432
let (events, lost) = crate::process_events::log().read(
34293433
after_sequence,
34303434
crate::process_events::MAX_READ,
@@ -9001,6 +9005,7 @@ mod linux {
90019005
let read_events = Request::ReadProcessEvents {
90029006
after_sequence: 0,
90039007
executions: None,
9008+
command_lines: None,
90049009
};
90059010
assert!(
90069011
boundary

‎crates/openshell-sandbox/src/delegated.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ pub async fn spawn_workload(
144144
.build()
145145
);
146146

147-
let recorded_launch = crate::process_events::record_launch(handle.pid(), program);
147+
let recorded_launch = crate::process_events::record_launch(handle.pid(), program, args);
148148

149149
Ok(SpawnedAgent {
150150
handle,

0 commit comments

Comments
 (0)