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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

48 changes: 48 additions & 0 deletions crates/openshell-binary-identity/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,20 @@ fn resolve_linux_process(
})
}

/// The process that owns task `tid`, as procfs reports it now. `None` when
/// procfs does not report it.
#[cfg(target_os = "linux")]
#[must_use]
pub fn observe_process(tid: u32) -> Option<ProcessInstance> {
let pid = thread_group_id(tid).ok()?;
let (parent_pid, start_time) = process_stat(pid).ok()?;
Some(ProcessInstance {
pid,
parent_pid,
start_time_ms: start_time_ms(start_time)?,
})
}

/// The process that owns `snapshot`'s task. A connection's task can be any
/// thread, so the PID and start time are the thread-group leader's. Audit
/// context only: unreadable values leave the identity without a process.
Expand Down Expand Up @@ -797,6 +811,40 @@ mod tests {
assert!(now_ms - leader.start_time_ms < 600_000);
}

#[test]
fn observed_process_matches_the_resolved_identity() {
let pid = std::process::id();
let resolved = ProcfsIdentityResolver::for_process_tree(pid)
.resolve(pid)
.expect("resolve")
.process;
assert!(resolved.is_some());
assert_eq!(observe_process(pid), resolved);
assert_eq!(observe_process(u32::MAX), None);
}

#[test]
fn observing_a_thread_reports_its_process() {
let (tid_tx, tid_rx) = std::sync::mpsc::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
let thread = std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(20));
let link = std::fs::read_link("/proc/thread-self").unwrap();
let tid: u32 = link
.file_name()
.and_then(|name| name.to_str())
.and_then(|name| name.parse().ok())
.unwrap();
tid_tx.send(tid).unwrap();
let _ = release_rx.recv();
});
let tid = tid_rx.recv().unwrap();
let observed = observe_process(tid);
drop(release_tx);
thread.join().unwrap();
assert_eq!(observed, observe_process(std::process::id()));
}

#[test]
fn process_tree_root_does_not_escape_into_host_ancestry() {
let pid = std::process::id();
Expand Down
14 changes: 14 additions & 0 deletions crates/openshell-core/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,20 @@ pub const REGISTERED_SETTINGS: &[RegisteredSetting] = &[
kind: SettingValueKind::Bool,
allowed_string_values: None,
},
// When true the sandbox records each exec in the workload and the
// supervisor emits it as OCSF Process Activity. Defaults to false.
RegisteredSetting {
key: "ocsf_process_exec_enabled",
kind: SettingValueKind::Bool,
allowed_string_values: None,
},
// Whether the sandbox records the arguments of each process it reports
// as OCSF Process Activity. Arguments can hold secrets. Defaults to false.
RegisteredSetting {
key: "ocsf_process_cmdline_enabled",
kind: SettingValueKind::Bool,
allowed_string_values: None,
},
// Deprecated and ignored: OpenShell emits OCSF 1.8.0 only. Still
// registered so existing values load; the supervisor reports a set value.
RegisteredSetting {
Expand Down
2 changes: 1 addition & 1 deletion crates/openshell-ocsf/src/builders/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ pub use finding::DetectionFindingBuilder;
pub use http::HttpActivityBuilder;
pub use lifecycle::AppLifecycleBuilder;
pub use network::NetworkActivityBuilder;
pub use process::ProcessActivityBuilder;
pub use process::{HasActor, ProcessActivityBuilder};
pub use ssh::SshActivityBuilder;

use std::net::IpAddr;
Expand Down
75 changes: 73 additions & 2 deletions crates/openshell-ocsf/src/builders/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ pub struct ProcessActivityBuilder<'a, ActorState = MissingActor> {
launch_type: Option<LaunchTypeId>,
exit_code: Option<i32>,
message: Option<String>,
time_ms: Option<i64>,
uid: Option<String>,
count: Option<u64>,
actor_state: std::marker::PhantomData<ActorState>,
}

Expand Down Expand Up @@ -55,6 +58,9 @@ impl<'a> ProcessActivityBuilder<'a, MissingActor> {
launch_type: None,
exit_code: None,
message: None,
time_ms: None,
uid: None,
count: None,
actor_state: std::marker::PhantomData,
}
}
Expand All @@ -74,6 +80,9 @@ impl<'a> ProcessActivityBuilder<'a, MissingActor> {
launch_type: self.launch_type,
exit_code: self.exit_code,
message: self.message,
time_ms: self.time_ms,
uid: self.uid,
count: self.count,
actor_state: std::marker::PhantomData,
}
}
Expand All @@ -100,6 +109,25 @@ impl<ActorState> ProcessActivityBuilder<'_, ActorState> {
self.exit_code = Some(code);
self
}
/// When the activity happened, if not when the event is built.
#[must_use]
pub fn time(mut self, time_ms: i64) -> Self {
self.time_ms = Some(time_ms);
self
}
/// How many occurrences the event stands for.
#[must_use]
pub fn count(mut self, count: u64) -> Self {
self.count = Some(count);
self
}
/// Replace the random event identifier with one that repeats when the
/// same activity is reported again.
#[must_use]
pub fn uid(mut self, uid: impl Into<String>) -> Self {
self.uid = Some(uid.into());
self
}
}

impl_activity_setter!(ProcessActivityBuilder<ActorState>);
Expand All @@ -110,6 +138,12 @@ impl ProcessActivityBuilder<'_, HasActor> {
#[must_use]
pub fn build(self) -> OcsfEvent {
let activity_name = self.activity.process_label().to_string();
let mut metadata = self
.ctx
.metadata(&["security_control", "container", "host"]);
if let Some(uid) = self.uid {
metadata.uid = Some(uid);
}
let mut base = BaseEventData::new(
1007,
"Process Activity",
Expand All @@ -118,9 +152,14 @@ impl ProcessActivityBuilder<'_, HasActor> {
self.activity.as_u8(),
&activity_name,
self.severity,
self.ctx
.metadata(&["security_control", "container", "host"]),
metadata,
);
if let Some(time_ms) = self.time_ms {
base.set_time(time_ms);
}
if let Some(count) = self.count {
base.set_count(count);
}
self.ctx
.apply_common_fields(&mut base, self.status, self.message);

Expand Down Expand Up @@ -176,4 +215,36 @@ mod tests {
let json = event.to_json().unwrap();
assert_eq!(json["exit_code"], 0);
}

#[test]
fn process_activity_carries_occurrence_time_and_event_uid() {
let ctx = test_sandbox_context();
let event = ProcessActivityBuilder::new(&ctx)
.activity(ActivityId::Close)
.process(Process::new("python3", 42))
.actor_process(Process::new("openshell-sandbox", 1))
.time(1_793_750_401_000)
.uid("proc:42:1793750400123:exit")
.build();

let json = event.to_json().unwrap();
assert_eq!(json["time"], 1_793_750_401_000_i64);
assert_eq!(json["metadata"]["uid"], "proc:42:1793750400123:exit");
}

#[test]
fn process_activity_carries_a_count() {
let ctx = test_sandbox_context();
let event = ProcessActivityBuilder::new(&ctx)
.activity(ActivityId::Other)
.process(Process::new("openshell-sandbox", 1))
.actor_process(Process::new("openshell-sandbox", 1))
.count(12)
.build();

let json = event.to_json().unwrap();
assert_eq!(json["count"], 12);
let round_trip: OcsfEvent = serde_json::from_value(json).unwrap();
assert_eq!(round_trip, event);
}
}
13 changes: 13 additions & 0 deletions crates/openshell-ocsf/src/events/base_event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ pub struct BaseEventData {
#[serde(skip_serializing_if = "Option::is_none")]
pub status_detail: Option<String>,

/// How many occurrences this event stands for.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<u64>,

/// Event metadata (schema version, product, profiles).
pub metadata: Metadata,

Expand Down Expand Up @@ -108,6 +112,9 @@ impl Serialize for BaseEventData {
if let Some(ref detail) = self.status_detail {
map.serialize_entry("status_detail", detail)?;
}
if let Some(count) = self.count {
map.serialize_entry("count", &count)?;
}
map.serialize_entry("metadata", &self.metadata)?;
if let Some(ref device) = self.device {
map.serialize_entry("device", device)?;
Expand Down Expand Up @@ -159,6 +166,7 @@ impl BaseEventData {
status: None,
message: None,
status_detail: None,
count: None,
metadata,
device: None,
ai_model: None,
Expand All @@ -182,6 +190,11 @@ impl BaseEventData {
self.message = Some(message.into());
}

/// Set how many occurrences this event stands for.
pub fn set_count(&mut self, count: u64) {
self.count = Some(count);
}

/// Set status detail.
pub fn set_status_detail(&mut self, detail: impl Into<String>) {
self.status_detail = Some(detail.into());
Expand Down
74 changes: 72 additions & 2 deletions crates/openshell-ocsf/src/format/shorthand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
//!
//! Pattern: `<HH:MM:SS.mmm> <severity> <CLASS:ACTIVITY> <action> <key fields> [context]`

use std::fmt::Write as _;

use crate::enums::UserTypeId;
use crate::events::OcsfEvent;
use crate::events::base_event::BaseEventData;
Expand Down Expand Up @@ -102,6 +104,30 @@ fn escape_quoted_field(text: &str) -> String {
escaped
}

/// A command line kept to one line that cannot end its context early:
/// control and text-direction characters as `\uXXXX`, and `]` escaped.
fn escape_command_line(text: &str) -> String {
let mut escaped = String::with_capacity(text.len());
for character in text.chars() {
match character {
']' => escaped.push_str("\\]"),
c if c.is_control() || is_direction_control(c) => {
let _ = write!(escaped, "\\u{:04x}", u32::from(c));
}
c => escaped.push(c),
}
}
escaped
}

/// Unicode characters that change how the text around them displays.
pub fn is_direction_control(character: char) -> bool {
matches!(
character,
'\u{200e}' | '\u{200f}' | '\u{2028}' | '\u{2029}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}'
)
}

fn escape_context_field(text: &str) -> String {
let mut escaped = String::with_capacity(text.len());
for character in text.chars() {
Expand Down Expand Up @@ -526,10 +552,15 @@ impl OcsfEvent {
.process
.cmd_line
.as_ref()
.map(|c| format!(" [cmd:{c}]"))
.map(|c| format!(" [cmd:{}]", escape_command_line(c)))
.unwrap_or_default();
let count_ctx = e
.base
.count
.map(|c| format!(" [count:{c}]"))
.unwrap_or_default();

format!("PROC:{activity} {sev} {proc_str}{exit_ctx}{cmd_ctx}")
format!("PROC:{activity} {sev} {proc_str}{exit_ctx}{cmd_ctx}{count_ctx}")
}

Self::DetectionFinding(e) => {
Expand Down Expand Up @@ -1236,6 +1267,45 @@ mod tests {
assert_eq!(shorthand, "PROC:TERMINATE [INFO] python3(42) [exit:0]");
}

#[test]
fn process_activity_shorthand_shows_the_count() {
let mut base = base(1007, "Process Activity", 1, "System Activity", 99, "Other");
base.set_count(251);
let event = OcsfEvent::ProcessActivity(ProcessActivityEvent {
base,
process: Process::new("openshell-sandbox", 1),
actor: None,
launch_type: None,
exit_code: None,
action: None,
disposition: None,
});

assert_eq!(
event.format_shorthand(),
"PROC:OTHER [INFO] openshell-sandbox(1) [count:251]"
);
}

#[test]
fn process_activity_shorthand_keeps_a_command_line_on_one_line() {
let event = OcsfEvent::ProcessActivity(ProcessActivityEvent {
base: base(1007, "Process Activity", 1, "System Activity", 1, "Launch"),
process: Process::new("/usr/bin/sh", 7)
.with_cmd_line("sh -c x\nOCSF NET:OPEN] \u{1b}[31m"),
actor: None,
launch_type: None,
exit_code: None,
action: None,
disposition: None,
});

assert_eq!(
event.format_shorthand(),
"PROC:LAUNCH [INFO] /usr/bin/sh(7) [cmd:sh -c x\\u000aOCSF NET:OPEN\\] \\u001b[31m]"
);
}

#[test]
fn test_detection_finding_shorthand() {
let event = OcsfEvent::DetectionFinding(DetectionFindingEvent {
Expand Down
1 change: 1 addition & 0 deletions crates/openshell-ocsf/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ pub use objects::{
};

// --- Sanitizers ---
pub use format::shorthand::is_direction_control;
pub use sanitize::sanitize_reason_for_audit;

// --- Builders ---
Expand Down
Loading
Loading