Skip to content

Commit 3a835f9

Browse files
committed
Add SMACK support for ls utility
1 parent efa1aa7 commit 3a835f9

8 files changed

Lines changed: 140 additions & 32 deletions

File tree

Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,10 @@ feat_selinux = [
6565
"selinux",
6666
"stat/selinux",
6767
]
68+
# "feat_smack" == enable support for SMACK Security Context (by using `--features feat_smack`)
69+
# NOTE:
70+
# * Running a uutils compiled with `feat_smack` requires a SMACK enabled Kernel at run time.
71+
feat_smack = ["ls/smack"]
6872
##
6973
## feature sets
7074
## (common/core and Tier1) feature sets

src/uu/ls/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,4 @@ harness = false
6060

6161
[features]
6262
feat_selinux = ["selinux", "uucore/selinux"]
63+
smack = ["uucore/smack"]

src/uu/ls/src/ls.rs

Lines changed: 49 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -365,7 +365,10 @@ pub struct Config {
365365
time_format_recent: String, // Time format for recent dates
366366
time_format_older: Option<String>, // Time format for older dates (optional, if not present, time_format_recent is used)
367367
context: bool,
368+
#[cfg(all(feature = "selinux", target_os = "linux"))]
368369
selinux_supported: bool,
370+
#[cfg(all(feature = "smack", target_os = "linux"))]
371+
smack_supported: bool,
369372
group_directories_first: bool,
370373
line_ending: LineEnding,
371374
dired: bool,
@@ -1157,16 +1160,10 @@ impl Config {
11571160
time_format_recent,
11581161
time_format_older,
11591162
context,
1160-
selinux_supported: {
1161-
#[cfg(all(feature = "selinux", target_os = "linux"))]
1162-
{
1163-
uucore::selinux::is_selinux_enabled()
1164-
}
1165-
#[cfg(not(all(feature = "selinux", target_os = "linux")))]
1166-
{
1167-
false
1168-
}
1169-
},
1163+
#[cfg(all(feature = "selinux", target_os = "linux"))]
1164+
selinux_supported: uucore::selinux::is_selinux_enabled(),
1165+
#[cfg(all(feature = "smack", target_os = "linux"))]
1166+
smack_supported: uucore::smack::is_smack_enabled(),
11701167
group_directories_first: options.get_flag(options::GROUP_DIRECTORIES_FIRST),
11711168
line_ending: LineEnding::from_zero_flag(options.get_flag(options::ZERO)),
11721169
dired,
@@ -3387,33 +3384,53 @@ fn get_security_context<'a>(
33873384
}
33883385
}
33893386

3387+
#[cfg(all(feature = "selinux", target_os = "linux"))]
33903388
if config.selinux_supported {
3391-
#[cfg(all(feature = "selinux", target_os = "linux"))]
3392-
{
3393-
match selinux::SecurityContext::of_path(path, must_dereference, false) {
3394-
Err(_r) => {
3395-
// TODO: show the actual reason why it failed
3396-
show_warning!("failed to get security context of: {}", path.quote());
3397-
return Cow::Borrowed(SUBSTITUTE_STRING);
3398-
}
3399-
Ok(None) => return Cow::Borrowed(SUBSTITUTE_STRING),
3400-
Ok(Some(context)) => {
3401-
let context = context.as_bytes();
3389+
match selinux::SecurityContext::of_path(path, must_dereference, false) {
3390+
Err(_r) => {
3391+
// TODO: show the actual reason why it failed
3392+
show_warning!("failed to get security context of: {}", path.quote());
3393+
return Cow::Borrowed(SUBSTITUTE_STRING);
3394+
}
3395+
Ok(None) => return Cow::Borrowed(SUBSTITUTE_STRING),
3396+
Ok(Some(context)) => {
3397+
let context = context.as_bytes();
34023398

3403-
let context = context.strip_suffix(&[0]).unwrap_or(context);
3399+
let context = context.strip_suffix(&[0]).unwrap_or(context);
34043400

3405-
let res: String = String::from_utf8(context.to_vec()).unwrap_or_else(|e| {
3406-
show_warning!(
3407-
"getting security context of: {}: {}",
3408-
path.quote(),
3409-
e.to_string()
3410-
);
3401+
let res: String = String::from_utf8(context.to_vec()).unwrap_or_else(|e| {
3402+
show_warning!(
3403+
"getting security context of: {}: {}",
3404+
path.quote(),
3405+
e.to_string()
3406+
);
34113407

3412-
String::from_utf8_lossy(context).to_string()
3413-
});
3408+
String::from_utf8_lossy(context).to_string()
3409+
});
34143410

3415-
return Cow::Owned(res);
3416-
}
3411+
return Cow::Owned(res);
3412+
}
3413+
}
3414+
}
3415+
3416+
#[cfg(all(feature = "smack", target_os = "linux"))]
3417+
if config.smack_supported {
3418+
// For SMACK, use the path to get the label
3419+
// If must_dereference is true, we follow the symlink
3420+
let target_path = if must_dereference {
3421+
match std::fs::canonicalize(path) {
3422+
Ok(p) => p,
3423+
Err(_) => path.to_path_buf(),
3424+
}
3425+
} else {
3426+
path.to_path_buf()
3427+
};
3428+
3429+
match uucore::smack::get_smack_label_for_path(&target_path) {
3430+
Ok(label) => return Cow::Owned(label),
3431+
Err(_) => {
3432+
// No label or error getting label
3433+
return Cow::Borrowed(SUBSTITUTE_STRING);
34173434
}
34183435
}
34193436
}

src/uucore/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,7 @@ ranges = []
162162
ringbuffer = []
163163
safe-traversal = ["libc"]
164164
selinux = ["dep:selinux"]
165+
smack = ["xattr"]
165166
signals = []
166167
sum = [
167168
"digest",

src/uucore/locales/en-US.ftl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,12 @@ selinux-error-context-retrieval-failure = failed to retrieve the security contex
4646
selinux-error-context-set-failure = failed to set default file creation context to '{ $context }': { $error }
4747
selinux-error-context-conversion-failure = failed to set default file creation context to '{ $context }': { $error }
4848
49+
# SMACK error messages
50+
smack-error-not-enabled = SMACK is not enabled on this system
51+
smack-error-label-retrieval-failure = failed to get SMACK label: { $error }
52+
smack-error-label-set-failure = failed to set SMACK label to '{ $context }': { $error }
53+
smack-error-no-label-set = no SMACK label set
54+
4955
# Safe traversal error messages
5056
safe-traversal-error-path-contains-null = path contains null byte
5157
safe-traversal-error-open-failed = failed to open '{ $path }': { $source }

src/uucore/src/lib/features.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,8 @@ pub mod hardware;
8585
pub mod selinux;
8686
#[cfg(all(unix, not(target_os = "fuchsia"), feature = "signals"))]
8787
pub mod signals;
88+
#[cfg(all(target_os = "linux", feature = "smack"))]
89+
pub mod smack;
8890
#[cfg(feature = "feat_systemd_logind")]
8991
pub mod systemd_logind;
9092
#[cfg(all(
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// This file is part of the uutils uucore package.
2+
//
3+
// For the full copyright and license information, please view the LICENSE
4+
// file that was distributed with this source code.
5+
6+
// spell-checker:ignore smackfs
7+
//! SMACK (Simplified Mandatory Access Control Kernel) support
8+
9+
use std::io;
10+
use std::path::Path;
11+
12+
use thiserror::Error;
13+
14+
use crate::error::{UError, strip_errno};
15+
use crate::translate;
16+
17+
#[derive(Debug, Error)]
18+
pub enum SmackError {
19+
#[error("{}", translate!("smack-error-not-enabled"))]
20+
SmackNotEnabled,
21+
22+
#[error("{}", translate!("smack-error-label-retrieval-failure", "error" => strip_errno(.0)))]
23+
LabelRetrievalFailure(io::Error),
24+
25+
#[error("{}", translate!("smack-error-label-set-failure", "context" => .0.clone(), "error" => strip_errno(.1)))]
26+
LabelSetFailure(String, io::Error),
27+
}
28+
29+
impl UError for SmackError {
30+
fn code(&self) -> i32 {
31+
match self {
32+
Self::SmackNotEnabled => 1,
33+
Self::LabelRetrievalFailure(_) => 2,
34+
Self::LabelSetFailure(_, _) => 3,
35+
}
36+
}
37+
}
38+
39+
impl From<SmackError> for i32 {
40+
fn from(error: SmackError) -> Self {
41+
error.code()
42+
}
43+
}
44+
45+
/// Checks if SMACK is enabled by verifying smackfs is mounted.
46+
pub fn is_smack_enabled() -> bool {
47+
Path::new("/sys/fs/smackfs").exists()
48+
}
49+
50+
/// Gets the SMACK label for a filesystem path via xattr.
51+
pub fn get_smack_label_for_path(path: &Path) -> Result<String, SmackError> {
52+
if !is_smack_enabled() {
53+
return Err(SmackError::SmackNotEnabled);
54+
}
55+
56+
match xattr::get(path, "security.SMACK64") {
57+
Ok(Some(value)) => Ok(String::from_utf8_lossy(&value).trim().to_string()),
58+
Ok(None) => Err(SmackError::LabelRetrievalFailure(io::Error::new(
59+
io::ErrorKind::NotFound,
60+
translate!("smack-error-no-label-set"),
61+
))),
62+
Err(e) => Err(SmackError::LabelRetrievalFailure(e)),
63+
}
64+
}
65+
66+
/// Sets the SMACK label for a filesystem path via xattr.
67+
pub fn set_smack_label_for_path(path: &Path, label: &str) -> Result<(), SmackError> {
68+
if !is_smack_enabled() {
69+
return Err(SmackError::SmackNotEnabled);
70+
}
71+
72+
xattr::set(path, "security.SMACK64", label.as_bytes())
73+
.map_err(|e| SmackError::LabelSetFailure(label.to_string(), e))
74+
}

src/uucore/src/lib/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,9 @@ pub use crate::features::fsxattr;
125125
#[cfg(all(target_os = "linux", feature = "selinux"))]
126126
pub use crate::features::selinux;
127127

128+
#[cfg(all(target_os = "linux", feature = "smack"))]
129+
pub use crate::features::smack;
130+
128131
//## core functions
129132

130133
#[cfg(unix)]

0 commit comments

Comments
 (0)