土法炼钢兴趣小组的算法知识备份

【操作系统百科】xattr/ACL/capabilities

文章导航

分类入口
os
标签入口
#xattr#acl#capability#selinux-label

目录

文件的基本权限(rwx + uid/gid)不够灵活——POSIX ACL 做细粒度访问控制、capability 做特权分解、SELinux label 做强制访问控制。这些都存在 xattr(扩展属性)里。

一、先看图

flowchart TD
    INODE[inode] --> XATTR[xattr 存储<br/>inline / block]
    XATTR --> USER["user.*<br/>用户自定义"]
    XATTR --> SECURITY["security.*<br/>SELinux label<br/>AppArmor<br/>capabilities"]
    XATTR --> SYSTEM["system.*<br/>POSIX ACL"]
    XATTR --> TRUSTED["trusted.*<br/>需 CAP_SYS_ADMIN"]
    classDef ns fill:#388bfd22,stroke:#388bfd,color:#adbac7;
    classDef store fill:#a371f722,stroke:#a371f7,color:#adbac7;
    class INODE,XATTR store
    class USER,SECURITY,SYSTEM,TRUSTED ns

二、xattr 基础

2.1 API

setxattr("/path", "user.mykey", "value", 5, 0);
getxattr("/path", "user.mykey", buf, sizeof(buf));
listxattr("/path", buf, sizeof(buf));
removexattr("/path", "user.mykey");

Shell:

setfattr -n user.mykey -v "hello" /tmp/file
getfattr -d /tmp/file

2.2 四命名空间

2.3 存储

ext4:小 xattr inline 在 inode 里(256 字节内);大的放额外 block。

btrfs / XFS:类似,各有自己的 xattr item。

三、POSIX ACL

3.1 为什么

传统 rwx 只有 owner/group/other 三类。要给特定用户 alice 读权限,其他人不行 → 需要 ACL。

3.2 设置

setfacl -m u:alice:r /tmp/data
setfacl -m g:devteam:rw /tmp/data
getfacl /tmp/data

3.3 内核实现

ACL 存在 system.posix_acl_access(文件 ACL)和 system.posix_acl_default(目录默认 ACL,新建文件继承)。

内核在 permission() 里检查 ACL。

3.4 注意事项

四、文件 capabilities

传统特权模型:root 拥有一切。capabilities 把特权拆成 40+ 个独立 cap。

文件级 capability:

setcap cap_net_bind_service=+ep /usr/bin/myserver
getcap /usr/bin/myserver

存在 security.capability xattr 里。exec 时内核合并到进程有效 capability set。

常用 cap:

五、SELinux / AppArmor label

ls -Z /etc/passwd
# system_u:object_r:passwd_file_t:s0 /etc/passwd

Label 存在 security.selinux xattr。内核在每次文件操作时用 LSM hook 检查。

容器场景:需要 --security-opt label=type:container_file_t--privileged

六、备份与 xattr

# tar 保留 xattr
tar --xattrs --xattrs-include='*' -cf backup.tar /data

# rsync 保留
rsync -avX /src/ /dst/

# cp 保留
cp --preserve=xattr file1 file2

不保留 → ACL、capability、SELinux label 全丢。

七、容器镜像与 xattr

OCI 镜像层是 tar 包——需要保留 security.*system.* xattr。

overlay2 存储驱动:

构建镜像时工具(buildkit、podman)需要正确处理 xattr。

八、xattr 大小限制

过多 xattr → inode 扩展开销增大、备份慢。

九、观察

getfattr -d -m - /tmp/file          # 列出所有命名空间 xattr
getfacl /tmp/file                    # ACL
getcap /usr/bin/*                    # 扫描 capability
ls -Z /etc/                          # SELinux label

# 统计 xattr 使用
debugfs -R "stat <inode_no>" /dev/sda1 | grep -i xattr

十、小结


参考文献

工具


上一篇文件锁 下一篇文件变化通知

同主题继续阅读

把当前热点继续串成多页阅读,而不是停在单篇消费。

2026-05-06 · os

【操作系统百科】内核内存调试

内核内存 bug 是最难追的:UAF、OOB、double free、leak 都可能沉默数月。本文讲 KASAN 三种模式、KFENCE 生产采样、kmemleak、SLUB_DEBUG、UBSAN/KCSAN 联动。

2026-05-08 · os

【操作系统百科】VFS 四层抽象

Linux 的一切皆文件靠 VFS 实现——superblock、inode、dentry、file 四层抽象加 ops 表。本文讲 VFS 核心数据结构、dcache、inode cache、RCU lookup,以及文件系统如何插入 VFS。

2026-04-22 · os

操作系统百科

Linux 6.x 视角下的操作系统系列索引:110 篇覆盖调度、虚拟内存、文件系统与 I/O、并发、隔离、可观测性,按主题、阅读路径与关键问题三种入口组织。


By .