const ACL_VERSION: u32 = 0x0001;
const XATTR_ACL_VERSION: u32 = 0x0002;
const XATTR_ENTRY_LEN: usize = 8;
const ACL_UNDEFINED_ID: u32 = u32::MAX;
pub const READ: u16 = 4;
pub const WRITE: u16 = 2;
pub const EXEC: u16 = 1;
const TAG_USER_OBJ: u16 = 0x01;
const TAG_USER: u16 = 0x02;
const TAG_GROUP_OBJ: u16 = 0x04;
const TAG_GROUP: u16 = 0x08;
const TAG_MASK: u16 = 0x10;
const TAG_OTHER: u16 = 0x20;
#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum AclError {
#[error("ACL is missing its required {tag} entry")]
#[non_exhaustive]
MissingRequired {
tag: &'static str,
},
#[error("ACL has a duplicate {tag} entry")]
#[non_exhaustive]
Duplicate {
tag: &'static str,
},
#[error("ACL names users or groups but has no mask entry")]
MaskRequired,
#[error("ACL entry has invalid permission bits {perm:#x}")]
#[non_exhaustive]
InvalidPerm {
perm: u16,
},
#[error("encoded ACL is malformed: {reason}")]
#[non_exhaustive]
Malformed {
reason: &'static str,
},
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum AclQualifier {
UserObj,
User(u32),
GroupObj,
Group(u32),
Mask,
Other,
}
impl AclQualifier {
fn tag_and_id(self) -> (u16, Option<u32>) {
match self {
AclQualifier::UserObj => (TAG_USER_OBJ, None),
AclQualifier::User(id) => (TAG_USER, Some(id)),
AclQualifier::GroupObj => (TAG_GROUP_OBJ, None),
AclQualifier::Group(id) => (TAG_GROUP, Some(id)),
AclQualifier::Mask => (TAG_MASK, None),
AclQualifier::Other => (TAG_OTHER, None),
}
}
fn sort_key(self) -> (u16, u32) {
let (tag, id) = self.tag_and_id();
(tag, id.unwrap_or(0))
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct AclEntry {
pub who: AclQualifier,
pub perm: u16,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Acl {
entries: Vec<AclEntry>,
}
impl Acl {
pub const ACCESS_NAME: &'static [u8] = b"system.posix_acl_access";
pub const DEFAULT_NAME: &'static [u8] = b"system.posix_acl_default";
pub fn new(mut entries: Vec<AclEntry>) -> Result<Self, AclError> {
for e in &entries {
if e.perm & !(READ | WRITE | EXEC) != 0 {
return Err(AclError::InvalidPerm { perm: e.perm });
}
}
entries.sort_by_key(|e| e.who.sort_key());
Self::validate(&entries)?;
Ok(Self { entries })
}
#[must_use]
pub fn entries(&self) -> &[AclEntry] {
&self.entries
}
fn validate(entries: &[AclEntry]) -> Result<(), AclError> {
let count =
|pred: fn(&AclQualifier) -> bool| entries.iter().filter(|e| pred(&e.who)).count();
let user_obj = count(|w| matches!(w, AclQualifier::UserObj));
let group_obj = count(|w| matches!(w, AclQualifier::GroupObj));
let other = count(|w| matches!(w, AclQualifier::Other));
let mask = count(|w| matches!(w, AclQualifier::Mask));
if user_obj == 0 {
return Err(AclError::MissingRequired { tag: "owner" });
}
if group_obj == 0 {
return Err(AclError::MissingRequired {
tag: "owning-group",
});
}
if other == 0 {
return Err(AclError::MissingRequired { tag: "other" });
}
if user_obj > 1 {
return Err(AclError::Duplicate { tag: "owner" });
}
if group_obj > 1 {
return Err(AclError::Duplicate {
tag: "owning-group",
});
}
if other > 1 {
return Err(AclError::Duplicate { tag: "other" });
}
if mask > 1 {
return Err(AclError::Duplicate { tag: "mask" });
}
let mut named = false;
let mut users: Vec<u32> = Vec::new();
let mut groups: Vec<u32> = Vec::new();
for e in entries {
match e.who {
AclQualifier::User(id) => {
named = true;
if users.contains(&id) {
return Err(AclError::Duplicate { tag: "named-user" });
}
users.push(id);
}
AclQualifier::Group(id) => {
named = true;
if groups.contains(&id) {
return Err(AclError::Duplicate { tag: "named-group" });
}
groups.push(id);
}
_ => {}
}
}
if named && mask == 0 {
return Err(AclError::MaskRequired);
}
Ok(())
}
#[must_use]
pub fn encode(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(4 + self.entries.len() * 8);
out.extend_from_slice(&ACL_VERSION.to_le_bytes());
for e in &self.entries {
let (tag, id) = e.who.tag_and_id();
out.extend_from_slice(&tag.to_le_bytes());
out.extend_from_slice(&e.perm.to_le_bytes());
if let Some(id) = id {
out.extend_from_slice(&id.to_le_bytes());
}
}
out
}
pub fn decode(bytes: &[u8]) -> Result<Self, AclError> {
if bytes.len() < 4 {
return Err(AclError::Malformed {
reason: "shorter than the version header",
});
}
let version = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
if version != ACL_VERSION {
return Err(AclError::Malformed {
reason: "unexpected version",
});
}
let mut entries = Vec::new();
let mut off = 4;
while off < bytes.len() {
if off + 4 > bytes.len() {
return Err(AclError::Malformed {
reason: "truncated entry",
});
}
let tag = u16::from_le_bytes([bytes[off], bytes[off + 1]]);
let perm = u16::from_le_bytes([bytes[off + 2], bytes[off + 3]]);
off += 4;
let who = match tag {
TAG_USER_OBJ => AclQualifier::UserObj,
TAG_GROUP_OBJ => AclQualifier::GroupObj,
TAG_MASK => AclQualifier::Mask,
TAG_OTHER => AclQualifier::Other,
TAG_USER | TAG_GROUP => {
if off + 4 > bytes.len() {
return Err(AclError::Malformed {
reason: "truncated entry id",
});
}
let id = u32::from_le_bytes([
bytes[off],
bytes[off + 1],
bytes[off + 2],
bytes[off + 3],
]);
off += 4;
if tag == TAG_USER {
AclQualifier::User(id)
} else {
AclQualifier::Group(id)
}
}
_ => {
return Err(AclError::Malformed {
reason: "unknown tag",
});
}
};
entries.push(AclEntry { who, perm });
}
Self::new(entries)
}
#[must_use]
pub fn encode_xattr_v2(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(4 + self.entries.len() * XATTR_ENTRY_LEN);
out.extend_from_slice(&XATTR_ACL_VERSION.to_le_bytes());
for e in &self.entries {
let (tag, id) = e.who.tag_and_id();
out.extend_from_slice(&tag.to_le_bytes());
out.extend_from_slice(&e.perm.to_le_bytes());
out.extend_from_slice(&id.unwrap_or(ACL_UNDEFINED_ID).to_le_bytes());
}
out
}
pub fn decode_xattr_v2(bytes: &[u8]) -> Result<Self, AclError> {
if bytes.len() < 4 {
return Err(AclError::Malformed {
reason: "shorter than the version header",
});
}
let (header, body) = bytes.split_at(4);
let version = u32::from_le_bytes(header.try_into().expect("split at four bytes"));
if version != XATTR_ACL_VERSION {
return Err(AclError::Malformed {
reason: "unexpected version",
});
}
if body.len() % XATTR_ENTRY_LEN != 0 {
return Err(AclError::Malformed {
reason: "truncated entry",
});
}
let mut entries = Vec::with_capacity(body.len() / XATTR_ENTRY_LEN);
for e in body.chunks_exact(XATTR_ENTRY_LEN) {
let tag = u16::from_le_bytes([e[0], e[1]]);
let perm = u16::from_le_bytes([e[2], e[3]]);
let id = u32::from_le_bytes([e[4], e[5], e[6], e[7]]);
let who = match tag {
TAG_USER_OBJ => AclQualifier::UserObj,
TAG_USER => AclQualifier::User(id),
TAG_GROUP_OBJ => AclQualifier::GroupObj,
TAG_GROUP => AclQualifier::Group(id),
TAG_MASK => AclQualifier::Mask,
TAG_OTHER => AclQualifier::Other,
_ => {
return Err(AclError::Malformed {
reason: "unknown tag",
});
}
};
entries.push(AclEntry { who, perm });
}
Self::new(entries)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> Acl {
Acl::new(vec![
AclEntry {
who: AclQualifier::Other,
perm: READ,
},
AclEntry {
who: AclQualifier::User(1000),
perm: READ | WRITE,
},
AclEntry {
who: AclQualifier::UserObj,
perm: READ | WRITE | EXEC,
},
AclEntry {
who: AclQualifier::Mask,
perm: READ | WRITE | EXEC,
},
AclEntry {
who: AclQualifier::GroupObj,
perm: READ | EXEC,
},
])
.expect("valid ACL")
}
#[test]
fn encodes_to_the_exact_ext4_byte_form() {
let expected: Vec<u8> = vec![
0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x07, 0x00, 0x02, 0x00, 0x06, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x04, 0x00, 0x05, 0x00, 0x10, 0x00, 0x07, 0x00, 0x20, 0x00, 0x04, 0x00, ];
assert_eq!(sample().encode(), expected);
}
#[test]
fn round_trips_through_bytes() {
let acl = sample();
assert_eq!(Acl::decode(&acl.encode()).unwrap(), acl);
}
#[test]
fn a_minimal_acl_needs_no_mask() {
let acl = Acl::new(vec![
AclEntry {
who: AclQualifier::UserObj,
perm: READ | WRITE,
},
AclEntry {
who: AclQualifier::GroupObj,
perm: READ,
},
AclEntry {
who: AclQualifier::Other,
perm: READ,
},
])
.expect("minimal ACL is valid without a mask");
assert_eq!(acl.encode().len(), 16);
}
#[test]
fn named_user_without_mask_is_rejected() {
let err = Acl::new(vec![
AclEntry {
who: AclQualifier::UserObj,
perm: READ | WRITE,
},
AclEntry {
who: AclQualifier::User(1000),
perm: READ,
},
AclEntry {
who: AclQualifier::GroupObj,
perm: READ,
},
AclEntry {
who: AclQualifier::Other,
perm: READ,
},
])
.unwrap_err();
assert_eq!(err, AclError::MaskRequired);
}
#[test]
fn missing_required_and_duplicate_and_bad_perm_are_rejected() {
assert_eq!(
Acl::new(vec![AclEntry {
who: AclQualifier::UserObj,
perm: READ,
}])
.unwrap_err(),
AclError::MissingRequired {
tag: "owning-group"
}
);
assert_eq!(
Acl::new(vec![AclEntry {
who: AclQualifier::UserObj,
perm: 0x40,
}])
.unwrap_err(),
AclError::InvalidPerm { perm: 0x40 }
);
}
#[test]
fn the_version_2_xattr_form_decodes_to_the_same_acl() {
let v2: Vec<u8> = vec![
0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x07, 0x00, 0xff, 0xff, 0xff, 0xff, 0x02, 0x00, 0x06, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x04, 0x00, 0x05, 0x00, 0xff, 0xff, 0xff, 0xff, 0x10, 0x00, 0x07, 0x00, 0xff, 0xff, 0xff, 0xff, 0x20, 0x00, 0x04, 0x00, 0xff, 0xff, 0xff, 0xff, ];
let acl = Acl::decode_xattr_v2(&v2).expect("valid version-2 ACL");
assert_eq!(acl, sample());
assert_eq!(acl.encode(), sample().encode());
assert!(acl.encode().len() < v2.len());
}
#[test]
fn the_version_2_xattr_form_is_encoded_exactly_as_getxattr_returns_it() {
let expected: Vec<u8> = vec![
0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x07, 0x00, 0xff, 0xff, 0xff, 0xff, 0x02, 0x00, 0x06, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x04, 0x00, 0x05, 0x00, 0xff, 0xff, 0xff, 0xff, 0x10, 0x00, 0x07, 0x00, 0xff, 0xff, 0xff, 0xff, 0x20, 0x00, 0x04, 0x00, 0xff, 0xff, 0xff, 0xff, ];
assert_eq!(sample().encode_xattr_v2(), expected);
}
#[test]
fn an_acl_round_trips_through_the_version_2_form() {
let acl = sample();
assert_eq!(Acl::decode_xattr_v2(&acl.encode_xattr_v2()).unwrap(), acl);
assert!(matches!(
Acl::decode(&acl.encode_xattr_v2()),
Err(AclError::Malformed { .. })
));
}
#[test]
fn the_version_2_xattr_form_rejects_a_bad_version_and_a_partial_entry() {
assert!(matches!(
Acl::decode_xattr_v2(&sample().encode()),
Err(AclError::Malformed { .. })
));
let mut truncated = vec![0x02, 0x00, 0x00, 0x00];
truncated.extend_from_slice(&[0x01, 0x00, 0x07, 0x00]); assert!(matches!(
Acl::decode_xattr_v2(&truncated),
Err(AclError::Malformed { .. })
));
}
#[test]
fn decode_rejects_bad_version_and_truncation() {
assert!(matches!(
Acl::decode(&[0x02, 0, 0, 0]),
Err(AclError::Malformed { .. })
));
assert!(matches!(
Acl::decode(&[0x01]),
Err(AclError::Malformed { .. })
));
}
}