caps-0.5.5/.cargo_vcs_info.json0000644000000001360000000000100117710ustar { "git": { "sha1": "511bc2b72fbefd57f4ee938ac48ce0f6604b4712" }, "path_in_vcs": "" }caps-0.5.5/.github/dependabot.yml000064400000000000000000000002211046102023000147440ustar 00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: daily time: "04:00" open-pull-requests-limit: 10 caps-0.5.5/.github/workflows/rust.yml000064400000000000000000000051351046102023000157020ustar 00000000000000--- name: Rust on: push: branches: [ master ] pull_request: branches: [ master ] env: CARGO_TERM_COLOR: always # Minimum supported Rust version (MSRV) ACTION_MSRV_TOOLCHAIN: 1.36.0 # Pinned toolchain for linting ACTION_LINTS_TOOLCHAIN: 1.53.0 jobs: tests-stable: name: "Tests, stable toolchain" runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install toolchain uses: actions-rs/toolchain@v1 with: toolchain: "stable" default: true - name: cargo build run: cargo build - name: cargo test run: cargo test tests-release-stable: name: "Tests (release), stable toolchain" runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install toolchain uses: actions-rs/toolchain@v1 with: toolchain: "stable" default: true - name: cargo build (release) run: cargo build --release - name: cargo test (release) run: cargo test --release tests-release-msrv: name: "Tests (release), minimum supported toolchain" runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install toolchain uses: actions-rs/toolchain@v1 with: toolchain: ${{ env['ACTION_MSRV_TOOLCHAIN'] }} default: true - name: cargo build (release) run: cargo build --release - name: cargo test (release) run: cargo test --release linting: name: "Lints, pinned toolchain" runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install toolchain uses: actions-rs/toolchain@v1 with: toolchain: ${{ env['ACTION_LINTS_TOOLCHAIN'] }} default: true components: rustfmt, clippy - name: cargo clippy (warnings) run: cargo clippy -- -D warnings - name: cargo fmt (check) run: cargo fmt -- --check -l tests-other-channels: name: "Tests, unstable toolchain" runs-on: ubuntu-latest continue-on-error: true strategy: matrix: channel: - "beta" - "nightly" steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install toolchain uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.channel }} default: true - name: cargo build run: cargo build - name: cargo test run: cargo test caps-0.5.5/COPYRIGHT000064400000000000000000000003341046102023000120540ustar 00000000000000Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: caps Source: https://www.github.com/lucab/caps-rs Files: * Copyright: 2017-2019, Project contributors License: MIT or Apache-2.0 caps-0.5.5/Cargo.lock0000644000000055130000000000100077500ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "caps" version = "0.5.5" dependencies = [ "libc", "serde", "serde_json", "thiserror", ] [[package]] name = "itoa" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4217ad341ebadf8d8e724e264f13e593e0648f5b3e94b3896a5df283be015ecc" [[package]] name = "libc" version = "0.2.137" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89" [[package]] name = "proc-macro2" version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" dependencies = [ "proc-macro2", ] [[package]] name = "ryu" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09" [[package]] name = "serde" version = "1.0.147" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d193d69bae983fc11a79df82342761dfbf28a99fc8d203dca4c3c1b590948965" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.147" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4f1d362ca8fc9c3e3a7484440752472d68a6caa98f1ab81d99b5dfe517cec852" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.87" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce777b7b150d76b9cf60d28b55f5847135a003f7d7350c6be7a773508ce7d45" dependencies = [ "itoa", "ryu", "serde", ] [[package]] name = "syn" version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "thiserror" version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "unicode-ident" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" caps-0.5.5/Cargo.toml0000644000000026040000000000100077710ustar # 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 = "2018" name = "caps" version = "0.5.5" authors = ["Luca Bruno "] exclude = [ ".gitignore", ".travis.yml", ] description = "A pure-Rust library to work with Linux capabilities" documentation = "https://docs.rs/caps" readme = "README.md" keywords = [ "Linux", "capabilities", "POSIX", "getcap", "setcap", ] license = "MIT/Apache-2.0" repository = "https://github.com/lucab/caps-rs" [package.metadata.release] publish = false push = false post-release-commit-message = "cargo: development version bump" pre-release-commit-message = "cargo: caps release {{version}}" sign-commit = true sign-tag = true tag-message = "caps {{version}}" [dependencies.libc] version = "^0.2" [dependencies.serde] version = "^1.0" features = ["derive"] optional = true [dependencies.thiserror] version = "^1.0" [dev-dependencies.serde_json] version = "^1.0" [features] serde_support = ["serde"] caps-0.5.5/Cargo.toml.orig000064400000000000000000000015141046102023000134510ustar 00000000000000[package] name = "caps" version = "0.5.5" edition = "2018" authors = ["Luca Bruno "] license = "MIT/Apache-2.0" repository = "https://github.com/lucab/caps-rs" documentation = "https://docs.rs/caps" description = "A pure-Rust library to work with Linux capabilities" keywords = ["Linux", "capabilities", "POSIX", "getcap", "setcap"] exclude = [ ".gitignore", ".travis.yml", ] [dependencies] libc = "^0.2" thiserror = "^1.0" serde = { version = "^1.0", features = ["derive"], optional = true} [features] serde_support = ["serde"] [dev-dependencies] serde_json = "^1.0" [package.metadata.release] publish = false push = false post-release-commit-message = "cargo: development version bump" pre-release-commit-message = "cargo: caps release {{version}}" sign-commit = true sign-tag = true tag-message = "caps {{version}}" caps-0.5.5/LICENSE-APACHE-2.0000064400000000000000000000261361046102023000130120ustar 00000000000000 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 [yyyy] [name of copyright owner] 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. caps-0.5.5/LICENSE-MIT000064400000000000000000000017771046102023000122310ustar 00000000000000Permission 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. caps-0.5.5/README.md000064400000000000000000000045071046102023000120460ustar 00000000000000# caps [![Build Status](https://travis-ci.com/lucab/caps-rs.svg?branch=master)](https://travis-ci.com/lucab/caps-rs) [![crates.io](https://img.shields.io/crates/v/caps.svg)](https://crates.io/crates/caps) [![Documentation](https://docs.rs/caps/badge.svg)](https://docs.rs/caps) A pure-Rust library to work with Linux capabilities. `caps` provides support for manipulating capabilities available in modern Linux kernels. It supports traditional POSIX sets (Effective, Inheritable, Permitted) as well as Linux-specific Ambient and Bounding capabilities sets. `caps` provides a simple and idiomatic interface to handle capabilities on Linux. See `capabilities(7)` for more details. ## Motivations This library tries to achieve the following goals: * fully support modern kernels, including recent capabilities and sets * provide an idiomatic interface * be usable in static targets, without requiring an external C library ## Example ```rust type ExResult = Result>; fn manipulate_caps() -> ExResult<()> { use caps::{Capability, CapSet}; // Retrieve permitted set. let cur = caps::read(None, CapSet::Permitted)?; println!("Current permitted caps: {:?}.", cur); // Retrieve effective set. let cur = caps::read(None, CapSet::Effective)?; println!("Current effective caps: {:?}.", cur); // Check if CAP_CHOWN is in permitted set. let perm_chown = caps::has_cap(None, CapSet::Permitted, Capability::CAP_CHOWN)?; if !perm_chown { return Err("Try running this as root!".into()); } // Clear all effective caps. caps::clear(None, CapSet::Effective)?; println!("Cleared effective caps."); let cur = caps::read(None, CapSet::Effective)?; println!("Current effective caps: {:?}.", cur); // Since `CAP_CHOWN` is still in permitted, it can be raised again. caps::raise(None, CapSet::Effective, Capability::CAP_CHOWN)?; println!("Raised CAP_CHOWN in effective set."); let cur = caps::read(None, CapSet::Effective)?; println!("Current effective caps: {:?}.", cur); Ok(()) } ``` Some more examples are available under [examples](examples). ## License Licensed under either of * MIT license - * Apache License, Version 2.0 - at your option. caps-0.5.5/examples/all_caps.rs000064400000000000000000000023701046102023000145250ustar 00000000000000/*! A simple example showing how to introspect all available capabilities. This differentiates between: * library set: the static set hardcoded in the library at build-time. * runtime set: the dynamic set available in the running kernel. The runtime set can be introspected in two different ways: via procfs (faster but not always possible) or via probing (slower). Where both mechanisms are available, they produce the exact same result. !*/ type ExResult = Result>; fn main() -> ExResult<()> { let library_set = caps::all(); let runtime_set = caps::runtime::procfs_all_supported(None).unwrap_or_else(|e| { eprintln!("procfs introspection failed: {}", e); caps::runtime::thread_all_supported() }); println!("Capabilities tally:"); println!(" -> known by this library: {}.", library_set.len()); println!(" -> known by the current kernel: {}.\n", runtime_set.len()); println!("Library vs kernel differences:"); println!( " -> newer caps only in the library set: {:?}.", library_set.difference(&runtime_set) ); println!( " -> newer caps only in the current kernel set: {:?}.", runtime_set.difference(&library_set) ); Ok(()) } caps-0.5.5/examples/clear_permitted.rs000064400000000000000000000042061046102023000161120ustar 00000000000000//! A simple example showing how to manipulate capabilities. //! //! It clears Permitted set to show its interaction //! with Effective set. //! //! This is an example ONLY: do NOT panic/unwrap/assert //! in production code! type ExResult = Result>; fn main() -> ExResult<()> { use caps::{CapSet, Capability}; // Check if `CAP_CHOWN` was originally available. let cur = caps::read(None, CapSet::Permitted)?; println!("-> Current permitted caps: {:?}.", cur); let cur = caps::read(None, CapSet::Effective)?; println!("-> Current effective caps: {:?}.", cur); let perm_chown = caps::has_cap(None, CapSet::Permitted, Capability::CAP_CHOWN); assert!(perm_chown.is_ok()); if !perm_chown? { return Err( "Try running this again as root/sudo or with CAP_CHOWN file capability!".into(), ); } // Clear all effective caps. let r = caps::clear(None, CapSet::Effective); assert!(r.is_ok()); println!("Cleared effective caps."); let cur = caps::read(None, CapSet::Effective)?; println!("-> Current effective caps: {:?}.", cur); // Since `CAP_CHOWN` is still in permitted, it can be raised again. let r = caps::raise(None, CapSet::Effective, Capability::CAP_CHOWN); assert!(r.is_ok()); println!("Raised CAP_CHOWN in effective set."); let cur = caps::read(None, CapSet::Effective)?; println!("-> Current effective caps: {:?}.", cur); // Clearing Permitted also impacts effective. let r = caps::clear(None, CapSet::Permitted); assert!(r.is_ok()); println!("Cleared permitted caps."); let cur = caps::read(None, CapSet::Permitted)?; println!("-> Current permitted caps: {:?}.", cur); let cur = caps::read(None, CapSet::Effective)?; println!("-> Current effective caps: {:?}.", cur); // Trying to raise `CAP_CHOWN` now fails. let r = caps::raise(None, CapSet::Effective, Capability::CAP_CHOWN); assert!(r.is_err()); println!("Tried to raise CAP_CHOWN but failed."); let cur = caps::read(None, CapSet::Effective)?; println!("-> Current effective caps: {:?}.", cur); Ok(()) } caps-0.5.5/examples/legacy.rs000064400000000000000000000005161046102023000142130ustar 00000000000000use caps::runtime; fn main() { let amb_set = runtime::ambient_set_supported().is_ok(); println!("Ambient set supported: {}", amb_set); let all = caps::all(); let supported = runtime::thread_all_supported(); let missing = all.difference(&supported); println!("Unsupported new capabilities: {:?}", missing); } caps-0.5.5/examples/manipulate_sys_nice.rs000064400000000000000000000046411046102023000170050ustar 00000000000000//! A simple example showing how to manipulate capabilities. //! //! It drops and raises `CAP_SYS_NICE` to show its interaction //! with `getpriority(2)`. //! //! This is an example ONLY: do NOT panic/unwrap/assert //! in production code! type ExResult = Result>; fn main() -> ExResult<()> { use caps::{CapSet, Capability}; // Any process can lower its own priority. println!("-> Current process priority is {}.", proc_nice()); let r = renice(19); assert_eq!(r, 0); println!("Lowered priority to +19."); println!("-> Current process priority is {}.", proc_nice()); // Without `CAP_SYS_NICE` increasing priority is not possible. let r = caps::drop(None, CapSet::Effective, Capability::CAP_SYS_NICE); assert!(r.is_ok()); println!("Dropped CAP_SYS_NICE."); let has_sys_nice = caps::has_cap(None, CapSet::Effective, Capability::CAP_SYS_NICE); assert!(has_sys_nice.is_ok()); assert_eq!(has_sys_nice.unwrap_or(true), false); let r = renice(-20); assert_eq!(r, -1); println!("Unprivileged, unable to raise priority to -20."); // If `CAP_SYS_NICE` is still in permitted set, it can be raised again. let perm_sys_nice = caps::has_cap(None, CapSet::Permitted, Capability::CAP_SYS_NICE); assert!(perm_sys_nice.is_ok()); if !perm_sys_nice? { return Err( "Try running this again as root/sudo or with CAP_SYS_NICE file capability!".into(), ); } let r = caps::raise(None, CapSet::Effective, Capability::CAP_SYS_NICE); assert!(r.is_ok()); println!("Raised CAP_SYS_NICE."); // With CAP_SYS_NICE, priority can be raised further. let r = renice(-20); assert_eq!(r, 0); println!("Privileged, raised priority to -20."); println!("-> Current process priority is {}.", proc_nice()); Ok(()) } #[cfg(target_env = "musl")] const PRIO_PROCESS: i32 = libc::PRIO_PROCESS; #[cfg(not(target_env = "musl"))] const PRIO_PROCESS: u32 = libc::PRIO_PROCESS as u32; fn renice(prio: libc::c_int) -> libc::c_int { // This is not proper logic, as it does not record errno value on error. unsafe { libc::setpriority(PRIO_PROCESS, 0, prio) } } fn proc_nice() -> libc::c_int { // This is not proper logic, as it does not special-case -1 nor record errno. let r = unsafe { libc::getpriority(PRIO_PROCESS as u32, 0) }; if r == -1 { panic!("getpriority failed."); } r } caps-0.5.5/examples/parse.rs000064400000000000000000000005711046102023000140620ustar 00000000000000use caps::Capability; use std::str::FromStr; fn main() { let input = std::env::args().nth(1).expect("missing argument"); match Capability::from_str(&input.to_uppercase()) { Ok(p) => println!( "Parsed: {} -> index={}, bitmask={}", p, p.index(), p.bitmask() ), Err(e) => println!("{}", e), } } caps-0.5.5/src/ambient.rs000064400000000000000000000042141046102023000133360ustar 00000000000000//! Implementation of Ambient set. use crate::errors::CapsError; use crate::nr; use crate::runtime; use crate::{Capability, CapsHashSet}; use std::io::Error; pub fn clear() -> Result<(), CapsError> { let ret = unsafe { libc::prctl(nr::PR_CAP_AMBIENT, nr::PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) }; match ret { 0 => Ok(()), _ => Err(format!( "PR_CAP_AMBIENT_CLEAR_ALL failure: {}", Error::last_os_error() ) .into()), } } pub fn drop(cap: Capability) -> Result<(), CapsError> { let ret = unsafe { libc::prctl( nr::PR_CAP_AMBIENT, nr::PR_CAP_AMBIENT_LOWER, libc::c_uint::from(cap.index()), 0, 0, ) }; match ret { 0 => Ok(()), _ => Err(format!("PR_CAP_AMBIENT_LOWER failure: {}", Error::last_os_error()).into()), } } pub fn has_cap(cap: Capability) -> Result { let ret = unsafe { libc::prctl( nr::PR_CAP_AMBIENT, nr::PR_CAP_AMBIENT_IS_SET, libc::c_uint::from(cap.index()), 0, 0, ) }; match ret { 0 => Ok(false), 1 => Ok(true), _ => Err(format!("PR_CAP_AMBIENT_IS_SET failure: {}", Error::last_os_error()).into()), } } pub fn raise(cap: Capability) -> Result<(), CapsError> { let ret = unsafe { libc::prctl( nr::PR_CAP_AMBIENT, nr::PR_CAP_AMBIENT_RAISE, libc::c_uint::from(cap.index()), 0, 0, ) }; match ret { 0 => Ok(()), _ => Err(format!("PR_CAP_AMBIENT_RAISE failure: {}", Error::last_os_error()).into()), } } pub fn read() -> Result { let mut res = super::CapsHashSet::new(); for c in runtime::thread_all_supported() { if has_cap(c)? { res.insert(c); } } Ok(res) } pub fn set(value: &super::CapsHashSet) -> Result<(), CapsError> { for c in runtime::thread_all_supported() { if value.contains(&c) { raise(c)?; } else { drop(c)?; }; } Ok(()) } caps-0.5.5/src/base.rs000064400000000000000000000116051046102023000126330ustar 00000000000000use crate::errors::CapsError; use crate::nr; use crate::{CapSet, Capability, CapsHashSet}; use std::io::Error; #[allow(clippy::unreadable_literal)] const CAPS_V3: u32 = 0x20080522; fn capget(hdr: &mut CapUserHeader, data: &mut CapUserData) -> Result<(), CapsError> { let r = unsafe { libc::syscall(nr::CAPGET, hdr, data) }; match r { 0 => Ok(()), _ => Err(format!("capget failure: {}", Error::last_os_error()).into()), } } fn capset(hdr: &mut CapUserHeader, data: &CapUserData) -> Result<(), CapsError> { let r = unsafe { libc::syscall(nr::CAPSET, hdr, data) }; match r { 0 => Ok(()), _ => Err(format!("capset failure: {}", Error::last_os_error()).into()), } } pub fn has_cap(tid: i32, cset: CapSet, cap: Capability) -> Result { let mut hdr = CapUserHeader { version: CAPS_V3, pid: tid, }; let mut data: CapUserData = Default::default(); capget(&mut hdr, &mut data)?; let caps: u64 = match cset { CapSet::Effective => (u64::from(data.effective_s1) << 32) + u64::from(data.effective_s0), CapSet::Inheritable => { (u64::from(data.inheritable_s1) << 32) + u64::from(data.inheritable_s0) } CapSet::Permitted => (u64::from(data.permitted_s1) << 32) + u64::from(data.permitted_s0), CapSet::Bounding | CapSet::Ambient => return Err("not a base set".into()), }; let has_cap = (caps & cap.bitmask()) != 0; Ok(has_cap) } pub fn clear(tid: i32, cset: CapSet) -> Result<(), CapsError> { let mut hdr = CapUserHeader { version: CAPS_V3, pid: tid, }; let mut data: CapUserData = Default::default(); capget(&mut hdr, &mut data)?; match cset { CapSet::Effective => { data.effective_s0 = 0; data.effective_s1 = 0; } CapSet::Inheritable => { data.inheritable_s0 = 0; data.inheritable_s1 = 0; } CapSet::Permitted => { data.effective_s0 = 0; data.effective_s1 = 0; data.permitted_s0 = 0; data.permitted_s1 = 0; } CapSet::Bounding | CapSet::Ambient => return Err("not a base set".into()), } capset(&mut hdr, &data) } pub fn read(tid: i32, cset: CapSet) -> Result { let mut hdr = CapUserHeader { version: CAPS_V3, pid: tid, }; let mut data: CapUserData = Default::default(); capget(&mut hdr, &mut data)?; let caps: u64 = match cset { CapSet::Effective => (u64::from(data.effective_s1) << 32) + u64::from(data.effective_s0), CapSet::Inheritable => { (u64::from(data.inheritable_s1) << 32) + u64::from(data.inheritable_s0) } CapSet::Permitted => (u64::from(data.permitted_s1) << 32) + u64::from(data.permitted_s0), CapSet::Bounding | CapSet::Ambient => return Err("not a base set".into()), }; let mut res = CapsHashSet::new(); for c in super::all() { if (caps & c.bitmask()) != 0 { res.insert(c); } } Ok(res) } pub fn set(tid: i32, cset: CapSet, value: &CapsHashSet) -> Result<(), CapsError> { let mut hdr = CapUserHeader { version: CAPS_V3, pid: tid, }; let mut data: CapUserData = Default::default(); capget(&mut hdr, &mut data)?; { let (s1, s0) = match cset { CapSet::Effective => (&mut data.effective_s1, &mut data.effective_s0), CapSet::Inheritable => (&mut data.inheritable_s1, &mut data.inheritable_s0), CapSet::Permitted => (&mut data.permitted_s1, &mut data.permitted_s0), CapSet::Bounding | CapSet::Ambient => return Err("not a base set".into()), }; *s1 = 0; *s0 = 0; for c in value { match c.index() { 0..=31 => { *s0 |= c.bitmask() as u32; } 32..=63 => { *s1 |= (c.bitmask() >> 32) as u32; } _ => return Err(format!("overlarge capability index {}", c.index()).into()), } } } capset(&mut hdr, &data)?; Ok(()) } pub fn drop(tid: i32, cset: CapSet, cap: Capability) -> Result<(), CapsError> { let mut caps = read(tid, cset)?; if caps.remove(&cap) { set(tid, cset, &caps)?; }; Ok(()) } pub fn raise(tid: i32, cset: CapSet, cap: Capability) -> Result<(), CapsError> { let mut caps = read(tid, cset)?; if caps.insert(cap) { set(tid, cset, &caps)?; }; Ok(()) } #[derive(Debug)] #[repr(C)] struct CapUserHeader { // Linux capabilities version (runtime kernel support) version: u32, // Process ID (thread) pid: i32, } #[derive(Debug, Default, Clone)] #[repr(C)] struct CapUserData { effective_s0: u32, permitted_s0: u32, inheritable_s0: u32, effective_s1: u32, permitted_s1: u32, inheritable_s1: u32, } caps-0.5.5/src/bounding.rs000064400000000000000000000022401046102023000135210ustar 00000000000000use crate::errors::CapsError; use crate::nr; use crate::runtime; use crate::Capability; use std::io::Error; pub fn clear() -> Result<(), CapsError> { for c in super::all() { if has_cap(c)? { drop(c)?; } } Ok(()) } pub fn drop(cap: Capability) -> Result<(), CapsError> { let ret = unsafe { libc::prctl(nr::PR_CAPBSET_DROP, libc::c_uint::from(cap.index()), 0, 0) }; match ret { 0 => Ok(()), _ => Err(CapsError::from(format!( "PR_CAPBSET_DROP failure: {}", Error::last_os_error() ))), } } pub fn has_cap(cap: Capability) -> Result { let ret = unsafe { libc::prctl(nr::PR_CAPBSET_READ, libc::c_uint::from(cap.index()), 0, 0) }; match ret { 0 => Ok(false), 1 => Ok(true), _ => Err(CapsError::from(format!( "PR_CAPBSET_READ failure: {}", Error::last_os_error() ))), } } pub fn read() -> Result { let mut res = super::CapsHashSet::new(); for c in runtime::thread_all_supported() { if has_cap(c)? { res.insert(c); } } Ok(res) } caps-0.5.5/src/errors.rs000064400000000000000000000005451046102023000132360ustar 00000000000000//! Error handling. use thiserror::Error; /// Library errors. #[derive(Error, Debug)] #[error("caps error: {0}")] pub struct CapsError(pub(crate) String); impl From<&str> for CapsError { fn from(arg: &str) -> Self { Self(arg.to_string()) } } impl From for CapsError { fn from(arg: String) -> Self { Self(arg) } } caps-0.5.5/src/lib.rs000064400000000000000000000437251046102023000124770ustar 00000000000000/*! A pure-Rust library to work with Linux capabilities. It provides support for manipulating capabilities available on modern Linux kernels. It supports traditional POSIX sets (Effective, Inheritable, Permitted) as well as Linux-specific Ambient and Bounding capabilities sets. ```rust type ExResult = Result>; fn manipulate_caps() -> ExResult<()> { use caps::{Capability, CapSet}; if caps::has_cap(None, CapSet::Permitted, Capability::CAP_SYS_NICE)? { caps::drop(None, CapSet::Effective, Capability::CAP_SYS_NICE)?; let effective = caps::read(None, CapSet::Effective)?; assert_eq!(effective.contains(&Capability::CAP_SYS_NICE), false); caps::clear(None, CapSet::Effective)?; let cleared = caps::read(None, CapSet::Effective)?; assert_eq!(cleared.is_empty(), true); }; Ok(()) } ``` !*/ pub mod errors; pub mod runtime; pub mod securebits; // Implementation of Bounding set. mod ambient; // Implementation of POSIX sets. mod base; // Implementation of Bounding set. mod bounding; // All kernel-related constants. mod nr; use crate::errors::CapsError; use std::iter::FromIterator; /// Linux capabilities sets. /// /// All capabilities sets supported by Linux, including standard /// POSIX and custom ones. See `capabilities(7)`. #[derive(Debug, Clone, Copy)] pub enum CapSet { /// Ambient capabilities set (from Linux 4.3). Ambient, /// Bounding capabilities set (from Linux 2.6.25) Bounding, /// Effective capabilities set (from POSIX) Effective, /// Inheritable capabilities set (from POSIX) Inheritable, /// Permitted capabilities set (from POSIX) Permitted, } /// Linux capabilities. /// /// All capabilities supported by Linux, including standard /// POSIX and custom ones. See `capabilities(7)`. #[allow(clippy::manual_non_exhaustive)] #[allow(non_camel_case_types)] #[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)] #[repr(u8)] #[cfg_attr( feature = "serde_support", derive(serde::Serialize, serde::Deserialize) )] pub enum Capability { /// `CAP_CHOWN` (from POSIX) CAP_CHOWN = nr::CAP_CHOWN, /// `CAP_DAC_OVERRIDE` (from POSIX) CAP_DAC_OVERRIDE = nr::CAP_DAC_OVERRIDE, /// `CAP_DAC_READ_SEARCH` (from POSIX) CAP_DAC_READ_SEARCH = nr::CAP_DAC_READ_SEARCH, /// `CAP_FOWNER` (from POSIX) CAP_FOWNER = nr::CAP_FOWNER, /// `CAP_FSETID` (from POSIX) CAP_FSETID = nr::CAP_FSETID, /// `CAP_KILL` (from POSIX) CAP_KILL = nr::CAP_KILL, /// `CAP_SETGID` (from POSIX) CAP_SETGID = nr::CAP_SETGID, /// `CAP_SETUID` (from POSIX) CAP_SETUID = nr::CAP_SETUID, /// `CAP_SETPCAP` (from Linux) CAP_SETPCAP = nr::CAP_SETPCAP, CAP_LINUX_IMMUTABLE = nr::CAP_LINUX_IMMUTABLE, CAP_NET_BIND_SERVICE = nr::CAP_NET_BIND_SERVICE, CAP_NET_BROADCAST = nr::CAP_NET_BROADCAST, CAP_NET_ADMIN = nr::CAP_NET_ADMIN, CAP_NET_RAW = nr::CAP_NET_RAW, CAP_IPC_LOCK = nr::CAP_IPC_LOCK, CAP_IPC_OWNER = nr::CAP_IPC_OWNER, /// `CAP_SYS_MODULE` (from Linux) CAP_SYS_MODULE = nr::CAP_SYS_MODULE, /// `CAP_SYS_RAWIO` (from Linux) CAP_SYS_RAWIO = nr::CAP_SYS_RAWIO, /// `CAP_SYS_CHROOT` (from Linux) CAP_SYS_CHROOT = nr::CAP_SYS_CHROOT, /// `CAP_SYS_PTRACE` (from Linux) CAP_SYS_PTRACE = nr::CAP_SYS_PTRACE, /// `CAP_SYS_PACCT` (from Linux) CAP_SYS_PACCT = nr::CAP_SYS_PACCT, /// `CAP_SYS_ADMIN` (from Linux) CAP_SYS_ADMIN = nr::CAP_SYS_ADMIN, /// `CAP_SYS_BOOT` (from Linux) CAP_SYS_BOOT = nr::CAP_SYS_BOOT, /// `CAP_SYS_NICE` (from Linux) CAP_SYS_NICE = nr::CAP_SYS_NICE, /// `CAP_SYS_RESOURCE` (from Linux) CAP_SYS_RESOURCE = nr::CAP_SYS_RESOURCE, /// `CAP_SYS_TIME` (from Linux) CAP_SYS_TIME = nr::CAP_SYS_TIME, /// `CAP_SYS_TTY_CONFIG` (from Linux) CAP_SYS_TTY_CONFIG = nr::CAP_SYS_TTY_CONFIG, /// `CAP_SYS_MKNOD` (from Linux, >= 2.4) CAP_MKNOD = nr::CAP_MKNOD, /// `CAP_LEASE` (from Linux, >= 2.4) CAP_LEASE = nr::CAP_LEASE, CAP_AUDIT_WRITE = nr::CAP_AUDIT_WRITE, /// `CAP_AUDIT_CONTROL` (from Linux, >= 2.6.11) CAP_AUDIT_CONTROL = nr::CAP_AUDIT_CONTROL, CAP_SETFCAP = nr::CAP_SETFCAP, CAP_MAC_OVERRIDE = nr::CAP_MAC_OVERRIDE, CAP_MAC_ADMIN = nr::CAP_MAC_ADMIN, /// `CAP_SYSLOG` (from Linux, >= 2.6.37) CAP_SYSLOG = nr::CAP_SYSLOG, /// `CAP_WAKE_ALARM` (from Linux, >= 3.0) CAP_WAKE_ALARM = nr::CAP_WAKE_ALARM, CAP_BLOCK_SUSPEND = nr::CAP_BLOCK_SUSPEND, /// `CAP_AUDIT_READ` (from Linux, >= 3.16). CAP_AUDIT_READ = nr::CAP_AUDIT_READ, /// `CAP_PERFMON` (from Linux, >= 5.8). CAP_PERFMON = nr::CAP_PERFMON, /// `CAP_BPF` (from Linux, >= 5.8). CAP_BPF = nr::CAP_BPF, /// `CAP_CHECKPOINT_RESTORE` (from Linux, >= 5.9). CAP_CHECKPOINT_RESTORE = nr::CAP_CHECKPOINT_RESTORE, #[doc(hidden)] __Nonexhaustive, } impl std::fmt::Display for Capability { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let name = match *self { Capability::CAP_CHOWN => "CAP_CHOWN", Capability::CAP_DAC_OVERRIDE => "CAP_DAC_OVERRIDE", Capability::CAP_DAC_READ_SEARCH => "CAP_DAC_READ_SEARCH", Capability::CAP_FOWNER => "CAP_FOWNER", Capability::CAP_FSETID => "CAP_FSETID", Capability::CAP_KILL => "CAP_KILL", Capability::CAP_SETGID => "CAP_SETGID", Capability::CAP_SETUID => "CAP_SETUID", Capability::CAP_SETPCAP => "CAP_SETPCAP", Capability::CAP_LINUX_IMMUTABLE => "CAP_LINUX_IMMUTABLE", Capability::CAP_NET_BIND_SERVICE => "CAP_NET_BIND_SERVICE", Capability::CAP_NET_BROADCAST => "CAP_NET_BROADCAST", Capability::CAP_NET_ADMIN => "CAP_NET_ADMIN", Capability::CAP_NET_RAW => "CAP_NET_RAW", Capability::CAP_IPC_LOCK => "CAP_IPC_LOCK", Capability::CAP_IPC_OWNER => "CAP_IPC_OWNER", Capability::CAP_SYS_MODULE => "CAP_SYS_MODULE", Capability::CAP_SYS_RAWIO => "CAP_SYS_RAWIO", Capability::CAP_SYS_CHROOT => "CAP_SYS_CHROOT", Capability::CAP_SYS_PTRACE => "CAP_SYS_PTRACE", Capability::CAP_SYS_PACCT => "CAP_SYS_PACCT", Capability::CAP_SYS_ADMIN => "CAP_SYS_ADMIN", Capability::CAP_SYS_BOOT => "CAP_SYS_BOOT", Capability::CAP_SYS_NICE => "CAP_SYS_NICE", Capability::CAP_SYS_RESOURCE => "CAP_SYS_RESOURCE", Capability::CAP_SYS_TIME => "CAP_SYS_TIME", Capability::CAP_SYS_TTY_CONFIG => "CAP_SYS_TTY_CONFIG", Capability::CAP_MKNOD => "CAP_MKNOD", Capability::CAP_LEASE => "CAP_LEASE", Capability::CAP_AUDIT_WRITE => "CAP_AUDIT_WRITE", Capability::CAP_AUDIT_CONTROL => "CAP_AUDIT_CONTROL", Capability::CAP_SETFCAP => "CAP_SETFCAP", Capability::CAP_MAC_OVERRIDE => "CAP_MAC_OVERRIDE", Capability::CAP_MAC_ADMIN => "CAP_MAC_ADMIN", Capability::CAP_SYSLOG => "CAP_SYSLOG", Capability::CAP_WAKE_ALARM => "CAP_WAKE_ALARM", Capability::CAP_BLOCK_SUSPEND => "CAP_BLOCK_SUSPEND", Capability::CAP_AUDIT_READ => "CAP_AUDIT_READ", Capability::CAP_PERFMON => "CAP_PERFMON", Capability::CAP_BPF => "CAP_BPF", Capability::CAP_CHECKPOINT_RESTORE => "CAP_CHECKPOINT_RESTORE", Capability::__Nonexhaustive => unreachable!("invalid capability"), }; write!(f, "{}", name) } } impl std::str::FromStr for Capability { type Err = CapsError; fn from_str(s: &str) -> std::result::Result { match s { "CAP_CHOWN" => Ok(Capability::CAP_CHOWN), "CAP_DAC_OVERRIDE" => Ok(Capability::CAP_DAC_OVERRIDE), "CAP_DAC_READ_SEARCH" => Ok(Capability::CAP_DAC_READ_SEARCH), "CAP_FOWNER" => Ok(Capability::CAP_FOWNER), "CAP_FSETID" => Ok(Capability::CAP_FSETID), "CAP_KILL" => Ok(Capability::CAP_KILL), "CAP_SETGID" => Ok(Capability::CAP_SETGID), "CAP_SETUID" => Ok(Capability::CAP_SETUID), "CAP_SETPCAP" => Ok(Capability::CAP_SETPCAP), "CAP_LINUX_IMMUTABLE" => Ok(Capability::CAP_LINUX_IMMUTABLE), "CAP_NET_BIND_SERVICE" => Ok(Capability::CAP_NET_BIND_SERVICE), "CAP_NET_BROADCAST" => Ok(Capability::CAP_NET_BROADCAST), "CAP_NET_ADMIN" => Ok(Capability::CAP_NET_ADMIN), "CAP_NET_RAW" => Ok(Capability::CAP_NET_RAW), "CAP_IPC_LOCK" => Ok(Capability::CAP_IPC_LOCK), "CAP_IPC_OWNER" => Ok(Capability::CAP_IPC_OWNER), "CAP_SYS_MODULE" => Ok(Capability::CAP_SYS_MODULE), "CAP_SYS_RAWIO" => Ok(Capability::CAP_SYS_RAWIO), "CAP_SYS_CHROOT" => Ok(Capability::CAP_SYS_CHROOT), "CAP_SYS_PTRACE" => Ok(Capability::CAP_SYS_PTRACE), "CAP_SYS_PACCT" => Ok(Capability::CAP_SYS_PACCT), "CAP_SYS_ADMIN" => Ok(Capability::CAP_SYS_ADMIN), "CAP_SYS_BOOT" => Ok(Capability::CAP_SYS_BOOT), "CAP_SYS_NICE" => Ok(Capability::CAP_SYS_NICE), "CAP_SYS_RESOURCE" => Ok(Capability::CAP_SYS_RESOURCE), "CAP_SYS_TIME" => Ok(Capability::CAP_SYS_TIME), "CAP_SYS_TTY_CONFIG" => Ok(Capability::CAP_SYS_TTY_CONFIG), "CAP_MKNOD" => Ok(Capability::CAP_MKNOD), "CAP_LEASE" => Ok(Capability::CAP_LEASE), "CAP_AUDIT_WRITE" => Ok(Capability::CAP_AUDIT_WRITE), "CAP_AUDIT_CONTROL" => Ok(Capability::CAP_AUDIT_CONTROL), "CAP_SETFCAP" => Ok(Capability::CAP_SETFCAP), "CAP_MAC_OVERRIDE" => Ok(Capability::CAP_MAC_OVERRIDE), "CAP_MAC_ADMIN" => Ok(Capability::CAP_MAC_ADMIN), "CAP_SYSLOG" => Ok(Capability::CAP_SYSLOG), "CAP_WAKE_ALARM" => Ok(Capability::CAP_WAKE_ALARM), "CAP_BLOCK_SUSPEND" => Ok(Capability::CAP_BLOCK_SUSPEND), "CAP_AUDIT_READ" => Ok(Capability::CAP_AUDIT_READ), "CAP_PERFMON" => Ok(Capability::CAP_PERFMON), "CAP_BPF" => Ok(Capability::CAP_BPF), "CAP_CHECKPOINT_RESTORE" => Ok(Capability::CAP_CHECKPOINT_RESTORE), _ => Err(format!("invalid capability: {}", s).into()), } } } impl Capability { /// Returns the bitmask corresponding to this capability value. #[allow(clippy::trivially_copy_pass_by_ref)] pub fn bitmask(&self) -> u64 { 1u64 << (*self as u8) } /// Returns the index of this capability, i.e. its kernel-defined value. #[allow(clippy::trivially_copy_pass_by_ref)] pub fn index(&self) -> u8 { *self as u8 } } /// An `HashSet` specialized on `Capability`. pub type CapsHashSet = std::collections::HashSet; /// Check if a thread contains a capability in a set. /// /// Check if set `cset` for thread `tid` contains capability `cap`. /// If `tid` is `None`, this operates on current thread (tid=0). /// It cannot check Ambient or Bounding capabilities of other processes. pub fn has_cap(tid: Option, cset: CapSet, cap: Capability) -> Result { let t = tid.unwrap_or(0); match cset { CapSet::Ambient if t == 0 => ambient::has_cap(cap), CapSet::Bounding if t == 0 => bounding::has_cap(cap), CapSet::Effective | CapSet::Inheritable | CapSet::Permitted => base::has_cap(t, cset, cap), _ => Err("operation not supported".into()), } } /// Return all capabilities in a set for a thread. /// /// Return current content of set `cset` for thread `tid`. /// If `tid` is `None`, this operates on current thread (tid=0). /// It cannot read Ambient or Bounding capabilities of other processes. pub fn read(tid: Option, cset: CapSet) -> Result { let t = tid.unwrap_or(0); match cset { CapSet::Ambient if t == 0 => ambient::read(), CapSet::Bounding if t == 0 => bounding::read(), CapSet::Effective | CapSet::Inheritable | CapSet::Permitted => base::read(t, cset), _ => Err("operation not supported".into()), } } /// Set a capability set for a thread to a new value. /// /// All and only capabilities in `value` will be set for set `cset` for thread `tid`. /// If `tid` is `None`, this operates on current thread (tid=0). /// It cannot manipulate Ambient set of other processes. /// Capabilities cannot be set in Bounding set. pub fn set(tid: Option, cset: CapSet, value: &CapsHashSet) -> Result<(), CapsError> { let t = tid.unwrap_or(0); match cset { CapSet::Ambient if t == 0 => ambient::set(value), CapSet::Effective | CapSet::Inheritable | CapSet::Permitted => base::set(t, cset, value), _ => Err("operation not supported".into()), } } /// Clear all capabilities in a set for a thread. /// /// All capabilities will be cleared from set `cset` for thread `tid`. /// If `tid` is `None`, this operates on current thread (tid=0). /// It cannot manipulate Ambient or Bounding set of other processes. pub fn clear(tid: Option, cset: CapSet) -> Result<(), CapsError> { let t = tid.unwrap_or(0); match cset { CapSet::Ambient if t == 0 => ambient::clear(), CapSet::Bounding if t == 0 => bounding::clear(), CapSet::Effective | CapSet::Permitted | CapSet::Inheritable => base::clear(t, cset), _ => Err("operation not supported".into()), } } /// Raise a single capability in a set for a thread. /// /// Capabilities `cap` will be raised from set `cset` of thread `tid`. /// If `tid` is `None`, this operates on current thread (tid=0). /// It cannot manipulate Ambient set of other processes. /// Capabilities cannot be raised in Bounding set. pub fn raise(tid: Option, cset: CapSet, cap: Capability) -> Result<(), CapsError> { let t = tid.unwrap_or(0); match cset { CapSet::Ambient if t == 0 => ambient::raise(cap), CapSet::Effective | CapSet::Permitted | CapSet::Inheritable => base::raise(t, cset, cap), _ => Err("operation not supported".into()), } } /// Drop a single capability from a set for a thread. /// /// Capabilities `cap` will be dropped from set `cset` of thread `tid`. /// If `tid` is `None`, this operates on current thread (tid=0). /// It cannot manipulate Ambient and Bounding sets of other processes. pub fn drop(tid: Option, cset: CapSet, cap: Capability) -> Result<(), CapsError> { let t = tid.unwrap_or(0); match cset { CapSet::Ambient if t == 0 => ambient::drop(cap), CapSet::Bounding if t == 0 => bounding::drop(cap), CapSet::Effective | CapSet::Permitted | CapSet::Inheritable => base::drop(t, cset, cap), _ => Err("operation not supported".into()), } } /// Return the set of all capabilities supported by this library. pub fn all() -> CapsHashSet { let slice = vec![ Capability::CAP_CHOWN, Capability::CAP_DAC_OVERRIDE, Capability::CAP_DAC_READ_SEARCH, Capability::CAP_FOWNER, Capability::CAP_FSETID, Capability::CAP_KILL, Capability::CAP_SETGID, Capability::CAP_SETUID, Capability::CAP_SETPCAP, Capability::CAP_LINUX_IMMUTABLE, Capability::CAP_NET_BIND_SERVICE, Capability::CAP_NET_BROADCAST, Capability::CAP_NET_ADMIN, Capability::CAP_NET_RAW, Capability::CAP_IPC_LOCK, Capability::CAP_IPC_OWNER, Capability::CAP_SYS_MODULE, Capability::CAP_SYS_RAWIO, Capability::CAP_SYS_CHROOT, Capability::CAP_SYS_PTRACE, Capability::CAP_SYS_PACCT, Capability::CAP_SYS_ADMIN, Capability::CAP_SYS_BOOT, Capability::CAP_SYS_NICE, Capability::CAP_SYS_RESOURCE, Capability::CAP_SYS_TIME, Capability::CAP_SYS_TTY_CONFIG, Capability::CAP_MKNOD, Capability::CAP_LEASE, Capability::CAP_AUDIT_WRITE, Capability::CAP_AUDIT_CONTROL, Capability::CAP_SETFCAP, Capability::CAP_MAC_OVERRIDE, Capability::CAP_MAC_ADMIN, Capability::CAP_SYSLOG, Capability::CAP_WAKE_ALARM, Capability::CAP_BLOCK_SUSPEND, Capability::CAP_AUDIT_READ, Capability::CAP_PERFMON, Capability::CAP_BPF, Capability::CAP_CHECKPOINT_RESTORE, ]; CapsHashSet::from_iter(slice) } /// Convert an informal capability name into a canonical form. /// /// This converts the input string to uppercase and ensures that it starts with /// `CAP_`, prepending it if necessary. It performs no validity checks so the /// output may not represent an actual capability. To check if it is, pass it /// to [`from_str`]. /// /// [`from_str`]: enum.Capability.html#method.from_str pub fn to_canonical(name: &str) -> String { let uppername = name.to_uppercase(); if uppername.starts_with("CAP_") { uppername } else { ["CAP_", &uppername].concat() } } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; #[test] fn test_all_roundtrip() { let all = all(); assert!(all.len() > 0); for c in all { let name = c.to_string(); let parsed: Capability = name.parse().unwrap(); assert_eq!(c, parsed); } } #[test] fn test_parse_invalid() { let p1 = Capability::from_str("CAP_FOO"); let p1_err = p1.unwrap_err(); assert!(p1_err.to_string().contains("invalid")); assert!(format!("{}", p1_err).contains("CAP_FOO")); let p2: Result = "CAP_BAR".parse(); assert!(p2.is_err()); } #[test] fn test_to_canonical() { let p1 = "foo"; assert!(Capability::from_str(&to_canonical(p1)).is_err()); let p2 = "sys_admin"; assert!(Capability::from_str(&to_canonical(p2)).is_ok()); let p3 = "CAP_SYS_CHROOT"; assert!(Capability::from_str(&to_canonical(p3)).is_ok()); } #[test] #[cfg(feature = "serde_support")] fn test_serde() { let p1 = Capability::from_str("CAP_CHOWN").unwrap(); let ser = serde_json::to_value(&p1).unwrap(); let deser: Capability = serde_json::from_value(ser).unwrap(); assert_eq!(deser, p1); } } caps-0.5.5/src/nr.rs000064400000000000000000000071431046102023000123420ustar 00000000000000/* from */ pub const CAP_CHOWN: u8 = 0; pub const CAP_DAC_OVERRIDE: u8 = 1; pub const CAP_DAC_READ_SEARCH: u8 = 2; pub const CAP_FOWNER: u8 = 3; pub const CAP_FSETID: u8 = 4; pub const CAP_KILL: u8 = 5; pub const CAP_SETGID: u8 = 6; pub const CAP_SETUID: u8 = 7; pub const CAP_SETPCAP: u8 = 8; pub const CAP_LINUX_IMMUTABLE: u8 = 9; pub const CAP_NET_BIND_SERVICE: u8 = 10; pub const CAP_NET_BROADCAST: u8 = 11; pub const CAP_NET_ADMIN: u8 = 12; pub const CAP_NET_RAW: u8 = 13; pub const CAP_IPC_LOCK: u8 = 14; pub const CAP_IPC_OWNER: u8 = 15; pub const CAP_SYS_MODULE: u8 = 16; pub const CAP_SYS_RAWIO: u8 = 17; pub const CAP_SYS_CHROOT: u8 = 18; pub const CAP_SYS_PTRACE: u8 = 19; pub const CAP_SYS_PACCT: u8 = 20; pub const CAP_SYS_ADMIN: u8 = 21; pub const CAP_SYS_BOOT: u8 = 22; pub const CAP_SYS_NICE: u8 = 23; pub const CAP_SYS_RESOURCE: u8 = 24; pub const CAP_SYS_TIME: u8 = 25; pub const CAP_SYS_TTY_CONFIG: u8 = 26; pub const CAP_MKNOD: u8 = 27; pub const CAP_LEASE: u8 = 28; pub const CAP_AUDIT_WRITE: u8 = 29; pub const CAP_AUDIT_CONTROL: u8 = 30; pub const CAP_SETFCAP: u8 = 31; pub const CAP_MAC_OVERRIDE: u8 = 32; pub const CAP_MAC_ADMIN: u8 = 33; pub const CAP_SYSLOG: u8 = 34; pub const CAP_WAKE_ALARM: u8 = 35; pub const CAP_BLOCK_SUSPEND: u8 = 36; pub const CAP_AUDIT_READ: u8 = 37; pub const CAP_PERFMON: u8 = 38; pub const CAP_BPF: u8 = 39; pub const CAP_CHECKPOINT_RESTORE: u8 = 40; /* from */ pub const PR_GET_KEEPCAPS: i32 = 7; pub const PR_SET_KEEPCAPS: i32 = 8; pub const PR_CAPBSET_READ: i32 = 23; pub const PR_CAPBSET_DROP: i32 = 24; pub const PR_CAP_AMBIENT: i32 = 47; pub const PR_CAP_AMBIENT_IS_SET: i32 = 1; pub const PR_CAP_AMBIENT_RAISE: i32 = 2; pub const PR_CAP_AMBIENT_LOWER: i32 = 3; pub const PR_CAP_AMBIENT_CLEAR_ALL: i32 = 4; /* from */ #[cfg(target_arch = "x86")] pub const CAPGET: i32 = 184; #[cfg(target_arch = "x86")] pub const CAPSET: i32 = 185; #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] pub const CAPGET: i64 = 125; #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] pub const CAPSET: i64 = 126; #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] pub const CAPGET: i32 = 0x40000000 + 125; #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] pub const CAPSET: i32 = 0x40000000 + 126; #[cfg(target_arch = "aarch64")] pub const CAPGET: i64 = 90; #[cfg(target_arch = "aarch64")] pub const CAPSET: i64 = 91; #[cfg(target_arch = "powerpc")] pub const CAPGET: i32 = 183; #[cfg(target_arch = "powerpc")] pub const CAPSET: i32 = 184; #[cfg(target_arch = "powerpc64")] pub const CAPGET: i64 = 183; #[cfg(target_arch = "powerpc64")] pub const CAPSET: i64 = 184; #[cfg(target_arch = "mips")] pub const CAPGET: i32 = 4204; #[cfg(target_arch = "mips")] pub const CAPSET: i32 = 4205; #[cfg(target_arch = "mips64")] pub const CAPGET: i64 = 5123; #[cfg(target_arch = "mips64")] pub const CAPSET: i64 = 5124; #[cfg(target_arch = "arm")] pub const CAPGET: i32 = 184; #[cfg(target_arch = "arm")] pub const CAPSET: i32 = 185; #[cfg(target_arch = "s390x")] pub const CAPGET: i64 = 184; #[cfg(target_arch = "s390x")] pub const CAPSET: i64 = 185; #[cfg(target_arch = "sparc")] pub const CAPGET: i64 = 21; #[cfg(target_arch = "sparc")] pub const CAPSET: i64 = 22; #[cfg(target_arch = "sparc64")] pub const CAPGET: i64 = 21; #[cfg(target_arch = "sparc64")] pub const CAPSET: i64 = 22; #[cfg(target_arch = "riscv64")] pub const CAPGET: i64 = 90; #[cfg(target_arch = "riscv64")] pub const CAPSET: i64 = 91; #[cfg(target_arch = "loongarch64")] pub const CAPGET: i64 = 90; #[cfg(target_arch = "loongarch64")] pub const CAPSET: i64 = 91; caps-0.5.5/src/runtime.rs000064400000000000000000000052321046102023000134030ustar 00000000000000/*! Detect kernel features at runtime. This module exposes methods to perform detection of kernel features at runtime. This allows applications to auto-detect whether recent options are implemented by the currently running kernel. ## Example ```rust let ambient = caps::runtime::ambient_set_supported().is_ok(); println!("Supported ambient set: {}", ambient); let all = caps::runtime::procfs_all_supported(None) .unwrap_or_else(|_| caps::runtime::thread_all_supported()); println!("Supported capabilities: {}", all.len()); ``` !*/ use super::{ambient, CapSet, Capability, CapsHashSet}; use crate::errors::CapsError; use std::io::Read; use std::path::{Path, PathBuf}; /// Check whether the running kernel supports the ambient set. /// /// Ambient set was introduced in Linux kernel 4.3. On recent kernels /// where the ambient set is supported, this will return `Ok`. /// On a legacy kernel, an `Err` is returned instead. pub fn ambient_set_supported() -> Result<(), CapsError> { ambient::has_cap(Capability::CAP_CHOWN)?; Ok(()) } /// Return the set of all capabilities supported by the running kernel. /// /// This requires a mounted `procfs` and a kernel version >= 3.2. By default, /// it uses `/proc/` as the procfs mountpoint. pub fn procfs_all_supported(proc_mountpoint: Option) -> Result { /// See `man 2 capabilities`. const LAST_CAP_FILEPATH: &str = "./sys/kernel/cap_last_cap"; let last_cap_path = proc_mountpoint .unwrap_or_else(|| PathBuf::from("/proc/")) .join(Path::new(LAST_CAP_FILEPATH)); let max_cap: u8 = { let mut buf = String::with_capacity(4); std::fs::File::open(last_cap_path.clone()) .and_then(|mut file| file.read_to_string(&mut buf)) .map_err(|e| format!("failed to read '{}': {}", last_cap_path.display(), e))?; buf.trim_end() .parse() .map_err(|e| format!("failed to parse '{}': {}", last_cap_path.display(), e))? }; let mut supported = super::all(); for c in super::all() { if c.index() > max_cap { supported.remove(&c); } } Ok(supported) } /// Return the set of all capabilities supported on the current thread. /// /// This does not require a mounted `procfs`, and it works with any /// kernel version >= 2.6.25. /// It internally uses `prctl(2)` and `PR_CAPBSET_READ`; if those are /// unavailable, this will result in an empty set. pub fn thread_all_supported() -> CapsHashSet { let mut supported = super::all(); for c in super::all() { if super::has_cap(None, CapSet::Bounding, c).is_err() { supported.remove(&c); } } supported } caps-0.5.5/src/securebits.rs000064400000000000000000000021031046102023000140620ustar 00000000000000//! Manipulate securebits flags //! //! This module exposes methods to get and set per-thread securebits //! flags, which can be used to disable special handling of capabilities //! for UID 0 (root). use crate::errors::CapsError; use crate::nr; use std::io::Error; /// Return whether the current thread's "keep capabilities" flag is set. pub fn has_keepcaps() -> Result { let ret = unsafe { libc::prctl(nr::PR_GET_KEEPCAPS, 0, 0, 0) }; match ret { 0 => Ok(false), 1 => Ok(true), _ => Err(CapsError::from(format!( "PR_GET_KEEPCAPS failure: {}", Error::last_os_error() ))), } } /// Set the value of the current thread's "keep capabilities" flag. pub fn set_keepcaps(keep_caps: bool) -> Result<(), CapsError> { let flag = if keep_caps { 1 } else { 0 }; let ret = unsafe { libc::prctl(nr::PR_SET_KEEPCAPS, flag, 0, 0) }; match ret { 0 => Ok(()), _ => Err(CapsError::from(format!( "PR_SET_KEEPCAPS failure: {}", Error::last_os_error() ))), } } caps-0.5.5/tests/ambient.rs000064400000000000000000000035161046102023000137150ustar 00000000000000#[test] fn test_ambient_has_cap() { caps::has_cap(None, caps::CapSet::Ambient, caps::Capability::CAP_CHOWN).unwrap(); } #[test] fn test_ambient_read() { caps::read(None, caps::CapSet::Ambient).unwrap(); } #[test] fn test_ambient_clear() { caps::clear(None, caps::CapSet::Ambient).unwrap(); let empty = caps::read(None, caps::CapSet::Ambient).unwrap(); assert_eq!(empty.len(), 0); } #[test] fn test_ambient_drop() { caps::drop(None, caps::CapSet::Ambient, caps::Capability::CAP_CHOWN).unwrap(); let no_cap = caps::has_cap(None, caps::CapSet::Ambient, caps::Capability::CAP_CHOWN).unwrap(); assert_eq!(no_cap, false); } #[test] fn test_ambient_drop_other() { assert!(caps::drop(Some(1), caps::CapSet::Ambient, caps::Capability::CAP_CHOWN).is_err()); } #[test] fn test_ambient_raise() { let r = caps::raise(None, caps::CapSet::Ambient, caps::Capability::CAP_CHOWN); let perm = caps::has_cap(None, caps::CapSet::Permitted, caps::Capability::CAP_CHOWN).unwrap(); let inhe = caps::has_cap(None, caps::CapSet::Inheritable, caps::Capability::CAP_CHOWN).unwrap(); match (perm, inhe) { (false, _) => assert!(r.is_err()), (true, false) => { caps::raise(None, caps::CapSet::Inheritable, caps::Capability::CAP_CHOWN).unwrap(); caps::raise(None, caps::CapSet::Ambient, caps::Capability::CAP_CHOWN).unwrap(); } (true, true) => r.unwrap(), }; } #[test] fn test_ambient_set() { let mut v = caps::CapsHashSet::new(); caps::set(None, caps::CapSet::Ambient, &v).unwrap(); let empty = caps::read(None, caps::CapSet::Ambient).unwrap(); assert_eq!(empty.len(), 0); v.insert(caps::Capability::CAP_CHOWN); caps::drop(None, caps::CapSet::Ambient, caps::Capability::CAP_CHOWN).unwrap(); assert!(caps::set(None, caps::CapSet::Ambient, &v).is_err()); } caps-0.5.5/tests/bounding.rs000064400000000000000000000027341046102023000141040ustar 00000000000000#[test] fn test_bounding_has_cap() { caps::has_cap( None, caps::CapSet::Bounding, caps::Capability::CAP_SYS_CHROOT, ) .unwrap(); } #[test] fn test_bounding_read() { caps::read(None, caps::CapSet::Bounding).unwrap(); } #[test] fn test_bounding_clear() { let ret = caps::clear(None, caps::CapSet::Bounding); if caps::has_cap(None, caps::CapSet::Effective, caps::Capability::CAP_SETPCAP).unwrap() { ret.unwrap(); let empty = caps::read(None, caps::CapSet::Bounding).unwrap(); assert_eq!(empty.len(), 0); } else { assert!(ret.is_err()); }; } #[test] fn test_bounding_drop() { let ret = caps::drop( None, caps::CapSet::Bounding, caps::Capability::CAP_SYS_CHROOT, ); if caps::has_cap(None, caps::CapSet::Effective, caps::Capability::CAP_SETPCAP).unwrap() { ret.unwrap(); let set = caps::read(None, caps::CapSet::Bounding).unwrap(); assert!(!set.contains(&caps::Capability::CAP_SYS_CHROOT)); } else { assert!(ret.is_err()); } } #[test] fn test_bounding_drop_other() { assert!(caps::drop(Some(1), caps::CapSet::Bounding, caps::Capability::CAP_CHOWN).is_err()); } #[test] fn test_bounding_raise() { assert!(caps::raise(None, caps::CapSet::Bounding, caps::Capability::CAP_CHOWN).is_err()); } #[test] fn test_bounding_set() { let v = caps::CapsHashSet::new(); assert!(caps::set(None, caps::CapSet::Bounding, &v).is_err()); } caps-0.5.5/tests/effective.rs000064400000000000000000000027251046102023000142370ustar 00000000000000#[test] fn test_effective_has_cap() { caps::has_cap(None, caps::CapSet::Effective, caps::Capability::CAP_CHOWN).unwrap(); } #[test] fn test_effective_read() { caps::read(None, caps::CapSet::Effective).unwrap(); } #[test] fn test_effective_clear() { caps::clear(None, caps::CapSet::Effective).unwrap(); let empty = caps::read(None, caps::CapSet::Effective).unwrap(); assert_eq!(empty.len(), 0); } #[test] fn test_effective_drop() { caps::drop(None, caps::CapSet::Effective, caps::Capability::CAP_CHOWN).unwrap(); let no_eff = caps::has_cap(None, caps::CapSet::Effective, caps::Capability::CAP_CHOWN).unwrap(); assert_eq!(no_eff, false); } #[test] fn test_effective_raise() { let perm = caps::has_cap(None, caps::CapSet::Permitted, caps::Capability::CAP_CHOWN).unwrap(); caps::drop(None, caps::CapSet::Effective, caps::Capability::CAP_CHOWN).unwrap(); let r = caps::raise(None, caps::CapSet::Effective, caps::Capability::CAP_CHOWN); if perm { r.unwrap(); } else { assert!(r.is_err()); } } #[test] fn test_effective_set() { let mut v = caps::CapsHashSet::new(); caps::set(None, caps::CapSet::Effective, &v).unwrap(); let empty = caps::read(None, caps::CapSet::Effective).unwrap(); assert_eq!(empty.len(), 0); v.insert(caps::Capability::CAP_CHOWN); caps::drop(None, caps::CapSet::Ambient, caps::Capability::CAP_CHOWN).unwrap(); assert!(caps::set(None, caps::CapSet::Ambient, &v).is_err()); } caps-0.5.5/tests/runtime.rs000064400000000000000000000015741046102023000137630ustar 00000000000000use caps::runtime; #[test] fn test_ambient_supported() { runtime::ambient_set_supported().unwrap(); } #[test] fn test_thread_all_supported() { assert!(runtime::thread_all_supported().len() > 0); assert!(runtime::thread_all_supported().len() <= caps::all().len()); } #[test] fn test_procfs_all_supported() { use std::path::PathBuf; let p1 = runtime::procfs_all_supported(None).unwrap(); let p2 = runtime::procfs_all_supported(Some(PathBuf::from("/proc"))).unwrap(); let thread = runtime::thread_all_supported(); let all = caps::all(); assert!(thread.len() > 0); assert!(thread.len() <= all.len()); assert_eq!( p1, p2, "{:?}", p1.symmetric_difference(&p2).collect::>() ); assert_eq!( p1, thread, "{:?}", p1.symmetric_difference(&thread).collect::>() ); } caps-0.5.5/tests/securebits.rs000064400000000000000000000005761046102023000144510ustar 00000000000000use caps::securebits; #[test] fn test_keepcaps() { // Test a roundtrip on SET_KEEPCAPS. let f0 = securebits::has_keepcaps().unwrap(); securebits::set_keepcaps(!f0).unwrap(); let f1 = securebits::has_keepcaps().unwrap(); assert_eq!(f0, !f1); securebits::set_keepcaps(!f1).unwrap(); let f2 = securebits::has_keepcaps().unwrap(); assert_eq!(f0, f2); }