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