Skip to main content

aios_collector/
binder_probe.rs

1//! Binder/eBPF probe interface for Android IPC observation.
2//!
3//! The probe is safe to construct on every development platform. A real Binder
4//! eBPF attachment requires a privileged Android/Linux daemon with kernel BPF
5//! support and Binder tracepoints. When those requirements are not met, the
6//! probe reports a clear status and returns an empty event stream.
7
8use std::path::Path;
9
10use aios_spec::BinderTxEvent;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum BinderProbeStatus {
14    Uninitialized,
15    UnsupportedPlatform,
16    TracepointUnavailable,
17    PermissionRequired,
18    Ready,
19}
20
21/// Binder probe subscribing to Binder transaction events.
22pub struct BinderProbe {
23    status: BinderProbeStatus,
24}
25
26/// Binder transaction decoded from an eBPF tracepoint record.
27#[derive(Debug, Clone)]
28pub struct BinderTransaction {
29    pub timestamp_ms: i64,
30    pub source_pid: u32,
31    pub source_uid: u32,
32    /// Target Binder service name, for example "notification" or "activity".
33    pub target_service: String,
34    /// Target method inferred from Binder transaction code.
35    pub target_method: String,
36    /// Whether the transaction is oneway.
37    pub is_oneway: bool,
38    /// Parcel payload size in bytes. Payload content is never stored.
39    pub payload_size: u32,
40}
41
42impl BinderProbe {
43    pub fn new() -> Self {
44        Self {
45            status: BinderProbeStatus::Uninitialized,
46        }
47    }
48
49    pub fn status(&self) -> BinderProbeStatus {
50        self.status
51    }
52
53    /// Attempts to initialize Binder/eBPF observation.
54    ///
55    /// `Ok(true)` means the probe can be polled. `Ok(false)` means the current
56    /// environment cannot support privileged Binder tracing and the daemon
57    /// should degrade to public/API and `/proc` inputs.
58    pub fn try_init(&mut self) -> Result<bool, ProbeError> {
59        self.status = detect_status();
60        match self.status {
61            BinderProbeStatus::Ready => {
62                tracing::info!("Binder tracepoint detected, probe initialized");
63                Ok(true)
64            },
65            BinderProbeStatus::PermissionRequired => {
66                tracing::warn!("Binder tracepoint exists but eBPF attachment requires privilege");
67                Ok(false)
68            },
69            BinderProbeStatus::UnsupportedPlatform | BinderProbeStatus::TracepointUnavailable => {
70                tracing::warn!("Binder tracepoint not available; probe will return no events");
71                Ok(false)
72            },
73            BinderProbeStatus::Uninitialized => Ok(false),
74        }
75    }
76
77    /// Polls Binder events observed since the previous call.
78    pub fn poll(&self) -> Vec<BinderTransaction> {
79        if self.status != BinderProbeStatus::Ready {
80            return Vec::new();
81        }
82
83        // A real implementation should load a BPF program, attach it to
84        // tracepoint/binder/binder_transaction, and drain a ring/perf buffer.
85        // Until that fd-backed path exists, keep the stream empty and explicit.
86        Vec::new()
87    }
88}
89
90impl Default for BinderProbe {
91    fn default() -> Self {
92        Self::new()
93    }
94}
95
96impl BinderTransaction {
97    pub fn to_event(&self) -> BinderTxEvent {
98        BinderTxEvent {
99            timestamp_ms: self.timestamp_ms,
100            source_pid: self.source_pid,
101            source_uid: self.source_uid,
102            target_service: self.target_service.clone(),
103            target_method: self.target_method.clone(),
104            is_oneway: self.is_oneway,
105            payload_size: self.payload_size,
106        }
107    }
108}
109
110fn detect_status() -> BinderProbeStatus {
111    if !cfg!(target_os = "linux") {
112        return BinderProbeStatus::UnsupportedPlatform;
113    }
114
115    let binder_trace =
116        Path::new("/sys/kernel/debug/tracing/events/binder/binder_transaction/enable");
117    if !binder_trace.exists() {
118        return BinderProbeStatus::TracepointUnavailable;
119    }
120
121    // The tracepoint exists, but this crate does not yet link an fd-backed BPF
122    // loader. Report the remaining deployment requirement explicitly.
123    BinderProbeStatus::PermissionRequired
124}
125
126#[derive(Debug, thiserror::Error)]
127pub enum ProbeError {
128    #[error("eBPF not supported on this kernel")]
129    EbpfNotSupported,
130    #[error("insufficient permissions for eBPF (need root or system daemon)")]
131    PermissionDenied,
132    #[error("BPF program load failed: {0}")]
133    LoadError(String),
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    #[test]
141    fn unavailable_probe_returns_no_events() {
142        let mut probe = BinderProbe::new();
143        let initialized = probe.try_init().expect("status detection should not fail");
144
145        assert!(!initialized);
146        assert!(matches!(
147            probe.status(),
148            BinderProbeStatus::UnsupportedPlatform
149                | BinderProbeStatus::TracepointUnavailable
150                | BinderProbeStatus::PermissionRequired
151        ));
152        assert!(probe.poll().is_empty());
153    }
154
155    #[test]
156    fn binder_transaction_converts_to_raw_event_payload() {
157        let tx = BinderTransaction {
158            timestamp_ms: 10,
159            source_pid: 11,
160            source_uid: 12,
161            target_service: "activity".into(),
162            target_method: "startActivity".into(),
163            is_oneway: false,
164            payload_size: 128,
165        };
166
167        let event = tx.to_event();
168        assert_eq!(event.timestamp_ms, 10);
169        assert_eq!(event.source_pid, 11);
170        assert_eq!(event.source_uid, 12);
171        assert_eq!(event.target_service, "activity");
172        assert_eq!(event.target_method, "startActivity");
173        assert!(!event.is_oneway);
174        assert_eq!(event.payload_size, 128);
175    }
176}