Skip to main content

starnix_core/security/
audit.rs

1// Copyright 2025 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::vfs::socket::AuditNetlinkClient;
6use linux_uapi::{
7    AUDIT_CONFIG_CHANGE, AUDIT_FAIL_PANIC, AUDIT_FAIL_PRINTK, AUDIT_FAIL_SILENT,
8    AUDIT_FIRST_USER_MSG, AUDIT_FIRST_USER_MSG2, AUDIT_GET, AUDIT_LAST_USER_MSG,
9    AUDIT_LAST_USER_MSG2, AUDIT_SET, AUDIT_STATUS_BACKLOG_LIMIT, AUDIT_STATUS_ENABLED,
10    AUDIT_STATUS_FAILURE, AUDIT_STATUS_LOST, AUDIT_STATUS_PID, AUDIT_USER,
11};
12use starnix_lifecycle::AtomicCounter;
13use starnix_logging::log_warn;
14use starnix_sync::{AuditQueueLock, AuditSinkLock, LockDepGuard, LockDepMutex};
15use starnix_uapi::errors::Errno;
16use starnix_uapi::{audit_status, error, pid_t};
17use std::collections::VecDeque;
18use std::fmt::Display;
19use std::sync::Arc;
20use std::sync::atomic::{AtomicU8, AtomicU32, Ordering};
21use std::time::SystemTime;
22use zx::MonotonicDuration;
23
24use crate::task::{ArgNameAndValue, CurrentTask, Kernel};
25const DEFAULT_BACKLOG_LIMIT: u32 = 128;
26
27/// Supported requests that manipulate the `AuditLogger`
28pub enum AuditRequest {
29    AuditGet,
30    AuditSet,
31    AuditUser,
32}
33
34impl TryFrom<u32> for AuditRequest {
35    type Error = Errno;
36
37    fn try_from(value: u32) -> Result<Self, Self::Error> {
38        match value {
39            AUDIT_GET => Ok(Self::AuditGet),
40            AUDIT_SET => Ok(Self::AuditSet),
41            AUDIT_USER
42            | AUDIT_FIRST_USER_MSG..=AUDIT_LAST_USER_MSG
43            | AUDIT_FIRST_USER_MSG2..=AUDIT_LAST_USER_MSG2 => Ok(Self::AuditUser),
44            _ => error!(ENOTSUP),
45        }
46    }
47}
48
49/// Possible modes of the audit framework.
50#[derive(PartialEq)]
51enum AuditMode {
52    Disabled,
53    Unspecified,
54    Enabled,
55}
56
57/// The audit sink reference structure.
58#[derive(Default)]
59struct AuditNetlinkClientRef {
60    /// Inner reference to the registered audit sink, if any.
61    client: Option<Arc<AuditNetlinkClient>>,
62    /// The PID of the registered audit sink.
63    pid: pid_t,
64    /// Deque for the audit messages, always present.
65    messages: VecDeque<AuditMessage>,
66}
67
68/// Audit status structure defining the behaviour of the logger.
69struct AuditConfig {
70    /// The audit mode set by kernel command line.
71    audit_mode: AuditMode,
72    /// The maximum number of audit messages that can be stored by the logger.
73    backlog_limit: AtomicU32,
74    /// Action to take in case of audit failure.
75    fail_action: AtomicU8,
76    /// Socket to which the logger writes audit messages.
77    audit_sink: LockDepMutex<AuditNetlinkClientRef, AuditSinkLock>,
78}
79
80impl Default for AuditConfig {
81    fn default() -> Self {
82        Self {
83            audit_mode: AuditMode::Unspecified,
84            backlog_limit: AtomicU32::new(DEFAULT_BACKLOG_LIMIT),
85            fail_action: AtomicU8::new(AUDIT_FAIL_PRINTK as u8),
86            audit_sink: Default::default(),
87        }
88    }
89}
90
91impl AuditConfig {
92    pub fn new<'a>(cmdline_iter: impl Iterator<Item = ArgNameAndValue<'a>>) -> Self {
93        let mut config = Self::default();
94        // The logger may be disabled by the kernel command line.
95        config.apply_kernel_cmdline(cmdline_iter);
96        config
97    }
98
99    /// Function to apply the optional kernel command line arguments.
100    fn apply_kernel_cmdline<'a>(
101        &mut self,
102        cmdline_iter: impl Iterator<Item = ArgNameAndValue<'a>>,
103    ) {
104        for arg in cmdline_iter {
105            match arg {
106                ArgNameAndValue { name: "audit", value: Some(value) } => match value {
107                    "0" | "off" => self.audit_mode = AuditMode::Disabled,
108                    // If the audit option is "1"/"on"/anything else, fully enable auditing.
109                    _ => self.audit_mode = AuditMode::Enabled,
110                },
111                ArgNameAndValue { name: "audit_backlog_limit", value: Some(value) } => self
112                    .backlog_limit
113                    .store(value.parse().unwrap_or(DEFAULT_BACKLOG_LIMIT), Ordering::Release),
114                _ => (),
115            }
116        }
117    }
118}
119
120/// Audit logging structure.
121pub struct AuditLogger {
122    /// Audit status structure.
123    configuration: AuditConfig,
124    /// The number of audit messages lost due to writing errors.
125    lost_audit_messages: AtomicU32,
126    /// Monotonic counter for audit serial numbers
127    serial_counter: AtomicCounter<u64>,
128    /// Audit message deque containing (audit type, audit string) up to `backlog_limit` messages.
129    /// TODO: https://fxbug.dev/438677236 - confirm single queue behaviour is valid.
130    audit_queue: LockDepMutex<VecDeque<AuditMessage>, AuditQueueLock>,
131}
132
133impl AuditLogger {
134    pub fn new(kernel: &Kernel) -> Self {
135        Self {
136            configuration: AuditConfig::new(kernel.cmdline_args_iter()),
137            lost_audit_messages: Default::default(),
138            serial_counter: Default::default(),
139            audit_queue: Default::default(),
140        }
141    }
142
143    pub fn is_disabled(&self) -> bool {
144        self.configuration.audit_mode == AuditMode::Disabled
145    }
146
147    /// Audit logging function that adds an audit message to the queue.
148    ///
149    /// The `audit_formatter` function is called only if the auditing is enabled.
150    pub fn audit_log<M: Display, T: FnOnce() -> M>(&self, audit_type: u16, audit_formatter: T) {
151        if self.configuration.audit_mode == AuditMode::Disabled {
152            return;
153        }
154        self.add_audit_to_backlog(audit_type, audit_formatter);
155    }
156
157    /// Called by the `NetlinkAuditClient` to pull the next audit log from the backlog.
158    pub fn read_audit_log(&self, client: &Arc<AuditNetlinkClient>) -> Option<AuditMessage> {
159        let mut client_guard = self.configuration.audit_sink.lock();
160        let Some(current_client) = client_guard.client.as_ref() else {
161            return None;
162        };
163        // Check if the current client is reading the backlog.
164        if !Arc::ptr_eq(&current_client, client) {
165            return None;
166        }
167        client_guard.messages.pop_front()
168    }
169
170    /// Function to detach the `AuditNetlinkClient` from the `AuditLogger` if
171    /// the provided client matches the one registered.
172    pub fn detach_client(&self, client: &Arc<AuditNetlinkClient>) {
173        let mut client_guard = self.configuration.audit_sink.lock();
174        if client_guard
175            .client
176            .as_ref()
177            .is_some_and(|current_client| Arc::ptr_eq(client, &current_client))
178        {
179            let pid = client_guard.pid;
180            client_guard.client = None;
181            client_guard.pid = 0;
182            client_guard.messages.clear();
183            drop(client_guard);
184            self.audit_log(AUDIT_CONFIG_CHANGE as u16, || format!("audit sink detached pid={pid}"));
185        }
186    }
187
188    /// Applies the specified changes to the audit logger settings.
189    pub fn set_status(
190        &self,
191        current_task: &CurrentTask,
192        status: audit_status,
193        client: &Arc<AuditNetlinkClient>,
194    ) -> Result<(), Errno> {
195        // Dummy check for enable/disable request. This should be used again if other
196        // subsystems will use the audit logger.
197        if status.mask & AUDIT_STATUS_ENABLED != 0 && status.enabled > 1 {
198            return error!(EINVAL);
199        }
200        if status.mask & AUDIT_STATUS_BACKLOG_LIMIT != 0 {
201            self.configuration.backlog_limit.store(status.backlog_limit, Ordering::Release);
202        }
203        if status.mask & AUDIT_STATUS_FAILURE != 0 {
204            self.configuration.fail_action.store(status.failure as u8, Ordering::Release);
205        }
206        if status.mask & AUDIT_STATUS_LOST != 0 {
207            self.lost_audit_messages.store(0, Ordering::Release);
208        }
209        if status.mask & AUDIT_STATUS_PID != 0 {
210            self.update_client(current_task.get_pid(), status.pid as pid_t, client)?;
211        }
212        Ok(())
213    }
214
215    /// Retrieve the `AuditConfig` as `audit_status` struct.
216    pub fn get_status(&self) -> audit_status {
217        let pid = self.configuration.audit_sink.lock().pid as u32;
218        let backlog = self.audit_queue.lock().len() as u32;
219        audit_status {
220            mask: Default::default(),
221            enabled: Default::default(),
222            failure: self.configuration.fail_action.load(Ordering::Acquire) as u32,
223            pid,
224            rate_limit: u32::MAX,
225            backlog_limit: self.configuration.backlog_limit.load(Ordering::Acquire),
226            lost: self.lost_audit_messages.load(Ordering::Acquire),
227            backlog,
228            __bindgen_anon_1: Default::default(),
229            backlog_wait_time: Default::default(),
230            backlog_wait_time_actual: Default::default(),
231        }
232    }
233
234    /// Retrieve the number of audit messages in the backlog.
235    pub fn get_backlog_count(&self, client: &Arc<AuditNetlinkClient>) -> usize {
236        let client_guard = self.configuration.audit_sink.lock();
237        if let Some(current_client) = &client_guard.client {
238            if Arc::ptr_eq(&current_client, client) {
239                return client_guard.messages.len();
240            }
241        }
242        0
243    }
244
245    /// Function to update the attached `client` and its PID
246    fn update_client(
247        &self,
248        pid: pid_t,
249        request_pid: pid_t,
250        client: &Arc<AuditNetlinkClient>,
251    ) -> Result<(), Errno> {
252        if request_pid == 0 {
253            let client_ref = {
254                let client_guard = self.configuration.audit_sink.lock();
255                // If there is no audit client registered and unregister is requested, return without error.
256                if client_guard.pid == 0 {
257                    return Ok(());
258                } else if pid != client_guard.pid {
259                    return error!(EPERM);
260                }
261                client_guard.client.clone()
262            };
263            client_ref.inspect(|client_ref| self.detach_client(&client_ref));
264            return Ok(());
265        }
266        if pid != request_pid {
267            return error!(EINVAL);
268        }
269
270        let mut client_guard = self.configuration.audit_sink.lock();
271        if client_guard.client.is_some() {
272            return error!(EEXIST);
273        }
274        client_guard.client = Some(client.clone());
275        client_guard.pid = pid;
276        drop(client_guard);
277        self.audit_log(AUDIT_CONFIG_CHANGE as u16, || format!("new audit sink attached pid={pid}"));
278        Ok(())
279    }
280
281    /// Add an audit message to the backlog if it is enabled.
282    fn add_audit_to_backlog<M: Display, T: FnOnce() -> M>(
283        &self,
284        audit_type: u16,
285        audit_formatter: T,
286    ) {
287        // At this point, we know that the audit framework is not disabled until reboot.
288        let audit_message = self.prepend_audit_metadata(audit_formatter);
289
290        let mut client_guard = self.configuration.audit_sink.lock();
291        // If there is no audit sink and the auditing is partially enabled, print and return
292        // without pushing the message to the backlog.
293        if client_guard.client.is_none() {
294            log_warn!("audit: type={audit_type} msg={audit_message}");
295        }
296
297        if client_guard.client.is_some() || self.configuration.audit_mode == AuditMode::Enabled {
298            self.push_back_audit(audit_type, audit_message, &mut client_guard);
299            let client = client_guard.client.clone();
300            drop(client_guard);
301            if let Some(client) = client {
302                client.notify();
303            }
304        }
305    }
306
307    /// Push the audit message in the backlog after checking its limit.
308    fn push_back_audit(
309        &self,
310        audit_type: u16,
311        audit_message: String,
312        client_guard: &mut LockDepGuard<'_, AuditNetlinkClientRef>,
313    ) {
314        // TODO: https://fxbug.dev/440090442 - implement backlog waiting.
315        if self.check_backlog(client_guard.messages.len() as u32) {
316            return;
317        }
318        client_guard.messages.push_back(AuditMessage { audit_type, message: audit_message.into() });
319    }
320
321    /// Function to check the backlog size against the backlog limit.
322    /// If the limit is set to 0, ignore the check.
323    ///
324    /// Return true if the limit is reached, false otherwise.
325    fn check_backlog(&self, backlog_size: u32) -> bool {
326        let limit = self.configuration.backlog_limit.load(Ordering::Acquire);
327        if limit != 0 && backlog_size >= limit {
328            let lost = self.lost_audit_messages.fetch_add(1, Ordering::Release) + 1;
329            log_warn!("audit_lost={lost} backlog_limit={limit}");
330            // If the backlog is full, use failure-to-log action.
331            match self.configuration.fail_action.load(Ordering::Acquire) as u32 {
332                AUDIT_FAIL_PANIC => panic!("backlog limit exceeded"),
333                AUDIT_FAIL_PRINTK => log_warn!("backlog limit exceeded"),
334                AUDIT_FAIL_SILENT | _ => (),
335            }
336            return true;
337        }
338        false
339    }
340
341    /// Function to prepend an audit message with a timestamp and serial number.
342    fn prepend_audit_metadata<M: Display, T: FnOnce() -> M>(&self, audit: T) -> String {
343        let epoch_time = MonotonicDuration::from(
344            SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap_or_default(),
345        )
346        .into_millis();
347
348        format!(
349            "audit({}.{}:{}): {}",
350            epoch_time / 1000,
351            epoch_time % 1000,
352            self.serial_counter.next(),
353            audit()
354        )
355    }
356}
357
358/// Audit message structure.
359pub struct AuditMessage {
360    /// The type of the audit message (e.g., AUDIT_AVC).
361    pub audit_type: u16,
362    /// The message to be audit-logged.
363    pub message: Vec<u8>,
364}