Linux服务器系统安全加固(centos7系列)
Posted 不跟风的细狗
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux服务器系统安全加固(centos7系列)相关的知识,希望对你有一定的参考价值。
文章目录
Linux服务器系统安全加固
系统安全加固的目的:
1. 操作系统之上的各种应用,要想获得信息的完整性、机密性、可用性和可控性,必须依赖于操作系统通用CentOs Linux 7操作系统缺省配置通常不满足系统安全性的要求。
2. 操作系统的薄弱环节有安装和运行了冗余的服务、弱密码及匿名访问、开放了不必要的对外通讯端口、易受攻击的TCP/IP参数配置等,都容易成为日常运行和管理过程中的弱点。
3. 安全加固就是对系统进行优化配置,杜绝系统配置不当出现的弱点,提高操作系统和服务器的防御能力,防止黑客攻击和病毒入侵,提升系统和网络安全。
系统安全加固的方法:
1. 账户安全:
1.1 锁定系统中多余的自建账号
查看账户、口令文件、与系统管理员确认不必要的账户。
查看账户文件:
cat /etc/passwd
用户信息详解:
格式:login_name:password:user_ID:group_ID:comment:home_dir:command
login_name:用户名
password:加密后的用户密码
user_ID:用户ID,(1 ~ 6000) 若用户ID=0,则该用户拥有超级用户的权限。查看此处是否有多个ID=0。
group_ID:用户组ID
comment:用户全名或其它注释信息
home_dir:用户根目录
command:用户登录后的执行命令
例:test :1001:1001::/home/test:/bin/bash
用户名:test
加密后的用户密码:x
用户id:1001
组id:1001
用户根目录:/home/test
用户登录后执行的命令:/bin/bash
查看口令文件:
cat /etc/shadow
注: 对于一些保留的系统伪帐户如:bin, sys,adm,uucp,lp, nuucp,hpdb, www, daemon等可根据需要锁定登陆。
备份方法:
cp -p /etc/passwd /etc/passwd_bak
cp -p /etc/shadow /etc/shadow_bak
加固方法:
使用 passwd -l 用户名 #锁定不必要的用户账号
使用 passwd -S 用户名 #查看账户状态
使用 passwd -u 用户名 #解锁用户账号
注意: 切换测试时不要用root用户,超管用户切换任意用户都是免密的,是看不出来密码锁定效果的
1.2 设置系统口令密码策略
查看密码关键策略
[root@xl-4 ~]# cat /etc/login.defs |grep PASS
# PASS_MAX_DAYS Maximum number of days a password may be used.
# PASS_MIN_DAYS Minimum number of days allowed between password changes.
# PASS_MIN_LEN Minimum acceptable password length.
# PASS_WARN_AGE Number of days warning given before a password expires.
PASS_MAX_DAYS 99999
PASS_MIN_DAYS 0
PASS_MIN_LEN 5
PASS_WARN_AGE 7
备份方法:
cp -p /etc/login.defs /etc/login.defs_bak
加固方法:
vim /etc/login.defs
PASS_MAX_DAYS 可以使用密码的最大天数。
PASS_MIN_DAYS 密码更改之间允许的最小天数。
PASS_MIN_LEN 最小可接受密码长度。
PASS_WARN_AGE 密码过期前发出警告的天数。
1.3 限制su为root的用户:
备份方法:
cp -p /etc/pam.d/su /etc/pam.d/su_bak
加固方法:
头部添加一行,这一行的目的是,只有wheel组的用户可以 su 到root
vim /etc/pam.d/su
auth required /lib/security/pam_wheel.so group=wheel
1.4 多次登录失败锁定用户
备份方法:
cp -p /etc/pam.d/system-auth /etc/pam.d/system-auth_bak
加固方法:
添加一行
vim /etc/pam.d/system-auth
auth requisite pam_tally.so per_user onerr=fail deny=4 unlock_time=3600
注:超过4次错误就会lock user,为了防止拒绝服务攻击,加入per_user参数
2. 最小化服务
2.1 查看系统运行级别
查看方法:
who -r 或 runlevel
查看所有服务的状态
chkconfig 处理的命令类似于我们平时执行的 /etc/init.d/sshd restart这样的命令每一个运行级别(0-6)对应一个 /etc/rc.d/rc3.d/ 这样的 目录
查看命令:
chkconfig --list
init级别对应表
⛅运行级别 0: shutdown.target (系统停机状态,系统默认运行级别不能设为0,否则不能正常启动)
⛅运行级别 1: emergency.target (单用户工作状态,root权限,用于系统维护,禁止远程登陆)
⛅运行级别 2: rescure.target (多用户状态(没有NFS))
⛅运行级别 3: multi-user.target (完全的多用户状态(有NFS),登陆后进入控制台命令行模式)
⛅运行级别 4: 系统未使用,保留
⛅运行级别 5: graphical.target (X11控制台,登陆后进入图形GUI模式)
⛅运行级别 6: reboot.target (系统正常关闭并重启,默认运行级别不能设为6,否则不能正常启动)
自定义一个启动服务:
vim /etc/init.d/FTL
# chkconfig: 345 77 69
# description: FTL is a protocol for secure remote shell access. \\
# This serddvice starts up the OpenSSH server daemon.
. /etc/init.d/functions
case "$1" in
start)
action "FTL Linux is $1ing"/bin/true
;;
esac
chmod` `+x ``/etc/init``.d``/FTL` `# 增加执行权限
chkconfig --add FTL ``# 添加到启动服务
chkconfig --list FTL ``# 查看启动服务,显示默认的345级别开, 默认修改/etc/rc3.d/ /etc/rc5.d/
加固方法:
chkconfig --level <级别> <service> on|off|reset # 设置服务在第N个init级别下的启动或关闭或重新设置
3. 数据访问控制
3.1设置合理的初始文件权限
对umask的解释:
1.对于root用户,系统默认的umask值是0022;对于普通用户,系统默认的umask值是0002
2.一共有4组数字,其中第1组数字用于定义特殊权限,我们一般不予考虑,与一般权限有关的是后3组数字
1.查看umask值:
[root@xl-4 ~]# umask
0022
-
默认情况下,对于目录,用户所能拥有的最大权限是777;对于文件,用户所能拥有的最大权限是目录的最大权限去掉执行权限,即666。因为x执行权限对于目录是必须的,没有执行权限就无法进入目录,而对于文件则不必默认赋予x执行权限。
-
对于root用户,他的umask值是022。当root用户创建目录时,默认的权限就是用最大权限777去掉相应位置的umask值权限,即对于所有者不必去掉任何权限,对于所属组要去掉w权限,对于其他用户也要去掉w权限,所以目录的默认权限就是755;当root用户创建文件时,默认的权限则是用最大权限666去掉相应位置的umask值,即文件的默认权限是644。
-
对于umask值权限的理解,即:系统默认的权限—umask值=文件/目录的权限
例:umask=0022 系统默认root的目录权限为777 即:777-22=755 因此,在root用户下,默认umask值,创建的目录权限为 755。文件的权限也可借助上述方法计算。
备份方法:
cp -p /etc/profile /etc/profile_bak
加固方法1:
临时修改umask值:
注:临时修改重启或刷新以后会失效
加固方法2:
-
如果要永久修改umask值,需要修改/etc/profile文件或是修改/etc/bashrc文件,例如要将默认umask值设置为027,那么可以在文件中增加一行“umask 027”
-
在/etc/profile和/etc/bashrc 中都可以用于设置用户登录系统时自动执行某些操作,他们的区别是/etc/profile只在用户第一次登录时被执行,而/etc/bashrc则在用户每次登录加载Bash Shell时都会被执行。
-
因而,如果是修改/etc/profile文件,将只对新创建的用户生效;而如果是修改/etc/bashrc文件,则对所有用户都生效。
vim /etc/profile
umask 027
vim /etc/bashrc
umask 027
4. 网络访问控制
4.1 使用SSH进行管理
ssh远程登录密码认证的方式有三种,password、Keyboard Interactive、Public Key 。前面两种方式就是密码认证,只展示一种ip限制登陆,含义都是一样大同小异。第三种是登录方式最安全的一种。
密码管理:
检查sshd服务是否存在
[root@xl-5 ~]# ps -ef |grep sshd
root 1469 1 0 18:07 ? 00:00:00 /usr/sbin/sshd -D
root 2634 1469 0 18:08 ? 00:00:00 sshd: root@pts/0
root 2656 2638 0 18:08 pts/0 00:00:00 grep --color=auto sshd
若不存在,则使用命令开启ssh服务
systemctl start sshd
允许远程登录的ip或某个ip网段
vim /etc/hosts.allow
sshd:192.168.29.24 #允许此ip使用ssh远程登录
限制某个ip或网段使用ssh进行远程登录
vim /etc/hosts.deny
sshd:192.168.29.23 #限制此ip使用ssh远程登录
修改完成重启sshd服务
systemctl restart sshd
允许访问实验测试:
使用24主机ip,即可正常访问,未被限制
被限制访问测试:
使用23主机ip进行ssh访问测试,无法正常登录
Public key (公钥)
- 服务端生成秘钥
ssh-keygen -t rsa
回车 回车 回车 即可
cd /root/.ssh/
touch authorized_keys
cat ./id_rsa.pub >> ./authorized_keys
chmod 600 /root/.ssh/authorized_keys
修改.ssh的权限为700, authorized_keys的权限为600或者更严格的400,否则登录的时候会提示server refuse you key。
然后将其发送到客户主机中
注:刚刚测试的实验修改的配置文件要还原回去
修改sshd的配置文件
vim /etc/ssh/sshd_config
PermitEmptyPasswords yes #限制使用密码登录 yes即为开启
PasswordAuthentication yes #使用密钥登录 yes即为开启
重启sshd服务
systemctl restart sshd
4.2 禁止root用户远程登录:
检查方法:
#cat /etc/ssh/sshd_config
查看PermitRootLogin是否为no
备份方法:
#cp -p /etc/ssh/sshd_config /etc/ssh/sshd_config_bak
加固方法:
vim /etc/ssh/sshd_config
PermitRootLogin no
重启服务:
systemctl restart sshd
重启以后就会生效了,或者刷新退出登录
验证:
4.6 屏蔽登录banner信息
一些应用的banner信息,容易让黑客更快的匹配到漏洞信息,所以隐藏起来可以提升一定的安全性。
查看方法:
查看文件中是否存在Banner字段,或banner字段为NONE
cat /etc/ssh/sshd_config
cat /etc/motd
查看文件内容,该处内容将作为banner信息显示给登录用户。
备份方法:
cp -p /etc/ssh/sshd_config /etc/ssh/sshd_config_bak
cp -p /etc/motd /etc/motd_bak
加固方法:
vi /etc/ssh/sshd_config
banner NONE
vi /etc/motd
删除全部内容或更新成自己想要添加的内容,此处一般为空
4.4 防止误使用Ctrl+Alt+Del重启系统
centos 5 6 7 ,不同版本有不同的配置文件和方法,大同小异
检查方法:
[root@xl-5 ~]# cat /etc/inittab |grep ctrl
查看输入行是否被注释
Ctrl-Alt-Delete is handled by /usr/lib/systemd/system/ctrl-alt-del.target`
备份方法:
cp -p /etc/inittab /etc/inittab_bak
加固方法:
vim /etc/inittab
我这默认是已经被注释
5. 用户鉴别
5.1 设置登录超时:
vim /etc/profile
#添加一行
TMOUT=300 #单位是秒 (S)
限制FTP登录
yum install -y vsftpd
检查方法:
cat /etc/vsftpd/ftpusers
Users that are not allowed to login via ftp #不允许通过ftp登录的用户
加固方法:
vim /etc/vsftpd/ftpusers
添加一行,添加的用户将被禁止登录FTP服务
5.2 设置Bash保留历史命令的条数
检查方法:
查看保留历史命令条数
cat /etc/profile|grep HISTSIZE=
备份方法:
cp -p /etc/profile /etc/profile_bak
加固方法:
vim /etc/profile
HISTSIZE=1000 #这个值就是保留命令的条数
6. 审计策略
6.1日志审计策略配置
检查方法:
[root@localhost ~]# ps -ef |grep syslog
root 893 1 0 20:24 ? 00:00:00 /usr/sbin/rsyslogd -n
root 3057 3038 0 22:13 pts/1 00:00:00 grep --color=auto syslog
查看syslogd的配置,并确认日志文件是否存在
[root@localhost ~]# cat /etc/audisp/plugins.d/syslog.conf
# This file controls the configuration of the syslog plugin.
# It simply takes events and writes them to syslog. The
# arguments provided can be the default priority that you
# want the events written with. And optionally, you can give
# a second argument indicating the facility that you want events
# logged to. Valid options are LOG_LOCAL0 through 7.
active = no
direction = out
path = builtin_syslog
type = builtin
args = LOG_INFO
format = string
系统日志(默认)/var/log/messages
cron日志(默认)/var/log/cron
安全日志(默认)/var/log/secure
备份方法:
cp /etc/audisp/plugins.d/syslog.conf /etc/audisp/plugins.d/syslog_bak.conf
6.2 为审计产生的数据分配合理的存储空间和存储时间
查看系统轮询配置,有无以下内容
[root@localhost ~]# cat /etc/logrotate.conf |grep rotate
# see "man logrotate" for details
# rotate log files weekly
rotate 4
# use date as a suffix of the rotated file
include /etc/logrotate.d
# no packages own wtmp and btmp -- we'll rotate them here
rotate 1
rotate 1
缺省配置 logrotate
备份方法:
cp -p /etc/logrotate.conf /etc/logrotate.conf_bak
加固方法:
vi /etc/logrotate.d/syslog
# see "man logrotate" for details
# rotate log files weekly
weekly
# keep 4 weeks worth of backlogs
rotate 4
# send errors to root
errors root
# create new (empty) log files after rotating old ones
create
# uncomment this if you want your log files compressed
#compress
1
# RPM packages drop log rotation information into this directory
include /etc/logrotate.d
# no packages own lastlog or wtmp --we'll rotate them here
/var/log/wtmp
monthly
create 0664 root utmp
rotate 1
/var/log/lastlog
monthly
rotate 1
# system-specific logs may be configured here
缺省的配置一般放在logrotate.conf 文件的最开始处,影响整个系统。在本例中就是前面12行。
第三行weekly 指定所有的日志文件每周转储一次。
第五行 rotate 4 指定转储文件的保留 4份。
第七行 errors root 指定错误信息发送给root。
第九行create 指定 logrotate 自动建立新的日志文件,新的日志文件具有和
原来的文件一样的权限。
第11行 #compress 指定不压缩转储文件,如果需要压缩,去掉注释就可以了。
7. 关闭自动更新
7.1 关闭系统自动更新
vim /etc/yum/yum-cron.conf
update_messages = no
download_updates = no
7.2 升级GUN bash
下载地址http://ftp.gnu.org/gnu/bash/
wget http://ftp.gnu.org/gnu/bash/bash-4.4.18.tar.gz
yum install -y gcc*
tar xvf bash-4.4.18.tar.gz
cd bash-4.4.18/
./configure && make && make install
mv /bin/bash /bin/bash.bak
ln -s /usr/local/bin/bash /bin/bash
7.3 配置dump备份工具
vim /etc/security/limits.conf
去掉两行注释即可
* soft core 0
* hard rss 10000
CentOS7一键安全加固及系统优化脚本
CentOS7一键安全加固及系统优化脚本
init_centos7.sh 脚本内容如下 脚本说明:本脚本在 https://github.com/vtrois/spacepack上下载,并在其脚本基础上做了调整,根据前期CentOS7安全加固系列文章,添加了部分加固项
#!/usr/bin/env bash
#
# Author: Seaton Jiang <seaton@vtrois.com>
# Github URL: https://github.com/vtrois/spacepack
# License: MIT
# Date: 2020-08-13
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
RGB_DANGER=' 33[31;1m'
RGB_WAIT=' 33[37;2m'
RGB_SUCCESS=' 33[32m'
RGB_WARNING=' 33[33;1m'
RGB_INFO=' 33[36;1m'
RGB_END=' 33[0m'
CHECK_CENTOS=$( cat /etc/redhat-release|sed -r 's/.* ([0-9]+)..*/1/' )
CHECK_RAM=$( cat /proc/meminfo | grep "MemTotal" | awk -F" " '{ram=$2/1000000}{printf("%.0f",ram)}' )
LOCK=/var/log/init_centos7_record.log
tool_info() {
echo -e "========================================================================================="
echo -e " Init CentOS 7 Script "
echo -e " For more information please visit https://github.com/vtrois/spacepack "
echo -e "========================================================================================="
}
check_root(){
if [[ $EUID -ne 0 ]]; then
echo -e "${RGB_DANGER}This script must be run as root!${RGB_END}"
exit 1
fi
}
check_lock() {
if [ ! -f "$LOCK" ];then
touch $LOCK
else
echo -e "${RGB_DANGER}Detects that the initialization is complete and does not need to be initialized any further!${RGB_END}"
exit 1
fi
}
check_os() {
if [ "${CHECK_CENTOS}" != '7' ]; then
echo -e "${RGB_DANGER}This script must be run in CentOS 7!${RGB_END}"
exit 1
fi
}
new_swap() {
echo "============= swap =============" >> ${LOCK} 2>&1
if [ "${CHECK_RAM}" -le '2' ]; then
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
dd if=/dev/zero of=/swapfile bs=1024 count=1048576 >> ${LOCK} 2>&1
chmod 600 /swapfile >> ${LOCK} 2>&1
mkswap /swapfile >> ${LOCK} 2>&1
swapon /swapfile >> ${LOCK} 2>&1
echo '/swapfile swap swap defaults 0 0' >> /etc/fstab
echo '# Swap' >> /etc/sysctl.conf
echo 'vm.swappiness = 10' >> /etc/sysctl.conf
sysctl -p >> ${LOCK} 2>&1
sysctl -n vm.swappiness >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
else
echo -e "${RGB_SUCCESS}Skip, no configuration needed${RGB_END}"
fi
}
open_bbr() {
echo "============= bbr =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
echo "# BBR" >> /etc/sysctl.conf
echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf
echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.conf
sysctl -p >> ${LOCK} 2>&1
sysctl -n net.ipv4.tcp_congestion_control >> ${LOCK} 2>&1
lsmod | grep bbr >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}
disable_software() {
echo "============= selinux firewalld =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
setenforce 0 >> ${LOCK} 2>&1
sed -i 's/^SELINUX=.*$/SELINUX=disabled/' /etc/selinux/config
systemctl disable firewalld.service >> ${LOCK} 2>&1
systemctl stop firewalld.service >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}
time_zone() {
echo "============= time zone =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
rm -rf /etc/localtime >> ${LOCK} 2>&1
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime >> ${LOCK} 2>&1
ls -ln /etc/localtime >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}
custom_profile() {
echo "============= custom profile =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
cat > /etc/profile.d/centos7init.sh << EOF
PS1="[e[37;40m][[e[32;40m]u[e[37;40m]@h [e[35;40m]W[e[0m]]\\$ "
GREP_OPTIONS="--color=auto"
alias l='ls -AFhlt'
alias grep='grep --color'
alias egrep='egrep --color'
alias fgrep='fgrep --color'
export HISTTIMEFORMAT="%Y-%m-%d %H:%M:%S "
EOF
cat /etc/profile.d/centos7init.sh >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}
adjust_ulimit() {
echo "============= adjust ulimit =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
sed -i '/^# End of file/,$d' /etc/security/limits.conf
cat >> /etc/security/limits.conf <<EOF
# End of file
* soft core unlimited
* hard core unlimited
* soft nproc 1000000
* hard nproc 1000000
* soft nofile 1000000
* hard nofile 1000000
root soft core unlimited
root hard core unlimited
root soft nproc 1000000
root hard nproc 1000000
root soft nofile 1000000
root hard nofile 1000000
EOF
cat /etc/security/limits.conf >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}
kernel_optimum() {
echo "============= kernel optimum =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
[ ! -e "/etc/sysctl.conf_bak" ] && /bin/mv /etc/sysctl.conf{,_bak}
cat > /etc/sysctl.conf << EOF
# Controls source route verification
net.ipv4.conf.default.rp_filter = 1
net.ipv4.ip_nonlocal_bind = 1
net.ipv4.ip_forward = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
net.ipv4.conf.all.promote_secondaries = 1
net.ipv4.conf.default.promote_secondaries = 1
# Controls the use of TCP syncookies
# Number of pid_max
kernel.core_uses_pid = 1
kernel.pid_max = 1000000
net.ipv4.tcp_syncookies = 1
# Controls the maximum size of a message, in bytes
# Controls the default maxmimum size of a mesage queue
# Controls the maximum shared segment size, in bytes
# Controls the maximum number of shared memory segments, in pages
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
kernel.sysrq = 1
kernel.softlockup_panic = 1
kernel.printk = 5
# TCP kernel paramater
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_rmem = 4096 87380 4194304
net.ipv4.tcp_wmem = 4096 16384 4194304
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_sack = 1
# Socket buffer
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.netdev_max_backlog = 32768
net.core.somaxconn = 65535
net.core.optmem_max = 81920
# TCP conn
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_retries1 = 3
net.ipv4.tcp_retries2 = 15
# TCP conn reuse
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 5
net.ipv4.tcp_max_tw_buckets = 7000
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.tcp_synack_retries = 1
# keepalive conn
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.ip_local_port_range = 1024 65535
net.ipv6.neigh.default.gc_thresh3 = 4096
net.ipv4.neigh.default.gc_thresh3 = 4096
EOF
sysctl -p >> ${LOCK} 2>&1
cat /etc/sysctl.conf >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}
updatedb_optimum() {
echo "============= updatedb optimum =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
sed -i 's,media,media /data,' /etc/updatedb.conf
cat /etc/updatedb.conf >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}
open_ipv6() {
echo "============= open ipv6 =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
echo '# IPV6' >> /etc/sysctl.conf
echo 'net.ipv6.conf.all.disable_ipv6=0' >> /etc/sysctl.conf
echo 'net.ipv6.conf.default.disable_ipv6=0' >> /etc/sysctl.conf
echo 'net.ipv6.conf.lo.disable_ipv6=0' >> /etc/sysctl.conf
sysctl -p >> ${LOCK} 2>&1
cat /etc/sysctl.conf >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}
disable_cad() {
echo "============= disable cad =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
systemctl mask ctrl-alt-del.target >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}
remove_users() {
echo "============= remove users =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
for u in adm lp sync shutdown halt mail operator games ftp
do
userdel ${u} >> ${LOCK} 2>&1
done
cut -d : -f 1 /etc/passwd >> ${LOCK} 2>&1
for g in adm lp mail games ftp
do
groupdel ${g} >> ${LOCK} 2>&1
done
cat /etc/group >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}
sys_permissions() {
echo "============= sys permissions =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
chmod 644 /etc/passwd >> ${LOCK} 2>&1
chmod 644 /etc/group >> ${LOCK} 2>&1
chmod 000 /etc/shadow >> ${LOCK} 2>&1
chmod 000 /etc/gshadow >> ${LOCK} 2>&1
ls -la /etc/passwd >> ${LOCK} 2>&1
ls -la /etc/group >> ${LOCK} 2>&1
ls -la /etc/shadow >> ${LOCK} 2>&1
ls -la /etc/gshadow >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}
password_policy() {
echo "============= password policy =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
sed -i 's/^PASS_MAX_DAYS.*$/PASS_MAX_DAYS 90/' /etc/login.defs
sed -i 's/^PASS_MIN_DAYS.*$/PASS_MIN_DAYS 10/' /etc/login.defs
cat /etc/login.defs >> ${LOCK} 2>&1
cat >>/etc/security/pwquality.conf << EOF
minlen = 8
dcredit = -1
ucredit = -1
ocredit = -1
lcredit = -1
EOF
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}
change_useradd() {
echo "============= change useradd =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
sed -i 's/^INACTIVE.*$/INACTIVE=180/' /etc/default/useradd
cat /etc/default/useradd >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}
sec_ssh() {
echo "============= sec ssh =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
sed -i 's/UseDNS.*$/UseDNS no/' /etc/ssh/sshd_config
sed -i 's/^#LoginGraceTime.*$/LoginGraceTime 60/' /etc/ssh/sshd_config
sed -i 's/^#PermitEmptyPasswords.*$/PermitEmptyPasswords no/' /etc/ssh/sshd_config
sed -i 's/^#PubkeyAuthentication.*$/PubkeyAuthentication yes/' /etc/ssh/sshd_config
sed -i 's/^#MaxAuthTries.*$/MaxAuthTries 3/' /etc/ssh/sshd_config
sed -i "s/#ClientAliveInterval 0/ClientAliveInterval 30/g" /etc/ssh/sshd_config
sed -i "s/#ClientAliveCountMax 3/ClientAliveCountMax 3/g" /etc/ssh/sshd_config
sed -i "s/X11Forwarding yes/X11Forwarding no/g" /etc/ssh/sshd_config
sed -i "s/#Banner none/Banner /etc/issue.net/g" /etc/ssh/sshd_config
echo "Authorized users only. All activity may be monitored and reported.">/etc/issue.net
systemctl restart sshd.service >> ${LOCK} 2>&1
cat /etc/ssh/sshd_config >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}
timeout_config() {
echo "============= timeout config =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
echo "export TMOUT=1800" >> /etc/profile.d/centos7init.sh
cat /etc/profile.d/centos7init.sh >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}
lockout_policy() {
echo "============= lockout policy =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
[ ! -e "/etc/pam.d/system-auth_bak" ] && /bin/mv /etc/pam.d/system-auth{,_bak}
cat > /etc/pam.d/system-auth << EOF
auth required pam_env.so
auth required pam_faillock.so preauth silent audit deny=3 unlock_time=300
auth required pam_faildelay.so delay=2000000
auth [default=1 ignore=ignore success=ok] pam_succeed_if.so uid >= 1000 quiet
auth [default=1 ignore=ignore success=ok] pam_localuser.so
auth sufficient pam_unix.so nullok try_first_pass
auth [default=die] pam_faillock.so authfail audit deny=3 unlock_time=300
auth requisite pam_succeed_if.so uid >= 1000 quiet_success
auth sufficient pam_sss.so forward_pass
auth required pam_deny.so
account required pam_unix.so
account sufficient pam_localuser.so
account sufficient pam_succeed_if.so uid < 1000 quiet
account [default=bad success=ok user_unknown=ignore] pam_sss.so
account required pam_permit.so
account required pam_faillock.so
password requisite pam_pwquality.so try_first_pass local_users_only
password sufficient pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password sufficient pam_sss.so use_authtok
password required pam_deny.so
session optional pam_keyinit.so revoke
session required pam_limits.so
-session optional pam_systemd.so
session [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session required pam_unix.so
session optional pam_sss.so
EOF
[ ! -e "/etc/pam.d/password-auth_bak" ] && /bin/mv /etc/pam.d/password-auth{,_bak}
cat > /etc/pam.d/password-auth << EOF
auth required pam_env.so
auth required pam_faillock.so preauth silent audit deny=3 unlock_time=300
auth required pam_faildelay.so delay=2000000
auth [default=1 ignore=ignore success=ok] pam_succeed_if.so uid >= 1000 quiet
auth [default=1 ignore=ignore success=ok] pam_localuser.so
auth sufficient pam_unix.so nullok try_first_pass
auth [default=die] pam_faillock.so authfail audit deny=3 unlock_time=300
auth requisite pam_succeed_if.so uid >= 1000 quiet_success
auth sufficient pam_sss.so forward_pass
auth required pam_deny.so
account required pam_unix.so
account sufficient pam_localuser.so
account sufficient pam_succeed_if.so uid < 1000 quiet
account [default=bad success=ok user_unknown=ignore] pam_sss.so
account required pam_permit.so
account required pam_faillock.so
password requisite pam_pwquality.so try_first_pass local_users_only
password sufficient pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password sufficient pam_sss.so use_authtok
password required pam_deny.so
session optional pam_keyinit.so revoke
session required pam_limits.so
-session optional pam_systemd.so
session [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session required pam_unix.so
session optional pam_sss.so
EOF
systemctl restart sshd.service >> ${LOCK} 2>&1
cat /etc/pam.d/etc/pam.d/system-auth >> ${LOCK} 2>&1
cat /etc/pam.d/password-auth >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}
reboot_os() {
echo -e "
${RGB_WARNING}Please restart the server and see if the services start up fine.${RGB_END}"
echo -en "${RGB_WARNING}Do you want to restart OS ? [y/n]: ${RGB_END}"
while :; do
read REBOOT_STATUS
if [[ ! "${REBOOT_STATUS}" =~ ^[y,n]$ ]]; then
echo -en "${RGB_DANGER}Input error, please only input 'y' or 'n': ${RGB_END}"
else
break
fi
done
[ "${REBOOT_STATUS}" == 'y' ] && reboot
}
main() {
echo -e "
${RGB_INFO}1/18 : Start Init CentOS7 Script ${RGB_END}"
echo -e "
${RGB_INFO}2/18 : Customize the profile (color and alias)${RGB_END}"
custom_profile
echo -e "
${RGB_INFO}3/18 : Time zone adjustment${RGB_END}"
time_zone
echo -e "
${RGB_INFO}4/18 : Disable selinux and firewalld${RGB_END}"
disable_software
echo -e "
${RGB_INFO}5/18 : Disable Ctrl+Alt+Del${RGB_END}"
disable_cad
echo -e "
${RGB_INFO}6/18 : Kernel parameter optimization${RGB_END}"
kernel_optimum
echo -e "
${RGB_INFO}7/18 : The updatedb optimization${RGB_END}"
updatedb_optimum
echo -e "
${RGB_INFO}8/18 : Adding swap space${RGB_END}"
new_swap
echo -e "
${RGB_INFO}9/18 : Adjustment of ulimit${RGB_END}"
adjust_ulimit
echo -e "
${RGB_INFO}10/18 : Enable tcp bbr congestion control algorithm${RGB_END}"
open_bbr
echo -e "
${RGB_INFO}11/18 : Enable IPV6${RGB_END}"
open_ipv6
echo -e "
${RGB_INFO}12/18 : Remove unnecessary users and user groups from the system${RGB_END}"
remove_users
echo -e "
${RGB_INFO}13/18 : System permissions for sensitive files${RGB_END}"
sys_permissions
echo -e "
${RGB_INFO}14/18 : Modify Account Password Survival Policy${RGB_END}"
password_policy
echo -e "
${RGB_INFO}15/18 : Maximum number of days an account is valid after password expiration strategy${RGB_END}"
change_useradd
echo -e "
${RGB_INFO}16/18 : Secure configuration of SSH${RGB_END}"
sec_ssh
echo -e "
${RGB_INFO}17/18 : Timeout Auto-Logout Configuration${RGB_END}"
timeout_config
echo -e "
${RGB_INFO}18/18 : Configure account login failure lockout policy${RGB_END}"
lockout_policy
reboot_os
}
clear
tool_info
check_root
check_os
check_lock
main
测试执行截图如下
再次执行脚本会提示已经做了安全加固优化,无须再次执行
以上是关于Linux服务器系统安全加固(centos7系列)的主要内容,如果未能解决你的问题,请参考以下文章