在 CentOS(以及所有使用 SELinux 的 Linux 系统)中,file context(文件上下文) 指的是 SELinux 为文件或目录分配的安全上下文(security context)。
简单说:file context 就是 SELinux 用来判断“这个文件能干什么、谁能访问它”的标签。
SELinux 中每个:
都有一个 安全上下文,格式通常是:
user:role:type:level
例如:
system_u:object_r:httpd_sys_content_t:s0
其中最关键的是 type(类型),它决定了访问规则。
在 CentOS 上可以用:
ls -Z /var/www/html/index.html
输出示例:
system_u:object_r:httpd_sys_content_t:s0 index.html
也可以查看目录:
ls -Zd /var/www/html
SELinux 通过 file context 来控制:
httpd_sys_content_t → Apache 可读取httpd_sys_script_exec_t → Apache 可执行 CGI 脚本default_t → Apache 默认不能访问如果文件 context 不对,即使 chmod 777,SELinux 也会拒绝访问。
| 类型 | 用途 |
|---|---|
etc_t |
/etc 下配置文件 |
var_log_t |
日志文件 |
httpd_sys_content_t |
Web 内容 |
mysqld_db_t |
MySQL 数据目录 |
bin_t |
可执行程序 |
chcon -t httpd_sys_content_t /srv/web/index.html
semanage fcontext -a -t httpd_sys_content_t "/srv/web(/.*)?"
restorecon -Rv /srv/web
restorecon -Rv /var/www
CentOS 的 file context 就是 SELinux 给文件贴的“安全标签”,决定了哪些进程可以访问或执行它。
如果你愿意,我也可以结合 具体服务(如 Nginx / Apache / FTP) 讲 file context 的实际排错例子。