libseccomp 0.4.0

Rust Language Bindings for the libseccomp Library
Documentation
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
// SPDX-License-Identifier: Apache-2.0 or MIT
//
// Copyright 2021 Sony Group Corporation
//

use std::borrow::Cow;
use std::error::Error;
use std::fmt;
use std::ops::Deref;

pub(crate) type Result<T> = std::result::Result<T, SeccompError>;

/// Errnos returned by the libseccomp API.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
// https://github.com/seccomp/libseccomp/blob/3c0dedd45713d7928c459b6523b78f4cfd435269/src/api.c#L60
pub enum SeccompErrno {
    /// The library doesn't permit the particular operation.
    EACCES,
    /// There was a system failure beyond the control of libseccomp.
    ECANCELED,
    /// Architecture/ABI specific failure.
    EDOM,
    /// Failure regarding the existence of argument.
    EEXIST,
    /// Internal libseccomp failure.
    EFAULT,
    /// Invalid input to the libseccomp API.
    EINVAL,
    /// No matching entry found.
    ENOENT,
    /// Unable to allocate enough memory to perform the requested operation.
    ENOMEM,
    /// The library doesn't support the particular operation.
    EOPNOTSUPP,
    /// Provided buffer is too small.
    ERANGE,
    /// Unable to load the filter due to thread issues.
    ESRCH,
}

impl SeccompErrno {
    fn strerror(&self) -> &'static str {
        use SeccompErrno::*;

        match self {
            EACCES => "The library doesn't permit the particular operation",
            ECANCELED => "There was a system failure beyond the control of libseccomp",
            EDOM => "Architecture/ABI specific failure",
            EEXIST => "Failure regarding the existence of argument",
            EFAULT => "Internal libseccomp failure",
            EINVAL => "Invalid input to the libseccomp API",
            ENOENT => "No matching entry found",
            ENOMEM => "Unable to allocate enough memory to perform the requested operation",
            EOPNOTSUPP => "The library doesn't support the particular operation",
            ERANGE => "Provided buffer is too small",
            ESRCH => "Unable to load the filter due to thread issues",
        }
    }

    fn to_sysrawrc(self) -> i32 {
        use SeccompErrno::*;

        match self {
            EACCES => libc::EACCES,
            ECANCELED => libc::ECANCELED,
            EDOM => libc::EDOM,
            EEXIST => libc::EEXIST,
            EFAULT => libc::EFAULT,
            EINVAL => libc::EINVAL,
            ENOENT => libc::ENOENT,
            ENOMEM => libc::ENOMEM,
            EOPNOTSUPP => libc::EOPNOTSUPP,
            ERANGE => libc::ERANGE,
            ESRCH => libc::ESRCH,
        }
    }
}

impl fmt::Display for SeccompErrno {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.strerror())
    }
}

/// A list specifying different categories of error.
#[derive(Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub(crate) enum ErrorKind {
    /// An error that represents error code on failure of the libseccomp API.
    Errno(SeccompErrno),
    /// A system's raw error code.
    SysRawRc(i32),
    /// An invalid Architecture.
    InvalidArch(u32),
    /// An invalid Action.
    InvalidAction(u32),
    /// An invalid string in from_str.
    FromStr(String),
    /// A lower-level error that is caused by an error from a lower-level module.
    Source,
    /// A custom error that does not fall under any other error kind.
    Common(Cow<'static, str>),
}

/// The error type for libseccomp operations.
pub struct SeccompError {
    kind: ErrorKind,
    source: Option<Box<dyn Error + Send + Sync>>,
}

impl SeccompError {
    pub(crate) fn new(kind: ErrorKind) -> Self {
        Self { kind, source: None }
    }

    pub(crate) fn with_source<E>(kind: ErrorKind, source: E) -> Self
    where
        E: Error + Send + Sync + 'static,
    {
        Self {
            kind,
            source: Some(Box::new(source)),
        }
    }

    pub(crate) fn with_msg<M>(msg: M) -> Self
    where
        M: Into<Cow<'static, str>>,
    {
        Self {
            kind: ErrorKind::Common(msg.into()),
            source: None,
        }
    }

    #[allow(dead_code)]
    pub(crate) fn with_msg_and_source<M, E>(msg: M, source: E) -> Self
    where
        M: Into<Cow<'static, str>>,
        E: Error + Send + Sync + 'static,
    {
        Self {
            kind: ErrorKind::Common(msg.into()),
            source: Some(Box::new(source)),
        }
    }

    pub(crate) fn from_errno(raw_errno: i32) -> Self {
        let seccomp_errno = match -raw_errno {
            libc::EACCES => SeccompErrno::EACCES,
            libc::ECANCELED => SeccompErrno::ECANCELED,
            libc::EDOM => SeccompErrno::EDOM,
            libc::EEXIST => SeccompErrno::EEXIST,
            libc::EFAULT => SeccompErrno::EFAULT,
            libc::EINVAL => SeccompErrno::EINVAL,
            libc::ENOENT => SeccompErrno::ENOENT,
            libc::ENOMEM => SeccompErrno::ENOMEM,
            libc::EOPNOTSUPP => SeccompErrno::EOPNOTSUPP,
            libc::ERANGE => SeccompErrno::ERANGE,
            libc::ESRCH => SeccompErrno::ESRCH,
            _ => return Self::new(ErrorKind::SysRawRc(raw_errno)),
        };
        Self::new(ErrorKind::Errno(seccomp_errno))
    }

    /// Query the errno returned by the libseccomp API.
    pub fn errno(&self) -> Option<SeccompErrno> {
        if let ErrorKind::Errno(errno) = self.kind {
            Some(errno)
        } else {
            None
        }
    }

    /// Query the system's raw error code returned when something goes wrong
    /// in the libc and the kernel.
    ///
    /// This function will be useful for users who want to extract the system's
    /// error code directly returned by [`ScmpFilterAttr::ApiSysRawRc`](`crate::ScmpFilterAttr::ApiSysRawRc`)
    /// , or get the errno returned by the libseccomp API as a negative integer rather than [`SeccompErrno`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use libseccomp::*;
    /// match set_api(1000) {
    ///     Err(e) => {
    ///         eprintln!("Error: {e}");
    ///         if let Some(sys) = e.sysrawrc() {
    ///             eprintln!("The system's raw error code: {sys}");
    ///             assert_eq!(sys, -libc::EINVAL);
    ///         }
    ///     }
    ///     _ => println!("No error"),
    /// }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn sysrawrc(&self) -> Option<i32> {
        match self.kind {
            ErrorKind::SysRawRc(rc) => Some(rc),
            ErrorKind::Errno(errno) => Some(-errno.to_sysrawrc()),
            _ => None,
        }
    }

    /// Returns the raw ffi value of an unsupported Action/Arch.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libseccomp::*;
    /// let mut ctx = ScmpFilterContext::new(ScmpAction::Allow)?;
    /// if let Err(err) = ctx.get_act_default() {
    ///     println!("{:#?}", err.raw_ffi_value())
    /// }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn raw_ffi_value(&self) -> Option<u32> {
        match self.kind {
            ErrorKind::InvalidArch(v) | ErrorKind::InvalidAction(v) => Some(v),
            _ => None,
        }
    }

    fn msg(&self) -> Cow<'_, str> {
        match &self.kind {
            ErrorKind::Errno(e) => e.strerror().into(),
            ErrorKind::SysRawRc(e) => {
                format!("The system's raw error code({}) was returned", e).into()
            }
            ErrorKind::InvalidArch(_) => "Parse error by invalid architecture".into(),
            ErrorKind::InvalidAction(_) => "Parse error by invalid action".into(),
            ErrorKind::FromStr(s) => format!("Error while parsing '{s}'").into(),
            ErrorKind::Source => self.source.as_ref().unwrap().to_string().into(),
            ErrorKind::Common(s) => s.deref().into(),
        }
    }
}

impl fmt::Display for SeccompError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let msg = self.msg();

        match &self.source {
            Some(source) if self.kind != ErrorKind::Source => {
                write!(f, "{} caused by: {}", msg, source)
            }
            Some(_) | None => {
                write!(f, "{}", msg)
            }
        }
    }
}

impl fmt::Debug for SeccompError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Error")
            .field("kind", &self.kind)
            .field("source", &self.source)
            .field("message", &self.msg())
            .finish()
    }
}

impl Error for SeccompError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match &self.source {
            Some(error) => Some(error.as_ref()),
            None => None,
        }
    }
}

/* Does not work without specialization (RFC 1210) or negative trait bounds
impl<T: Error> From<T> for SeccompError {
    fn from(err: T) -> Self {
        Self::with_source(ErrorKind::Source, err)
    }
}
*/

macro_rules! impl_seccomperror_from {
    ($errty:ty) => {
        impl From<$errty> for SeccompError {
            fn from(err: $errty) -> Self {
                Self::with_source(ErrorKind::Source, err)
            }
        }
    };
}
impl_seccomperror_from!(std::ffi::NulError);
impl_seccomperror_from!(std::num::TryFromIntError);
impl_seccomperror_from!(std::str::Utf8Error);

#[cfg(test)]
mod tests {
    use super::ErrorKind::*;
    use super::*;
    use std::ffi::CString;

    const TEST_ERR_MSG: &str = "test error";
    const TEST_NULL_STR: &str = "f\0oo";
    const NULL_ERR_MSG: &str = "nul byte found in provided data at position: 1";

    #[test]
    fn test_msg() {
        let null_err = CString::new(TEST_NULL_STR).unwrap_err();

        // Errno
        assert_eq!(
            SeccompError::from_errno(-libc::EACCES).msg(),
            SeccompErrno::EACCES.strerror()
        );
        assert_eq!(
            SeccompError::from_errno(-libc::ECANCELED).msg(),
            SeccompErrno::ECANCELED.strerror()
        );
        assert_eq!(
            SeccompError::from_errno(-libc::EDOM).msg(),
            SeccompErrno::EDOM.strerror()
        );
        assert_eq!(
            SeccompError::from_errno(-libc::EEXIST).msg(),
            SeccompErrno::EEXIST.strerror()
        );
        assert_eq!(
            SeccompError::from_errno(-libc::EFAULT).msg(),
            SeccompErrno::EFAULT.strerror()
        );
        assert_eq!(
            SeccompError::from_errno(-libc::EINVAL).msg(),
            SeccompErrno::EINVAL.strerror()
        );
        assert_eq!(
            SeccompError::from_errno(-libc::ENOENT).msg(),
            SeccompErrno::ENOENT.strerror()
        );
        assert_eq!(
            SeccompError::from_errno(-libc::ENOMEM).msg(),
            SeccompErrno::ENOMEM.strerror()
        );
        assert_eq!(
            SeccompError::new(Errno(SeccompErrno::EOPNOTSUPP)).msg(),
            SeccompErrno::EOPNOTSUPP.strerror(),
        );
        assert_eq!(
            SeccompError::from_errno(-libc::ERANGE).msg(),
            SeccompErrno::ERANGE.strerror()
        );
        assert_eq!(
            SeccompError::from_errno(-libc::ESRCH).msg(),
            SeccompErrno::ESRCH.strerror()
        );

        // Common
        assert_eq!(
            SeccompError::new(Common(TEST_ERR_MSG.into())).msg(),
            TEST_ERR_MSG
        );

        // Source
        assert_eq!(
            SeccompError::with_source(Source, null_err).msg(),
            NULL_ERR_MSG
        );

        // SysRawRc
        assert_eq!(
            SeccompError::from_errno(-libc::EPIPE).msg(),
            format!("The system's raw error code({}) was returned", -libc::EPIPE)
        );

        // InvalidArch
        assert_eq!(
            SeccompError::new(InvalidArch(123)).msg(),
            "Parse error by invalid architecture",
        );

        // InvalidAction
        assert_eq!(
            SeccompError::new(InvalidAction(123)).msg(),
            "Parse error by invalid action",
        );

        // FromStr
        assert_eq!(
            SeccompError::new(FromStr("SCMP".to_string())).msg(),
            "Error while parsing 'SCMP'",
        );
    }

    #[test]
    fn test_source() {
        let null_err = CString::new(TEST_NULL_STR).unwrap_err();

        assert!(SeccompError::new(Errno(SeccompErrno::EACCES))
            .source()
            .is_none());
        assert!(
            SeccompError::with_source(Errno(SeccompErrno::EACCES), null_err)
                .source()
                .is_some()
        );
    }

    #[test]
    fn test_with_msg() {
        assert_eq!(SeccompError::with_msg(TEST_ERR_MSG).msg(), TEST_ERR_MSG);
        assert!(SeccompError::with_msg(TEST_ERR_MSG).source().is_none());
    }

    #[test]
    fn test_with_msg_and_source() {
        let null_err = CString::new(TEST_NULL_STR).unwrap_err();

        assert_eq!(
            SeccompError::with_msg_and_source(TEST_ERR_MSG, null_err.clone()).msg(),
            TEST_ERR_MSG
        );
        assert!(SeccompError::with_msg_and_source(TEST_ERR_MSG, null_err)
            .source()
            .is_some());
    }

    #[test]
    fn test_errno() {
        assert_eq!(
            SeccompError::from_errno(-libc::EACCES).errno().unwrap(),
            SeccompErrno::EACCES
        );
        assert!(SeccompError::from_errno(libc::EBADFD).errno().is_none());
    }

    #[test]
    fn test_sysrawrc() {
        let tests = &[
            // The EBADFD is not handled by SeccompErrno
            libc::EBADFD,
            // The following errnos are handled by SeccompErrno
            libc::EACCES,
            libc::ECANCELED,
            libc::EDOM,
            libc::EEXIST,
            libc::EFAULT,
            libc::EINVAL,
            libc::ENOENT,
            libc::ENOMEM,
            libc::EOPNOTSUPP,
            libc::ERANGE,
            libc::ESRCH,
        ];

        for errno in tests {
            assert_eq!(SeccompError::from_errno(-errno).sysrawrc().unwrap(), -errno);
        }
        assert!(SeccompError::with_msg("no errno").sysrawrc().is_none());
    }

    #[test]
    fn test_raw_ffi_value() {
        assert_eq!(
            SeccompError::new(InvalidArch(123)).raw_ffi_value().unwrap(),
            123
        );
        assert_eq!(
            SeccompError::new(InvalidAction(123))
                .raw_ffi_value()
                .unwrap(),
            123
        );
        assert!(SeccompError::new(Common("".into()))
            .raw_ffi_value()
            .is_none());
    }

    #[test]
    fn test_from() {
        let null_err = CString::new(TEST_NULL_STR).unwrap_err();
        let scmp_err = SeccompError::from(null_err.clone());

        assert_eq!(scmp_err.kind, ErrorKind::Source);
        assert_eq!(scmp_err.source().unwrap().to_string(), null_err.to_string());
    }

    #[test]
    fn test_display() {
        let null_err = CString::new(TEST_NULL_STR).unwrap_err();

        // fmt::Display for SeccompErrno
        assert_eq!(
            format!("{}", SeccompErrno::EACCES),
            SeccompErrno::EACCES.strerror()
        );

        // Errno without source
        assert_eq!(
            format!("{}", SeccompError::new(Errno(SeccompErrno::EACCES))),
            SeccompErrno::EACCES.strerror()
        );
        // Errno with source
        assert_eq!(
            format!(
                "{}",
                SeccompError::with_source(Errno(SeccompErrno::EACCES), null_err.clone())
            ),
            format!(
                "{} caused by: {}",
                SeccompErrno::EACCES.strerror(),
                NULL_ERR_MSG
            )
        );

        // Common without source
        assert_eq!(
            format!("{}", SeccompError::new(Common(TEST_ERR_MSG.into()))),
            TEST_ERR_MSG
        );
        // Common with source
        assert_eq!(
            format!(
                "{}",
                SeccompError::with_source(Common(TEST_ERR_MSG.into()), null_err.clone())
            ),
            format!("{} caused by: {}", TEST_ERR_MSG, NULL_ERR_MSG)
        );

        // Source
        assert_eq!(
            format!("{}", SeccompError::with_source(ErrorKind::Source, null_err)),
            NULL_ERR_MSG
        );
    }

    #[test]
    fn test_debug() {
        let null_err = CString::new(TEST_NULL_STR).unwrap_err();

        // Errno without source
        assert_eq!(
            format!("{:?}", SeccompError::new(Errno(SeccompErrno::EACCES))),
            format!(
                "Error {{ kind: Errno({}), source: {}, message: \"{}\" }}",
                "EACCES",
                "None",
                SeccompErrno::EACCES.strerror()
            )
        );
        // Errno with source
        assert_eq!(
            format!(
                "{:?}",
                SeccompError::with_source(Errno(SeccompErrno::EACCES), null_err),
            ),
            format!(
                "Error {{ kind: Errno({}), source: {}, message: \"{}\" }}",
                "EACCES",
                "Some(NulError(1, [102, 0, 111, 111]))",
                SeccompErrno::EACCES.strerror()
            )
        );
    }
}