landlock 0.4.5

Landlock LSM helpers
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Landlock is a security feature available since Linux 5.13.
//! The goal is to enable to restrict ambient rights
//! (e.g., global filesystem access)
//! for a set of processes by creating safe security sandboxes as new security layers
//! in addition to the existing system-wide access-controls.
//! This kind of sandbox is expected to help mitigate the security impact of bugs,
//! unexpected or malicious behaviors in applications.
//! Landlock empowers any process, including unprivileged ones, to securely restrict themselves.
//! More information about Landlock can be found in the [official website](https://landlock.io).
//!
//! This crate provides a safe abstraction for the Landlock system calls, along with some helpers.
//!
//! Minimum Supported Rust Version (MSRV): 1.71
//!
//! # Use cases
//!
//! This crate is especially useful to protect users' data by sandboxing:
//! * trusted applications dealing with potentially malicious data
//!   (e.g., complex file format, network request) that could exploit security vulnerabilities;
//! * sandbox managers, container runtimes or shells launching untrusted applications.
//!
//! # Examples
//!
//! A simple example can be found with the [`path_beneath_rules()`] helper.
//! More complex examples can be found with the [`Ruleset` documentation](Ruleset)
//! and the [sandboxer example](https://github.com/landlock-lsm/rust-landlock/blob/master/examples/sandboxer.rs).
//!
//! # Current limitations
//!
//! This crate exposes the Landlock features available as of Linux 6.15 (Landlock [ABI v7](ABI::V7))
//! and then inherits some [kernel limitations](https://www.kernel.org/doc/html/latest/userspace-api/landlock.html#current-limitations)
//! that will be addressed with future kernel releases
//! (e.g., arbitrary mounts are always denied).
//!
//! # Compatibility
//!
//! Types defined in this crate are designed to enable the strictest Landlock configuration
//! for the given kernel on which the program runs.
//! In the default [best-effort](CompatLevel::BestEffort) mode,
//! [`Ruleset`] will determine compatibility
//! with the intersection of the currently running kernel's features
//! and those required by the caller.
//! This way, callers can distinguish between
//! Landlock compatibility issues inherent to the current system
//! (e.g., file names that don't exist)
//! and misconfiguration that should be fixed in the program
//! (e.g., empty or inconsistent access rights).
//! [`RulesetError`] identifies such kind of errors.
//!
//! With [`set_compatibility(CompatLevel::BestEffort)`](Compatible::set_compatibility),
//! users of the crate may mark Landlock features that are deemed required
//! and other features that may be downgraded to use lower security on systems
//! where they can't be enforced.
//! It is discouraged to compare the system's provided [Landlock ABI](ABI) version directly,
//! as it is difficult to track detailed ABI differences
//! which are handled thanks to the [`Compatible`] trait.
//!
//! To make it easier to migrate to a new version of this library,
//! we use the builder pattern
//! and designed objects to require the minimal set of method arguments.
//! Most `enum` are marked as `non_exhaustive` to enable backward-compatible evolutions.
//!
//! ## Test strategy
//!
//! Developers should test their sandboxed applications
//! with a kernel that supports all requested Landlock features
//! and check that [`RulesetCreated::restrict_self()`] returns a status matching
//! [`Ok(RestrictionStatus { ruleset: RulesetStatus::FullyEnforced, no_new_privs: true, })`](RestrictionStatus)
//! to make sure everything works as expected in an enforced sandbox.
//! Alternatively, using [`set_compatibility(CompatLevel::HardRequirement)`](Compatible::set_compatibility)
//! will immediately inform about unsupported Landlock features.
//! These configurations should only depend on the test environment
//! (e.g. [by checking an environment variable](https://github.com/landlock-lsm/rust-landlock/search?q=LANDLOCK_CRATE_TEST_ABI)).
//! However, applications should only check that no error is returned (i.e. `Ok(_)`)
//! and optionally log and inform users that the application is not fully sandboxed
//! because of missing features from the running kernel.
//!
//! ## Audit logging
//!
//! Landlock ABI v7 adds control over audit logging through boolean setters, especially
//! [`log_new_exec()`](RulesetCreatedAttr::log_new_exec)) which is useful (but noisy) for sandboxer
//! tools.

#[cfg(test)]
#[macro_use]
extern crate lazy_static;

pub use access::{Access, HandledAccess};
pub use compat::{CompatLevel, Compatible, LandlockStatus, ABI};
pub use enumflags2::{make_bitflags, BitFlags};
pub use errata::Erratum;
pub use errors::{
    AccessError, AddRuleError, AddRulesError, CompatError, CreateRulesetError, Errno,
    HandleAccessError, HandleAccessesError, PathBeneathError, PathFdError, RestrictSelfError,
    RulesetError, ScopeError, SyscallFlagError,
};
pub use flags::{RestrictSelfFlag, SyscallFlag};
pub use fs::{path_beneath_rules, AccessFs, PathBeneath, PathFd};
pub use net::{AccessNet, NetPort};
pub use restrict_self::{RestrictSelf, RestrictSelfAttr, RestrictSelfStatus};
pub use ruleset::{
    RestrictionStatus, Rule, Ruleset, RulesetAttr, RulesetCreated, RulesetCreatedAttr,
    RulesetStatus,
};
pub use scope::Scope;

use access::PrivateHandledAccess;
use compat::{CompatResult, CompatState, Compatibility, TailoredCompatLevel, TryCompat};
use ruleset::PrivateRule;

#[cfg(test)]
use compat::{can_emulate, get_errno_from_landlock_status};
#[cfg(test)]
use errors::TestRulesetError;
#[cfg(test)]
use strum::IntoEnumIterator;

mod access;
mod compat;
mod errata;
mod errors;
mod flags;
mod fs;
mod net;
mod prctl;
mod restrict_self;
mod ruleset;
mod scope;
mod uapi;

// Makes sure private traits cannot be implemented outside of this crate.
mod private {
    pub trait Sealed {}

    impl Sealed for crate::AccessFs {}
    impl Sealed for crate::AccessNet {}
    impl Sealed for crate::Scope {}
    impl Sealed for crate::RestrictSelfFlag {}
}

#[cfg(test)]
mod tests {
    use crate::*;

    // These integration tests exercise the full builder-to-syscall path via
    // check_ruleset_support().  Other tests in compat.rs and errata.rs make
    // read-only kernel queries (LandlockStatus::current(), Erratum::current())
    // but do not create rulesets or restrict threads.  All remaining tests use
    // Ruleset::from(ABI) to exercise the builder logic and compatibility
    // engine without kernel interaction.

    // Emulate old kernel supports.  Iterates each ABI variant, mocks the
    // builder via B::from(abi), runs the closure on a dedicated thread, and
    // dispatches to the caller's assertion closures based on whether the
    // mocked ABI is emulatable on the running kernel.
    fn check_support<B, S, F, OkFn, ErrFn>(
        partial: ABI,
        full: Option<ABI>,
        check: F,
        assert_ok: OkFn,
        assert_err: ErrFn,
    ) where
        B: From<ABI> + Send + 'static,
        F: Fn(B) -> Result<S, TestRulesetError> + Send + Copy + 'static,
        S: std::fmt::Debug + Send + 'static,
        OkFn: Fn(ABI, Result<S, TestRulesetError>),
        ErrFn: Fn(Result<S, TestRulesetError>),
    {
        // If there is no partial support, it means that `full == partial`.
        assert!(partial <= full.unwrap_or(partial));
        for abi in ABI::iter() {
            // Ensures restrict_self() is called on a dedicated thread to avoid inconsistent tests.
            let ret = std::thread::spawn(move || check(B::from(abi)))
                .join()
                .unwrap();

            // Useful for failed tests and with cargo test -- --show-output
            println!("Checking ABI {abi:?}: received {ret:#?}");
            if can_emulate(abi, partial, full) {
                assert_ok(abi, ret);
            } else {
                assert_err(ret);
            }
        }
    }

    fn check_ruleset_support<F>(
        partial: ABI,
        full: Option<ABI>,
        check: F,
        error_if_abi_lt_partial: bool,
    ) where
        F: Fn(Ruleset) -> Result<RestrictionStatus, TestRulesetError> + Send + Copy + 'static,
    {
        check_support(
            partial,
            full,
            check,
            |abi, ret| {
                if abi < partial && error_if_abi_lt_partial {
                    // TODO: Check exact error type; this may require better error types.
                    assert!(matches!(ret, Err(TestRulesetError::Ruleset(_))));
                } else {
                    let full_support = if let Some(full_inner) = full {
                        abi >= full_inner
                    } else {
                        false
                    };
                    let ruleset_status = if full_support {
                        RulesetStatus::FullyEnforced
                    } else if abi >= partial {
                        RulesetStatus::PartiallyEnforced
                    } else {
                        RulesetStatus::NotEnforced
                    };
                    let landlock_status = abi.into();
                    println!("Expecting ruleset status {ruleset_status:?}");
                    println!("Expecting Landlock status {landlock_status:?}");
                    assert!(matches!(
                        ret,
                        Ok(RestrictionStatus {
                            ruleset,
                            landlock,
                            no_new_privs: true,
                            ..
                        }) if ruleset == ruleset_status && landlock == landlock_status
                    ))
                }
            },
            |ret| {
                // The errno value should be ENOSYS, EOPNOTSUPP, EINVAL (e.g. when an unknown
                // access right is provided), or E2BIG (e.g. when there is an unknown field in a
                // Landlock syscall attribute).
                let errno = get_errno_from_landlock_status();
                println!("Expecting error {errno:?}");
                match ret {
                    Err(
                        ref error @ TestRulesetError::Ruleset(RulesetError::CreateRuleset(
                            CreateRulesetError::CreateRulesetCall { ref source },
                        )),
                    ) => {
                        assert_eq!(source.raw_os_error(), Some(*Errno::from(error)));
                        match (source.raw_os_error(), errno) {
                            (Some(e1), Some(e2)) => assert_eq!(e1, e2),
                            (Some(e1), None) => assert!(matches!(e1, libc::EINVAL | libc::E2BIG)),
                            _ => unreachable!(),
                        }
                    }
                    // restrict_self flags may be rejected by the kernel with EINVAL
                    // when the mock ABI is higher than the running kernel's ABI.
                    Err(TestRulesetError::Ruleset(RulesetError::RestrictSelf(
                        RestrictSelfError::RestrictSelfCall { ref source },
                    ))) => {
                        assert_eq!(source.raw_os_error(), Some(libc::EINVAL));
                    }
                    _ => unreachable!(),
                }
            },
        );
    }

    // Emulate old kernel supports for the domain-less RestrictSelf builder.
    //
    // Unlike check_ruleset_support, RestrictSelf does not create a Landlock domain, so there is no
    // ruleset enforcement status to assert.  We verify the kernel probe (status.landlock) and
    // propagate any syscall error.  RestrictSelf::apply() enforces PR_SET_NO_NEW_PRIVS by default.
    fn check_restrict_self_support<F>(partial: ABI, full: Option<ABI>, check: F)
    where
        F: Fn(RestrictSelf) -> Result<RestrictSelfStatus, TestRulesetError> + Send + Copy + 'static,
    {
        check_support(
            partial,
            full,
            check,
            |abi, ret| {
                let landlock_status: LandlockStatus = abi.into();
                println!("Expecting Landlock status {landlock_status:?}");
                assert!(matches!(
                    ret,
                    Ok(RestrictSelfStatus { landlock, .. }) if landlock == landlock_status
                ));
            },
            |ret| {
                // The errno value should be ENOSYS, EOPNOTSUPP, or EINVAL (e.g. when actual_flags
                // carries bits unknown to the running kernel).  Unlike check_ruleset_support,
                // landlock_restrict_self() is the first syscall here, so ENOSYS is possible when
                // Landlock is unavailable.
                let errno = get_errno_from_landlock_status();
                println!("Expecting error {errno:?}");
                match ret {
                    Err(
                        ref error @ TestRulesetError::Ruleset(RulesetError::RestrictSelf(
                            RestrictSelfError::RestrictSelfCall { ref source },
                        )),
                    ) => {
                        assert_eq!(source.raw_os_error(), Some(*Errno::from(error)));
                        match (source.raw_os_error(), errno) {
                            (Some(e1), Some(e2)) => assert_eq!(e1, e2),
                            (Some(e1), None) => assert!(matches!(e1, libc::EINVAL | libc::E2BIG)),
                            _ => unreachable!(),
                        }
                    }
                    _ => unreachable!(),
                }
            },
        );
    }

    #[test]
    fn allow_root_compat() {
        let abi = ABI::V1;

        check_ruleset_support(
            abi,
            Some(abi),
            move |ruleset: Ruleset| -> _ {
                Ok(ruleset
                    .handle_access(AccessFs::from_all(abi))?
                    .create()?
                    .add_rule(PathBeneath::new(PathFd::new("/")?, AccessFs::from_all(abi)))?
                    .restrict_self()?)
            },
            false,
        );
    }

    #[test]
    fn too_much_access_rights_for_a_file() {
        let abi = ABI::V1;

        check_ruleset_support(
            abi,
            Some(abi),
            move |ruleset: Ruleset| -> _ {
                Ok(ruleset
                    .handle_access(AccessFs::from_all(abi))?
                    .create()?
                    // Same code as allow_root_compat() but with /etc/passwd instead of /
                    .add_rule(PathBeneath::new(
                        PathFd::new("/etc/passwd")?,
                        // Only allow legitimate access rights on a file.
                        AccessFs::from_file(abi),
                    ))?
                    .restrict_self()?)
            },
            false,
        );

        check_ruleset_support(
            abi,
            None,
            move |ruleset: Ruleset| -> _ {
                Ok(ruleset
                    .handle_access(AccessFs::from_all(abi))?
                    .create()?
                    // Same code as allow_root_compat() but with /etc/passwd instead of /
                    .add_rule(PathBeneath::new(
                        PathFd::new("/etc/passwd")?,
                        // Tries to allow all access rights on a file.
                        AccessFs::from_all(abi),
                    ))?
                    .restrict_self()?)
            },
            false,
        );
    }

    #[test]
    fn path_beneath_rules_with_too_much_access_rights_for_a_file() {
        let abi = ABI::V1;

        check_ruleset_support(
            abi,
            Some(abi),
            move |ruleset: Ruleset| -> _ {
                Ok(ruleset
                    .handle_access(AccessFs::from_all(ABI::V1))?
                    .create()?
                    // Same code as too_much_access_rights_for_a_file() but using path_beneath_rules()
                    .add_rules(path_beneath_rules(["/etc/passwd"], AccessFs::from_all(abi)))?
                    .restrict_self()?)
            },
            false,
        );
    }

    #[test]
    fn allow_root_fragile() {
        let abi = ABI::V1;

        check_ruleset_support(
            abi,
            Some(abi),
            move |ruleset: Ruleset| -> _ {
                // Sets default support requirement: abort the whole sandboxing for any Landlock error.
                Ok(ruleset
                    // Must have at least the execute check…
                    .set_compatibility(CompatLevel::HardRequirement)
                    .handle_access(AccessFs::Execute)?
                    // …and possibly others.
                    .set_compatibility(CompatLevel::BestEffort)
                    .handle_access(AccessFs::from_all(abi))?
                    .create()?
                    .no_new_privs(true)
                    .add_rule(PathBeneath::new(PathFd::new("/")?, AccessFs::from_all(abi)))?
                    .restrict_self()?)
            },
            true,
        );
    }

    #[test]
    fn ruleset_enforced() {
        let abi = ABI::V1;

        check_ruleset_support(
            abi,
            Some(abi),
            move |ruleset: Ruleset| -> _ {
                Ok(ruleset
                    // Restricting without rule exceptions is legitimate to forbid a set of actions.
                    .handle_access(AccessFs::Execute)?
                    .create()?
                    .restrict_self()?)
            },
            false,
        );
    }

    #[test]
    fn abi_v2_exec_refer() {
        check_ruleset_support(
            ABI::V1,
            Some(ABI::V2),
            move |ruleset: Ruleset| -> _ {
                Ok(ruleset
                    .handle_access(AccessFs::Execute)?
                    // AccessFs::Refer is not supported by ABI::V1 (best-effort).
                    .handle_access(AccessFs::Refer)?
                    .create()?
                    .restrict_self()?)
            },
            false,
        );
    }

    #[test]
    fn abi_v2_refer_only() {
        // When no access is handled, do not try to create a ruleset without access.
        check_ruleset_support(
            ABI::V2,
            Some(ABI::V2),
            move |ruleset: Ruleset| -> _ {
                Ok(ruleset
                    .handle_access(AccessFs::Refer)?
                    .create()?
                    .restrict_self()?)
            },
            false,
        );
    }

    #[test]
    fn abi_v3_truncate() {
        check_ruleset_support(
            ABI::V2,
            Some(ABI::V3),
            move |ruleset: Ruleset| -> _ {
                Ok(ruleset
                    .handle_access(AccessFs::Refer)?
                    .handle_access(AccessFs::Truncate)?
                    .create()?
                    .add_rule(PathBeneath::new(PathFd::new("/")?, AccessFs::Refer))?
                    .restrict_self()?)
            },
            false,
        );
    }

    #[test]
    fn ruleset_created_try_clone() {
        check_ruleset_support(
            ABI::V1,
            Some(ABI::V1),
            move |ruleset: Ruleset| -> _ {
                Ok(ruleset
                    .handle_access(AccessFs::Execute)?
                    .create()?
                    .add_rule(PathBeneath::new(PathFd::new("/")?, AccessFs::Execute))?
                    .try_clone()?
                    .restrict_self()?)
            },
            false,
        );
    }

    #[test]
    fn abi_v4_tcp() {
        check_ruleset_support(
            ABI::V3,
            Some(ABI::V4),
            move |ruleset: Ruleset| -> _ {
                Ok(ruleset
                    .handle_access(AccessFs::Truncate)?
                    .handle_access(AccessNet::BindTcp | AccessNet::ConnectTcp)?
                    .create()?
                    .add_rule(NetPort::new(1, AccessNet::ConnectTcp))?
                    .restrict_self()?)
            },
            false,
        );
    }

    #[test]
    fn abi_v5_ioctl_dev() {
        check_ruleset_support(
            ABI::V4,
            Some(ABI::V5),
            move |ruleset: Ruleset| -> _ {
                Ok(ruleset
                    .handle_access(AccessNet::BindTcp)?
                    .handle_access(AccessFs::IoctlDev)?
                    .create()?
                    .add_rule(PathBeneath::new(PathFd::new("/")?, AccessFs::IoctlDev))?
                    .restrict_self()?)
            },
            false,
        );
    }

    #[test]
    fn abi_v6_scope_mix() {
        check_ruleset_support(
            ABI::V5,
            Some(ABI::V6),
            move |ruleset: Ruleset| -> _ {
                Ok(ruleset
                    .handle_access(AccessFs::IoctlDev)?
                    .scope(Scope::AbstractUnixSocket | Scope::Signal)?
                    .create()?
                    .restrict_self()?)
            },
            false,
        );
    }

    #[test]
    fn abi_v6_scope_only() {
        check_ruleset_support(
            ABI::V6,
            Some(ABI::V6),
            move |ruleset: Ruleset| -> _ {
                Ok(ruleset
                    .scope(Scope::AbstractUnixSocket | Scope::Signal)?
                    .create()?
                    .restrict_self()?)
            },
            false,
        );
    }

    #[test]
    fn abi_v7_log_flags() {
        // Uses Scope::Signal to get partial enforcement at V6 (scopes supported
        // but log flags not).
        check_ruleset_support(
            ABI::V6,
            Some(ABI::V7),
            move |ruleset: Ruleset| -> _ {
                let status = ruleset
                    .scope(Scope::Signal)?
                    .create()?
                    .log_same_exec(false)?
                    .log_new_exec(true)?
                    .log_subdomains(false)?
                    .restrict_self()?;

                if status.ruleset == RulesetStatus::FullyEnforced {
                    assert!(!status.log_same_exec);
                    assert!(status.log_new_exec);
                    assert!(!status.log_subdomains);
                } else {
                    assert!(status.log_same_exec);
                    assert!(!status.log_new_exec);
                    assert!(status.log_subdomains);
                }

                Ok(status)
            },
            false,
        );
    }

    #[test]
    fn ruleset_created_try_clone_ownedfd() {
        use std::os::unix::io::{AsRawFd, OwnedFd};

        let abi = ABI::V1;
        check_ruleset_support(
            abi,
            Some(abi),
            move |ruleset: Ruleset| -> _ {
                let ruleset1 = ruleset.handle_access(AccessFs::from_all(abi))?.create()?;
                let ruleset2 = ruleset1.try_clone().unwrap();
                let ruleset3 = ruleset2.try_clone().unwrap();

                let some1: Option<OwnedFd> = ruleset1.into();
                if let Some(fd1) = some1 {
                    assert!(fd1.as_raw_fd() >= 0);

                    let some2: Option<OwnedFd> = ruleset2.into();
                    let fd2 = some2.unwrap();
                    assert!(fd2.as_raw_fd() >= 0);

                    assert_ne!(fd1.as_raw_fd(), fd2.as_raw_fd());
                }
                Ok(ruleset3.restrict_self()?)
            },
            false,
        );
    }

    #[test]
    fn restrict_self_log_subdomains() {
        check_restrict_self_support(ABI::V7, Some(ABI::V7), move |rs: RestrictSelf| -> _ {
            Ok(rs.log_subdomains(false)?.apply()?)
        });
    }
}