活动公告

系统通知
05-18 21:22
系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

深入浅出CentOS安全优化方案 从基础配置到高级技巧全面保障服务器安全

SunJu_FaceMall

3万

主题

2860

科技点

3万

积分

白金月票

碾压王

积分
32872

塔罗立华奏

<font color=白金月票" /> 发表于 2025-9-17 00:10:19 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

在当今数字化时代,服务器安全已成为企业和个人不可忽视的重要议题。CentOS作为企业级Linux发行版,以其稳定性和安全性广受欢迎,但默认安装并不能提供足够的安全保障。本文将从基础配置到高级技巧,全面介绍CentOS服务器的安全优化方案,帮助系统管理员构建一个更加安全可靠的服务器环境。

一、基础安全配置

1. 系统更新与补丁管理

保持系统最新是安全的第一道防线。及时更新系统可以修复已知的安全漏洞,防止被攻击者利用。
  1. # 检查系统版本
  2. cat /etc/redhat-release
  3. # 更新系统软件包
  4. yum update -y
  5. # 设置自动更新
  6. yum install -y yum-cron
  7. systemctl enable yum-cron
  8. systemctl start yum-cron
  9. # 配置yum-cron自动应用安全更新
  10. vi /etc/yum/yum-cron.conf
  11. # 修改以下配置
  12. apply_updates = yes
  13. update_cmd = minimal-security
复制代码

2. 账户安全配置

账户安全是系统安全的基础,合理的账户管理可以大大提高系统的安全性。
  1. # 禁用root远程登录
  2. vi /etc/ssh/sshd_config
  3. # 修改或添加以下行
  4. PermitRootLogin no
  5. # 创建普通用户并设置sudo权限
  6. useradd admin
  7. passwd admin  # 设置强密码
  8. usermod -aG wheel admin  # 添加到wheel组获得sudo权限
  9. # 禁用不必要账户
  10. for user in adm lp sync shutdown halt mail news uucp operator games gopher; do
  11.     userdel -r $user 2>/dev/null
  12. done
  13. # 设置密码策略
  14. vi /etc/login.defs
  15. # 修改以下配置
  16. PASS_MAX_DAYS   90
  17. PASS_MIN_DAYS   7
  18. PASS_WARN_AGE   14
  19. # 安装并配置PAM模块进行密码强度检查
  20. yum install -y libpwquality
  21. vi /etc/security/pwquality.conf
  22. # 设置以下参数
  23. minlen = 12
  24. minclass = 4
  25. dcredit = -1
  26. ucredit = -1
  27. lcredit = -1
  28. ocredit = -1
复制代码

3. SSH安全配置

SSH是远程管理服务器的常用工具,加强SSH配置可以有效防止未授权访问。
  1. # 备份原始SSH配置
  2. cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
  3. # 修改SSH配置
  4. vi /etc/ssh/sshd_config
  5. # 修改或添加以下行
  6. Port 2222  # 更改默认端口
  7. PermitRootLogin no
  8. MaxAuthTries 3
  9. MaxSessions 3
  10. PasswordAuthentication no  # 禁用密码认证,使用密钥认证
  11. PubkeyAuthentication yes
  12. AuthorizedKeysFile .ssh/authorized_keys
  13. PermitEmptyPasswords no
  14. ClientAliveInterval 300
  15. ClientAliveCountMax 2
  16. AllowUsers admin  # 只允许特定用户登录
  17. # 重启SSH服务
  18. systemctl restart sshd
  19. # 为用户设置SSH密钥认证
  20. su - admin
  21. mkdir -p ~/.ssh
  22. chmod 700 ~/.ssh
  23. echo "your_public_key" > ~/.ssh/authorized_keys
  24. chmod 600 ~/.ssh/authorized_keys
复制代码

4. 防火墙基础设置

防火墙是网络安全的第一道屏障,正确配置防火墙规则可以阻止不必要的网络访问。
  1. # 安装并启用firewalld
  2. yum install -y firewalld
  3. systemctl enable firewalld
  4. systemctl start firewalld
  5. # 查看默认区域
  6. firewall-cmd --get-default-zone
  7. # 设置默认区域为public
  8. firewall-cmd --set-default-zone=public
  9. # 开放必要端口(示例:SSH端口2222)
  10. firewall-cmd --permanent --add-port=2222/tcp
  11. # 开放HTTP和HTTPS服务(如果需要)
  12. firewall-cmd --permanent --add-service=http
  13. firewall-cmd --permanent --add-service=https
  14. # 阻止Ping请求
  15. firewall-cmd --permanent --add-protocol=icmp --add-rich-rule='rule protocol value=icmp drop'
  16. # 重新加载防火墙配置
  17. firewall-cmd --reload
  18. # 查看防火墙规则
  19. firewall-cmd --list-all
复制代码

二、中级安全优化

1. 文件系统安全

文件系统安全是保护数据不被未授权访问的关键。
  1. # 设置关键文件权限
  2. chmod 600 /etc/passwd-
  3. chmod 600 /etc/shadow-
  4. chmod 600 /etc/group-
  5. chmod 600 /etc/gshadow-
  6. chmod 750 /etc/sudoers
  7. chmod 750 /etc/sudoers.d
  8. # 查找并设置SUID/SGID文件
  9. find / -type f \( -perm -4000 -o -perm -2000 \) -ls
  10. # 移除不必要的SUID/SGID权限
  11. chmod a-s /path/to/file
  12. # 查找并设置全局可写文件
  13. find / -type f -perm -o+w -ls
  14. # 移除不必要的全局写权限
  15. chmod o-w /path/to/file
  16. # 查找并设置无主文件
  17. find / -nouser -o -nogroup -ls
  18. # 为无主文件分配所有者或删除
  19. # 配置/etc/fstab增加安全选项
  20. vi /etc/fstab
  21. # 为/、/boot、/home分区添加nodev、nosuid、noexec选项(根据需要)
  22. /dev/sda1   /   ext4    defaults,nodev,nosuid   1   1
  23. /dev/sda2   /boot ext4   defaults,nodev,nosuid,noexec   1   2
  24. # 重新挂载分区
  25. mount -o remount /
  26. mount -o remount /boot
复制代码

2. 服务安全加固

关闭不必要的服务并加固必要服务是提高系统安全性的重要步骤。
  1. # 查看已启用的服务
  2. systemctl list-unit-files | grep enabled
  3. # 停止并禁用不必要的服务
  4. systemctl stop telnet.socket
  5. systemctl disable telnet.socket
  6. systemctl stop rsh.socket
  7. systemctl disable rsh.socket
  8. systemctl stop ypbind
  9. systemctl disable ypbind
  10. systemctl stop tftp.socket
  11. systemctl disable tftp.socket
  12. systemctl stop xinetd
  13. systemctl disable xinetd
  14. # 禁用IPv6(如果不需要)
  15. vi /etc/sysctl.conf
  16. # 添加以下行
  17. net.ipv6.conf.all.disable_ipv6 = 1
  18. net.ipv6.conf.default.disable_ipv6 = 1
  19. # 应用sysctl设置
  20. sysctl -p
  21. # 加固网络服务(以Nginx为例)
  22. vi /etc/nginx/nginx.conf
  23. # 修改以下配置
  24. user nginx;
  25. worker_processes auto;
  26. error_log /var/log/nginx/error.log crit;
  27. pid /run/nginx.pid;
  28. # 隐藏Nginx版本号
  29. server_tokens off;
  30. # 限制HTTP方法
  31. if ($request_method !~ ^(GET|HEAD|POST)$ ) {
  32.     return 405;
  33. }
  34. # 重启Nginx服务
  35. systemctl restart nginx
复制代码

3. 安全审计与日志管理

日志是安全事件调查的重要依据,合理的日志管理可以帮助及时发现安全问题。
  1. # 安装并配置auditd
  2. yum install -y audit
  3. systemctl enable auditd
  4. systemctl start auditd
  5. # 配置审计规则
  6. vi /etc/audit/rules.d/audit.rules
  7. # 添加以下规则
  8. # 监控文件删除
  9. -a always,exit -F arch=b64 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -F auid!=4294967295 -k delete
  10. # 监控文件权限变更
  11. -a always,exit -F arch=b64 -S chmod -S fchmod -S fchmodat -F auid>=1000 -F auid!=4294967295 -k perm_mod
  12. # 监控sudo使用
  13. -a always,exit -F arch=b64 -S execve -C uid!=euid -F euid=0 -k setuid
  14. # 监控登录失败
  15. -w /var/log/faillog -p wa -k logins
  16. -w /var/log/lastlog -p wa -k logins
  17. # 重载audit规则
  18. augenrules --load
  19. # 配置日志轮转
  20. vi /etc/logrotate.d/syslog
  21. # 添加或修改以下配置
  22. /var/log/cron
  23. /var/log/maillog
  24. /var/log/messages
  25. /var/log/secure
  26. /var/log/spooler
  27. {
  28.     sharedscripts
  29.     postrotate
  30.         /bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true
  31.     endscript
  32.     daily
  33.     rotate 90
  34.     compress
  35.     delaycompress
  36.     missingok
  37.     notifempty
  38.     create 640 root root
  39. }
  40. # 安装并配置logwatch进行日志分析
  41. yum install -y logwatch
  42. vi /etc/logwatch/conf/logwatch.conf
  43. # 修改以下配置
  44. Output = mail
  45. Format = html
  46. MailTo = admin@example.com
  47. Range = yesterday
  48. Detail = High
  49. # 设置每日日志报告
  50. echo "0 0 * * * /usr/sbin/logwatch" > /etc/cron.daily/00logwatch
  51. chmod +x /etc/cron.daily/00logwatch
复制代码

4. 入侵检测系统配置

入侵检测系统(IDS)可以帮助及时发现潜在的入侵行为。
  1. # 安装AIDE(高级入侵检测环境)
  2. yum install -y aide
  3. # 初始化AIDE数据库
  4. aide --init
  5. # 移动数据库到标准位置
  6. mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz
  7. # 配置AIDE
  8. vi /etc/aide.conf
  9. # 根据需要修改检查规则
  10. # 创建每日AIDE检查脚本
  11. vi /etc/cron.daily/aide
  12. #!/bin/bash
  13. /usr/sbin/aide --check
  14. exit 0
  15. # 设置脚本可执行权限
  16. chmod +x /etc/cron.daily/aide
  17. # 安装OSSEC(开源主机入侵检测系统)
  18. yum install -y ossec-hids-server
  19. # 配置OSSEC
  20. vi /var/ossec/etc/ossec.conf
  21. # 配置邮件通知、系统监控、文件完整性检查等
  22. # 启动OSSEC
  23. /var/ossec/bin/ossec-control start
  24. # 安装并配置Fail2ban防止暴力破解
  25. yum install -y epel-release
  26. yum install -y fail2ban
  27. # 创建Fail2ban配置文件
  28. cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
  29. # 配置SSH保护
  30. vi /etc/fail2ban/jail.local
  31. [sshd]
  32. enabled = true
  33. port = 2222
  34. filter = sshd
  35. logpath = /var/log/secure
  36. maxretry = 3
  37. bantime = 3600
  38. findtime = 600
  39. # 启动Fail2ban
  40. systemctl enable fail2ban
  41. systemctl start fail2ban
  42. # 查看被禁止的IP
  43. fail2ban-client status sshd
复制代码

三、高级安全技巧

1. SELinux高级配置

SELinux是Linux内核中的强制访问控制(MAC)系统,可以提供比传统权限更细粒度的访问控制。
  1. # 检查SELinux状态
  2. sestatus
  3. # 设置SELinux为强制模式
  4. setenforce 1
  5. vi /etc/selinux/config
  6. # 修改以下行
  7. SELINUX=enforcing
  8. # 查看SELinux布尔值
  9. getsebool -a
  10. # 设置SELinux布尔值(示例:允许HTTP连接网络)
  11. setsebool -P httpd_can_network_connect on
  12. # 查看文件的安全上下文
  13. ls -Z /path/to/file
  14. # 修改文件的安全上下文
  15. chcon -t httpd_sys_content_t /path/to/file
  16. # 恢复文件默认安全上下文
  17. restorecon -v /path/to/file
  18. # 创建自定义SELinux策略模块
  19. # 示例:允许Nginx连接外部网络
  20. ausearch -m avc -ts recent | grep nginx
  21. # 根据审计日志创建策略模块
  22. audit2allow -M nginx_connect
  23. semodule -i nginx_connect.pp
  24. # 查看已加载的SELinux策略模块
  25. semodule -l
复制代码

2. 安全内核参数调优

通过调整内核参数,可以增强系统的网络安全性。
  1. # 配置sysctl安全参数
  2. vi /etc/sysctl.d/security.conf
  3. # 添加以下参数
  4. # 防止IP欺骗
  5. net.ipv4.conf.all.rp_filter = 1
  6. net.ipv4.conf.default.rp_filter = 1
  7. # 忽略ICMP重定向
  8. net.ipv4.conf.all.accept_redirects = 0
  9. net.ipv4.conf.default.accept_redirects = 0
  10. net.ipv4.conf.all.secure_redirects = 0
  11. net.ipv4.conf.default.secure_redirects = 0
  12. # 忽略发送ICMP重定向
  13. net.ipv4.conf.all.send_redirects = 0
  14. net.ipv4.conf.default.send_redirects = 0
  15. # 不接受源路由包
  16. net.ipv4.conf.all.accept_source_route = 0
  17. net.ipv4.conf.default.accept_source_route = 0
  18. # 启用TCP SYN Cookie保护
  19. net.ipv4.tcp_syncookies = 1
  20. # 防止TCP SYN洪水攻击
  21. net.ipv4.tcp_max_syn_backlog = 2048
  22. net.ipv4.tcp_synack_retries = 2
  23. net.ipv4.tcp_syn_retries = 5
  24. # 记录可疑数据包
  25. net.ipv4.conf.all.log_martians = 1
  26. net.ipv4.conf.default.log_martians = 1
  27. # 防止IP地址欺骗
  28. net.ipv4.ip_forward = 0
  29. net.ipv4.conf.all.send_redirects = 0
  30. net.ipv4.conf.default.send_redirects = 0
  31. # 增加文件描述符限制
  32. fs.file-max = 65535
  33. # 应用sysctl设置
  34. sysctl -p /etc/sysctl.d/security.conf
  35. # 设置进程限制
  36. vi /etc/security/limits.conf
  37. # 添加以下配置
  38. * soft nofile 65535
  39. * hard nofile 65535
  40. * soft nproc 4096
  41. * hard nproc 4096
  42. # 配置PAM模块
  43. vi /etc/pam.d/system-auth
  44. # 添加以下行
  45. session required pam_limits.so
复制代码

3. 系统监控与异常检测

实时监控系统状态和异常行为是及时发现安全问题的关键。
  1. # 安装并配置Zabbix监控系统
  2. yum install -y zabbix-server-mysql zabbix-web-mysql zabbix-agent
  3. # 创建Zabbix数据库
  4. mysql -u root -p
  5. CREATE DATABASE zabbix CHARACTER SET utf8 COLLATE utf8_bin;
  6. GRANT ALL PRIVILEGES ON zabbix.* TO zabbix@localhost IDENTIFIED BY 'password';
  7. FLUSH PRIVILEGES;
  8. EXIT;
  9. # 导入初始数据
  10. zcat /usr/share/doc/zabbix-server-mysql*/create.sql.gz | mysql -uzabbix -p zabbix
  11. # 配置Zabbix服务器
  12. vi /etc/zabbix/zabbix_server.conf
  13. DBHost=localhost
  14. DBName=zabbix
  15. DBUser=zabbix
  16. DBPassword=password
  17. # 启动Zabbix服务
  18. systemctl enable zabbix-server zabbix-agent httpd
  19. systemctl start zabbix-server zabbix-agent httpd
  20. # 安装并配置Osquery进行系统监控
  21. yum install -y https://osquery-packages.s3.amazonaws.com/centos7/noarch/osquery-3.3.2-1.linux.x86_64.rpm
  22. # 配置Osquery
  23. vi /etc/osquery/osquery.conf
  24. {
  25.   "options": {
  26.     "config_plugin": "filesystem",
  27.     "logger_plugin": "filesystem",
  28.     "logger_path": "/var/log/osquery",
  29.     "schedule_splay_percent": 10
  30.   },
  31.   "schedule": {
  32.     "system_info": {
  33.       "query": "SELECT * FROM system_info;",
  34.       "interval": 3600
  35.     },
  36.     "listening_ports": {
  37.       "query": "SELECT pid, port, protocol, address FROM listening_ports;",
  38.       "interval": 300
  39.     },
  40.     "processes": {
  41.       "query": "SELECT name, pid, path, cmdline FROM processes;",
  42.       "interval": 300
  43.     },
  44.     "suspicious_processes": {
  45.       "query": "SELECT name, pid, path, cmdline FROM processes WHERE name LIKE '%crypto%' OR name LIKE '%miner%' OR name LIKE '%xmr%';",
  46.       "interval": 600
  47.     },
  48.     "crontab": {
  49.       "query": "SELECT * FROM crontab;",
  50.       "interval": 3600
  51.     }
  52.   }
  53. }
  54. # 启动Osquery
  55. systemctl enable osqueryd
  56. systemctl start osqueryd
  57. # 安装Wazuh(开源安全监控平台)
  58. yum install -y wazuh-server wazuh-agent wazuh-api
  59. # 配置Wazuh
  60. vi /var/ossec/etc/ossec.conf
  61. # 配置文件完整性监控、rootkit检测、日志监控等
  62. # 启动Wazuh
  63. systemctl enable wazuh-server
  64. systemctl enable wazuh-agent
  65. systemctl enable wazuh-api
  66. systemctl start wazuh-server
  67. systemctl start wazuh-agent
  68. systemctl start wazuh-api
复制代码

4. 安全应急响应

建立完善的安全应急响应机制,可以在发生安全事件时快速有效地应对。
  1. # 创建安全应急响应脚本目录
  2. mkdir -p /opt/security-tools
  3. cd /opt/security-tools
  4. # 创建系统快照脚本
  5. vi system_snapshot.sh
  6. #!/bin/bash
  7. DATE=$(date +%Y%m%d_%H%M%S)
  8. mkdir -p /opt/security-logs/$DATE
  9. # 收集系统信息
  10. echo "Collecting system information..."
  11. uname -a > /opt/security-logs/$DATE/system_info.txt
  12. df -h >> /opt/security-logs/$DATE/system_info.txt
  13. free -m >> /opt/security-logs/$DATE/system_info.txt
  14. ps auxf > /opt/security-logs/$DATE/processes.txt
  15. netstat -tulnp > /opt/security-logs/$DATE/network_connections.txt
  16. last > /opt/security-logs/$DATE/last_logins.txt
  17. lastb > /opt/security-logs/$DATE/failed_logins.txt
  18. # 收集关键日志
  19. echo "Collecting critical logs..."
  20. cp /var/log/secure /opt/security-logs/$DATE/
  21. cp /var/log/messages /opt/security-logs/$DATE/
  22. cp /var/log/cron /opt/security-logs/$DATE/
  23. cp /var/log/maillog /opt/security-logs/$DATE/
  24. # 收集用户和认证信息
  25. echo "Collecting user and authentication information..."
  26. cp /etc/passwd /opt/security-logs/$DATE/
  27. cp /etc/shadow /opt/security-logs/$DATE/
  28. cp /etc/group /opt/security-logs/$DATE/
  29. cp /etc/sudoers /opt/security-logs/$DATE/
  30. # 收集网络配置
  31. echo "Collecting network configuration..."
  32. cp /etc/sysconfig/network-scripts/ifcfg-* /opt/security-logs/$DATE/
  33. cp /etc/hosts /opt/security-logs/$DATE/
  34. cp /etc/resolv.conf /opt/security-logs/$DATE/
  35. # 收集计划任务
  36. echo "Collecting scheduled tasks..."
  37. crontab -l > /opt/security-logs/$DATE/crontab_root.txt 2>/dev/null
  38. for user in $(cut -d: -f1 /etc/passwd); do
  39.   crontab -u $user -l > /opt/security-logs/$DATE/crontab_$user.txt 2>/dev/null
  40. done
  41. # 收集RPM包信息
  42. echo "Collecting RPM package information..."
  43. rpm -qa > /opt/security-logs/$DATE/rpm_packages.txt
  44. # 收集服务状态
  45. echo "Collecting service status..."
  46. systemctl list-units --type=service > /opt/security-logs/$DATE/services.txt
  47. echo "System snapshot completed. Results saved in /opt/security-logs/$DATE/"
  48. exit 0
  49. # 设置脚本可执行权限
  50. chmod +x system_snapshot.sh
  51. # 创建系统入侵检测脚本
  52. vi intrusion_detection.sh
  53. #!/bin/bash
  54. DATE=$(date +%Y%m%d_%H%M%S)
  55. LOG_FILE="/opt/security-logs/intrusion_detection_$DATE.log"
  56. ALERT_COUNT=0
  57. echo "Starting intrusion detection at $(date)" > $LOG_FILE
  58. # 检测异常登录
  59. echo "Checking for abnormal logins..." >> $LOG_FILE
  60. last | grep -v "reboot" | grep -v "wtmp" | awk '{print $1, $3, $4, $5, $6}' | sort | uniq -c | sort -nr | head -10 >> $LOG_FILE
  61. # 检测异常进程
  62. echo "Checking for suspicious processes..." >> $LOG_FILE
  63. ps auxf | grep -E "(crypto|miner|xmr|bitcoin)" | grep -v grep >> $LOG_FILE
  64. if [ $? -eq 0 ]; then
  65.   echo "ALERT: Suspicious processes found!" >> $LOG_FILE
  66.   ((ALERT_COUNT++))
  67. fi
  68. # 检测异常网络连接
  69. echo "Checking for suspicious network connections..." >> $LOG_FILE
  70. netstat -tulnp | grep -E ":([0-9]{4,5})" | grep -v -E "(22|80|443)" >> $LOG_FILE
  71. # 检测异常文件权限
  72. echo "Checking for abnormal file permissions..." >> $LOG_FILE
  73. find / -type f \( -perm -4000 -o -perm -2000 \) -ls | head -20 >> $LOG_FILE
  74. # 检测异常用户
  75. echo "Checking for abnormal user accounts..." >> $LOG_FILE
  76. awk -F: '($3 == 0) { print $1 }' /etc/passwd | grep -v root >> $LOG_FILE
  77. if [ $? -eq 0 ]; then
  78.   echo "ALERT: Non-root user with UID 0 found!" >> $LOG_FILE
  79.   ((ALERT_COUNT++))
  80. fi
  81. # 检测空密码账户
  82. echo "Checking for accounts with empty passwords..." >> $LOG_FILE
  83. awk -F: '($2 == "") { print $1 }' /etc/shadow >> $LOG_FILE
  84. if [ $? -eq 0 ]; then
  85.   echo "ALERT: Accounts with empty passwords found!" >> $LOG_FILE
  86.   ((ALERT_COUNT++))
  87. fi
  88. # 检测异常sudo配置
  89. echo "Checking for abnormal sudo configurations..." >> $LOG_FILE
  90. grep -v "^#" /etc/sudoers | grep -v "^$" >> $LOG_FILE
  91. # 检测异常cron任务
  92. echo "Checking for suspicious cron jobs..." >> $LOG_FILE
  93. for user in $(cut -d: -f1 /etc/passwd); do
  94.   crontab -u $user -l 2>/dev/null | grep -v "^#" | grep -v "^$" >> $LOG_FILE
  95. done
  96. echo "Intrusion detection completed at $(date)" >> $LOG_FILE
  97. echo "Total alerts: $ALERT_COUNT" >> $LOG_FILE
  98. if [ $ALERT_COUNT -gt 0 ]; then
  99.   echo "Security alerts detected! Check $LOG_FILE for details."
  100.   # 发送邮件通知
  101.   echo "Security alerts detected on $(hostname). Check $LOG_FILE for details." | mail -s "Security Alert: Intrusion Detection" admin@example.com
  102. fi
  103. exit 0
  104. # 设置脚本可执行权限
  105. chmod +x intrusion_detection.sh
  106. # 创建定期任务
  107. echo "0 2 * * * /opt/security-tools/system_snapshot.sh" > /etc/cron.daily/security_snapshot
  108. echo "0 */6 * * * /opt/security-tools/intrusion_detection.sh" > /etc/cron.d/intrusion_detection
  109. chmod +x /etc/cron.daily/security_snapshot
  110. chmod +x /etc/cron.d/intrusion_detection
复制代码

四、综合安全策略

1. 安全基线建设

建立安全基线是确保系统安全的基础,它定义了系统必须满足的最低安全要求。
  1. # 创建安全基线检查脚本
  2. vi security_baseline.sh
  3. #!/bin/bash
  4. LOG_FILE="/opt/security-logs/baseline_check_$(date +%Y%m%d_%H%M%S).log"
  5. COMPLIANCE_COUNT=0
  6. TOTAL_CHECKS=0
  7. echo "Starting security baseline check at $(date)" > $LOG_FILE
  8. # 检查系统更新
  9. echo "1. Checking for system updates..." >> $LOG_FILE
  10. ((TOTAL_CHECKS++))
  11. if yum check-update | grep -q "No packages marked for update"; then
  12.   echo "PASS: System is up to date." >> $LOG_FILE
  13.   ((COMPLIANCE_COUNT++))
  14. else
  15.   echo "FAIL: System updates are available." >> $LOG_FILE
  16. fi
  17. # 检查SELinux状态
  18. echo "2. Checking SELinux status..." >> $LOG_FILE
  19. ((TOTAL_CHECKS++))
  20. if getenforce | grep -q "Enforcing"; then
  21.   echo "PASS: SELinux is in enforcing mode." >> $LOG_FILE
  22.   ((COMPLIANCE_COUNT++))
  23. else
  24.   echo "FAIL: SELinux is not in enforcing mode." >> $LOG_FILE
  25. fi
  26. # 检查防火墙状态
  27. echo "3. Checking firewall status..." >> $LOG_FILE
  28. ((TOTAL_CHECKS++))
  29. if systemctl is-active firewalld | grep -q "active"; then
  30.   echo "PASS: Firewall is active." >> $LOG_FILE
  31.   ((COMPLIANCE_COUNT++))
  32. else
  33.   echo "FAIL: Firewall is not active." >> $LOG_FILE
  34. fi
  35. # 检查root远程登录
  36. echo "4. Checking root remote login..." >> $LOG_FILE
  37. ((TOTAL_CHECKS++))
  38. if grep -q "^PermitRootLogin no" /etc/ssh/sshd_config; then
  39.   echo "PASS: Root remote login is disabled." >> $LOG_FILE
  40.   ((COMPLIANCE_COUNT++))
  41. else
  42.   echo "FAIL: Root remote login is enabled." >> $LOG_FILE
  43. fi
  44. # 检查密码策略
  45. echo "5. Checking password policy..." >> $LOG_FILE
  46. ((TOTAL_CHECKS++))
  47. if grep -q "^PASS_MAX_DAYS.*90" /etc/login.defs; then
  48.   echo "PASS: Password policy is compliant." >> $LOG_FILE
  49.   ((COMPLIANCE_COUNT++))
  50. else
  51.   echo "FAIL: Password policy is not compliant." >> $LOG_FILE
  52. fi
  53. # 检查AIDE状态
  54. echo "6. Checking AIDE status..." >> $LOG_FILE
  55. ((TOTAL_CHECKS++))
  56. if systemctl is-active aide | grep -q "active"; then
  57.   echo "PASS: AIDE is active." >> $LOG_FILE
  58.   ((COMPLIANCE_COUNT++))
  59. else
  60.   echo "FAIL: AIDE is not active." >> $LOG_FILE
  61. fi
  62. # 检查auditd状态
  63. echo "7. Checking auditd status..." >> $LOG_FILE
  64. ((TOTAL_CHECKS++))
  65. if systemctl is-active auditd | grep -q "active"; then
  66.   echo "PASS: Auditd is active." >> $LOG_FILE
  67.   ((COMPLIANCE_COUNT++))
  68. else
  69.   echo "FAIL: Auditd is not active." >> $LOG_FILE
  70. fi
  71. # 检查Fail2ban状态
  72. echo "8. Checking Fail2ban status..." >> $LOG_FILE
  73. ((TOTAL_CHECKS++))
  74. if systemctl is-active fail2ban | grep -q "active"; then
  75.   echo "PASS: Fail2ban is active." >> $LOG_FILE
  76.   ((COMPLIANCE_COUNT++))
  77. else
  78.   echo "FAIL: Fail2ban is not active." >> $LOG_FILE
  79. fi
  80. # 检查系统日志
  81. echo "9. Checking system logging..." >> $LOG_FILE
  82. ((TOTAL_CHECKS++))
  83. if systemctl is-active rsyslog | grep -q "active"; then
  84.   echo "PASS: System logging is active." >> $LOG_FILE
  85.   ((COMPLIANCE_COUNT++))
  86. else
  87.   echo "FAIL: System logging is not active." >> $LOG_FILE
  88. fi
  89. # 检查时间同步
  90. echo "10. Checking time synchronization..." >> $LOG_FILE
  91. ((TOTAL_CHECKS++))
  92. if systemctl is-active chronyd | grep -q "active"; then
  93.   echo "PASS: Time synchronization is active." >> $LOG_FILE
  94.   ((COMPLIANCE_COUNT++))
  95. else
  96.   echo "FAIL: Time synchronization is not active." >> $LOG_FILE
  97. fi
  98. # 计算合规百分比
  99. COMPLIANCE_PERCENT=$((COMPLIANCE_COUNT * 100 / TOTAL_CHECKS))
  100. echo "Baseline check completed at $(date)" >> $LOG_FILE
  101. echo "Compliance: $COMPLIANCE_COUNT/$TOTAL_CHECKS ($COMPLIANCE_PERCENT%)" >> $LOG_FILE
  102. if [ $COMPLIANCE_PERCENT -lt 100 ]; then
  103.   echo "WARNING: System is not fully compliant with security baseline. Check $LOG_FILE for details."
  104.   # 发送邮件通知
  105.   echo "Security baseline check failed on $(hostname). Compliance: $COMPLIANCE_PERCENT%. Check $LOG_FILE for details." | mail -s "Security Alert: Baseline Check Failed" admin@example.com
  106. else
  107.   echo "System is fully compliant with security baseline."
  108. fi
  109. exit 0
  110. # 设置脚本可执行权限
  111. chmod +x security_baseline.sh
  112. # 创建定期基线检查任务
  113. echo "0 3 * * 0 /opt/security-tools/security_baseline.sh" > /etc/cron.weekly/security_baseline
  114. chmod +x /etc/cron.weekly/security_baseline
复制代码

2. 安全合规性检查

对于需要符合特定安全标准(如PCI-DSS、HIPAA、GDPR等)的系统,定期进行合规性检查是必要的。
  1. # 安装OpenSCAP进行安全合规性检查
  2. yum install -y openscap-scanner scap-security-guide
  3. # 下载最新的安全基准
  4. yum update -y scap-security-guide
  5. # 运行系统扫描
  6. oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_pci-dss --results-arf arf-pci-dss.xml --report pci-dss-report.html /usr/share/xml/scap/ssg/content/ssg-centos7-ds.xml
  7. # 查看扫描结果
  8. cat pci-dss-report.html
  9. # 根据扫描结果修复问题
  10. # 示例:修复密码策略
  11. vi /etc/login.defs
  12. # 修改以下行
  13. PASS_MAX_DAYS   90
  14. PASS_MIN_DAYS   7
  15. PASS_WARN_AGE   14
  16. # 示例:修复SSH配置
  17. vi /etc/ssh/sshd_config
  18. # 修改或添加以下行
  19. PermitRootLogin no
  20. MaxAuthTries 3
  21. ClientAliveInterval 300
  22. ClientAliveCountMax 2
  23. # 重启SSH服务
  24. systemctl restart sshd
  25. # 创建自定义合规性检查脚本
  26. vi compliance_check.sh
  27. #!/bin/bash
  28. LOG_FILE="/opt/security-logs/compliance_check_$(date +%Y%m%d_%H%M%S).log"
  29. COMPLIANCE_COUNT=0
  30. TOTAL_CHECKS=0
  31. echo "Starting compliance check at $(date)" > $LOG_FILE
  32. # PCI-DSS合规性检查
  33. echo "PCI-DSS Compliance Check" >> $LOG_FILE
  34. # 检查防火墙配置
  35. echo "1. Checking firewall configuration..." >> $LOG_FILE
  36. ((TOTAL_CHECKS++))
  37. if firewall-cmd --list-all | grep -q "services:"; then
  38.   echo "PASS: Firewall is configured with allowed services." >> $LOG_FILE
  39.   ((COMPLIANCE_COUNT++))
  40. else
  41.   echo "FAIL: Firewall is not properly configured." >> $LOG_FILE
  42. fi
  43. # 检查密码复杂度
  44. echo "2. Checking password complexity..." >> $LOG_FILE
  45. ((TOTAL_CHECKS++))
  46. if grep -q "^minlen = 12" /etc/security/pwquality.conf; then
  47.   echo "PASS: Password complexity is configured." >> $LOG_FILE
  48.   ((COMPLIANCE_COUNT++))
  49. else
  50.   echo "FAIL: Password complexity is not configured." >> $LOG_FILE
  51. fi
  52. # 检查SSH配置
  53. echo "3. Checking SSH configuration..." >> $LOG_FILE
  54. ((TOTAL_CHECKS++))
  55. if grep -q "^PermitRootLogin no" /etc/ssh/sshd_config && grep -q "^PasswordAuthentication no" /etc/ssh/sshd_config; then
  56.   echo "PASS: SSH is properly configured." >> $LOG_FILE
  57.   ((COMPLIANCE_COUNT++))
  58. else
  59.   echo "FAIL: SSH is not properly configured." >> $LOG_FILE
  60. fi
  61. # 检查日志记录
  62. echo "4. Checking logging configuration..." >> $LOG_FILE
  63. ((TOTAL_CHECKS++))
  64. if grep -q "^*.info;mail.none;authpriv.none;cron.none" /etc/rsyslog.conf; then
  65.   echo "PASS: Logging is properly configured." >> $LOG_FILE
  66.   ((COMPLIANCE_COUNT++))
  67. else
  68.   echo "FAIL: Logging is not properly configured." >> $LOG_FILE
  69. fi
  70. # 检查文件完整性监控
  71. echo "5. Checking file integrity monitoring..." >> $LOG_FILE
  72. ((TOTAL_CHECKS++))
  73. if systemctl is-active aide | grep -q "active"; then
  74.   echo "PASS: File integrity monitoring is active." >> $LOG_FILE
  75.   ((COMPLIANCE_COUNT++))
  76. else
  77.   echo "FAIL: File integrity monitoring is not active." >> $LOG_FILE
  78. fi
  79. # HIPAA合规性检查
  80. echo -e "\nHIPAA Compliance Check" >> $LOG_FILE
  81. # 检查数据加密
  82. echo "6. Checking data encryption..." >> $LOG_FILE
  83. ((TOTAL_CHECKS++))
  84. if lsblk | grep -q "crypt"; then
  85.   echo "PASS: Disk encryption is configured." >> $LOG_FILE
  86.   ((COMPLIANCE_COUNT++))
  87. else
  88.   echo "FAIL: Disk encryption is not configured." >> $LOG_FILE
  89. fi
  90. # 检查访问控制
  91. echo "7. Checking access control..." >> $LOG_FILE
  92. ((TOTAL_CHECKS++))
  93. if grep -q "^auth.*required.*pam_wheel.so use_uid" /etc/pam.d/su; then
  94.   echo "PASS: Access control is configured." >> $LOG_FILE
  95.   ((COMPLIANCE_COUNT++))
  96. else
  97.   echo "FAIL: Access control is not configured." >> $LOG_FILE
  98. fi
  99. # 检查审计日志
  100. echo "8. Checking audit logs..." >> $LOG_FILE
  101. ((TOTAL_CHECKS++))
  102. if grep -q "action.*acct" /etc/audit/rules.d/audit.rules; then
  103.   echo "PASS: Audit logs are configured." >> $LOG_FILE
  104.   ((COMPLIANCE_COUNT++))
  105. else
  106.   echo "FAIL: Audit logs are not configured." >> $LOG_FILE
  107. fi
  108. # GDPR合规性检查
  109. echo -e "\nGDPR Compliance Check" >> $LOG_FILE
  110. # 检查数据保护
  111. echo "9. Checking data protection..." >> $LOG_FILE
  112. ((TOTAL_CHECKS++))
  113. if grep -q "^umask 077" /etc/bashrc; then
  114.   echo "PASS: Data protection is configured." >> $LOG_FILE
  115.   ((COMPLIANCE_COUNT++))
  116. else
  117.   echo "FAIL: Data protection is not configured." >> $LOG_FILE
  118. fi
  119. # 检查数据保留策略
  120. echo "10. Checking data retention policy..." >> $LOG_FILE
  121. ((TOTAL_CHECKS++))
  122. if grep -q "^rotate 90" /etc/logrotate.conf; then
  123.   echo "PASS: Data retention policy is configured." >> $LOG_FILE
  124.   ((COMPLIANCE_COUNT++))
  125. else
  126.   echo "FAIL: Data retention policy is not configured." >> $LOG_FILE
  127. fi
  128. # 计算合规百分比
  129. COMPLIANCE_PERCENT=$((COMPLIANCE_COUNT * 100 / TOTAL_CHECKS))
  130. echo "Compliance check completed at $(date)" >> $LOG_FILE
  131. echo "Compliance: $COMPLIANCE_COUNT/$TOTAL_CHECKS ($COMPLIANCE_PERCENT%)" >> $LOG_FILE
  132. if [ $COMPLIANCE_PERCENT -lt 100 ]; then
  133.   echo "WARNING: System is not fully compliant. Check $LOG_FILE for details."
  134.   # 发送邮件通知
  135.   echo "Compliance check failed on $(hostname). Compliance: $COMPLIANCE_PERCENT%. Check $LOG_FILE for details." | mail -s "Security Alert: Compliance Check Failed" admin@example.com
  136. else
  137.   echo "System is fully compliant."
  138. fi
  139. exit 0
  140. # 设置脚本可执行权限
  141. chmod +x compliance_check.sh
  142. # 创建定期合规性检查任务
  143. echo "0 4 * * 1 /opt/security-tools/compliance_check.sh" > /etc/cron.weekly/compliance_check
  144. chmod +x /etc/cron.weekly/compliance_check
复制代码

3. 定期安全评估

定期进行安全评估可以发现潜在的安全问题,并及时采取措施加以解决。
  1. # 安装安全评估工具
  2. yum install -y lynis nmap nikto
  3. # 运行Lynis安全审计
  4. lynis audit system
  5. # 查看Lynis报告
  6. cat /var/log/lynis-report.dat
  7. # 创建综合安全评估脚本
  8. vi security_assessment.sh
  9. #!/bin/bash
  10. LOG_DIR="/opt/security-logs/assessment_$(date +%Y%m%d_%H%M%S)"
  11. mkdir -p $LOG_DIR
  12. LOG_FILE="$LOG_DIR/assessment_report.txt"
  13. HTML_REPORT="$LOG_DIR/assessment_report.html"
  14. echo "Starting comprehensive security assessment at $(date)" > $LOG_FILE
  15. # 1. 系统信息收集
  16. echo "1. Collecting system information..." >> $LOG_FILE
  17. uname -a > $LOG_DIR/system_info.txt
  18. df -h >> $LOG_DIR/system_info.txt
  19. free -m >> $LOG_DIR/system_info.txt
  20. cat /etc/redhat-release >> $LOG_DIR/system_info.txt
  21. # 2. 网络安全评估
  22. echo "2. Performing network security assessment..." >> $LOG_FILE
  23. # 扫描开放端口
  24. nmap -sS -O localhost > $LOG_DIR/nmap_scan.txt
  25. # 检查网络连接
  26. netstat -tulnp > $LOG_DIR/network_connections.txt
  27. # 检查路由表
  28. netstat -rn > $LOG_DIR/routing_table.txt
  29. # 3. 文件系统安全评估
  30. echo "3. Performing file system security assessment..." >> $LOG_FILE
  31. # 查找SUID/SGID文件
  32. find / -type f \( -perm -4000 -o -perm -2000 \) -ls > $LOG_DIR/suid_sgid_files.txt
  33. # 查找全局可写文件
  34. find / -type f -perm -o+w -ls > $LOG_DIR/world_writable_files.txt
  35. # 查找无主文件
  36. find / -nouser -o -nogroup -ls > $LOG_DIR/unowned_files.txt
  37. # 4. 用户和认证安全评估
  38. echo "4. Performing user and authentication security assessment..." >> $LOG_FILE
  39. # 检查用户账户
  40. awk -F: '($3 == 0) { print $1 }' /etc/passwd > $LOG_DIR/root_accounts.txt
  41. # 检查空密码账户
  42. awk -F: '($2 == "") { print $1 }' /etc/shadow > $LOG_DIR/empty_passwords.txt
  43. # 检查密码策略
  44. grep -E "PASS_MAX_DAYS|PASS_MIN_DAYS|PASS_WARN_AGE" /etc/login.defs > $LOG_DIR/password_policy.txt
  45. # 5. 服务安全评估
  46. echo "5. Performing service security assessment..." >> $LOG_FILE
  47. # 检查运行的服务
  48. systemctl list-units --type=service --state=running > $LOG_DIR/running_services.txt
  49. # 检查启动服务
  50. systemctl list-unit-files | grep enabled > $LOG_DIR/enabled_services.txt
  51. # 6. 日志和审计评估
  52. echo "6. Performing log and audit assessment..." >> $LOG_FILE
  53. # 检查日志配置
  54. ls -la /var/log/ > $LOG_DIR/log_files.txt
  55. # 检查审计规则
  56. auditctl -l > $LOG_DIR/audit_rules.txt
  57. # 7. 运行Lynis安全审计
  58. echo "7. Running Lynis security audit..." >> $LOG_FILE
  59. lynis audit system --quiet > $LOG_DIR/lynis_output.txt
  60. cp /var/log/lynis-report.dat $LOG_DIR/
  61. # 8. 生成HTML报告
  62. echo "8. Generating HTML report..." >> $LOG_FILE
  63. cat > $HTML_REPORT << EOF
  64. <!DOCTYPE html>
  65. <html>
  66. <head>
  67.     <title>Security Assessment Report - $(date +%Y-%m-%d)</title>
  68.     <style>
  69.         body { font-family: Arial, sans-serif; margin: 20px; }
  70.         h1 { color: #333366; }
  71.         h2 { color: #4444aa; }
  72.         pre { background-color: #f5f5f5; padding: 10px; border-radius: 5px; overflow-x: auto; }
  73.         .section { margin-bottom: 30px; }
  74.         .warning { color: #ff6600; }
  75.         .success { color: #009900; }
  76.     </style>
  77. </head>
  78. <body>
  79.     <h1>Security Assessment Report</h1>
  80.     <p><strong>Date:</strong> $(date)</p>
  81.     <p><strong>Hostname:</strong> $(hostname)</p>
  82.    
  83.     <div class="section">
  84.         <h2>Executive Summary</h2>
  85.         <p>This security assessment was performed on $(date) for the system $(hostname). The assessment includes system information review, network security evaluation, file system security check, user and authentication assessment, service security review, and log and audit evaluation.</p>
  86.     </div>
  87.    
  88.     <div class="section">
  89.         <h2>System Information</h2>
  90.         <pre>$(cat $LOG_DIR/system_info.txt)</pre>
  91.     </div>
  92.    
  93.     <div class="section">
  94.         <h2>Network Security</h2>
  95.         <h3>Open Ports</h3>
  96.         <pre>$(cat $LOG_DIR/nmap_scan.txt)</pre>
  97.         <h3>Network Connections</h3>
  98.         <pre>$(cat $LOG_DIR/network_connections.txt)</pre>
  99.     </div>
  100.    
  101.     <div class="section">
  102.         <h2>File System Security</h2>
  103.         <h3>SUID/SGID Files</h3>
  104.         <pre>$(cat $LOG_DIR/suid_sgid_files.txt)</pre>
  105.         <h3>World Writable Files</h3>
  106.         <pre>$(cat $LOG_DIR/world_writable_files.txt)</pre>
  107.     </div>
  108.    
  109.     <div class="section">
  110.         <h2>User and Authentication Security</h2>
  111.         <h3>Root Accounts</h3>
  112.         <pre>$(cat $LOG_DIR/root_accounts.txt)</pre>
  113.         <h3>Password Policy</h3>
  114.         <pre>$(cat $LOG_DIR/password_policy.txt)</pre>
  115.     </div>
  116.    
  117.     <div class="section">
  118.         <h2>Service Security</h2>
  119.         <h3>Running Services</h3>
  120.         <pre>$(cat $LOG_DIR/running_services.txt)</pre>
  121.         <h3>Enabled Services</h3>
  122.         <pre>$(cat $LOG_DIR/enabled_services.txt)</pre>
  123.     </div>
  124.    
  125.     <div class="section">
  126.         <h2>Recommendations</h2>
  127.         <ul>
  128.             <li>Review and remove unnecessary SUID/SGID files</li>
  129.             <li>Restrict access to world writable files</li>
  130.             <li>Ensure only authorized users have root access</li>
  131.             <li>Disable unnecessary services</li>
  132.             <li>Implement strong password policies</li>
  133.             <li>Regularly review system logs for suspicious activities</li>
  134.         </ul>
  135.     </div>
  136. </body>
  137. </html>
  138. EOF
  139. # 9. 汇总评估结果
  140. echo "9. Summarizing assessment results..." >> $LOG_FILE
  141. echo "Assessment completed at $(date)" >> $LOG_FILE
  142. echo "Detailed results saved in $LOG_DIR" >> $LOG_FILE
  143. echo "HTML report generated: $HTML_REPORT" >> $LOG_FILE
  144. # 发送邮件通知
  145. echo "Security assessment completed for $(hostname). Detailed results saved in $LOG_DIR. HTML report: $HTML_REPORT" | mail -s "Security Assessment Report - $(hostname)" admin@example.com
  146. exit 0
  147. # 设置脚本可执行权限
  148. chmod +x security_assessment.sh
  149. # 创建定期安全评估任务
  150. echo "0 5 1 * * /opt/security-tools/security_assessment.sh" > /etc/cron.monthly/security_assessment
  151. chmod +x /etc/cron.monthly/security_assessment
复制代码

五、总结与最佳实践

CentOS服务器的安全优化是一个持续的过程,需要系统管理员不断学习和适应新的安全威胁。通过本文介绍的基础配置、中级优化和高级技巧,您可以构建一个更加安全可靠的服务器环境。

最佳实践总结:

1. 保持系统更新:定期应用安全补丁,确保系统免受已知漏洞的威胁。
2. 最小权限原则:为用户和服务分配最小必要权限,减少潜在的安全风险。
3. 深度防御:采用多层次的安全措施,包括防火墙、SELinux、入侵检测系统等。
4. 定期监控与审计:实施全面的日志记录和监控,及时发现异常活动。
5. 安全基线与合规性:建立安全基线,定期进行合规性检查,确保系统符合安全标准。
6. 应急响应计划:制定并测试安全事件应急响应计划,确保在发生安全事件时能够快速有效地应对。
7. 安全意识培训:对系统管理员和用户进行安全意识培训,提高整体安全水平。

保持系统更新:定期应用安全补丁,确保系统免受已知漏洞的威胁。

最小权限原则:为用户和服务分配最小必要权限,减少潜在的安全风险。

深度防御:采用多层次的安全措施,包括防火墙、SELinux、入侵检测系统等。

定期监控与审计:实施全面的日志记录和监控,及时发现异常活动。

安全基线与合规性:建立安全基线,定期进行合规性检查,确保系统符合安全标准。

应急响应计划:制定并测试安全事件应急响应计划,确保在发生安全事件时能够快速有效地应对。

安全意识培训:对系统管理员和用户进行安全意识培训,提高整体安全水平。

通过实施这些最佳实践,您可以显著提高CentOS服务器的安全性,保护关键数据和系统资源免受各种安全威胁。记住,安全是一个持续的过程,需要不断地评估、改进和适应新的安全挑战。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则