starnix_core/security/selinux_hooks/
audit.rs1use crate::task::{CurrentTask, Task};
6use crate::vfs::{
7 DirEntry, DirEntryHandle, FileObject, FileSystem, FsNode, FsStr, NamespaceNode,
8 PathWithReachability,
9};
10use bstr::BStr;
11use fuchsia_rcu::RcuReadScope;
12use hex;
13use linux_uapi::AUDIT_AVC;
14use selinux::permission_check::{PermissionCheck, PermissionCheckResult};
15use selinux::{ClassPermission, KernelClass, KernelPermission, SecurityId};
16use starnix_logging::CATEGORY_STARNIX_SECURITY;
17use starnix_sync::{AuditDenyCountsLock, LockDepMutex};
18use std::collections::HashMap;
19use std::fmt::{Display, Error};
20use std::num::NonZeroU32;
21use std::sync::LazyLock;
22
23#[derive(Clone, Eq, Hash, PartialEq)]
25struct AuditableInstance {
26 source_sid: SecurityId,
27 target_sid: SecurityId,
28 class: KernelClass,
29 bug: NonZeroU32,
30}
31
32static TODO_DENY_COUNTS: LazyLock<
34 LockDepMutex<HashMap<AuditableInstance, u32>, AuditDenyCountsLock>,
35> = LazyLock::new(|| Default::default());
36
37fn should_audit(
39 source_sid: SecurityId,
40 target_sid: SecurityId,
41 class: KernelClass,
42 bug: NonZeroU32,
43) -> bool {
44 const MAX_TODO_AUDIT_DENIALS: u32 = 5;
46
47 let mut counts = TODO_DENY_COUNTS.lock();
48 let count = counts.entry(AuditableInstance { source_sid, target_sid, class, bug }).or_default();
49 *count += 1;
50 *count <= MAX_TODO_AUDIT_DENIALS
51}
52
53#[derive(Debug, Clone, Copy)]
75pub enum Auditable<'a> {
76 AuditContext(&'a [Auditable<'a>]),
78 Bug(u32),
79 CurrentTask,
80 DirEntry(&'a DirEntry),
81 FileObject(&'a FileObject),
82 FileSystem(&'a FileSystem),
83 FsNode(&'a FsNode),
84 IoctlCommand(u16),
85 Location(&'a std::panic::Location<'a>),
86 Name(&'a FsStr),
87 NamespaceNode(&'a NamespaceNode),
88 NlMsgtype(u16),
89 None,
90 SockOptArguments(u32, u32),
91 Task(&'a Task),
92 }
94
95impl Auditable<'_> {
96 fn from_bug(bug_id: u32) -> Self {
97 Auditable::Bug(bug_id)
98 }
99}
100
101impl<'a> From<&'a CurrentTask> for Auditable<'a> {
102 fn from(_value: &'a CurrentTask) -> Self {
103 Auditable::CurrentTask
105 }
106}
107
108impl<'a> From<&'a Task> for Auditable<'a> {
109 fn from(value: &'a Task) -> Self {
110 Auditable::Task(value)
111 }
112}
113
114impl<'a> From<&'a DirEntry> for Auditable<'a> {
115 fn from(value: &'a DirEntry) -> Self {
116 Auditable::DirEntry(value)
117 }
118}
119
120impl<'a> From<&'a DirEntryHandle> for Auditable<'a> {
121 fn from(value: &'a DirEntryHandle) -> Self {
122 Auditable::DirEntry(&*value)
123 }
124}
125
126impl<'a> From<&'a FileObject> for Auditable<'a> {
127 fn from(value: &'a FileObject) -> Self {
128 Auditable::FileObject(value)
129 }
130}
131
132impl<'a> From<&'a FsNode> for Auditable<'a> {
133 fn from(value: &'a FsNode) -> Self {
134 Auditable::FsNode(value)
135 }
136}
137
138impl<'a> From<&'a FileSystem> for Auditable<'a> {
139 fn from(value: &'a FileSystem) -> Self {
140 Auditable::FileSystem(value)
141 }
142}
143
144impl<'a> From<&'a std::panic::Location<'a>> for Auditable<'a> {
145 fn from(value: &'a std::panic::Location<'a>) -> Self {
146 Auditable::Location(value)
147 }
148}
149
150impl<'a> From<&'a NamespaceNode> for Auditable<'a> {
151 fn from(value: &'a NamespaceNode) -> Self {
152 Auditable::NamespaceNode(value)
153 }
154}
155
156impl<'a, const N: usize> From<&'a [Auditable<'a>; N]> for Auditable<'a> {
157 fn from(value: &'a [Auditable<'a>; N]) -> Self {
158 Auditable::AuditContext(value)
159 }
160}
161
162pub(super) fn audit_decision(
176 current_task: &CurrentTask,
177 permission_check: &PermissionCheck<'_>,
178 result: PermissionCheckResult,
179 source_sid: SecurityId,
180 target_sid: SecurityId,
181 permission: KernelPermission,
182 audit_data: Auditable<'_>,
183) {
184 fuchsia_trace::instant!(
185 CATEGORY_STARNIX_SECURITY,
186 match (result.granted, result.todo_bug) {
187 (true, None) => c"audit.granted",
188 (true, Some(_)) => c"audit.todo_deny",
189 _ => c"audit.denied",
190 },
191 fuchsia_trace::Scope::Thread
192 );
193
194 let decision = if let Some(todo_bug) = result.todo_bug {
195 if !should_audit(source_sid, target_sid, permission.class(), todo_bug) {
201 return;
202 }
203
204 "todo_deny"
206 } else {
207 if result.granted { "granted" } else { "denied" }
208 };
209
210 let audit_data_with_bug =
212 [Auditable::from_bug(result.todo_bug.map(NonZeroU32::get).unwrap_or(0)), audit_data];
213 let audit_data =
214 if result.todo_bug.is_some() { (&audit_data_with_bug).into() } else { audit_data };
215
216 let audit_logger = current_task.kernel().audit_logger();
217 audit_logger.audit_log(
218 AUDIT_AVC as u16,
219 || {
220 let tclass = permission.class().name();
221 let permission_name = permission.name();
222
223 let security_server = permission_check.security_server();
226 let scontext = security_server.sid_to_security_context(source_sid).unwrap();
227 let scontext = BStr::new(&scontext);
228 let tcontext = security_server.sid_to_security_context(target_sid).unwrap();
229 let tcontext = BStr::new(&tcontext);
230
231 let pid = current_task.get_pid();
233 let command = current_task.command();
234
235 let is_permissive = result.permissive as u8;
236
237 format!("avc: {decision} {{ {permission_name} }} for pid={pid} comm=\"{command}\"{audit_data} scontext={scontext} tcontext={tcontext} tclass={tclass} permissive={is_permissive}")
238 }
239 );
240}
241
242impl Display for Auditable<'_> {
243 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), Error> {
244 match self {
245 Auditable::AuditContext(audit_context) => {
246 for item in *audit_context {
247 item.fmt(f)?;
248 }
249 Ok(())
250 }
251 Auditable::Bug(bug_id) => {
252 write!(f, " bug={}", bug_id)
253 }
254 Auditable::CurrentTask => Ok(()),
255 Auditable::DirEntry(entry) => {
256 let scope = RcuReadScope::new();
257 write!(f, " name={}", hex_escape(entry.local_name(&scope)))
258 }
259 Auditable::FileObject(file) => {
260 write!(f, " path={}", hex_escape(&file.name.path_escaping_chroot()))
261 }
262 Auditable::FileSystem(fs) => {
263 write!(f, " dev={}", hex_escape(&fs.options.source))
264 }
265 Auditable::FsNode(node) => {
266 write!(f, " ino={}", node.ino)
267 }
268 Auditable::IoctlCommand(ioctl) => {
269 write!(f, " ioctlcmd={:#x}", ioctl)
270 }
271 Auditable::NlMsgtype(message_type) => {
272 write!(f, " nl-msgtype={}", message_type)
273 }
274 Auditable::Location(location) => {
275 write!(f, " caller={:?}", location)
276 }
277 Auditable::Name(name) => {
278 write!(f, " name={}", hex_escape(name))
279 }
280 Auditable::NamespaceNode(node) => {
281 let PathWithReachability::Reachable(path) = node.path_from_root(None) else {
282 return Ok(());
283 };
284 write!(f, " path={}", hex_escape(&path))
285 }
286 Auditable::SockOptArguments(level, optname) => {
287 write!(f, " level={}, optname={}", level, optname)
288 }
289 Auditable::None => Ok(()),
290 Auditable::Task(task) => {
291 write!(f, " pid={}, comm={}", task.get_pid(), task.command())
292 }
293 }
294 }
295}
296
297struct EscapedString<'a> {
298 value: &'a [u8],
299}
300
301impl<'a> Display for EscapedString<'a> {
302 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), Error> {
303 let maybe_utf8 = str::from_utf8(self.value).ok();
308 if let Some(utf8) = maybe_utf8 {
309 if utf8.find(|c| c <= ' ').is_none() {
310 return write!(f, "\"{}\"", BStr::new(self.value));
311 }
312 }
313 hex::encode_upper(self.value).fmt(f)
314 }
315}
316
317fn hex_escape<'a>(value: &'a [u8]) -> EscapedString<'a> {
318 EscapedString { value }
319}