作为IT工程师,我为您提供一套全面的CentOS系统安全加固方案,以防止恶意代码的下载和执行。
# 创建专用低权限用户
sudo useradd -r -s /sbin/nologin appuser
# 限制root远程登录
sudo sed -i 's/^PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config
sudo systemctl restart sshd
# 编辑sudoers文件,限制特权命令
sudo visudo
# 添加以下内容:
%admin ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart httpd
# 启用firewalld
sudo systemctl enable --now firewalld
# 仅开放必要端口
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --remove-service=ssh # 如需SSH,限制源IP
sudo firewall-cmd --reload
# 确保SELinux处于强制模式
sudo setenforce 1
sudo sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
# 检查SELinux状态
sestatus
# 系统目录保护
sudo chmod -R 750 /etc/init.d/
sudo chmod -R 750 /etc/rc.d/
sudo chmod 600 /etc/shadow
# 限制/tmp目录
sudo chmod 1777 /tmp
# 编辑/etc/fstab,添加以下选项:
/dev/sda1 / ext4 defaults,nodev,nosuid,noexec 1 1
/tmp /tmp tmpfs defaults,nosuid,nodev,noexec 0 0
# 禁止用户目录执行脚本
sudo find /home -type f -iname "*.sh" -exec chmod -x {} \;
sudo find /home -type f -iname "*.py" -exec chmod -x {} \;
# 安装ClamAV防病毒
sudo yum install -y epel-release
sudo yum install -y clamav clamd clamav-update
sudo freshclam # 更新病毒库
sudo systemctl enable --now clamd@scan
# 安装Rootkit检测工具
sudo yum install -y rkhunter
sudo rkhunter --update
sudo rkhunter --check
# 配置自动安全更新
sudo yum install -y yum-cron
sudo sed -i 's/^apply_updates.*/apply_updates = yes/' /etc/yum/yum-cron.conf
sudo systemctl enable --now yum-cron
# 仅保留官方和可信源
sudo rm -f /etc/yum.repos.d/*.repo
sudo cp /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
sudo curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
sudo yum clean all
sudo yum makecache
# 安装并配置auditd
sudo yum install -y audit
sudo systemctl enable --now auditd
# 监控关键文件修改
sudo auditctl -w /etc/passwd -p wa -k passwd_changes
sudo auditctl -w /etc/shadow -p wa -k shadow_changes
# 安装并配置logwatch
sudo yum install -y logwatch
sudo cp /usr/share/logwatch/default.conf/logwatch.conf /etc/logwatch/conf/
sudo sed -i 's/^Output.*/Output = mail/' /etc/logwatch/conf/logwatch.conf
# 禁用不必要服务
sudo systemctl disable --now rpcbind
sudo systemctl disable --now nfs-server
# 编辑/etc/sysctl.conf,添加:
net.ipv4.conf.all.rp_filter=1
net.ipv4.conf.default.rp_filter=1
net.ipv4.icmp_echo_ignore_broadcasts=1
net.ipv4.tcp_syncookies=1
kernel.exec-shield=1
kernel.randomize_va_space=2
# 应用设置
sudo sysctl -p
sudo rkhunter --check
sudo freshclam
ausearch -k passwd_changes | aureport -f -i
sudo awk -F: '($3 == 0) {print}' /etc/passwd
这套方案从多个层面提供了防护措施,可有效降低恶意代码下载和执行的风险。根据您的具体业务需求,可能需要调整某些设置。