caps-0.3.3/COPYRIGHT010064400017500001750000000003341350324225300121560ustar0000000000000000Format: 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.3.3/Cargo.toml.orig010064400017500001750000000013531352262431400135570ustar0000000000000000[package] name = "caps" version = "0.3.3" 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] errno = "0.2" error-chain = {version = "0.12", default-features = false} libc = "0.2" [package.metadata.release] sign-commit = true upload-doc = false disable-publish = true disable-push = true pre-release-commit-message = "cargo: caps release {{version}}" pro-release-commit-message = "cargo: development version bump" tag-message = "caps {{version}}" caps-0.3.3/Cargo.toml0000644000000024360000000000000100270ustar00# 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "caps" version = "0.3.3" authors = ["Luca Bruno "] exclude = [".gitignore", ".travis.yml"] description = "A pure-Rust library to work with Linux capabilities" documentation = "https://docs.rs/caps" keywords = ["Linux", "capabilities", "POSIX", "getcap", "setcap"] license = "MIT/Apache-2.0" repository = "https://github.com/lucab/caps-rs" [package.metadata.release] disable-publish = true disable-push = true pre-release-commit-message = "cargo: caps release {{version}}" pro-release-commit-message = "cargo: development version bump" sign-commit = true tag-message = "caps {{version}}" upload-doc = false [dependencies.errno] version = "0.2" [dependencies.error-chain] version = "0.12" default-features = false [dependencies.libc] version = "0.2" caps-0.3.3/LICENSE-APACHE-2.0010064400017500001750000000261361350324225300131140ustar0000000000000000 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.3.3/LICENSE-MIT010064400017500001750000000017771350324225300123330ustar0000000000000000Permission 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.3.3/README.md010064400017500001750000000046401347544041500121560ustar0000000000000000# caps [![Build Status](https://travis-ci.org/lucab/caps-rs.svg?branch=master)](https://travis-ci.org/lucab/caps-rs) [![crates.io](https://img.shields.io/crates/v/caps.svg)](https://crates.io/crates/caps) [![LoC](https://tokei.rs/b1/github/lucab/caps-rs?category=code)](https://github.com/lucab/caps-rs) [![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 extern crate caps; use caps::{Capability, CapSet}; fn manipulate_caps() { // Retrieve permitted set. let cur = caps::read(None, CapSet::Permitted).unwrap(); println!("Current permitted caps: {:?}.", cur); // Retrieve effective set. let cur = caps::read(None, CapSet::Effective).unwrap(); 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).unwrap(); if !perm_chown.unwrap() { println!("Try running this as root!"); return; } // Clear all effective caps. caps::clear(None, CapSet::Effective).unwrap(); println!("Cleared effective caps."); let cur = caps::read(None, CapSet::Effective).unwrap(); 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).unwrap(); println!("Raised CAP_CHOWN in effective set."); let cur = caps::read(None, CapSet::Effective).unwrap(); println!("Current effective caps: {:?}.", cur); } ``` 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.3.3/examples/clear_permitted.rs010064400017500001750000000041511347544041500162230ustar0000000000000000//! A simple example showing how to manipulate capabilities. //! //! It clears Permitted set to show its interaction //! with Effective set. //! //! This is a caps example ONLY: do NOT panic/unwrap/assert //! in production code! extern crate caps; use caps::{CapSet, Capability}; fn main() { // Check if `CAP_CHOWN` was originally available. let cur = caps::read(None, CapSet::Permitted).unwrap(); println!("-> Current permitted caps: {:?}.", cur); let cur = caps::read(None, CapSet::Effective).unwrap(); 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.unwrap() { println!("Try running this again as root/sudo or with CAP_CHOWN file capability!"); return; } // 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).unwrap(); 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).unwrap(); 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).unwrap(); println!("-> Current permitted caps: {:?}.", cur); let cur = caps::read(None, CapSet::Effective).unwrap(); 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).unwrap(); println!("-> Current effective caps: {:?}.", cur); } caps-0.3.3/examples/legacy.rs010064400017500001750000000005331347544041500143240ustar0000000000000000extern crate caps; use 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::all_supported(); let missing = all.difference(&supported); println!("Unsupported new capabilities: {:?}", missing); } caps-0.3.3/examples/manipulate_sys_nice.rs010064400017500001750000000045071347544041500171200ustar0000000000000000//! A simple example showing how to manipulate capabilities. //! //! It drops and raises `CAP_SYS_NICE` to show its interaction //! with `getpriority(2)`. //! //! This is a caps example ONLY: do NOT panic/unwrap/assert //! in production code! extern crate caps; extern crate libc; use caps::{CapSet, Capability}; fn main() { // 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(), 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.unwrap() { println!("Try running this again as root/sudo or with CAP_SYS_NICE file capability!"); return; } 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()); } #[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 drain errno. 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 drain errno. let r = unsafe { libc::getpriority(PRIO_PROCESS as u32, 0) }; if r == -1 { panic!("getpriority failed."); } r } caps-0.3.3/examples/parse.rs010064400017500001750000000006151347544041500141730ustar0000000000000000extern crate caps; use 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.3.3/src/ambient.rs010064400017500001750000000040541347544041500134520ustar0000000000000000use errno; use libc; use super::Capability; use errors::*; use nr; pub fn clear() -> Result<()> { let ret = unsafe { libc::prctl(nr::PR_CAP_AMBIENT, nr::PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) }; match ret { 0 => Ok(()), _ => Err(Error::from_kind(ErrorKind::Sys(errno::errno())) .chain_err(|| "PR_CAP_AMBIENT_CLEAR_ALL error")), } } pub fn drop(cap: Capability) -> Result<()> { 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(Error::from_kind(ErrorKind::Sys(errno::errno())) .chain_err(|| "PR_CAP_AMBIENT_LOWER error")), } } 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(Error::from_kind(ErrorKind::Sys(errno::errno())) .chain_err(|| "PR_CAP_AMBIENT_IS_SET error")), } } pub fn raise(cap: Capability) -> Result<()> { 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(Error::from_kind(ErrorKind::Sys(errno::errno())) .chain_err(|| "PR_CAP_AMBIENT_RAISE error")), } } pub fn read() -> Result { let mut res = super::CapsHashSet::new(); for c in super::all() { if try!(has_cap(c)) { res.insert(c); } } Ok(res) } pub fn set(value: &super::CapsHashSet) -> Result<()> { for c in super::all() { if value.contains(&c) { try!(raise(c)); } else { try!(drop(c)); }; } Ok(()) } caps-0.3.3/src/base.rs010064400017500001750000000114501347544041500127430ustar0000000000000000use errno; use libc; use super::{CapSet, Capability}; use errors::*; use nr; #[allow(unknown_lints, unreadable_literal)] const CAPS_V3: u32 = 0x20080522; fn capget(hdr: &mut CapUserHeader, data: &mut CapUserData) -> Result<()> { let r = unsafe { libc::syscall(nr::CAPGET, hdr, data) }; match r { 0 => Ok(()), _ => Err(Error::from_kind(ErrorKind::Sys(errno::errno())).chain_err(|| "capget error")), } } fn capset(hdr: &mut CapUserHeader, data: &CapUserData) -> Result<()> { let r = unsafe { libc::syscall(nr::CAPSET, hdr, data) }; match r { 0 => Ok(()), _ => Err(Error::from_kind(ErrorKind::Sys(errno::errno())).chain_err(|| "capset error")), } } 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(); try!(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 => bail!("not a base set"), }; let has_cap = (caps & cap.bitmask()) != 0; Ok(has_cap) } pub fn clear(tid: i32, cset: CapSet) -> Result<()> { let mut hdr = CapUserHeader { version: CAPS_V3, pid: tid, }; let mut data: CapUserData = Default::default(); try!(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 => bail!("not a base set"), } 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(); try!(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 => bail!("not a base set"), }; let mut res = super::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: super::CapsHashSet) -> Result<()> { let mut hdr = CapUserHeader { version: CAPS_V3, pid: tid, }; let mut data: CapUserData = Default::default(); try!(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 => bail!("not a base set"), }; *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; } _ => bail!("overlarge cap index {}", c.index()), } } } try!(capset(&mut hdr, &data)); Ok(()) } pub fn drop(tid: i32, cset: CapSet, cap: Capability) -> Result<()> { let mut caps = try!(read(tid, cset)); if caps.remove(&cap) { try!(set(tid, cset, caps)); }; Ok(()) } pub fn raise(tid: i32, cset: CapSet, cap: Capability) -> Result<()> { let mut caps = try!(read(tid, cset)); if caps.insert(cap) { try!(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.3.3/src/bounding.rs010064400017500001750000000021421350761307000136270ustar0000000000000000use errno; use libc; use super::Capability; use errors::*; use nr; pub fn clear() -> Result<()> { for c in super::all() { if try!(has_cap(c)) { try!(drop(c)); } } Ok(()) } pub fn drop(cap: Capability) -> Result<()> { let ret = unsafe { libc::prctl(nr::PR_CAPBSET_DROP, libc::c_uint::from(cap.index()), 0, 0) }; match ret { 0 => Ok(()), _ => { Err(Error::from_kind(ErrorKind::Sys(errno::errno())) .chain_err(|| "PR_CAPBSET_DROP 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(Error::from_kind(ErrorKind::Sys(errno::errno())) .chain_err(|| "PR_CAPBSET_READ error")) } } } pub fn read() -> Result { let mut res = super::CapsHashSet::new(); for c in super::all() { if try!(has_cap(c)) { res.insert(c); } } Ok(res) } caps-0.3.3/src/errors.rs010064400017500001750000000012471350761307000133430ustar0000000000000000//! Error handling. use errno; error_chain! { errors { /// Parsing error due to invalid capability name. InvalidCapName(name: String) { description("invalid capability name") display("invalid capability name: '{}'", name) } /// Syscall error, as `errno(3)`. Sys(errno: errno::Errno) { description("syscall failed") display("{}", errno) } } } #[test] fn test_sys_errno() { let eperm = errno::Errno(1); let err = ErrorKind::Sys(eperm); assert!(err.description().contains("syscall failed")); assert!(format!("{}", err).contains("Operation not permitted")); } caps-0.3.3/src/lib.rs010064400017500001750000000407401350761307000125760ustar0000000000000000//! A pure-Rust library to work with Linux capabilities. //! //! It provides support for manipulating capabilities available //! in modern Linux kernel. It supports traditional POSIX sets //! (Effective, Inheritable, Permitted) as well as Linux-specific //! Ambient and Bounding capabilities sets. //! //! ```rust //! use caps::{Capability, CapSet}; //! //! fn manipulate_caps() { //! if caps::has_cap(None, CapSet::Permitted, Capability::CAP_SYS_NICE).unwrap() { //! caps::drop(None, CapSet::Effective, Capability::CAP_SYS_NICE).unwrap(); //! let s = caps::read(None, CapSet::Effective).unwrap(); //! assert_eq!(s.contains(&Capability::CAP_SYS_NICE), false); //! caps::clear(None, CapSet::Effective).unwrap(); //! }; //! } //! ``` #[macro_use] extern crate error_chain; extern crate errno; extern crate libc; mod ambient; // Implementation of Ambient set mod base; // Implementation of POSIX sets mod bounding; // Implementation of Bounding set pub mod errors; // Error wrapping mod nr; // All kernel-related constants pub mod runtime; // Features/legacy detection at runtime pub mod securebits; // Thread security bits use errors::*; 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)`. #[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)] #[allow(non_camel_case_types)] #[repr(u8)] 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, } 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", }; write!(f, "{}", name) } } impl std::str::FromStr for Capability { type Err = errors::Error; 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), _ => Err(ErrorKind::InvalidCapName(s.to_string()).into()), } } } impl Capability { /// Returns the bitmask corresponding to this capability value. #[cfg_attr(feature = "cargo-clippy", allow(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. #[cfg_attr(feature = "cargo-clippy", allow(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), _ => bail!("operation not supported"), } } /// 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), _ => bail!("operation not supported"), } } /// 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<()> { 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), _ => bail!("operation not supported"), } } /// 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<()> { 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), _ => bail!("operation not supported"), } } /// 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<()> { 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), _ => bail!("operation not supported"), } } /// 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<()> { 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), _ => bail!("operation not supported"), } } /// Return an `HashSet` with all known capabilities. 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, ]; 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() } } #[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() { use std::str::FromStr; let p1 = Capability::from_str("CAP_FOO"); let p1_err = p1.unwrap_err(); assert!(p1_err.description().contains("invalid")); assert!(format!("{}", p1_err).contains("CAP_FOO")); let p2: Result = "CAP_BAR".parse(); assert!(p2.is_err()); } #[test] fn test_to_canonical() { use std::str::FromStr; 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()); } caps-0.3.3/src/nr.rs010064400017500001750000000057471352262347400124650ustar0000000000000000/* 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; /* 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(target_arch = "x86_64")] pub const CAPGET: i64 = 125; #[cfg(target_arch = "x86_64")] pub const CAPSET: i64 = 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; caps-0.3.3/src/runtime.rs010064400017500001750000000017471347544041500135240ustar0000000000000000//! 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. use super::{ambient, CapSet, Capability, CapsHashSet}; use errors::*; /// 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<()> { ambient::has_cap(Capability::CAP_CHOWN)?; Ok(()) } /// Return an `HashSet` with all capabilities supported by the running kernel. pub fn 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.3.3/src/securebits.rs010064400017500001750000000020631350761307000141740ustar0000000000000000//! 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 errno; use libc; use errors::*; use nr; /// 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(Error::from_kind(ErrorKind::Sys(errno::errno())) .chain_err(|| "PR_GET_KEEPCAPS error")) } } } /// Set the value of the current thread's "keep capabilities" flag. pub fn set_keepcaps(keep_caps: bool) -> Result<()> { 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(Error::from_kind(ErrorKind::Sys(errno::errno())) .chain_err(|| "PR_SET_KEEPCAPS error")) } } } caps-0.3.3/tests/ambient.rs010064400017500001750000000035501347544041500140250ustar0000000000000000extern crate caps; #[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.clone()).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.3.3/tests/bounding.rs010064400017500001750000000027571350761307000142160ustar0000000000000000extern crate caps; #[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.3.3/tests/effective.rs010064400017500001750000000027571347544041500143560ustar0000000000000000extern crate caps; #[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.clone()).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.3.3/tests/runtime.rs010064400017500001750000000003321347544041500140640ustar0000000000000000extern crate caps; use caps::runtime; #[test] fn test_ambient_supported() { runtime::ambient_set_supported().unwrap(); } #[test] fn test_all_supported() { assert_eq!(runtime::all_supported(), caps::all()); } caps-0.3.3/tests/securebits.rs010064400017500001750000000006211347544041500145520ustar0000000000000000extern crate caps; use 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); } caps-0.3.3/.cargo_vcs_info.json0000644000000001120000000000000120160ustar00{ "git": { "sha1": "eabca98b3eef61c4d27c369684200fdd937c55af" } }