如何在CentOS9上配置SELinux策略?
美国、香港服务器
如何在CentOS9上配置SELinux策略?
04-22 来源:
在 CentOS 9 上配置 SELinux 策略,核心就 4 件事:查看布尔值、管理文件上下文、开放端口、查看日志排错。下面全是最常用、直接能用的命令。
一、查看 SELinux 状态
bash
运行
sestatus
getenforce
二、开关策略布尔值(最常用)
SELinux 用 bool 控制各种权限开关,永久生效加 -P。
1. 查看所有布尔值
bash
运行
semanage boolean -l
2. 搜索相关布尔值(以 http 为例)
bash
运行
semanage boolean -l | grep http
3. 开启 / 关闭布尔值
bash
运行
# 允许网站程序联网(反向代理、API请求)
setsebool -P httpd_can_network_connect 1
# 允许网站连接数据库
setsebool -P httpd_can_network_connect_db 1
# 允许 FTP 用户写入家目录
setsebool -P ftpd_full_access 1
# 关闭某个布尔值
setsebool -P 名称 0
三、文件 / 目录上下文(解决 403、权限不足)
1. 查看文件上下文
bash
运行
ls -Z 文件名
ls -Zd 目录
2. 临时修改上下文(重启失效)
bash
运行
chcon -t httpd_sys_content_t /var/www/html -R
3. 永久添加上下文(推荐)
bash
运行
semanage fcontext -a -t httpd_sys_content_t "/var/www/html(/.*)?"
restorecon -R /var/www/html
4. 允许网站目录可写(上传、缓存)
bash
运行
semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/html/upload(/.*)?"
restorecon -R /var/www/html/upload
四、端口策略(自定义端口必须配置)
1. 查看已开放端口
bash
运行
semanage port -l
2. 添加自定义 HTTP 端口(如 8080、8088)
bash
运行
semanage port -a -t http_port_t -p tcp 8080
3. 删除端口策略
bash
运行
semanage port -d -t http_port_t -p tcp 8080
五、排错:查看拦截日志
bash
运行
# 查看最近被拦截的操作
ausearch -m AVC -ts recent
# 实时查看日志
tail -f /var/log/audit/audit.log | grep AVC
六、安装依赖工具(如提示 semanage 不存在)
bash
运行
dnf install policycoreutils-python-utils -y
七、常用完整示例(Nginx 网站)
bash
运行
# 1. 允许程序联网
setsebool -P httpd_can_network_connect 1
# 2. 设置网站目录只读
semanage fcontext -a -t httpd_sys_content_t "/www/wwwroot(/.*)?"
restorecon -R /www/wwwroot
# 3. 设置上传目录可写
semanage fcontext -a -t httpd_sys_rw_content_t "/www/wwwroot/upload(/.*)?"
restorecon -R /www/wwwroot/upload
# 4. 放行自定义端口
semanage port -a -t http_port_t -p tcp 8088
三二互联专业提供香港VPS,美国VPS主机,香港云服务器租用等业务香港美国到大陆CN2 GIA速度最快