Skip to content

Commit 2251252

Browse files
jamieknvidiaaraza008
authored andcommitted
fix(mxc-etw): guard pending-event replay against PID recycling
CodeRabbit flagged that drain_resolved() re-resolved buffered events against the live by_pid map, so if Windows recycled a wxc-exec PID within PENDING_TTL a stale event from the dead sandbox could be emitted under the new owner. Stamp each by_pid registration with its Instant and add resolve_replay(), used only on the buffered/replay path. It (a) never falls back to the recycle-/ambiguity-prone by_cmd or last_pid_sid keys, and (b) trusts a PID match only when the registration is not newer than the buffered event by more than REPLAY_PID_GRACE (2s) - a recycled PID's registration lands well outside that window, so the stale event ages out instead of misattributing. The legitimate #2 seed race (registration lands ~immediately) still replays. Adds unit tests for the recycle-refusal, in-grace acceptance, and weak-fallback exclusion. Signed-off-by: Akber Raza <[email protected]>
1 parent 65647db commit 2251252

1 file changed

Lines changed: 152 additions & 13 deletions

File tree

‎crates/openshell-driver-mxc/src/etw_consumer.rs‎

Lines changed: 152 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -904,9 +904,27 @@ const PENDING_MAX: usize = 4096;
904904
/// unattributable (e.g. an unrelated Sandboxing-provider consumer on the box).
905905
const PENDING_TTL: Duration = Duration::from_secs(5);
906906

907+
/// Grace window for trusting a PID match when *replaying* a buffered event.
908+
/// The driver seeds `by_pid` within milliseconds of spawning `wxc-exec`, so a
909+
/// legitimate seed event's registration lands at (or just after) the moment the
910+
/// event was buffered. A recycled PID, by contrast, requires the prior
911+
/// `wxc-exec` to exit and a new one to spawn — far longer than this window — so
912+
/// a registration that is newer than the buffered event by more than this grace
913+
/// is treated as a *different* (recycled) owner and the PID match is refused.
914+
const REPLAY_PID_GRACE: Duration = Duration::from_secs(2);
915+
916+
/// A `wxc-exec` PID registration: which sandbox owns the PID and *when* it was
917+
/// registered. The timestamp lets the replay path (see [`AttributionIndex::
918+
/// resolve_replay`]) reject a PID that was recycled to a different sandbox after
919+
/// a still-buffered event was captured.
920+
struct PidReg {
921+
sid: String,
922+
at: Instant,
923+
}
924+
907925
#[derive(Default)]
908926
pub(crate) struct AttributionIndex {
909-
by_pid: HashMap<u32, String>,
927+
by_pid: HashMap<u32, PidReg>,
910928
by_identity: HashMap<String, String>,
911929
by_activity: HashMap<String, String>,
912930
by_cv: HashMap<String, String>,
@@ -952,17 +970,23 @@ impl AttributionIndex {
952970
// and Windows has recycled the number. Rebind to the new owner and drop
953971
// the stale per-PID "last resolved" hint so it can't misroute.
954972
if let Some(prev) = self.by_pid.get(&wxc_pid) {
955-
if prev != sandbox_id {
973+
if prev.sid != sandbox_id {
956974
tracing::warn!(
957975
target: "mxc_etw",
958976
pid = wxc_pid,
959-
prev = %prev,
977+
prev = %prev.sid,
960978
new = %sandbox_id,
961979
"wxc-exec PID reused before prior sandbox was forgotten; rebinding attribution"
962980
);
963981
}
964982
}
965-
self.by_pid.insert(wxc_pid, sandbox_id.to_string());
983+
self.by_pid.insert(
984+
wxc_pid,
985+
PidReg {
986+
sid: sandbox_id.to_string(),
987+
at: Instant::now(),
988+
},
989+
);
966990
self.last_pid_sid.remove(&wxc_pid);
967991

968992
// Command line is only trustworthy while unique. Promote to `by_cmd` on
@@ -987,7 +1011,7 @@ impl AttributionIndex {
9871011

9881012
/// Drop all keys for a finished sandbox to bound memory.
9891013
pub fn forget(&mut self, sandbox_id: &str) {
990-
self.by_pid.retain(|_, v| v != sandbox_id);
1014+
self.by_pid.retain(|_, r| r.sid != sandbox_id);
9911015
self.by_identity.retain(|_, v| v != sandbox_id);
9921016
self.by_activity.retain(|_, v| v != sandbox_id);
9931017
self.by_cv.retain(|_, v| v != sandbox_id);
@@ -1023,7 +1047,7 @@ impl AttributionIndex {
10231047
let sid = self
10241048
.by_pid
10251049
.get(&ev.process_id)
1026-
.cloned()
1050+
.map(|registration| registration.sid.clone())
10271051
.or_else(|| {
10281052
identity
10291053
.as_ref()
@@ -1038,18 +1062,78 @@ impl AttributionIndex {
10381062
.or_else(|| cmd.as_ref().and_then(|c| self.by_cmd.get(c).cloned()))
10391063
.or_else(|| self.last_pid_sid.get(&ev.process_id).cloned())?;
10401064

1065+
self.cross_link(&sid, identity, cv, activity, ev.process_id);
1066+
Some(sid)
1067+
}
1068+
1069+
/// Resolve a *buffered* (replayed) event. Unlike [`Self::resolve`], this is
1070+
/// hardened against PID recycling and command-line ambiguity that can occur
1071+
/// during the buffer window ([`PENDING_TTL`]):
1072+
///
1073+
/// - It **never** falls back to `by_cmd` or `last_pid_sid` — both are
1074+
/// recycle-/ambiguity-prone and a stale entry could bind a buffered event
1075+
/// to the wrong sandbox.
1076+
/// - A `by_pid` match is only trusted if the PID's registration is not newer
1077+
/// than the buffered event by more than [`REPLAY_PID_GRACE`]. If the PID
1078+
/// was recycled to a *different* sandbox after this event was captured, the
1079+
/// registration timestamp will be well beyond the grace window and the PID
1080+
/// match is refused (the event stays buffered and ages out rather than
1081+
/// being misattributed to the new owner).
1082+
///
1083+
/// Strong, per-sandbox-unique correlators (`identity`, `activity`, CV) are
1084+
/// always trusted — they are cross-linked from the driver-owned PID anchor
1085+
/// and are not reused across sandboxes.
1086+
fn resolve_replay(&mut self, ev: &DecodedEtwEvent, buffered_at: Instant) -> Option<String> {
1087+
let identity = ev.identity();
1088+
let cv = ev.cv_base();
1089+
let activity = guid_key(&ev.activity_id);
1090+
1091+
let sid = identity
1092+
.as_ref()
1093+
.and_then(|i| self.by_identity.get(i).cloned())
1094+
.or_else(|| {
1095+
activity
1096+
.as_ref()
1097+
.and_then(|a| self.by_activity.get(a).cloned())
1098+
})
1099+
.or_else(|| cv.as_ref().and_then(|c| self.by_cv.get(c).cloned()))
1100+
.or_else(|| {
1101+
self.by_pid.get(&ev.process_id).and_then(|r| {
1102+
// Refuse a PID that was (re)registered well after this event
1103+
// was buffered — that registration belongs to a recycled PID
1104+
// owned by a different sandbox, not this event's emitter.
1105+
if r.at <= buffered_at + REPLAY_PID_GRACE {
1106+
Some(r.sid.clone())
1107+
} else {
1108+
None
1109+
}
1110+
})
1111+
})?;
1112+
1113+
self.cross_link(&sid, identity, cv, activity, ev.process_id);
1114+
Some(sid)
1115+
}
1116+
1117+
/// Cross-link the strong keys an event carries to its resolved `sandbox_id`
1118+
/// so later keyless events for the same sandbox attribute correctly.
1119+
fn cross_link(
1120+
&mut self,
1121+
sid: &str,
1122+
identity: Option<String>,
1123+
cv: Option<String>,
1124+
activity: Option<String>,
1125+
pid: u32,
1126+
) {
10411127
if let Some(i) = identity {
1042-
self.by_identity.entry(i).or_insert_with(|| sid.clone());
1128+
self.by_identity.entry(i).or_insert_with(|| sid.to_string());
10431129
}
10441130
if let Some(c) = cv {
1045-
self.by_cv.entry(c).or_insert_with(|| sid.clone());
1131+
self.by_cv.entry(c).or_insert_with(|| sid.to_string());
10461132
}
10471133
if let Some(a) = activity {
1048-
self.by_activity.entry(a).or_insert_with(|| sid.clone());
1134+
self.by_activity.entry(a).or_insert_with(|| sid.to_string());
10491135
}
1050-
self.last_pid_sid.insert(ev.process_id, sid.clone());
1051-
1052-
Some(sid)
1136+
self.last_pid_sid.insert(pid, sid.to_string());
10531137
}
10541138

10551139
/// Hold an event that didn't resolve yet, evicting expired and (if needed)
@@ -1091,7 +1175,7 @@ impl AttributionIndex {
10911175
tracing::debug!(target: "mxc_etw", pid = p.ev.process_id, "dropping unattributed (aged out) {}", p.ev.summary());
10921176
continue;
10931177
}
1094-
match self.resolve(&p.ev) {
1178+
match self.resolve_replay(&p.ev, p.at) {
10951179
Some(sid) => {
10961180
let name = self.name_of(&sid);
10971181
ready.push((sid, name, p.ev));
@@ -1651,4 +1735,59 @@ mod tests {
16511735
.push(("commandLine".into(), "\"agent --unique\"".into()));
16521736
assert_eq!(idx.resolve(&uniq).as_deref(), Some("sbx-3"));
16531737
}
1738+
1739+
// CodeRabbit (replay PID recycle): a buffered event whose only key is a PID
1740+
// must NOT be replayed onto a sandbox that registered that PID *after* the
1741+
// event was captured — that registration is a recycled PID owned by someone
1742+
// else. Refusing (event ages out) beats misattributing to the new owner.
1743+
#[test]
1744+
fn replayed_pid_match_refused_after_recycle() {
1745+
let mut idx = AttributionIndex::new();
1746+
// Stale event for a now-dead sandbox, buffered a while ago.
1747+
let ev = mk_event(1000, "CreateProcessInSandbox");
1748+
let buffered_at = Instant::now() - Duration::from_secs(3);
1749+
1750+
// PID 1000 is recycled and registered to a brand-new sandbox *now*.
1751+
idx.register_launch("sbx-new", "new", 1000, "agent");
1752+
1753+
assert!(
1754+
idx.resolve_replay(&ev, buffered_at).is_none(),
1755+
"stale PID-only event must not bind to the recycled PID's new owner"
1756+
);
1757+
}
1758+
1759+
// The legitimate #2 seed race is preserved: an event buffered essentially
1760+
// when the driver seeds attribution still replays via its PID.
1761+
#[test]
1762+
fn replayed_pid_match_accepted_within_grace() {
1763+
let mut idx = AttributionIndex::new();
1764+
let ev = mk_event(1000, "CreateProcessInSandbox");
1765+
let buffered_at = Instant::now();
1766+
idx.register_launch("sbx-1", "s1", 1000, "agent");
1767+
assert_eq!(
1768+
idx.resolve_replay(&ev, buffered_at).as_deref(),
1769+
Some("sbx-1"),
1770+
"a seed event buffered at registration time must still replay"
1771+
);
1772+
}
1773+
1774+
// Replay must not lean on the weak fallbacks (`by_cmd` / `last_pid_sid`):
1775+
// a buffered event whose only match is a command line is refused on replay
1776+
// (it would be resolved on the live path, but is too weak to trust after a
1777+
// buffering delay).
1778+
#[test]
1779+
fn replay_ignores_weak_fallbacks() {
1780+
let mut idx = AttributionIndex::new();
1781+
idx.register_launch("sbx-1", "s1", 11, "agent --unique");
1782+
1783+
let mut only_cmd = mk_event(999, "SandboxConfig");
1784+
only_cmd
1785+
.props
1786+
.push(("commandLine".into(), "\"agent --unique\"".into()));
1787+
1788+
// Live path would resolve it via by_cmd...
1789+
// (not asserted here to avoid mutating cross-links)
1790+
// ...but the replay path refuses the weak command-line key.
1791+
assert!(idx.resolve_replay(&only_cmd, Instant::now()).is_none());
1792+
}
16541793
}

0 commit comments

Comments
 (0)