Skip to content

Commit c7d39dd

Browse files
committed
stat: add support for selinux
1 parent 8220f06 commit c7d39dd

File tree

4 files changed

+49
-1
lines changed

4 files changed

+49
-1
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ feat_selinux = [
5151
"id/selinux",
5252
"ls/selinux",
5353
"mkdir/selinux",
54+
"stat/selinux",
5455
"selinux",
5556
"feat_require_selinux",
5657
]

src/uu/stat/Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ clap = { workspace = true }
2222
uucore = { workspace = true, features = ["entries", "libc", "fs", "fsext"] }
2323
chrono = { workspace = true }
2424

25+
[features]
26+
selinux = ["uucore/selinux"]
27+
2528
[[bin]]
2629
name = "stat"
2730
path = "src/main.rs"

src/uu/stat/src/stat.rs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -902,7 +902,27 @@ impl Stater {
902902
// FIXME: blocksize differs on various platform
903903
// See coreutils/gnulib/lib/stat-size.h ST_NBLOCKSIZE // spell-checker:disable-line
904904
'B' => OutputType::Unsigned(512),
905-
905+
// SELinux security context string
906+
'C' => {
907+
#[cfg(feature = "selinux")]
908+
{
909+
if uucore::selinux::check_selinux_enabled().is_ok() {
910+
match uucore::selinux::get_selinux_security_context(Path::new(file))
911+
{
912+
Ok(ctx) => OutputType::Str(ctx),
913+
Err(_) => OutputType::Str(
914+
"failed to get security context".to_string(),
915+
),
916+
}
917+
} else {
918+
OutputType::Str("unsupported on this system".to_string())
919+
}
920+
}
921+
#[cfg(not(feature = "selinux"))]
922+
{
923+
OutputType::Str("unsupported for this operating system".to_string())
924+
}
925+
}
906926
// device number in decimal
907927
'd' => OutputType::Unsigned(meta.dev()),
908928
// device number in hex

tests/by-util/test_stat.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -490,3 +490,27 @@ fn test_printf_invalid_directive() {
490490
.fails_with_code(1)
491491
.stderr_contains("'%9%': invalid directive");
492492
}
493+
494+
#[test]
495+
#[cfg(feature = "feat_selinux")]
496+
fn test_stat_selinux() {
497+
let ts = TestScenario::new(util_name!());
498+
let at = &ts.fixtures;
499+
at.touch("f");
500+
ts.ucmd()
501+
.arg("--printf='%C'")
502+
.arg("f")
503+
.succeeds()
504+
.no_stderr()
505+
.stdout_contains("unconfined_u");
506+
ts.ucmd()
507+
.arg("--printf='%C'")
508+
.arg("/bin/")
509+
.succeeds()
510+
.no_stderr()
511+
.stdout_contains("system_u");
512+
// Count that we have 4 fields
513+
let result = ts.ucmd().arg("--printf='%C'").arg("/bin/").succeeds();
514+
let s: Vec<_> = result.stdout_str().split(":").collect();
515+
assert!(s.len() == 4);
516+
}

0 commit comments

Comments
 (0)