Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ This file records each release. The format follows [Keep a Changelog](https://ke
### Added

- Multipath routes, as Linux. An IPv4 `RTM_NEWROUTE` with `RTA_MULTIPATH` makes a route with a path for each `rtnexthop`, with the checks of `fib_count_nexthops`, `fib_get_nhs` and `fib_check_nh`, and a weight of `rtnh_hops` and one. A request with one path makes a route with one path. The dump shows `RTA_MULTIPATH`, and `RTM_DELROUTE` with paths matches them in order, as `fib_nh_match`. A device that goes down marks its paths `dead linkdown`, and the route goes away when all of its paths are dead. An IPv6 route with `RTA_MULTIPATH` makes a route for each path, and these routes are siblings, as `ip6_route_multipath_add`. The dump and the notifications show the siblings in one `RTA_MULTIPATH` with their weights, and a delete without a gateway removes the siblings too. An IPv6 path whose device goes down also stays, marked `dead linkdown`, while another path is alive, as `fib6_ifdown`. A flow takes a path from a hash of its addresses and the weights, so its packets stay in order. Before, the kernel did not use `RTA_MULTIPATH` in a route (#538).
- SELinux checks the capabilities, as `selinux_capable` and `cred_has_capability` of Linux. After the check of the capability module, a capability needs its permission on the task itself in the class `capability` or `capability2`, or in `cap_userns` or `cap2_userns` for a user namespace that is not the first one. The record has `capability=N`, and a check with `CAP_OPT_NOAUDIT` makes no record. The `capable` hook now gets the user namespace of the request, as on Linux. The check of `CAP_MAC_ADMIN` for a context that the policy does not know is that of `has_cap_mac_admin`, without a record for a read of the label (#540).

### Fixed

Expand Down
12 changes: 7 additions & 5 deletions fs/rk-vfs/src/cred.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,26 +303,28 @@ impl Cred {
/// effective set, and no security module denies it, as `ns_capable(current_user_ns(), cap)`
/// of Linux.
pub fn has_cap(&self, cap: u32) -> bool {
self.cap_effective & cap::bit(cap) != 0 && crate::security::capable_lsm(self, cap, 0)
self.cap_effective & cap::bit(cap) != 0
&& crate::security::capable_lsm(self, &self.user_ns, cap, 0)
}

/// The process has the capability in the user namespace `ns`, as `ns_capable` and
/// `cap_capable` of Linux. The capabilities apply in the namespace of the process and in the
/// namespaces below it. The owner of a namespace has all the capabilities in it, if the
/// process is in the parent of the namespace. After this check of the capability module, the
/// other security modules check the capability, as `security_capable` of Linux.
pub fn ns_capable(&self, ns: &UserNs, cap: u32) -> bool {
let mut ns = ns;
pub fn ns_capable(&self, target: &UserNs, cap: u32) -> bool {
let mut ns = target;
loop {
if *ns == *self.user_ns {
return self.has_cap(cap);
return self.cap_effective & cap::bit(cap) != 0
&& crate::security::capable_lsm(self, target, cap, 0);
}
if ns.level() <= self.user_ns.level() {
return false;
}
let Some(parent) = ns.parent() else { return false };
if **parent == *self.user_ns && ns.owner() == self.euid {
return crate::security::capable_lsm(self, cap, 0);
return crate::security::capable_lsm(self, target, cap, 0);
}
ns = parent;
}
Expand Down
3 changes: 2 additions & 1 deletion fs/rk-vfs/src/security/capability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@ use super::hooks::SecurityHooks;
use super::{BlobSizes, LsmId, LsmInfo, Order, id};
use crate::cred::{Cred, cap};
use crate::inode::Result;
use crate::user_ns::UserNs;
use rk_abi::Errno;

/// The hooks of the capability module.
pub struct Capability;

impl SecurityHooks for Capability {
fn capable(&self, cred: &Cred, c: u32, _opts: u32) -> Result<()> {
fn capable(&self, cred: &Cred, _ns: &UserNs, c: u32, _opts: u32) -> Result<()> {
if cred.cap_effective & cap::bit(c) != 0 { Ok(()) } else { Err(Errno::EPERM) }
}
}
Expand Down
7 changes: 4 additions & 3 deletions fs/rk-vfs/src/security/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use crate::cred::{Cred, IpcOwner};
use crate::dentry::Location;
use crate::file::File;
use crate::inode::{Inode, Result, SetAttr};
use crate::user_ns::UserNs;
use alloc::vec::Vec;

/// The names of the LSM hooks of Linux, in the order of include/linux/lsm_hook_defs.h.
Expand Down Expand Up @@ -311,9 +312,9 @@ pub fn hook_index(name: &str) -> Option<usize> {
/// Linux. The methods without a result are the hooks of `call_void_hook`.
#[allow(unused_variables)]
pub trait SecurityHooks: Sync {
/// `capable`: the task with `cred` uses the capability `cap`. `opts` has the `CAP_OPT_*`
/// bits.
fn capable(&self, cred: &Cred, cap: u32, opts: u32) -> Result<()> {
/// `capable`: the task with `cred` uses the capability `cap` in the user namespace `ns`.
/// `opts` has the `CAP_OPT_*` bits.
fn capable(&self, cred: &Cred, ns: &UserNs, cap: u32, opts: u32) -> Result<()> {
Ok(())
}

Expand Down
13 changes: 7 additions & 6 deletions fs/rk-vfs/src/security/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use crate::cred::{Cred, IpcOwner};
use crate::dentry::Location;
use crate::file::File;
use crate::inode::{Inode, InodeRef, Result, SetAttr};
use crate::user_ns::UserNs;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
Expand Down Expand Up @@ -408,18 +409,18 @@ pub trait SockNames {

/// `security_capable`: the task with `cred` has the capability `cap`. `opts` has the
/// `CAP_OPT_*` bits.
pub fn capable(cred: &Cred, cap: u32, opts: u32) -> bool {
call_int_hook!(capable, cred, cap, opts).is_ok()
pub fn capable(cred: &Cred, ns: &UserNs, cap: u32, opts: u32) -> bool {
call_int_hook!(capable, cred, ns, cap, opts).is_ok()
}

/// `security_capable` after the capability module: the other active modules check the
/// capability `cap` of the task with `cred`. The caller has done the check of the capability
/// module, `cap_capable` of Linux, in the user namespace of the request.
pub fn capable_lsm(cred: &Cred, cap: u32, opts: u32) -> bool {
/// capability `cap` of the task with `cred` in the user namespace `ns`. The caller has done the
/// check of the capability module, `cap_capable` of Linux, in `ns`.
pub fn capable_lsm(cred: &Cred, ns: &UserNs, cap: u32, opts: u32) -> bool {
modules()
.iter()
.filter(|m| m.info.id.id != id::CAPABILITY)
.all(|m| m.info.hooks.capable(cred, cap, opts).is_ok())
.all(|m| m.info.hooks.capable(cred, ns, cap, opts).is_ok())
}

/// `security_capget`.
Expand Down
2 changes: 1 addition & 1 deletion fs/rk-vfs/src/security/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ fn the_first_error_stops_the_call() {
#[test]
fn the_capability_module_checks_the_effective_set() {
let mut c = Cred::root();
assert!(capable(&c, cap::SYS_ADMIN, 0));
assert!(capable(&c, crate::user_ns::init(), cap::SYS_ADMIN, 0));
c.cap_effective = cap::bit(cap::NET_BIND_SERVICE);
assert!(!c.capable(cap::SYS_ADMIN));
assert!(c.capable(cap::NET_BIND_SERVICE));
Expand Down
3 changes: 2 additions & 1 deletion sec/rk-lsm-apparmor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,13 @@ use rk_vfs::security::{
self, BlobSizes, Bprm, ExecFiles, FLAG_EXCLUSIVE, FLAG_LEGACY_MAJOR, LsmId, LsmInfo, Order,
SecurityHooks, Sock, Task, id,
};
use rk_vfs::user_ns::UserNs;

/// The hooks of AppArmor. A hook gives the error of a denial of a profile in enforce mode.
struct AppArmor;

impl SecurityHooks for AppArmor {
fn capable(&self, cred: &Cred, cap: u32, opts: u32) -> Result<()> {
fn capable(&self, cred: &Cred, _ns: &UserNs, cap: u32, opts: u32) -> Result<()> {
capability::capable(cred, cap, opts)
}

Expand Down
4 changes: 2 additions & 2 deletions sec/rk-lsm-apparmor/src/ns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use core::sync::atomic::{AtomicI32, Ordering};
use rk_abi::Errno;
use rk_vfs::cred::{self, Cred, cap};
use rk_vfs::inode::Result;
use rk_vfs::security::Sysctl;
use rk_vfs::security::{self, Sysctl};

/// `AA_USERNS_CREATE`.
const USERNS_CREATE: u32 = 8;
Expand Down Expand Up @@ -160,7 +160,7 @@ fn profile_ns_perm(p: Option<&Arc<Profile>>, cred: &Cred) -> Result<Label> {
match (p, state) {
(None, _) => {
let admin = cred.cap_effective & cap::bit(cap::SYS_ADMIN) != 0
&& rk_vfs::security::capable_lsm(cred, cap::SYS_ADMIN, CAP_OPT_NOAUDIT);
&& security::capable_lsm(cred, &cred.user_ns, cap::SYS_ADMIN, CAP_OPT_NOAUDIT);
if RESTRICTED.load(Ordering::Relaxed) == 0 || admin {
return Ok(new);
}
Expand Down
2 changes: 1 addition & 1 deletion sec/rk-lsm-selinux/src/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ pub fn file_ioctl(f: &File, cmd: u32) -> Result<()> {
FS_IOC_SETFLAGS | FS_IOC_SETVERSION => file_has_perm(f, file::SETATTR),
FIONBIO | FIOASYNC => file_has_perm(f, 0),
KDSKBENT | KDSKBSENT => {
task::cred_has_capability(&rk_vfs::cred::current(), CAP_SYS_TTY_CONFIG, true)
task::cred_has_capability(&rk_vfs::cred::current(), CAP_SYS_TTY_CONFIG, 0, true)
}
FIOCLEX | FIONCLEX
if crate::policy().is_some_and(|p| p.db.policycap(POLICYCAP_IOCTL_SKIP_CLOEXEC)) =>
Expand Down
3 changes: 1 addition & 2 deletions sec/rk-lsm-selinux/src/inode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use crate::sidtab::sid;
use alloc::vec;
use alloc::vec::Vec;
use rk_abi::Errno;
use rk_vfs::cred::cap;
use rk_vfs::dentry::Location;
use rk_vfs::inode::{Inode, Result};
use rk_vfs::security::blob::Blob;
Expand Down Expand Up @@ -242,7 +241,7 @@ pub fn getsecurity(
return None;
}
let sid = inode_sid(inode, at);
let text = if rk_vfs::cred::current().capable(cap::MAC_ADMIN) {
let text = if crate::task::has_cap_mac_admin(false) {
server::sid_to_context_force(sid)
} else {
server::sid_to_context(sid)
Expand Down
13 changes: 9 additions & 4 deletions sec/rk-lsm-selinux/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
//! with its table of SIDs ([`sidtab`]), the text of the contexts ([`context`]), the classes of
//! the kernel ([`classmap`]), the access vector cache ([`avc`]), the SIDs of the tasks with
//! their change at an exec, their attributes in `/proc/PID/attr` and the checks of the
//! operations on other tasks ([`task`]), the labels of the files ([`inode`]), the checks of
//! the access to the files and to the open files ([`file`]), of the mounts ([`mount`]) and of
//! the operations on the names of the directories ([`namei`]), and the labels of the new files
//! and the changes of the labels ([`xattr`]).
//! operations on other tasks and of the capabilities ([`task`]), the labels of the files
//! ([`inode`]), the checks of the access to the files and to the open files ([`file`]), of the
//! mounts ([`mount`]) and of the operations on the names of the directories ([`namei`]), and
//! the labels of the new files and the changes of the labels ([`xattr`]).
//!
//! The module is active when the command line has `selinux=1`, when `lsm=` names it, or with
//! `security=selinux`. With `selinux=0` it is not active. The module starts in permissive
Expand Down Expand Up @@ -59,11 +59,16 @@ use rk_vfs::security::{
BlobSizes, Bprm, FLAG_EXCLUSIVE, FLAG_LEGACY_MAJOR, LsmId, LsmInfo, MountReq, Order,
SecurityHooks, Task, id,
};
use rk_vfs::user_ns::UserNs;

/// The hooks of SELinux.
struct SeLinux;

impl SecurityHooks for SeLinux {
fn capable(&self, cred: &Cred, ns: &UserNs, cap: u32, opts: u32) -> Result<()> {
task::capable(cred, ns, cap, opts)
}

fn capget(&self, target: &Task<'_>) -> Result<()> {
task::current_has_perm(target, process::GETCAP)
}
Expand Down
2 changes: 1 addition & 1 deletion sec/rk-lsm-selinux/src/policydb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1585,7 +1585,7 @@ mod tests {
let p = Policydb::read(data).unwrap();
assert_eq!(p.version, v);
assert!(p.mls && !p.reject_unknown && !p.allow_unknown);
assert_eq!(p.classes.len(), 13);
assert_eq!(p.classes.len(), 16);
assert_eq!(p.class(p.process_class).unwrap().name, "process");
assert_eq!(p.process_trans_perms, (1 << 1) | (1 << 23));
assert_eq!(p.name(sym::CLASSES, 1), Some("security"));
Expand Down
92 changes: 86 additions & 6 deletions sec/rk-lsm-selinux/src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use rk_vfs::cred::{Cred, cap};
use rk_vfs::dentry::Location;
use rk_vfs::inode::Result;
use rk_vfs::security::{Bprm, Task, attr, id};
use rk_vfs::user_ns::UserNs;

/// The size of the part of SELinux in the credentials blob: the six SIDs of [`slot`], one in
/// each word.
Expand Down Expand Up @@ -69,16 +70,21 @@ pub fn cred_sid(cred: &Cred) -> u32 {
load(cred, slot::SID)
}

/// The bit of the `opts` of [`cred_has_capability`] for a check without an audit record,
/// `CAP_OPT_NOAUDIT` of Linux.
pub const CAP_OPT_NOAUDIT: u32 = 1 << 1;

/// Checks the capability `cap` of the task with `cred`, as `cred_has_capability` of Linux:
/// the permission of the capability in the class `capability` or `capability2` on the task
/// itself, or in `cap_userns` or `cap2_userns` if the capability is not for the first user
/// namespace (`initns` false). The record has ` capability=N `.
/// namespace (`initns` false). The record has ` capability=N `. There is no record if `opts` has
/// [`CAP_OPT_NOAUDIT`].
///
/// # Errors
///
/// `EACCES` if the policy denies the permission in enforcing mode, and `EINVAL` for a
/// capability after the last one.
pub fn cred_has_capability(cred: &Cred, cap: u32, initns: bool) -> Result<()> {
pub fn cred_has_capability(cred: &Cred, cap: u32, opts: u32, initns: bool) -> Result<()> {
let sclass = match (cap / 32, initns) {
(0, true) => class::CAPABILITY,
(0, false) => class::CAP_USERNS,
Expand All @@ -90,9 +96,36 @@ pub fn cred_has_capability(cred: &Cred, cap: u32, initns: bool) -> Result<()> {
}
};
let sid = cred_sid(cred);
avc::has_perm(sid, sid, sclass, 1 << (cap % 32), |s| {
let _ = write!(s, " capability={cap} ");
})
let av = 1 << (cap % 32);
let (avd, rc) = avc::has_perm_noaudit(sid, sid, sclass, av);
if opts & CAP_OPT_NOAUDIT == 0 {
avc::audit(sid, sid, sclass, av, &avd, rc, 0, |s| {
let _ = write!(s, " capability={cap} ");
});
}
rc
}

/// The `capable` hook, `selinux_capable` of Linux: checks the capability `cap` of the task with
/// `cred` in the user namespace `ns`, with the classes of the first user namespace if `ns` is the
/// first one.
///
/// # Errors
///
/// As [`cred_has_capability`].
pub fn capable(cred: &Cred, ns: &UserNs, cap: u32, opts: u32) -> Result<()> {
cred_has_capability(cred, cap, opts, ns.is_init())
}

/// The current task has `CAP_MAC_ADMIN` in the first user namespace, as `has_cap_mac_admin` of
/// Linux: the check of the capability module, then the check of SELinux, with a record if
/// `audit` is true.
pub fn has_cap_mac_admin(audit: bool) -> bool {
let cred = rk_vfs::cred::current();
let opts = if audit { 0 } else { CAP_OPT_NOAUDIT };
cred.user_ns.is_init()
&& cred.cap_effective & cap::bit(cap::MAC_ADMIN) != 0
&& cred_has_capability(&cred, cap::MAC_ADMIN, opts, true).is_ok()
}

/// The SID of the file `at`, from [`crate::inode::inode_sid`].
Expand Down Expand Up @@ -316,7 +349,7 @@ pub fn setattr(attr: u64, value: &[u8]) -> Result<usize> {
let text = &value[..size];
sid = match server::context_to_sid(text, 0, false) {
Err(Errno::EINVAL) if attr == attr::FSCREATE => {
if !cred.capable(cap::MAC_ADMIN) {
if !has_cap_mac_admin(true) {
let mut s = String::from("op=fscreate invalid_context=");
avc::untrusted(&mut s, text.strip_suffix(&[0]).unwrap_or(text));
services::log_err(&s);
Expand Down Expand Up @@ -672,6 +705,53 @@ mod tests {
assert_eq!(capset(&init, &me), Ok(()));
}

#[test]
fn a_capability_needs_its_permission_in_the_policy() {
let _guard = setup();
let me = Cred::root();
let host = rk_vfs::user_ns::init();
let child = rk_vfs::user_ns::create(&me).unwrap();
let free = Cred::root();
store(&free, slot::SID, sid_of("system_u:system_r:unconfined_t:s0"));
// CAP_SYS_TTY_CONFIG, and CAP_WAKE_ALARM, the fourth capability of the class
// capability2.
let (tty_config, wake_alarm) = (26, 35);
crate::set_enforcing(true);
// The rules give each domain the capabilities on itself in the first user namespace,
// without sys_time, sys_tty_config and wake_alarm.
for c in [cap::CHOWN, cap::SYS_ADMIN, cap::SETFCAP, cap::MAC_ADMIN, cap::LAST] {
assert_eq!(capable(&me, host, c, 0), Ok(()), "{c}");
}
for c in [cap::SYS_TIME, tty_config, wake_alarm] {
assert_eq!(capable(&me, host, c, 0), Err(Errno::EACCES), "{c}");
assert_eq!(capable(&me, host, c, CAP_OPT_NOAUDIT), Err(Errno::EACCES), "{c}");
}
// In another user namespace, the classes are cap_userns and cap2_userns, and the
// policy has no rules for them.
for c in [cap::CHOWN, cap::SYS_ADMIN, cap::MAC_ADMIN, cap::LAST] {
assert_eq!(capable(&child, &child.user_ns, c, 0), Err(Errno::EACCES), "{c}");
}
assert_eq!(capable(&free, host, cap::SYS_TIME, 0), Ok(()));
// As on Linux, a capability after the last one of capability2 is a bit of the class
// that the policy does not know, and a capability after the class capability2 is not
// valid.
assert_eq!(capable(&me, host, cap::LAST + 1, 0), Err(Errno::EACCES));
assert_eq!(capable(&me, host, 64, 0), Err(Errno::EINVAL));
// After the check of the effective set, the capability functions of the credentials
// ask SELinux, with the user namespace of the request.
assert!(me.capable(cap::SYS_ADMIN));
assert!(!me.capable(cap::SYS_TIME));
assert!(!child.capable(cap::SYS_ADMIN));
assert!(!child.ns_capable(&child.user_ns, cap::SYS_ADMIN));
assert!(has_cap_mac_admin(false));
crate::set_enforcing(false);
// Permissive mode only makes the records.
assert_eq!(capable(&me, host, cap::SYS_TIME, 0), Ok(()));
assert_eq!(capable(&child, &child.user_ns, cap::SYS_ADMIN, 0), Ok(()));
assert!(child.ns_capable(&child.user_ns, cap::SYS_ADMIN));
assert_eq!(capable(&me, host, 64, 0), Err(Errno::EINVAL));
}

#[test]
fn the_attributes_give_the_contexts_with_a_nul() {
let _guard = setup();
Expand Down
3 changes: 1 addition & 2 deletions sec/rk-lsm-selinux/src/xattr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ use crate::{avc, server, services, task};
use alloc::string::String;
use alloc::vec::Vec;
use rk_abi::Errno;
use rk_vfs::cred::cap;
use rk_vfs::dentry::Location;
use rk_vfs::inode::{Inode, Result};

Expand Down Expand Up @@ -52,7 +51,7 @@ pub fn init_security(
fn new_sid(value: &[u8]) -> Result<u32> {
match server::context_to_sid(value, 0, false) {
Err(Errno::EINVAL) => {
if !rk_vfs::cred::current().capable(cap::MAC_ADMIN) {
if !crate::task::has_cap_mac_admin(true) {
let mut s = String::from("op=setxattr invalid_context=");
avc::untrusted(&mut s, value.strip_suffix(&[0]).unwrap_or(value));
services::log_err(&s);
Expand Down
Binary file modified sec/rk-lsm-selinux/tests/rk_test.24.bin
Binary file not shown.
Binary file modified sec/rk-lsm-selinux/tests/rk_test.33.bin
Binary file not shown.
Binary file modified sec/rk-lsm-selinux/tests/rk_test.35.bin
Binary file not shown.
Loading
Loading