| 1 | // SPDX-License-Identifier: Apache-2.0 or MIT |
| 2 | // |
| 3 | // Copyright 2021 Sony Group Corporation |
| 4 | // |
| 5 | |
| 6 | use super::cvt; |
| 7 | use crate::api::ensure_supported_api; |
| 8 | use crate::error::{Result, SeccompError}; |
| 9 | use crate::{ScmpArch, ScmpFilterContext, ScmpSyscall, ScmpVersion}; |
| 10 | use bitflags::bitflags; |
| 11 | use libseccomp_sys::*; |
| 12 | use std::ops::BitOr; |
| 13 | use std::os::unix::io::RawFd; |
| 14 | |
| 15 | fn get_errno() -> i32 { |
| 16 | std::io::Error::last_os_error().raw_os_error().unwrap_or(0) |
| 17 | } |
| 18 | |
| 19 | /// Checks the libseccomp API level and the libseccomp version for |
| 20 | /// the userspace notification. |
| 21 | /// |
| 22 | /// This function succeeds if the libseccomp API level and the libseccomp |
| 23 | /// version being used are equal to or greater than 6 and 2.5.0. |
| 24 | /// |
| 25 | /// # Errors |
| 26 | /// |
| 27 | /// If both the libseccomp API level and the libseccomp version being used are |
| 28 | /// less than 6 and 2.5.0, an error will be returned. |
| 29 | fn notify_supported() -> Result<()> { |
| 30 | ensure_supported_api("seccomp notification", 6, ScmpVersion::from((2, 5, 0)))?; |
| 31 | |
| 32 | Ok(()) |
| 33 | } |
| 34 | |
| 35 | /// Represents a file descriptor used for the userspace notification. |
| 36 | pub type ScmpFd = RawFd; |
| 37 | |
| 38 | bitflags! { |
| 39 | /// Userspace notification response flags |
| 40 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 41 | pub struct ScmpNotifRespFlags: u32 { |
| 42 | /// Tells the kernel to continue executing the system call that triggered the |
| 43 | /// notification. Must only be used when the notification response's error and value is 0. |
| 44 | const CONTINUE = SECCOMP_USER_NOTIF_FLAG_CONTINUE; |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | /// Userspace notification response flag |
| 49 | /// |
| 50 | /// Tells the kernel to continue executing the system call that triggered the |
| 51 | /// notification. Must only be used when the notification response's error is 0. |
| 52 | #[deprecated( |
| 53 | since = "0.3.0", |
| 54 | note = "Use ScmpNotifRespFlags::CONTINUE or ScmpNotifRespFlags::CONTINUE.bits()" |
| 55 | )] |
| 56 | pub const NOTIF_FLAG_CONTINUE: u32 = ScmpNotifRespFlags::CONTINUE.bits(); |
| 57 | |
| 58 | impl ScmpFilterContext { |
| 59 | /// Gets a file descriptor for the userspace notification associated with the |
| 60 | /// given filter context. |
| 61 | /// |
| 62 | /// Such a file descriptor is only valid after the filter has been loaded |
| 63 | /// and only when the filter uses the [`crate::ScmpAction::Notify`] action. |
| 64 | /// The file descriptor can be used to retrieve and respond to notifications |
| 65 | /// associated with the filter (see [`ScmpNotifReq::receive()`], |
| 66 | /// [`ScmpNotifResp::respond()`], and [`notify_id_valid()`]). |
| 67 | /// |
| 68 | /// **Note**: This file descriptor is shared between all threads. |
| 69 | /// |
| 70 | /// This function returns a raw file descriptor for the userspace notification. |
| 71 | /// The ownership of this file descriptor is not moved and you must not close it. |
| 72 | /// |
| 73 | /// This function corresponds to |
| 74 | /// [`seccomp_notify_fd`](https://man7.org/linux/man-pages/man3/seccomp_notify_fd.3.html). |
| 75 | /// |
| 76 | /// # Errors |
| 77 | /// |
| 78 | /// If an issue is encountered getting the file descriptor, |
| 79 | /// an error will be returned. |
| 80 | /// # Examples |
| 81 | /// |
| 82 | /// ``` |
| 83 | /// # use libseccomp::*; |
| 84 | /// let mut ctx = ScmpFilterContext::new(ScmpAction::Allow)?; |
| 85 | /// ctx.add_rule(ScmpAction::Notify, ScmpSyscall::from_name("getpid")?)?; |
| 86 | /// ctx.load()?; |
| 87 | /// let fd = ctx.get_notify_fd()?; |
| 88 | /// # Ok::<(), Box<dyn std::error::Error>>(()) |
| 89 | /// ``` |
| 90 | pub fn get_notify_fd(&self) -> Result<ScmpFd> { |
| 91 | notify_supported()?; |
| 92 | |
| 93 | let ret = unsafe { seccomp_notify_fd(self.as_ptr()) }; |
| 94 | if ret < 0 { |
| 95 | return Err(SeccompError::from_errno(ret)); |
| 96 | } |
| 97 | |
| 98 | Ok(ret) |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | /// Describes the system call context that triggered a notification. |
| 103 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 104 | #[non_exhaustive] |
| 105 | pub struct ScmpNotifData { |
| 106 | /// The syscall number |
| 107 | pub syscall: ScmpSyscall, |
| 108 | /// The filter architecture |
| 109 | pub arch: ScmpArch, |
| 110 | /// Address of the instruction that triggered a notification |
| 111 | pub instr_pointer: u64, |
| 112 | /// Arguments (up to 6) for the syscall |
| 113 | pub args: [u64; 6], |
| 114 | } |
| 115 | |
| 116 | impl ScmpNotifData { |
| 117 | fn from_sys(data: seccomp_data) -> Result<Self> { |
| 118 | Ok(Self { |
| 119 | syscall: ScmpSyscall::from(data.nr), |
| 120 | arch: ScmpArch::from_sys(data.arch)?, |
| 121 | instr_pointer: data.instruction_pointer, |
| 122 | args: data.args, |
| 123 | }) |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | /// Represents a userspace notification request. |
| 128 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 129 | #[non_exhaustive] |
| 130 | pub struct ScmpNotifReq { |
| 131 | /// Notification ID |
| 132 | pub id: u64, |
| 133 | /// Process that triggered the notification event |
| 134 | pub pid: u32, |
| 135 | /// Filter flags (see seccomp(2)) |
| 136 | pub flags: u32, |
| 137 | /// System call context that triggered the notification |
| 138 | pub data: ScmpNotifData, |
| 139 | } |
| 140 | |
| 141 | impl ScmpNotifReq { |
| 142 | fn from_sys(req: seccomp_notif) -> Result<Self> { |
| 143 | Ok(Self { |
| 144 | id: req.id, |
| 145 | pid: req.pid, |
| 146 | flags: req.flags, |
| 147 | data: ScmpNotifData::from_sys(req.data)?, |
| 148 | }) |
| 149 | } |
| 150 | |
| 151 | /// Retrieves a userspace notification from a filter whose |
| 152 | /// [`crate::ScmpAction::Notify`] action has triggered. |
| 153 | /// |
| 154 | /// The caller is expected to process the notification and return a |
| 155 | /// response via [`ScmpNotifResp::respond()`]. Each invocation of |
| 156 | /// this function returns one notification. |
| 157 | /// As multiple notifications may be pending at any time, this function is |
| 158 | /// normally called within a polling loop. |
| 159 | /// |
| 160 | /// This function returns a userspace notification request. |
| 161 | /// |
| 162 | /// This function corresponds to |
| 163 | /// [`seccomp_notify_receive`](https://man7.org/linux/man-pages/man3/seccomp_notify_receive.3.html). |
| 164 | /// |
| 165 | /// # Arguments |
| 166 | /// |
| 167 | /// * `fd` - A file descriptor for the userspace notification |
| 168 | /// |
| 169 | /// # Errors |
| 170 | /// |
| 171 | /// If an issue is encountered getting a notification request, |
| 172 | /// an error will be returned. |
| 173 | /// |
| 174 | /// # Examples |
| 175 | /// |
| 176 | /// ``` |
| 177 | /// # use libseccomp::*; |
| 178 | /// # use std::process::exit; |
| 179 | /// // Get the current process ID |
| 180 | /// let parent_pid = std::process::id(); |
| 181 | /// let mut ctx = ScmpFilterContext::new(ScmpAction::Allow)?; |
| 182 | /// ctx.add_rule(ScmpAction::Notify, ScmpSyscall::from_name("getpid")?)?; |
| 183 | /// ctx.load()?; |
| 184 | /// let fd = ctx.get_notify_fd()?; |
| 185 | /// let pid = unsafe { libc::fork() }; |
| 186 | /// if pid == 0 { |
| 187 | /// // Child process |
| 188 | /// |
| 189 | /// let child_pid = std::process::id(); |
| 190 | /// // The child PID will be same as the parent PID by the user notification. |
| 191 | /// assert_eq!(child_pid, parent_pid); |
| 192 | /// exit(0); |
| 193 | /// } |
| 194 | /// let req = ScmpNotifReq::receive(fd)?; |
| 195 | /// let resp = ScmpNotifResp::new_val(req.id, parent_pid as i64, ScmpNotifRespFlags::empty()); |
| 196 | /// resp.respond(fd); |
| 197 | /// # Ok::<(), Box<dyn std::error::Error>>(()) |
| 198 | /// ``` |
| 199 | pub fn receive(fd: ScmpFd) -> Result<Self> { |
| 200 | notify_supported()?; |
| 201 | |
| 202 | let mut req_ptr: *mut seccomp_notif = std::ptr::null_mut(); |
| 203 | |
| 204 | // We only use the request here; the response is unused. |
| 205 | cvt(unsafe { seccomp_notify_alloc(&mut req_ptr, std::ptr::null_mut()) })?; |
| 206 | |
| 207 | loop { |
| 208 | let ret = unsafe { seccomp_notify_receive(fd, req_ptr) }; |
| 209 | let errno = get_errno(); |
| 210 | |
| 211 | if ret == 0 { |
| 212 | break; |
| 213 | } else if errno == libc::EINTR { |
| 214 | continue; |
| 215 | } else { |
| 216 | unsafe { seccomp_notify_free(req_ptr, std::ptr::null_mut()) }; |
| 217 | return Err(SeccompError::from_errno(ret)); |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | // Copy notify request before freeing the memory. |
| 222 | let req = seccomp_notif { |
| 223 | id: unsafe { (*req_ptr).id }, |
| 224 | pid: unsafe { (*req_ptr).pid }, |
| 225 | flags: unsafe { (*req_ptr).flags }, |
| 226 | data: unsafe { (*req_ptr).data }, |
| 227 | }; |
| 228 | |
| 229 | unsafe { seccomp_notify_free(req_ptr, std::ptr::null_mut()) }; |
| 230 | |
| 231 | Self::from_sys(req) |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | /// Represents a userspace notification response. |
| 236 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 237 | #[non_exhaustive] |
| 238 | pub struct ScmpNotifResp { |
| 239 | /// Notification ID (must match the corresponding `ScmpNotifReq` ID) |
| 240 | pub id: u64, |
| 241 | /// Return value for the syscall that created the notification. |
| 242 | /// Only relevant if the error is 0. |
| 243 | pub val: i64, |
| 244 | /// An error code. |
| 245 | /// Must be 0 if no error occurred, or an error constant from package |
| 246 | /// syscall (e.g., `libc::EPERM`, etc). In the latter case, it's used |
| 247 | /// as an error return from the syscall that created the notification. |
| 248 | pub error: i32, |
| 249 | /// Userspace notification response flag |
| 250 | pub flags: u32, |
| 251 | } |
| 252 | |
| 253 | impl ScmpNotifResp { |
| 254 | unsafe fn to_sys(self, resp: *mut seccomp_notif_resp) { |
| 255 | unsafe { |
| 256 | (*resp).id = self.id; |
| 257 | (*resp).val = self.val; |
| 258 | (*resp).error = self.error; |
| 259 | (*resp).flags = self.flags; |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | /// Creates `ScmpNotifResp` from the specified arguments. |
| 264 | /// |
| 265 | /// It is recommended to use the convenient functions [`new_val`](ScmpNotifResp::new_val), |
| 266 | /// [`new_error`](ScmpNotifResp::new_error) and [`new_continue`](ScmpNotifResp::new_continue) |
| 267 | /// rather than this function. |
| 268 | /// |
| 269 | /// # Arguments |
| 270 | /// |
| 271 | /// * `id` - Notification ID |
| 272 | /// * `val` - Return value for the syscall that created the notification |
| 273 | /// * `error` - An error code |
| 274 | /// * `flags` - Userspace notification response flag |
| 275 | /// |
| 276 | /// # Examples |
| 277 | /// |
| 278 | /// ```ignore |
| 279 | /// let resp = ScmpNotifResp::new(req.id, val, error, flags); |
| 280 | /// ``` |
| 281 | #[must_use] |
| 282 | pub fn new(id: u64, val: i64, error: i32, flags: u32) -> Self { |
| 283 | Self { |
| 284 | id, |
| 285 | val, |
| 286 | error, |
| 287 | flags, |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | /// Creates `ScmpNotifResp` for a spoofed success response. |
| 292 | /// |
| 293 | /// # Arguments |
| 294 | /// |
| 295 | /// * `id` - Notification ID |
| 296 | /// * `val` - Return value for the syscall that created the notification |
| 297 | /// * `flags` - Reserved for future use, specify as `ScmpNotifRespFlags::empty()`. |
| 298 | /// |
| 299 | /// # Examples |
| 300 | /// |
| 301 | /// ```ignore |
| 302 | /// let resp = ScmpNotifResp::new_val(req.id, val, ScmpNotifRespFlags::empty()); |
| 303 | /// ``` |
| 304 | #[must_use] |
| 305 | pub fn new_val(id: u64, val: i64, flags: ScmpNotifRespFlags) -> Self { |
| 306 | Self { |
| 307 | id, |
| 308 | val, |
| 309 | error: 0, |
| 310 | flags: flags.bits(), |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | /// Creates `ScmpNotifResp` for a spoofed error response. |
| 315 | /// |
| 316 | /// # Arguments |
| 317 | /// |
| 318 | /// * `id` - Notification ID |
| 319 | /// * `error` - An *negative* error code |
| 320 | /// * `flags` - Reserved for future use, specify as `ScmpNotifRespFlags::empty()`. |
| 321 | /// |
| 322 | /// # Examples |
| 323 | /// |
| 324 | /// ```ignore |
| 325 | /// let resp = ScmpNotifResp::new_error(req.id, error, ScmpNotifRespFlags::empty()); |
| 326 | /// ``` |
| 327 | #[must_use] |
| 328 | pub fn new_error(id: u64, error: i32, flags: ScmpNotifRespFlags) -> Self { |
| 329 | debug_assert!(error.is_negative()); |
| 330 | Self { |
| 331 | id, |
| 332 | val: 0, |
| 333 | error, |
| 334 | flags: flags.bits(), |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | /// Creates `ScmpNotifResp` which continues the syscall execution. |
| 339 | /// |
| 340 | /// # Arguments |
| 341 | /// |
| 342 | /// * `id` - Notification ID |
| 343 | /// * `flags` - Reserved for future use, specify as `ScmpNotifRespFlags::empty()`. |
| 344 | /// |
| 345 | /// # Examples |
| 346 | /// |
| 347 | /// ```ignore |
| 348 | /// let resp = ScmpNotifResp::new_continue(req.id, ScmpNotifRespFlags::empty()); |
| 349 | /// ``` |
| 350 | #[must_use] |
| 351 | pub fn new_continue(id: u64, flags: ScmpNotifRespFlags) -> Self { |
| 352 | Self { |
| 353 | id, |
| 354 | val: 0, |
| 355 | error: 0, |
| 356 | flags: ScmpNotifRespFlags::CONTINUE.bitor(flags).bits(), |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | /// Responds to a userspace notification retrieved via [`ScmpNotifReq::receive()`]. |
| 361 | /// |
| 362 | /// The response ID must match that of the corresponding notification retrieved |
| 363 | /// via [`ScmpNotifReq::receive()`]. |
| 364 | /// |
| 365 | /// This function corresponds to |
| 366 | /// [`seccomp_notify_respond`](https://man7.org/linux/man-pages/man3/seccomp_notify_respond.3.html). |
| 367 | /// |
| 368 | /// # Arguments |
| 369 | /// |
| 370 | /// * `fd` - A file descriptor for the userspace notification |
| 371 | /// |
| 372 | /// # Errors |
| 373 | /// |
| 374 | /// If an issue is encountered responding a notification, |
| 375 | /// an error will be returned. |
| 376 | /// |
| 377 | /// # Examples |
| 378 | /// |
| 379 | /// ``` |
| 380 | /// # use libseccomp::*; |
| 381 | /// # use std::process::exit; |
| 382 | /// // Get the current process ID |
| 383 | /// let parent_pid = std::process::id(); |
| 384 | /// let mut ctx = ScmpFilterContext::new(ScmpAction::Allow)?; |
| 385 | /// ctx.add_rule(ScmpAction::Notify, ScmpSyscall::from_name("getpid")?)?; |
| 386 | /// ctx.load()?; |
| 387 | /// let fd = ctx.get_notify_fd()?; |
| 388 | /// let pid = unsafe { libc::fork() }; |
| 389 | /// if pid == 0 { |
| 390 | /// // Child process |
| 391 | /// |
| 392 | /// let child_pid = std::process::id(); |
| 393 | /// // The child PID will be same as the parent PID by the user notification. |
| 394 | /// assert_eq!(child_pid, parent_pid); |
| 395 | /// exit(0); |
| 396 | /// } |
| 397 | /// let req = ScmpNotifReq::receive(fd)?; |
| 398 | /// let resp = ScmpNotifResp::new_val(req.id, parent_pid as i64, ScmpNotifRespFlags::empty()); |
| 399 | /// resp.respond(fd); |
| 400 | /// # Ok::<(), Box<dyn std::error::Error>>(()) |
| 401 | /// ``` |
| 402 | pub fn respond(&self, fd: ScmpFd) -> Result<()> { |
| 403 | notify_supported()?; |
| 404 | |
| 405 | let mut resp_ptr: *mut seccomp_notif_resp = std::ptr::null_mut(); |
| 406 | |
| 407 | // We only use the response here; the request is unused. |
| 408 | cvt(unsafe { seccomp_notify_alloc(std::ptr::null_mut(), &mut resp_ptr) })?; |
| 409 | |
| 410 | unsafe { self.to_sys(resp_ptr) }; |
| 411 | |
| 412 | loop { |
| 413 | let ret = unsafe { seccomp_notify_respond(fd, resp_ptr) }; |
| 414 | let errno = get_errno(); |
| 415 | |
| 416 | if ret == 0 { |
| 417 | break; |
| 418 | } else if errno == libc::EINTR { |
| 419 | continue; |
| 420 | } else { |
| 421 | unsafe { seccomp_notify_free(std::ptr::null_mut(), resp_ptr) }; |
| 422 | return Err(SeccompError::from_errno(ret)); |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | unsafe { seccomp_notify_free(std::ptr::null_mut(), resp_ptr) }; |
| 427 | |
| 428 | Ok(()) |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | /// Checks if a userspace notification is still valid. |
| 433 | /// |
| 434 | /// A return value of `Ok` means the notification is still valid. |
| 435 | /// Otherwise the notification is not valid. This can be used to mitigate |
| 436 | /// time-of-check-time-of-use (TOCTOU) attacks as described in [`seccomp_notify_id_valid(2)`]. |
| 437 | /// |
| 438 | /// [`seccomp_notify_id_valid(2)`]: https://man7.org/linux/man-pages/man3/seccomp_notify_id_valid.3.html |
| 439 | /// |
| 440 | /// This function corresponds to |
| 441 | /// [`seccomp_notify_id_valid`](https://man7.org/linux/man-pages/man3/seccomp_notify_id_valid.3.html). |
| 442 | /// |
| 443 | /// # Arguments |
| 444 | /// |
| 445 | /// * `fd` - A file descriptor for the userspace notification |
| 446 | /// * `id` - Notification ID |
| 447 | /// |
| 448 | /// # Errors |
| 449 | /// |
| 450 | /// If the notification ID is invalid, an error will be returned. |
| 451 | /// |
| 452 | /// # Examples |
| 453 | /// |
| 454 | /// ``` |
| 455 | /// # use libseccomp::*; |
| 456 | /// # use std::{fs::File, io::Read, process::Command, thread}; |
| 457 | /// let notify_fd = thread::spawn(|| -> Result<ScmpFd, error::SeccompError> { |
| 458 | /// let mut ctx = ScmpFilterContext::new(ScmpAction::Allow)?; |
| 459 | /// ctx.add_rule(ScmpAction::Notify, ScmpSyscall::from_name("openat")?)? |
| 460 | /// .load()?; |
| 461 | /// let notify_fd = ctx.get_notify_fd()?; |
| 462 | /// |
| 463 | /// /// Example command execution |
| 464 | /// let _ = Command::new("ls").spawn(); |
| 465 | /// Ok(notify_fd) |
| 466 | /// }) |
| 467 | /// .join() |
| 468 | /// .unwrap()?; |
| 469 | /// |
| 470 | /// let req = ScmpNotifReq::receive(notify_fd)?; |
| 471 | /// assert_eq!(req.data.arch, ScmpArch::native()); |
| 472 | /// assert_eq!(req.data.syscall, ScmpSyscall::from_name("openat")?); |
| 473 | /// |
| 474 | /// let mut stat = File::open(&format!("/proc/{}/stat", req.pid))?; |
| 475 | /// |
| 476 | /// // Checks if a notification is still valid. |
| 477 | /// notify_id_valid(notify_fd, req.id)?; |
| 478 | /// |
| 479 | /// let mut stat_data = String::new(); |
| 480 | /// let _ = stat.read_to_string(&mut stat_data)?; |
| 481 | /// println!("{}", stat_data); |
| 482 | /// |
| 483 | /// // Checks if a notification is still valid. |
| 484 | /// notify_id_valid(notify_fd, req.id)?; |
| 485 | /// |
| 486 | /// let resp = ScmpNotifResp::new_continue(req.id, ScmpNotifRespFlags::empty()); |
| 487 | /// resp.respond(notify_fd)?; |
| 488 | /// # Ok::<(), Box<dyn std::error::Error>>(()) |
| 489 | /// ``` |
| 490 | pub fn notify_id_valid(fd: ScmpFd, id: u64) -> Result<()> { |
| 491 | notify_supported()?; |
| 492 | |
| 493 | loop { |
| 494 | let ret = unsafe { seccomp_notify_id_valid(fd, id) }; |
| 495 | let errno = get_errno(); |
| 496 | |
| 497 | if ret == 0 { |
| 498 | break; |
| 499 | } else if errno == libc::EINTR { |
| 500 | continue; |
| 501 | } else { |
| 502 | return Err(SeccompError::from_errno(ret)); |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | Ok(()) |
| 507 | } |