landlock-0.4.4/.cargo_vcs_info.json 0000644 00000000136 00000000001 0012630 0 ustar {
"git": {
"sha1": "89c56e2db04cf0a4d63e192e7b4371af516a1ccc"
},
"path_in_vcs": ""
} landlock-0.4.4/.github/workflows/pages.yml 0000644 0000000 0000000 00000002171 10461020230 0016640 0 ustar 0000000 0000000 name: GitHub Pages
on:
push:
branches: [ main ]
workflow_dispatch:
concurrency:
group: "pages"
cancel-in-progress: false
jobs:
build:
if: github.repository == 'landlock-lsm/rust-landlock'
runs-on: ubuntu-24.04
env:
CARGO_TERM_COLOR: always
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@v3
- name: Install Rust stable
run: |
rm ~/.cargo/bin/{cargo-fmt,rustfmt} || :
rustup default stable
rustup update
- name: Build documentation
run: rustup run stable cargo doc --no-deps
- name: Add index
run: |
echo '' > target/doc/index.html
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: target/doc
deploy:
needs: build
runs-on: ubuntu-24.04
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
permissions:
pages: write
id-token: write
steps:
- name: Deploy to GitHub Pages
uses: actions/deploy-pages@v4
landlock-0.4.4/.github/workflows/rust.yml 0000644 0000000 0000000 00000020344 10461020230 0016540 0 ustar 0000000 0000000 name: Rust checks
permissions: {}
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
env:
CARGO_TERM_COLOR: always
RUSTDOCFLAGS: -D warnings
RUSTFLAGS: -D warnings
LANDLOCK_TEST_TOOLS_COMMIT: fad769c39b42183fb2a2e1263fe00dfa5b9f2bda
# Ubuntu versions: https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners#supported-runners-and-hardware-resources
jobs:
commit_list:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get commit list (push)
id: get_commit_list_push
if: ${{ github.event_name == 'push' }}
run: |
echo "id0=$GITHUB_SHA" > $GITHUB_OUTPUT
echo "List of tested commits:" > $GITHUB_STEP_SUMMARY
sed -n 's,^id[0-9]\+=\(.*\),- https://github.com/landlock-lsm/rust-landlock/commit/\1,p' -- $GITHUB_OUTPUT >> $GITHUB_STEP_SUMMARY
- name: Get commit list (PR)
id: get_commit_list_pr
if: ${{ github.event_name == 'pull_request' }}
run: |
git rev-list --reverse refs/remotes/origin/${{ github.base_ref }}..${{ github.event.pull_request.head.sha }} | awk '{ print "id" NR "=" $1 }' > $GITHUB_OUTPUT
git diff --quiet ${{ github.event.pull_request.head.sha }} ${{ github.sha }} || echo "id0=$GITHUB_SHA" >> $GITHUB_OUTPUT
echo "List of tested commits:" > $GITHUB_STEP_SUMMARY
sed -n 's,^id[0-9]\+=\(.*\),- https://github.com/landlock-lsm/rust-landlock/commit/\1,p' -- $GITHUB_OUTPUT >> $GITHUB_STEP_SUMMARY
outputs:
commits: ${{ toJSON(steps.*.outputs.*) }}
kernel_list:
runs-on: ubuntu-24.04
outputs:
kernels: ${{ toJSON(steps.id.outputs.*) }}
steps:
- name: Identify latest Linux versions
id: id
run: |
echo "List of tested kernels:" > $GITHUB_STEP_SUMMARY
abi=0
for version in 5.10 5.15 6.1 6.4 6.7 6.10 6.12; do
commit="$(git ls-remote https://github.com/landlock-lsm/linux refs/heads/linux-${version}.y | awk 'NR == 1 { print $1 }')"
if [[ -z "${commit}" ]]; then
echo "ERROR: Failed to fetch Linux ${version}" >&2
exit 1
fi
echo "kernel_${abi}={ \"version\":\"${version}\", \"abi\":\"${abi}\", \"commit\":\"${commit}\" }" >> $GITHUB_OUTPUT
echo "- Linux ${version}.y with Landlock ABI ${abi}: https://github.com/landlock-lsm/linux/commit/${commit}" >> $GITHUB_STEP_SUMMARY
let abi++ || :
done
get_kernels:
runs-on: ubuntu-24.04
needs: kernel_list
strategy:
fail-fast: false
matrix:
kernel: ${{ fromJSON(needs.kernel_list.outputs.kernels) }}
steps:
- name: Cache Linux ${{ fromJSON(matrix.kernel).version}}.y
id: cache_linux
uses: actions/cache@v4
with:
path: linux-${{ fromJSON(matrix.kernel).version }}
key: linux-${{ fromJSON(matrix.kernel).commit }}-${{ env.LANDLOCK_TEST_TOOLS_COMMIT }}
- name: Clone Landlock test tools
if: steps.cache_linux.outputs.cache-hit != 'true'
uses: actions/checkout@v4
with:
repository: landlock-lsm/landlock-test-tools
ref: ${{ env.LANDLOCK_TEST_TOOLS_COMMIT }}
path: landlock-test-tools
- name: Clone Linux ${{ fromJSON(matrix.kernel).version}}.y
if: steps.cache_linux.outputs.cache-hit != 'true'
uses: actions/checkout@v4
with:
repository: landlock-lsm/linux
ref: ${{ fromJSON(matrix.kernel).commit }}
path: linux
- name: Build Linux ${{ fromJSON(matrix.kernel).version}}.y
if: steps.cache_linux.outputs.cache-hit != 'true'
working-directory: linux
run: |
O=. ../landlock-test-tools/check-linux.sh build_light
mv linux ../linux-${{ fromJSON(matrix.kernel).version}}
ubuntu_24_rust_msrv:
runs-on: ubuntu-24.04
needs: commit_list
strategy:
fail-fast: false
matrix:
commit: ${{ fromJSON(needs.commit_list.outputs.commits) }}
env:
LANDLOCK_CRATE_TEST_ABI: 5
steps:
- uses: actions/checkout@v4
with:
ref: ${{ matrix.commit }}
- name: Clone Landlock test tools
uses: actions/checkout@v4
with:
repository: landlock-lsm/landlock-test-tools
ref: ${{ env.LANDLOCK_TEST_TOOLS_COMMIT }}
path: landlock-test-tools
- name: Get MSRV
run: sed -n 's/^rust-version = "\([0-9.]\+\)"$/RUST_TOOLCHAIN=\1/p' Cargo.toml >> $GITHUB_ENV
- name: Install 32-bit development libraries
run: |
sudo apt update
sudo apt install gcc-multilib libc6-dev-i386
- name: Install Rust MSRV
run: |
rm ~/.cargo/bin/{cargo-fmt,rustfmt} || :
rustup self update
rustup default ${{ env.RUST_TOOLCHAIN }}
rustup update ${{ env.RUST_TOOLCHAIN }}
rustup target add i686-unknown-linux-gnu
rustup target add x86_64-unknown-linux-gnu
- name: Build (x86_64)
run: rustup run ${{ env.RUST_TOOLCHAIN }} cargo build --target x86_64-unknown-linux-gnu --verbose
- name: Build (x86)
run: rustup run ${{ env.RUST_TOOLCHAIN }} cargo build --target i686-unknown-linux-gnu --verbose
- name: Run tests against the local kernel (Landlock ABI ${{ env.LANDLOCK_CRATE_TEST_ABI }} on x86_64)
run: rustup run ${{ env.RUST_TOOLCHAIN }} cargo test --target x86_64-unknown-linux-gnu --verbose
- name: Run tests against the local kernel (Landlock ABI ${{ env.LANDLOCK_CRATE_TEST_ABI }} on x86)
run: rustup run ${{ env.RUST_TOOLCHAIN }} cargo test --target i686-unknown-linux-gnu --verbose
- name: Run tests against Linux 6.1
run: CARGO="rustup run ${{ env.RUST_TOOLCHAIN }} cargo" ./landlock-test-tools/test-rust.sh linux-6.1 2
ubuntu_22_rust_stable:
runs-on: ubuntu-22.04
needs: commit_list
strategy:
fail-fast: false
matrix:
commit: ${{ fromJSON(needs.commit_list.outputs.commits) }}
env:
LANDLOCK_CRATE_TEST_ABI: 4
steps:
- name: Install Rust stable
run: |
rm ~/.cargo/bin/{cargo-fmt,rustfmt} || :
rustup self update
rustup default stable
rustup component add rustfmt clippy
rustup update
- uses: actions/checkout@v4
with:
ref: ${{ matrix.commit }}
- name: Build
run: rustup run stable cargo build --verbose
- name: Run tests against the local kernel (Landlock ABI ${{ env.LANDLOCK_CRATE_TEST_ABI }})
run: rustup run stable cargo test --verbose
- name: Check format
run: rustup run stable cargo fmt --all -- --check
- name: Check source with Clippy
run: rustup run stable cargo clippy -- --deny warnings
- name: Check tests with Clippy
run: rustup run stable cargo clippy --tests -- --deny warnings
- name: Check documentation
run: rustup run stable cargo doc --no-deps
ubuntu_24_rust_stable:
runs-on: ubuntu-24.04
needs: [commit_list, kernel_list, get_kernels]
strategy:
fail-fast: false
matrix:
commit: ${{ fromJSON(needs.commit_list.outputs.commits) }}
kernel: ${{ fromJSON(needs.kernel_list.outputs.kernels) }}
env:
LANDLOCK_CRATE_TEST_ABI: 4
# $CARGO is used by landlock-test-tools/test-rust.sh
CARGO: rustup run stable cargo
steps:
- name: Install Rust stable
run: |
rm ~/.cargo/bin/{cargo-fmt,rustfmt} || :
rustup self update
rustup default stable
rustup update
- name: Clone Landlock test tools
uses: actions/checkout@v4
with:
repository: landlock-lsm/landlock-test-tools
ref: ${{ env.LANDLOCK_TEST_TOOLS_COMMIT }}
path: landlock-test-tools
- name: Clone rust-landlock
uses: actions/checkout@v4
with:
ref: ${{ matrix.commit }}
path: rust-landlock
- name: Get Linux ${{ fromJSON(matrix.kernel).version}}.y
uses: actions/cache/restore@v4
with:
path: linux-${{ fromJSON(matrix.kernel).version }}
key: linux-${{ fromJSON(matrix.kernel).commit }}-${{ env.LANDLOCK_TEST_TOOLS_COMMIT }}
fail-on-cache-miss: true
- name: Run tests against Linux ${{ fromJSON(matrix.kernel).version }}.y
working-directory: rust-landlock
run: ../landlock-test-tools/test-rust.sh ../linux-${{ fromJSON(matrix.kernel).version }} ${{ fromJSON(matrix.kernel).abi }}
landlock-0.4.4/CHANGELOG.md 0000644 0000000 0000000 00000022016 10461020230 0013232 0 ustar 0000000 0000000 # Landlock changelog
## [v0.4.4](https://github.com/landlock-lsm/rust-landlock/releases/tag/v0.4.4)
### New API
- Added support for all architectures ([PR #111](https://github.com/landlock-lsm/rust-landlock/pull/111)).
- Added `LandlockStatus` type to query the running kernel and display information about available Landlock features ([PR #103](https://github.com/landlock-lsm/rust-landlock/pull/103) and [PR #113](https://github.com/landlock-lsm/rust-landlock/pull/113)).
### Dependencies
- Bumped MSRV to Rust 1.68 ([PR #112](https://github.com/landlock-lsm/rust-landlock/pull/112)).
### Testing
- Extended CI to build and test on i686 architecture ([PR #111](https://github.com/landlock-lsm/rust-landlock/pull/111)).
### Example
- Enhanced sandboxer example to print helpful hints about Landlock status ([PR #103](https://github.com/landlock-lsm/rust-landlock/pull/103)).
## [v0.4.3](https://github.com/landlock-lsm/rust-landlock/releases/tag/v0.4.3)
### New API
- Implemented common traits (e.g., `Debug`) for public types ([PR #108](https://github.com/landlock-lsm/rust-landlock/pull/108)).
### Documentation
- Extended [CONTRIBUTING.md](CONTRIBUTING.md) documentation with additional testing and development guidelines ([PR #95](https://github.com/landlock-lsm/rust-landlock/pull/95)).
- Added more background information to [`path_beneath_rules()`](https://landlock.io/rust-landlock/landlock/fn.path_beneath_rules.html) documentation ([PR #94](https://github.com/landlock-lsm/rust-landlock/pull/94)).
### Testing
- Added test case for `AccessFs::from_file()` method ([PR #92](https://github.com/landlock-lsm/rust-landlock/pull/92)).
## [v0.4.2](https://github.com/landlock-lsm/rust-landlock/releases/tag/v0.4.2)
### New API
- Added support for Landlock ABI 6: control abstract UNIX sockets and signal scoping with the new [`Ruleset::scope()`](https://landlock.io/rust-landlock/landlock/struct.Ruleset.html#method.scope) method taking a [`Scope`](https://landlock.io/rust-landlock/landlock/enum.Scope.html) enum ([PR #96](https://github.com/landlock-lsm/rust-landlock/pull/96) and [PR #98](https://github.com/landlock-lsm/rust-landlock/pull/98)).
- Added `From` implementation for `Option` ([PR #104](https://github.com/landlock-lsm/rust-landlock/pull/104))
- Introduced a new [`HandledAccess`](https://landlock.io/rust-landlock/landlock/trait.HandledAccess.html) trait specific to `AccessFs` and `AccessNet` (commit [554217dda0b7](https://github.com/landlock-lsm/rust-landlock/commit/554217dda0b775756e38db71f471dd414b199234)).
- Added a new [`Errno`](https://landlock.io/rust-landlock/landlock/struct.Errno.html) type to improve FFI support ([PR #86](https://github.com/landlock-lsm/rust-landlock/pull/86) and [PR #102](https://github.com/landlock-lsm/rust-landlock/pull/102)).
- Exposed `From` implementation for [`ABI`](https://landlock.io/rust-landlock/landlock/enum.ABI.html) ([PR #88](https://github.com/landlock-lsm/rust-landlock/pull/88)).
### Documentation
- Added clarifying notes about `AccessFs::WriteFile` behavior and `path_beneath_rules` usage ([PR #80](https://github.com/landlock-lsm/rust-landlock/pull/80)).
- Introduced [CONTRIBUTING.md](CONTRIBUTING.md) with testing workflow explanations ([PR #76](https://github.com/landlock-lsm/rust-landlock/pull/76)).
### Testing
- Enhanced test coverage for new API and added testing against Linux 6.12 ([PR #96](https://github.com/landlock-lsm/rust-landlock/pull/96)).
- Updated CI configuration to use the latest Ubuntu versions ([PR #87](https://github.com/landlock-lsm/rust-landlock/pull/87) and [PR #97](https://github.com/landlock-lsm/rust-landlock/pull/97)).
- Modified default `LANDLOCK_CRATE_TEST_ABI` to match the current kernel for more convenient local testing ([PR #76](https://github.com/landlock-lsm/rust-landlock/pull/76)).
### Example
- Synchronized the sandboxer example with the C version ([PR #101](https://github.com/landlock-lsm/rust-landlock/pull/101)): improved error handling for inaccessible file paths and enhanced help documentation.
## [v0.4.1](https://github.com/landlock-lsm/rust-landlock/releases/tag/v0.4.1)
### New API
Add support for Landlock ABI 5: control IOCTL commands on character and block devices with the new [`AccessFs::IoctlDev`](https://landlock.io/rust-landlock/landlock/enum.AccessFs.html#variant.IoctlDev) right ([PR #74](https://github.com/landlock-lsm/rust-landlock/pull/74)).
### Testing
Improved the CI to better test against different kernel versions ([PR #72](https://github.com/landlock-lsm/rust-landlock/pull/72)).
## [v0.4.0](https://github.com/landlock-lsm/rust-landlock/releases/tag/v0.4.0)
### New API
Add support for Landlock ABI 4: control TCP binding and connection according to specified network ports.
This is now possible with the [`AccessNet`](https://landlock.io/rust-landlock/landlock/enum.AccessNet.html) rights and
the [`NetPort`](https://landlock.io/rust-landlock/landlock/struct.NetPort.html) rule
([PR #55](https://github.com/landlock-lsm/rust-landlock/pull/55)).
### Breaking change
The `from_read()` and `from_write()` methods moved from the `Access` trait to the `AccessFs` struct
([commit 68f066eba571](https://github.com/landlock-lsm/rust-landlock/commit/68f066eba571c1f9212f5a07016aac9ffb0d1c27)).
### Compatibility management
Improve compatibility consistency and prioritize runtime errors against compatibility errors
([PR #67](https://github.com/landlock-lsm/rust-landlock/pull/67)).
Fixed a corner case where a ruleset was created on a kernel not supporting Landlock, while requesting to add a rule with an access right handled by the ruleset (`BestEffort`).
When trying to enforce this ruleset, this led to a runtime error (i.e. wrong file descriptor) instead of a compatibility error.
To simplify compatibility management, always call `prctl(PR_SET_NO_NEW_PRIVS, 1)` by default (see `set_no_new_privs()`).
This was required to get a consistent compatibility management and it should not be an issue given that this feature is supported by all LTS kernels
([commit d99f75155bec](https://github.com/landlock-lsm/rust-landlock/commit/d99f75155bec2040cf4ce1532007cd3b8a23e2fb)).
## [v0.3.1](https://github.com/landlock-lsm/rust-landlock/releases/tag/v0.3.1)
### New API
Add [`RulesetCreated::try_clone()`](https://landlock.io/rust-landlock/landlock/struct.RulesetCreated.html#method.try_clone) ([PR #38](https://github.com/landlock-lsm/rust-landlock/pull/38)).
## [v0.3.0](https://github.com/landlock-lsm/rust-landlock/releases/tag/v0.3.0)
### New API
Add support for Landlock ABI 3: control truncate operations with the new
[`AccessFs::Truncate`](https://landlock.io/rust-landlock/landlock/enum.AccessFs.html#variant.Truncate)
right ([PR #40](https://github.com/landlock-lsm/rust-landlock/pull/40)).
Revamp the compatibility handling and add a new
[`set_compatibility()`](https://landlock.io/rust-landlock/landlock/trait.Compatible.html#method.set_compatibility)
method for `Ruleset`, `RulesetCreated`, and `PathBeneath`.
We can now fine-tune the compatibility behavior according to the running kernel
and then the supported features thanks to three compatible levels:
best effort, soft requirement and hard requirement
([PR #12](https://github.com/landlock-lsm/rust-landlock/pull/12)).
Add a new [`AccessFs::from_file()`](https://landlock.io/rust-landlock/landlock/enum.AccessFs.html#method.from_file)
helper ([commit 0b3238c6dd70](https://github.com/landlock-lsm/rust-landlock/commit/0b3238c6dd70)).
### Deprecated API
Deprecate the [`set_best_effort()`](https://landlock.io/rust-landlock/landlock/trait.Compatible.html#method.set_best_effort)
method and replace it with `set_compatibility()`
([PR #12](https://github.com/landlock-lsm/rust-landlock/pull/12)).
Deprecate [`Ruleset::new()`](https://landlock.io/rust-landlock/landlock/struct.Ruleset.html#method.new)
and replace it with `Ruleset::default()`
([PR #44](https://github.com/landlock-lsm/rust-landlock/pull/44)).
### Breaking changes
We now check that a ruleset really handles at least one access right,
which can now cause `Ruleset::create()` to return an error if the ruleset compatibility level is
`HardRequirement` or `set_best_effort(false)`
([commit 95addc13b4a8](https://github.com/landlock-lsm/rust-landlock/commit/95addc13b4a8)).
We now check that access rights passed to `add_rule()` make sense according to the file type.
To handle most use cases,
`path_beneath_rules()` now automatically check and downgrade access rights for files
(i.e. remove superfluous directory-only access rights,
[commit 8e47940b3722](https://github.com/landlock-lsm/rust-landlock/commit/8e47940b3722)).
### Testing
Test coverage in the CI is greatly improved by running all tests on all relevant kernel versions:
Linux 5.10, 5.15, 6.1, and 6.4
([PR #41](https://github.com/landlock-lsm/rust-landlock/pull/41)).
Run each test in a dedicated thread to avoid inconsistent behavior
([PR #46](https://github.com/landlock-lsm/rust-landlock/pull/46)).
## [v0.2.0](https://github.com/landlock-lsm/rust-landlock/releases/tag/v0.2.0)
This is the first major release of this crate.
It brings a high-level interface to the Landlock kernel interface.
landlock-0.4.4/CONTRIBUTING.md 0000644 0000000 0000000 00000002521 10461020230 0013651 0 ustar 0000000 0000000 # Contributing
Thanks for your interest in contributing to rust-landlock!
## Testing vs kernel ABI
The Landlock functionality exposed differs between kernel versions. Based on
the Landlock ABI version of the running system, rust-landlock runs different
subsets of tests. For local development, running `cargo test` will test against
your currently running kernel version (and the Landlock ABI that it ships).
However, this may result in some tests being skipped.
To fully test a change, it should be verified against a range of ABI versions.
This is done by the Github Actions CI, but doing so locally is challenging.
Using the `LANDLOCK_CRATE_TEST_ABI` variable, the tested ABI version can be
overridden. For more details, take a look at the comment in
[`compat.rs:current_kernel_abi()`][current-kernel-abi].
For more information about Landlock ABIs, see: [enum ABI][enum-abi]
[current-kernel-abi]: https://github.com/landlock-lsm/rust-landlock/blob/main/src/compat.rs
[enum-abi]: https://landlock.io/rust-landlock/landlock/enum.ABI.html
## Licensing & DCO
rust-landlock is double-licensed under the terms of [Apache 2.0][apache-2.0]
and [MIT][mit].
All changes submitted to rust-landlock must be [signed off][dco].
[apache-2.0]: https://spdx.org/licenses/Apache-2.0.html
[mit]: https://spdx.org/licenses/MIT.html
[dco]: https://github.com/apps/dco
landlock-0.4.4/COPYRIGHT 0000644 0000000 0000000 00000000544 10461020230 0012716 0 ustar 0000000 0000000 Copyright 2020 Mickaël Salaün
Licensed under the Apache License, Version 2.0 or the MIT license
, at your
option. All files in the project carrying such notice may not be
copied, modified, or distributed except according to those terms.
landlock-0.4.4/Cargo.lock 0000644 00000006765 00000000001 0010621 0 ustar # This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "anyhow"
version = "1.0.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
[[package]]
name = "enumflags2"
version = "0.7.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
dependencies = [
"enumflags2_derive",
]
[[package]]
name = "enumflags2_derive"
version = "0.7.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "landlock"
version = "0.4.4"
dependencies = [
"anyhow",
"enumflags2",
"lazy_static",
"libc",
"strum",
"strum_macros",
"thiserror",
]
[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "libc"
version = "0.2.177"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976"
[[package]]
name = "proc-macro2"
version = "1.0.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a338cc41d27e6cc6dce6cefc13a0729dfbb81c262b1f519331575dd80ef3067f"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rustversion"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
[[package]]
name = "strum"
version = "0.26.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"
[[package]]
name = "strum_macros"
version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"
dependencies = [
"heck",
"proc-macro2",
"quote",
"rustversion",
"syn",
]
[[package]]
name = "syn"
version = "2.0.110"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a99801b5bd34ede4cf3fc688c5919368fea4e4814a4664359503e6015b280aea"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "2.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unicode-ident"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"
landlock-0.4.4/Cargo.toml 0000644 00000002665 00000000001 0010637 0 ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.68"
name = "landlock"
version = "0.4.4"
build = false
exclude = [".gitignore"]
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Landlock LSM helpers"
homepage = "https://landlock.io"
readme = "README.md"
keywords = [
"access-control",
"linux",
"sandbox",
"security",
]
categories = [
"api-bindings",
"os::linux-apis",
"virtualization",
"filesystem",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/landlock-lsm/rust-landlock"
[lib]
name = "landlock"
path = "src/lib.rs"
[[example]]
name = "sandboxer"
path = "examples/sandboxer.rs"
[dependencies.enumflags2]
version = "0.7"
[dependencies.libc]
version = "0.2.175"
[dependencies.thiserror]
version = "2.0"
[dev-dependencies.anyhow]
version = "1.0"
[dev-dependencies.lazy_static]
version = "1"
[dev-dependencies.strum]
version = "0.26"
[dev-dependencies.strum_macros]
version = "0.26"
landlock-0.4.4/Cargo.toml.orig 0000644 0000000 0000000 00000001122 10461020230 0014303 0 ustar 0000000 0000000 [package]
name = "landlock"
version = "0.4.4"
edition = "2021"
rust-version = "1.68"
description = "Landlock LSM helpers"
homepage = "https://landlock.io"
repository = "https://github.com/landlock-lsm/rust-landlock"
license = "MIT OR Apache-2.0"
keywords = ["access-control", "linux", "sandbox", "security"]
categories = ["api-bindings", "os::linux-apis", "virtualization", "filesystem"]
exclude = [".gitignore"]
readme = "README.md"
[dependencies]
enumflags2 = "0.7"
libc = "0.2.175"
thiserror = "2.0"
[dev-dependencies]
anyhow = "1.0"
lazy_static = "1"
strum = "0.26"
strum_macros = "0.26"
landlock-0.4.4/LICENSE-APACHE 0000644 0000000 0000000 00000026123 10461020230 0013350 0 ustar 0000000 0000000
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2020 Mickaël Salaün
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
landlock-0.4.4/LICENSE-MIT 0000644 0000000 0000000 00000002061 10461020230 0013053 0 ustar 0000000 0000000 MIT License
Copyright (c) 2020 Mickaël Salaün
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
landlock-0.4.4/README.md 0000644 0000000 0000000 00000003261 10461020230 0012701 0 ustar 0000000 0000000 # Rust Landlock library
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 Rust crate provides a safe abstraction for the Landlock system calls along with some helpers.
## 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()`](https://landlock.io/rust-landlock/landlock/fn.path_beneath_rules.html) helper.
More complex examples can be found with the
[`Ruleset` documentation](https://landlock.io/rust-landlock/landlock/struct.Ruleset.html)
and the [sandboxer example](examples/sandboxer.rs).
## [Crate documentation](https://landlock.io/rust-landlock/landlock/)
## Changelog
* [v0.4.4](CHANGELOG.md#v044)
* [v0.4.3](CHANGELOG.md#v043)
* [v0.4.2](CHANGELOG.md#v042)
* [v0.4.1](CHANGELOG.md#v041)
* [v0.4.0](CHANGELOG.md#v040)
* [v0.3.1](CHANGELOG.md#v031)
* [v0.3.0](CHANGELOG.md#v030)
* [v0.2.0](CHANGELOG.md#v020)
landlock-0.4.4/examples/sandboxer.rs 0000644 0000000 0000000 00000022066 10461020230 0015577 0 ustar 0000000 0000000 // SPDX-License-Identifier: Apache-2.0 OR MIT
// This is an idiomatic Rust rewrite of a C example:
// https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/samples/landlock/sandboxer.c
use anyhow::{anyhow, bail, Context};
use landlock::{
path_beneath_rules, Access, AccessFs, AccessNet, BitFlags, LandlockStatus, NetPort,
PathBeneath, PathFd, Ruleset, RulesetAttr, RulesetCreatedAttr, RulesetStatus, Scope, ABI,
};
use std::env;
use std::ffi::OsStr;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::os::unix::process::CommandExt;
use std::process::Command;
const ENV_FS_RO_NAME: &str = "LL_FS_RO";
const ENV_FS_RW_NAME: &str = "LL_FS_RW";
const ENV_TCP_BIND_NAME: &str = "LL_TCP_BIND";
const ENV_TCP_CONNECT_NAME: &str = "LL_TCP_CONNECT";
const ENV_SCOPED_NAME: &str = "LL_SCOPED";
struct PathEnv {
paths: Vec,
access: BitFlags,
}
impl PathEnv {
/// Create an object able to iterate PathBeneath rules
///
/// # Arguments
///
/// * `name`: String identifying an environment variable containing paths requested to be
/// allowed. Paths are separated with ":", e.g. "/bin:/lib:/usr:/proc". In case an empty
/// string is provided, NO restrictions are applied.
/// * `access`: Set of access-rights allowed for each of the parsed paths.
fn new<'a>(name: &'a str, access: BitFlags) -> anyhow::Result {
Ok(Self {
paths: env::var_os(name)
.ok_or(anyhow!("missing environment variable {name}"))?
.into_vec(),
access,
})
}
fn iter(&self) -> impl Iterator- >> + '_ {
let is_empty = self.paths.is_empty();
path_beneath_rules(
self.paths
.split(|b| *b == b':')
// Skips the first empty element of an empty string.
.skip_while(move |_| is_empty)
.map(OsStr::from_bytes),
self.access,
)
.map(|r| Ok(r?))
}
}
struct PortEnv {
ports: Vec,
access: AccessNet,
}
impl PortEnv {
fn new<'a>(name: &'a str, access: AccessNet) -> anyhow::Result {
Ok(Self {
ports: env::var_os(name).unwrap_or_default().into_vec(),
access,
})
}
fn iter(&self) -> impl Iterator
- > + '_ {
let is_empty = self.ports.is_empty();
self.ports
.split(|b| *b == b':')
// Skips the first empty element of an empty string.
.skip_while(move |_| is_empty)
.map(OsStr::from_bytes)
.map(|port| {
let port = port
.to_str()
.context("failed to convert port string")?
.parse::()
.context("failed to convert port to 16-bit integer")?;
Ok(NetPort::new(port, self.access))
})
}
}
fn main() -> anyhow::Result<()> {
let mut args = env::args_os();
let program_name = args
.next()
.context("Missing the sandboxer program name (i.e. argv[0])")?;
let cmd_name = args.next().ok_or_else(|| {
let program_name = program_name.to_string_lossy();
eprintln!(
"usage: {ENV_FS_RO_NAME}=\"...\" {ENV_FS_RW_NAME}=\"...\" [other environment variables] {program_name} [args]...\n"
);
eprintln!("Execute the given command in a restricted environment.");
eprintln!("Multi-valued settings (lists of ports, paths, scopes) are colon-delimited.\n");
eprintln!("Mandatory settings:");
eprintln!("* {ENV_FS_RO_NAME}: paths allowed to be used in a read-only way");
eprintln!("* {ENV_FS_RW_NAME}: paths allowed to be used in a read-write way\n");
eprintln!("Optional settings (when not set, their associated access check is always allowed, which is different from an empty string which means an empty list):");
eprintln!("* {ENV_TCP_BIND_NAME}: ports allowed to bind (server)");
eprintln!("* {ENV_TCP_CONNECT_NAME}: ports allowed to connect (client)");
eprintln!("* {ENV_SCOPED_NAME}: actions denied on the outside of the Landlock domain:");
eprintln!(" - \"a\" to restrict opening abstract unix sockets");
eprintln!(" - \"s\" to restrict sending signals");
eprintln!(
"\nExample:\n\
{ENV_FS_RO_NAME}=\"${{PATH}}:/lib:/usr:/proc:/etc:/dev/urandom\" \
{ENV_FS_RW_NAME}=\"/dev/null:/dev/full:/dev/zero:/dev/pts:/tmp\" \
{ENV_TCP_BIND_NAME}=\"9418\" \
{ENV_TCP_CONNECT_NAME}=\"80:443\" \
{ENV_SCOPED_NAME}=\"a:s\" \
{program_name} bash -i\n"
);
anyhow!("Missing command")
})?;
let abi = ABI::V6;
let mut ruleset = Ruleset::default().handle_access(AccessFs::from_all(abi))?;
let ruleset_ref = &mut ruleset;
if env::var_os(ENV_TCP_BIND_NAME).is_some() {
ruleset_ref.handle_access(AccessNet::BindTcp)?;
}
if env::var_os(ENV_TCP_CONNECT_NAME).is_some() {
ruleset_ref.handle_access(AccessNet::ConnectTcp)?;
}
if let Some(scoped) = env::var_os(ENV_SCOPED_NAME) {
let mut abstract_scoping = false;
let mut signal_scoping = false;
let scopes = scoped.to_string_lossy();
let is_empty = scopes.is_empty();
for scope in scopes.split(':').skip_while(move |_| is_empty) {
match scope {
"a" => {
if abstract_scoping {
bail!("Duplicate scope 'a'");
}
ruleset_ref.scope(Scope::AbstractUnixSocket)?;
abstract_scoping = true;
}
"s" => {
if signal_scoping {
bail!("Duplicate scope 's'");
}
ruleset_ref.scope(Scope::Signal)?;
signal_scoping = true;
}
_ => bail!("Unknown scope \"{scope}\""),
}
}
}
let status = ruleset
.create()?
.add_rules(PathEnv::new(ENV_FS_RO_NAME, AccessFs::from_read(abi))?.iter())?
.add_rules(PathEnv::new(ENV_FS_RW_NAME, AccessFs::from_all(abi))?.iter())?
.add_rules(PortEnv::new(ENV_TCP_BIND_NAME, AccessNet::BindTcp)?.iter())?
.add_rules(PortEnv::new(ENV_TCP_CONNECT_NAME, AccessNet::ConnectTcp)?.iter())?
.restrict_self()
.expect("Failed to enforce ruleset");
match status.landlock {
// This should never happen because of the previous check:
LandlockStatus::NotEnabled => {
eprintln!(
"Hint: Landlock is currently disabled. \
It can be enabled in the kernel configuration by prepending \"landlock,\"
to the content of CONFIG_LSM, or at boot time by setting the same content to
the \"lsm\" kernel parameter."
);
}
LandlockStatus::NotImplemented => {
eprintln!(
"Hint: Landlock is not built into the current kernel. \
To support it, build the kernel with CONFIG_SECURITY_LANDLOCK=y and \
prepend \"landlock,\" to the content of CONFIG_LSM."
);
}
LandlockStatus::Available {
kernel_abi: Some(raw_abi),
..
} => {
eprintln!(
"Hint: This sandboxer only supports Landlock ABI version up to {abi} \
whereas the current kernel supports Landlock ABI version {raw_abi}. \
To leverage all Landlock features, update this sandboxer."
);
}
LandlockStatus::Available {
kernel_abi: None,
effective_abi,
} => {
if effective_abi < abi {
eprintln!(
"Hint: This sandboxer supports Landlock ABI version up to {abi} \
but the current kernel only supports Landlock ABI version {effective_abi}. \
To leverage all Landlock features, update the kernel."
);
} else if effective_abi > abi {
// This should not happen because the ABI used by the sandboxer
// should be the latest supported by the Landlock crate, and
// they should be updated at the same time.
eprintln!(
"Warning: This sandboxer only supports Landlock ABI version up to {abi} \
but the current kernel supports Landlock ABI version {effective_abi}. \
To leverage all Landlock features, update this sandboxer."
);
}
}
}
if status.ruleset == RulesetStatus::NotEnforced {
bail!("The ruleset cannot be enforced at all");
}
eprintln!("Executing the sandboxed command...");
Err(Command::new(cmd_name)
.env_remove(ENV_FS_RO_NAME)
.env_remove(ENV_FS_RW_NAME)
.env_remove(ENV_TCP_BIND_NAME)
.env_remove(ENV_TCP_CONNECT_NAME)
.args(args)
.exec()
.into())
}
landlock-0.4.4/src/access.rs 0000644 0000000 0000000 00000014615 10461020230 0014025 0 ustar 0000000 0000000 // SPDX-License-Identifier: Apache-2.0 OR MIT
use crate::{
private, AccessError, AddRuleError, AddRulesError, BitFlags, CompatError, CompatResult,
HandleAccessError, HandleAccessesError, Ruleset, TailoredCompatLevel, TryCompat, ABI,
};
use enumflags2::BitFlag;
#[cfg(test)]
use crate::{make_bitflags, AccessFs, CompatLevel, CompatState, Compatibility};
pub trait Access: BitFlag + private::Sealed {
/// Gets the access rights defined by a specific [`ABI`].
fn from_all(abi: ABI) -> BitFlags;
}
// This HandledAccess trait is useful to document the API.
pub trait HandledAccess: Access {}
pub trait PrivateHandledAccess: HandledAccess {
fn ruleset_handle_access(
ruleset: &mut Ruleset,
access: BitFlags,
) -> Result<(), HandleAccessesError>
where
Self: Access;
fn into_add_rules_error(error: AddRuleError) -> AddRulesError
where
Self: Access;
fn into_handle_accesses_error(error: HandleAccessError) -> HandleAccessesError
where
Self: Access;
}
// Creates an illegal/overflowed BitFlags with all its bits toggled, including undefined ones.
fn full_negation(flags: BitFlags) -> BitFlags
where
T: Access,
{
unsafe { BitFlags::::from_bits_unchecked(!flags.bits()) }
}
#[test]
fn bit_flags_full_negation() {
let scoped_negation = !BitFlags::::all();
assert_eq!(scoped_negation, BitFlags::::empty());
// !BitFlags::::all() could be equal to full_negation(BitFlags::::all()))
// if all the 64-bits would be used, which is not currently the case.
assert_ne!(scoped_negation, full_negation(BitFlags::::all()));
}
impl TailoredCompatLevel for BitFlags where A: Access {}
impl TryCompat for BitFlags
where
A: Access,
{
fn try_compat_inner(&mut self, abi: ABI) -> Result, CompatError> {
if self.is_empty() {
// Empty access-rights would result to a runtime error.
Err(AccessError::Empty.into())
} else if !Self::all().contains(*self) {
// Unknown access-rights (at build time) would result to a runtime error.
// This can only be reached by using the unsafe BitFlags::from_bits_unchecked().
Err(AccessError::Unknown {
access: *self,
unknown: *self & full_negation(Self::all()),
}
.into())
} else {
let compat = *self & A::from_all(abi);
let ret = if compat.is_empty() {
Ok(CompatResult::No(
AccessError::Incompatible { access: *self }.into(),
))
} else if compat != *self {
let error = AccessError::PartiallyCompatible {
access: *self,
incompatible: *self & full_negation(compat),
}
.into();
Ok(CompatResult::Partial(error))
} else {
Ok(CompatResult::Full)
};
*self = compat;
ret
}
}
}
#[test]
fn compat_bit_flags() {
use crate::ABI;
let mut compat: Compatibility = ABI::V1.into();
assert!(compat.state == CompatState::Init);
let ro_access = make_bitflags!(AccessFs::{Execute | ReadFile | ReadDir});
assert_eq!(
ro_access,
ro_access
.try_compat(compat.abi(), compat.level, &mut compat.state)
.unwrap()
.unwrap()
);
assert!(compat.state == CompatState::Full);
let empty_access = BitFlags::::empty();
assert!(matches!(
empty_access
.try_compat(compat.abi(), compat.level, &mut compat.state)
.unwrap_err(),
CompatError::Access(AccessError::Empty)
));
let all_unknown_access = unsafe { BitFlags::::from_bits_unchecked(1 << 63) };
assert!(matches!(
all_unknown_access.try_compat(compat.abi(), compat.level, &mut compat.state).unwrap_err(),
CompatError::Access(AccessError::Unknown { access, unknown }) if access == all_unknown_access && unknown == all_unknown_access
));
// An error makes the state final.
assert!(compat.state == CompatState::Dummy);
let some_unknown_access = unsafe { BitFlags::::from_bits_unchecked(1 << 63 | 1) };
assert!(matches!(
some_unknown_access.try_compat(compat.abi(), compat.level, &mut compat.state).unwrap_err(),
CompatError::Access(AccessError::Unknown { access, unknown }) if access == some_unknown_access && unknown == all_unknown_access
));
assert!(compat.state == CompatState::Dummy);
compat = ABI::Unsupported.into();
// Tests that the ruleset is marked as unsupported.
assert!(compat.state == CompatState::Init);
// Access-rights are valid (but ignored) when they are not required for the current ABI.
assert_eq!(
None,
ro_access
.try_compat(compat.abi(), compat.level, &mut compat.state)
.unwrap()
);
assert!(compat.state == CompatState::No);
// Access-rights are not valid when they are required for the current ABI.
compat.level = Some(CompatLevel::HardRequirement);
assert!(matches!(
ro_access.try_compat(compat.abi(), compat.level, &mut compat.state).unwrap_err(),
CompatError::Access(AccessError::Incompatible { access }) if access == ro_access
));
compat = ABI::V1.into();
// Tests that the ruleset is marked as the unknown compatibility state.
assert!(compat.state == CompatState::Init);
// Access-rights are valid (but ignored) when they are not required for the current ABI.
assert_eq!(
ro_access,
ro_access
.try_compat(compat.abi(), compat.level, &mut compat.state)
.unwrap()
.unwrap()
);
// Tests that the ruleset is in an unsupported state, which is important to be able to still
// enforce no_new_privs.
assert!(compat.state == CompatState::Full);
let v2_access = ro_access | AccessFs::Refer;
// Access-rights are not valid when they are required for the current ABI.
compat.level = Some(CompatLevel::HardRequirement);
assert!(matches!(
v2_access.try_compat(compat.abi(), compat.level, &mut compat.state).unwrap_err(),
CompatError::Access(AccessError::PartiallyCompatible { access, incompatible })
if access == v2_access && incompatible == AccessFs::Refer
));
}
landlock-0.4.4/src/compat.rs 0000644 0000000 0000000 00000074714 10461020230 0014055 0 ustar 0000000 0000000 // SPDX-License-Identifier: Apache-2.0 OR MIT
use crate::{uapi, Access, CompatError};
use std::fmt::{self, Display, Formatter};
use std::io::Error;
#[cfg(test)]
use std::convert::TryInto;
#[cfg(test)]
use strum::{EnumCount, IntoEnumIterator};
#[cfg(test)]
use strum_macros::{EnumCount as EnumCountMacro, EnumIter};
/// Version of the Landlock [ABI](https://en.wikipedia.org/wiki/Application_binary_interface).
///
/// `ABI` enables getting the features supported by a specific Landlock ABI
/// (without relying on the kernel version which may not be accessible or patched).
/// For example, [`AccessFs::from_all(ABI::V1)`](Access::from_all)
/// gets all the file system access rights defined by the first version.
///
/// Without `ABI`, it would be hazardous to rely on the the full set of access flags
/// (e.g., `BitFlags::::all()` or `BitFlags::ALL`),
/// a moving target that would change the semantics of your Landlock rule
/// when migrating to a newer version of this crate.
/// Indeed, a simple `cargo update` or `cargo install` run by any developer
/// can result in a new version of this crate (fixing bugs or bringing non-breaking changes).
/// This crate cannot give any guarantee concerning the new restrictions resulting from
/// these unknown bits (i.e. access rights) that would not be controlled by your application but by
/// a future version of this crate instead.
/// Because we cannot know what the effect on your application of an unknown restriction would be
/// when handling an untested Landlock access right (i.e. denied-by-default access),
/// it could trigger bugs in your application.
///
/// This crate provides a set of tools to sandbox as much as possible
/// while guaranteeing a consistent behavior thanks to the [`Compatible`] methods.
/// You should also test with different relevant kernel versions,
/// see [landlock-test-tools](https://github.com/landlock-lsm/landlock-test-tools) and
/// [CI integration](https://github.com/landlock-lsm/rust-landlock/pull/41).
///
/// This way, we can have the guarantee that the use of a set of tested Landlock ABI works as
/// expected because features brought by newer Landlock ABI will never be enabled by default
/// (cf. [Linux kernel compatibility contract](https://docs.kernel.org/userspace-api/landlock.html#compatibility)).
///
/// In a nutshell, test the access rights you request on a kernel that support them and
/// on a kernel that doesn't support them.
///
/// Derived `Debug` formats are [not stable](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#stability).
#[cfg_attr(test, derive(EnumIter, EnumCountMacro))]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum ABI {
/// Kernel not supporting Landlock, either because it is not built with Landlock
/// or Landlock is not enabled at boot.
Unsupported = 0,
/// First Landlock ABI, introduced with
/// [Linux 5.13](https://git.kernel.org/stable/c/17ae69aba89dbfa2139b7f8024b757ab3cc42f59).
V1 = 1,
/// Second Landlock ABI, introduced with
/// [Linux 5.19](https://git.kernel.org/stable/c/cb44e4f061e16be65b8a16505e121490c66d30d0).
V2 = 2,
/// Third Landlock ABI, introduced with
/// [Linux 6.2](https://git.kernel.org/stable/c/299e2b1967578b1442128ba8b3e86ed3427d3651).
V3 = 3,
/// Fourth Landlock ABI, introduced with
/// [Linux 6.7](https://git.kernel.org/stable/c/136cc1e1f5be75f57f1e0404b94ee1c8792cb07d).
V4 = 4,
/// Fifth Landlock ABI, introduced with
/// [Linux 6.10](https://git.kernel.org/stable/c/2fc0e7892c10734c1b7c613ef04836d57d4676d5).
V5 = 5,
/// Sixth Landlock ABI, introduced with
/// [Linux 6.12](https://git.kernel.org/stable/c/e1b061b444fb01c237838f0d8238653afe6a8094).
V6 = 6,
}
// ABI should not be dynamically created (in other crates) according to the running kernel
// to avoid inconsistent behaviors and non-determinism. Creating ABIs based on runtime detection
// can lead to unreliable sandboxing where rules might differ between executions.
impl ABI {
#[cfg(test)]
fn is_known(value: i32) -> bool {
value > 0 && value < ABI::COUNT as i32
}
}
/// Converting from an integer to an ABI should only be used for testing.
/// Indeed, manually setting the ABI can lead to inconsistent and unexpected behaviors.
/// Instead, just use the appropriate access rights, this library will handle the rest.
impl From for ABI {
fn from(value: i32) -> ABI {
match value {
n if n <= 0 => ABI::Unsupported,
1 => ABI::V1,
2 => ABI::V2,
3 => ABI::V3,
4 => ABI::V4,
5 => ABI::V5,
// Returns the greatest known ABI.
_ => ABI::V6,
}
}
}
#[test]
fn abi_from() {
// EOPNOTSUPP (-95), ENOSYS (-38)
for n in [-95, -38, -1, 0] {
assert_eq!(ABI::from(n), ABI::Unsupported);
}
let mut last_i = 1;
let mut last_abi = ABI::Unsupported;
for (i, abi) in ABI::iter().enumerate() {
last_i = i.try_into().unwrap();
last_abi = abi;
assert_eq!(ABI::from(last_i), last_abi);
}
assert_eq!(ABI::from(last_i + 1), last_abi);
assert_eq!(ABI::from(999), last_abi);
}
#[test]
fn known_abi() {
assert!(!ABI::is_known(-1));
assert!(!ABI::is_known(0));
assert!(!ABI::is_known(999));
let mut last_i = -1;
for (i, _) in ABI::iter().enumerate().skip(1) {
last_i = i as i32;
assert!(ABI::is_known(last_i));
}
assert!(!ABI::is_known(last_i + 1));
}
impl Display for ABI {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
ABI::Unsupported => write!(f, "unsupported"),
v => (*v as u32).fmt(f),
}
}
}
/// Status of Landlock support for the running system.
///
/// This enum is used to represent the status of the Landlock support for the system where the code
/// is executed. It can indicate whether Landlock is available or not.
///
/// # Warning
///
/// Sandboxed programs should only use this data to log or provide information to users,
/// not to change their behavior according to this status. Indeed, the `Ruleset` and the other
/// types are designed to handle the compatibility in a simple and safe way.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum LandlockStatus {
/// Landlock is supported but not enabled (`EOPNOTSUPP`).
NotEnabled,
/// Landlock is not implemented (i.e. not built into the running kernel: `ENOSYS`).
NotImplemented,
/// Landlock is available and working on the running system.
///
/// This indicates that the kernel supports Landlock and it's properly enabled.
/// The crate uses the `effective_abi` for all operations, which represents
/// the highest ABI version that both the kernel and this crate understand.
Available {
/// The effective ABI version that this crate will use for Landlock operations.
/// This is the intersection of what the kernel supports and what this crate knows about.
effective_abi: ABI,
/// The actual kernel ABI version when it's newer than any ABI supported by this crate.
///
/// If `Some(version)`, it means the running kernel supports Landlock ABI `version`
/// which is higher than the latest ABI known by this crate.
///
/// This field is purely informational and is never used for Landlock operations.
/// The crate always and only uses `effective_abi` for all functionality.
kernel_abi: Option,
},
}
impl LandlockStatus {
// Must remain private to avoid inconsistent behavior using such unknown-at-build-time ABI
// e.g., AccessFs::from_all(ABI::new_current())
//
// This should not be Default::default() because the returned value would may not be the same
// for all users.
fn current() -> Self {
// Landlock ABI version starts at 1 but errno is only set for negative values.
let v = unsafe {
uapi::landlock_create_ruleset(
std::ptr::null(),
0,
uapi::LANDLOCK_CREATE_RULESET_VERSION,
)
};
if v < 0 {
// The only possible error values should be EOPNOTSUPP and ENOSYS.
match Error::last_os_error().raw_os_error() {
Some(libc::EOPNOTSUPP) => Self::NotEnabled,
_ => Self::NotImplemented,
}
} else {
let abi = ABI::from(v);
Self::Available {
effective_abi: abi,
kernel_abi: (v != abi as i32).then_some(v),
}
}
}
}
// Test against the running kernel.
#[test]
fn test_current_landlock_status() {
let status = LandlockStatus::current();
if *TEST_ABI == ABI::Unsupported {
assert_eq!(status, LandlockStatus::NotImplemented);
} else {
assert!(
matches!(status, LandlockStatus::Available { effective_abi, .. } if effective_abi == *TEST_ABI)
);
if std::env::var(TEST_ABI_ENV_NAME).is_ok() {
// We cannot reliably check for unknown kernel.
assert!(matches!(
status,
LandlockStatus::Available {
kernel_abi: None,
..
}
));
}
}
}
impl From for ABI {
fn from(status: LandlockStatus) -> Self {
match status {
// The only possible error values should be EOPNOTSUPP and ENOSYS,
// but let's convert all kind of errors as unsupported.
LandlockStatus::NotEnabled | LandlockStatus::NotImplemented => ABI::Unsupported,
LandlockStatus::Available { effective_abi, .. } => effective_abi,
}
}
}
// This is only useful to tests and should not be exposed publicly because
// the mapping can only be partial.
#[cfg(test)]
impl From for LandlockStatus {
fn from(abi: ABI) -> Self {
match abi {
// Convert to ENOSYS because of check_ruleset_support() and ruleset_unsupported() tests.
ABI::Unsupported => Self::NotImplemented,
_ => Self::Available {
effective_abi: abi,
kernel_abi: None,
},
}
}
}
#[cfg(test)]
static TEST_ABI_ENV_NAME: &str = "LANDLOCK_CRATE_TEST_ABI";
#[cfg(test)]
lazy_static! {
static ref TEST_ABI: ABI = match std::env::var("LANDLOCK_CRATE_TEST_ABI") {
Ok(s) => {
let n = s.parse::().unwrap();
if ABI::is_known(n) || n == 0 {
ABI::from(n)
} else {
panic!("Unknown ABI: {n}");
}
}
Err(std::env::VarError::NotPresent) => LandlockStatus::current().into(),
Err(e) => panic!("Failed to read LANDLOCK_CRATE_TEST_ABI: {e}"),
};
}
#[cfg(test)]
pub(crate) fn can_emulate(mock: ABI, partial_support: ABI, full_support: Option) -> bool {
mock < partial_support
|| mock <= *TEST_ABI
|| if let Some(full) = full_support {
full <= *TEST_ABI
} else {
partial_support <= *TEST_ABI
}
}
#[cfg(test)]
pub(crate) fn get_errno_from_landlock_status() -> Option {
match LandlockStatus::current() {
LandlockStatus::NotImplemented | LandlockStatus::NotEnabled => {
match Error::last_os_error().raw_os_error() {
// Returns ENOSYS when the kernel is not built with Landlock support,
// or EOPNOTSUPP when Landlock is supported but disabled at boot time.
ret @ Some(libc::ENOSYS | libc::EOPNOTSUPP) => ret,
// Other values can only come from bogus seccomp filters or debugging tampering.
ret => {
eprintln!("Current kernel should support this Landlock ABI according to $LANDLOCK_CRATE_TEST_ABI");
eprintln!("Unexpected result: {ret:?}");
unreachable!();
}
}
}
LandlockStatus::Available { .. } => None,
}
}
#[test]
fn current_kernel_abi() {
// Ensures that the tested Landlock ABI is the latest known version supported by the running
// kernel. If this test failed, you need set the LANDLOCK_CRATE_TEST_ABI environment variable
// to the Landlock ABI version supported by your kernel. With a missing variable, the latest
// Landlock ABI version known by this crate is automatically set.
// From Linux 5.13 to 5.18, you need to run: LANDLOCK_CRATE_TEST_ABI=1 cargo test
let test_abi = *TEST_ABI;
let current_abi = LandlockStatus::current().into();
println!(
"Current kernel version: {}",
std::fs::read_to_string("/proc/version")
.unwrap_or_else(|_| "unknown".into())
.trim()
);
println!("Expected Landlock ABI {test_abi:?} whereas the current ABI is {current_abi:#?}");
assert_eq!(test_abi, current_abi);
}
// CompatState is not public outside this crate.
/// Returned by ruleset builder.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum CompatState {
/// Initial undefined state.
Init,
/// All requested restrictions are enforced.
Full,
/// Some requested restrictions are enforced, following a best-effort approach.
Partial,
/// The running system doesn't support Landlock.
No,
/// Final unsupported state.
Dummy,
}
impl CompatState {
fn update(&mut self, other: Self) {
*self = match (*self, other) {
(CompatState::Init, other) => other,
(CompatState::Dummy, _) => CompatState::Dummy,
(_, CompatState::Dummy) => CompatState::Dummy,
(CompatState::No, CompatState::No) => CompatState::No,
(CompatState::Full, CompatState::Full) => CompatState::Full,
(_, _) => CompatState::Partial,
}
}
}
#[test]
fn compat_state_update_1() {
let mut state = CompatState::Full;
state.update(CompatState::Full);
assert_eq!(state, CompatState::Full);
state.update(CompatState::No);
assert_eq!(state, CompatState::Partial);
state.update(CompatState::Full);
assert_eq!(state, CompatState::Partial);
state.update(CompatState::Full);
assert_eq!(state, CompatState::Partial);
state.update(CompatState::No);
assert_eq!(state, CompatState::Partial);
state.update(CompatState::Dummy);
assert_eq!(state, CompatState::Dummy);
state.update(CompatState::Full);
assert_eq!(state, CompatState::Dummy);
}
#[test]
fn compat_state_update_2() {
let mut state = CompatState::Full;
state.update(CompatState::Full);
assert_eq!(state, CompatState::Full);
state.update(CompatState::No);
assert_eq!(state, CompatState::Partial);
state.update(CompatState::Full);
assert_eq!(state, CompatState::Partial);
}
#[cfg_attr(test, derive(PartialEq))]
#[derive(Copy, Clone, Debug)]
pub(crate) struct Compatibility {
status: LandlockStatus,
pub(crate) level: Option,
pub(crate) state: CompatState,
}
impl From for Compatibility {
fn from(status: LandlockStatus) -> Self {
Compatibility {
status,
level: Default::default(),
state: CompatState::Init,
}
}
}
#[cfg(test)]
impl From for Compatibility {
fn from(abi: ABI) -> Self {
Self::from(LandlockStatus::from(abi))
}
}
impl Compatibility {
// Compatibility is a semi-opaque struct.
#[allow(clippy::new_without_default)]
pub(crate) fn new() -> Self {
LandlockStatus::current().into()
}
pub(crate) fn update(&mut self, state: CompatState) {
self.state.update(state);
}
pub(crate) fn abi(&self) -> ABI {
self.status.into()
}
pub(crate) fn status(&self) -> LandlockStatus {
self.status
}
}
pub(crate) mod private {
use crate::CompatLevel;
pub trait OptionCompatLevelMut {
fn as_option_compat_level_mut(&mut self) -> &mut Option;
}
}
/// Properly handles runtime unsupported features.
///
/// This guarantees consistent behaviors across crate users
/// and runtime kernels even if this crate get new features.
/// It eases backward compatibility and enables future-proofness.
///
/// Landlock is a security feature designed to help improve security of a running system
/// thanks to application developers.
/// To protect users as much as possible,
/// compatibility with the running system should then be handled in a best-effort way,
/// contrary to common system features.
/// In some circumstances
/// (e.g. applications carefully designed to only be run with a specific set of kernel features),
/// it may be required to error out if some of these features are not available
/// and will then not be enforced.
pub trait Compatible: Sized + private::OptionCompatLevelMut {
/// To enable a best-effort security approach,
/// Landlock features that are not supported by the running system
/// are silently ignored by default,
/// which is a sane choice for most use cases.
/// However, on some rare circumstances,
/// developers may want to have some guarantees that their applications
/// will not run if a certain level of sandboxing is not possible.
/// If we really want to error out when not all our requested requirements are met,
/// then we can configure it with `set_compatibility()`.
///
/// The `Compatible` trait is implemented for all object builders
/// (e.g. [`Ruleset`](crate::Ruleset)).
/// Such builders have a set of methods to incrementally build an object.
/// These build methods rely on kernel features that may not be available at runtime.
/// The `set_compatibility()` method enables to control the effect of
/// the following build method calls starting after the `set_compatibility()` call.
/// Such effect can be:
/// * to silently ignore unsupported features
/// and continue building ([`CompatLevel::BestEffort`]);
/// * to silently ignore unsupported features
/// and ignore the whole build ([`CompatLevel::SoftRequirement`]);
/// * to return an error for any unsupported feature ([`CompatLevel::HardRequirement`]).
///
/// Taking [`Ruleset`](crate::Ruleset) as an example,
/// the [`handle_access()`](crate::RulesetAttr::handle_access()) build method
/// returns a [`Result`] that can be [`Err(RulesetError)`](crate::RulesetError)
/// with a nested [`CompatError`].
/// Such error can only occur with a running Linux kernel not supporting the requested
/// Landlock accesses *and* if the current compatibility level is
/// [`CompatLevel::HardRequirement`].
/// However, such error is not possible with [`CompatLevel::BestEffort`]
/// nor [`CompatLevel::SoftRequirement`].
///
/// The order of this call is important because
/// it defines the behavior of the following build method calls that return a [`Result`].
/// If `set_compatibility(CompatLevel::HardRequirement)` is called on an object,
/// then a [`CompatError`] may be returned for the next method calls,
/// until the next call to `set_compatibility()`.
/// This enables to change the behavior of a set of build method calls,
/// for instance to be sure that the sandbox will at least restrict some access rights.
///
/// New objects inherit the compatibility configuration of their parents, if any.
/// For instance, [`Ruleset::create()`](crate::Ruleset::create()) returns
/// a [`RulesetCreated`](crate::RulesetCreated) object that inherits the
/// `Ruleset`'s compatibility configuration.
///
/// # Example with `SoftRequirement`
///
/// Let's say an application legitimately needs to rename files between directories.
/// Because of [previous Landlock limitations](https://docs.kernel.org/userspace-api/landlock.html#file-renaming-and-linking-abi-2),
/// this was forbidden with the [first version of Landlock](ABI::V1),
/// but it is now handled starting with the [second version](ABI::V2).
/// For this use case, we only want the application to be sandboxed
/// if we have the guarantee that it will not break a legitimate usage (i.e. rename files).
/// We then create a ruleset which will either support file renaming
/// (thanks to [`AccessFs::Refer`](crate::AccessFs::Refer)) or silently do nothing.
///
/// ```
/// use landlock::*;
///
/// fn ruleset_handling_renames() -> Result {
/// Ok(Ruleset::default()
/// // This ruleset must either handle the AccessFs::Refer right,
/// // or it must silently ignore the whole sandboxing.
/// .set_compatibility(CompatLevel::SoftRequirement)
/// .handle_access(AccessFs::Refer)?
/// // However, this ruleset may also handle other (future) access rights
/// // if they are supported by the running kernel.
/// .set_compatibility(CompatLevel::BestEffort)
/// .handle_access(AccessFs::from_all(ABI::V6))?
/// .create()?)
/// }
/// ```
///
/// # Example with `HardRequirement`
///
/// Security-dedicated applications may want to ensure that
/// an untrusted software component is subject to a minimum of restrictions before launching it.
/// In this case, we want to create a ruleset which will at least support
/// all restrictions provided by the [first version of Landlock](ABI::V1),
/// and opportunistically handle restrictions supported by newer kernels.
///
/// ```
/// use landlock::*;
///
/// fn ruleset_fragile() -> Result {
/// Ok(Ruleset::default()
/// // This ruleset must either handle at least all accesses defined by
/// // the first Landlock version (e.g. AccessFs::WriteFile),
/// // or the following handle_access() call must return a wrapped
/// // AccessError::Incompatible error.
/// .set_compatibility(CompatLevel::HardRequirement)
/// .handle_access(AccessFs::from_all(ABI::V1))?
/// // However, this ruleset may also handle new access rights
/// // (e.g. AccessFs::Refer defined by the second version of Landlock)
/// // if they are supported by the running kernel,
/// // but without returning any error otherwise.
/// .set_compatibility(CompatLevel::BestEffort)
/// .handle_access(AccessFs::from_all(ABI::V6))?
/// .create()?)
/// }
/// ```
fn set_compatibility(mut self, level: CompatLevel) -> Self {
*self.as_option_compat_level_mut() = Some(level);
self
}
/// Cf. [`set_compatibility()`](Compatible::set_compatibility()):
///
/// - `set_best_effort(true)` translates to `set_compatibility(CompatLevel::BestEffort)`.
///
/// - `set_best_effort(false)` translates to `set_compatibility(CompatLevel::HardRequirement)`.
#[deprecated(note = "Use set_compatibility() instead")]
fn set_best_effort(self, best_effort: bool) -> Self
where
Self: Sized,
{
self.set_compatibility(match best_effort {
true => CompatLevel::BestEffort,
false => CompatLevel::HardRequirement,
})
}
}
#[test]
#[allow(deprecated)]
fn deprecated_set_best_effort() {
use crate::{CompatLevel, Compatible, Ruleset};
assert_eq!(
Ruleset::default().set_best_effort(true).compat,
Ruleset::default()
.set_compatibility(CompatLevel::BestEffort)
.compat
);
assert_eq!(
Ruleset::default().set_best_effort(false).compat,
Ruleset::default()
.set_compatibility(CompatLevel::HardRequirement)
.compat
);
}
/// See the [`Compatible`] documentation.
#[cfg_attr(test, derive(EnumIter))]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum CompatLevel {
/// Takes into account the build requests if they are supported by the running system,
/// or silently ignores them otherwise.
/// Never returns a compatibility error.
#[default]
BestEffort,
/// Takes into account the build requests if they are supported by the running system,
/// or silently ignores the whole build object otherwise.
/// Never returns a compatibility error.
/// If not supported,
/// the call to [`RulesetCreated::restrict_self()`](crate::RulesetCreated::restrict_self())
/// will return a
/// [`RestrictionStatus { ruleset: RulesetStatus::NotEnforced, no_new_privs: false, }`](crate::RestrictionStatus).
SoftRequirement,
/// Takes into account the build requests if they are supported by the running system,
/// or returns a compatibility error otherwise ([`CompatError`]).
HardRequirement,
}
impl From