跳到主要内容

CentOS 服务安全设置

介绍

在CentOS系统中,服务是运行在后台的程序,负责处理各种任务,如网络请求、数据库管理等。为了确保系统的安全性,必须对这些服务进行适当的安全设置。本文将介绍如何配置CentOS服务的安全性,包括禁用不必要的服务、配置防火墙、使用SELinux等。

禁用不必要的服务

在CentOS系统中,默认情况下会启动许多服务,但并非所有服务都是必需的。禁用不必要的服务可以减少系统的攻击面。

查看当前运行的服务

使用以下命令查看当前正在运行的服务:

bash
systemctl list-units --type=service --state=running

输出示例:

bash
UNIT                      LOAD   ACTIVE SUB     DESCRIPTION
auditd.service loaded active running Security Auditing Service
crond.service loaded active running Command Scheduler
sshd.service loaded active running OpenSSH server daemon

禁用不必要的服务

假设我们不需要 auditd 服务,可以使用以下命令禁用它:

bash
sudo systemctl stop auditd.service
sudo systemctl disable auditd.service

解释:

  • systemctl stop 停止服务。
  • systemctl disable 禁用服务,使其在系统启动时不会自动启动。

配置防火墙

CentOS默认使用 firewalld 作为防火墙管理工具。通过配置防火墙,可以限制对服务的访问。

查看当前防火墙规则

使用以下命令查看当前防火墙规则:

bash
sudo firewall-cmd --list-all

输出示例:

bash
public (active)
target: default
icmp-block-inversion: no
interfaces: eth0
sources:
services: ssh dhcpv6-client
ports:
protocols:
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:

允许或拒绝特定服务

假设我们只允许SSH服务通过防火墙,可以使用以下命令:

bash
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload

解释:

  • --permanent 使更改永久生效。
  • --add-service=ssh 允许SSH服务通过防火墙。
  • --reload 重新加载防火墙配置。

使用SELinux增强安全性

SELinux(Security-Enhanced Linux)是一个强大的安全模块,可以提供额外的安全层。

查看SELinux状态

使用以下命令查看SELinux的状态:

bash
sestatus

输出示例:

bash
SELinux status:                 enabled
SELinuxfs mount: /sys/fs/selinux
SELinux root directory: /etc/selinux
Loaded policy name: targeted
Current mode: enforcing
Mode from config file: enforcing
Policy MLS status: enabled
Policy deny_unknown status: allowed
Memory protection checking: actual (secure)
Max kernel policy version: 31

配置SELinux策略

假设我们需要允许Apache服务访问特定目录,可以使用以下命令:

bash
sudo chcon -R -t httpd_sys_rw_content_t /var/www/html

解释:

  • chcon 更改文件或目录的安全上下文。
  • -R 递归更改目录及其内容。
  • -t httpd_sys_rw_content_t 设置安全上下文为允许Apache读写。

实际案例

假设我们有一个运行在CentOS上的Web服务器,我们需要确保其安全性。以下是具体步骤:

  1. 禁用不必要的服务: 禁用 auditdcups 服务。
  2. 配置防火墙: 只允许HTTP(端口80)和HTTPS(端口443)通过防火墙。
  3. 使用SELinux: 设置Web根目录的安全上下文,确保Apache可以访问。

示例命令

bash
# 禁用不必要的服务
sudo systemctl stop auditd.service
sudo systemctl disable auditd.service
sudo systemctl stop cups.service
sudo systemctl disable cups.service

# 配置防火墙
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

# 使用SELinux
sudo chcon -R -t httpd_sys_rw_content_t /var/www/html

总结

通过禁用不必要的服务、配置防火墙和使用SELinux,可以显著提高CentOS系统的安全性。这些措施不仅减少了系统的攻击面,还增强了服务的访问控制。

附加资源

练习

  1. 查看你当前系统中运行的服务,并尝试禁用其中不必要的服务。
  2. 配置防火墙,只允许SSH和HTTP服务通过。
  3. 使用SELinux为你的Web服务器目录设置适当的安全上下文。