Linux服务器安全加固Shell脚本代码
相关实现代码如下所示:
#!/bin/sh
# 描述:执行Linux系统安全设置
# 作者:coralzd
# 技术支持:www.freebsdsystem.org
# 版本 0.1.2,编写日期 2011.05.03
# 账户安全配置部分
passwd -l xfs
passwd -l news
passwd -l nscd
passwd -l dbus
passwd -l vcsa
passwd -l games
passwd -l nobody
passwd -l avahi
passwd -l haldaemon
passwd -l gopher
passwd -l ftp
passwd -l mailnull
passwd -l pcap
passwd -l mail
passwd -l shutdown
passwd -l halt
passwd -l uucp
passwd -l operator
passwd -l sync
passwd -l adm
passwd -l lp
# 使用chattr保护系统核心密码文件
chattr +i /etc/passwd
chattr +i /etc/shadow
chattr +i /etc/group
chattr +i /etc/gshadow
# 配置连续输入错误3次后锁定账户,解锁时间为5分钟
sed -i 's#auth required pam_env.so#auth required pam_env.so\nauth required pam_tally.so onerr=fail deny=3 unlock_time=300\nauth required /lib/security/$ISA/pam_tally.so onerr=fail deny=3 unlock_time=300#' /etc/pam.d/system-auth
# 设置系统空闲5分钟后自动注销
echo "TMOUT=300" >>/etc/profile
# 将历史命令记录数量限制为10条
sed -i "s/HISTSIZE=1000/HISTSIZE=10/" /etc/profile
# 使/etc/profile配置立即生效
source /etc/profile
# 在/etc/sysctl.conf中启用syncookies防护
echo "net.ipv4.tcp_syncookies=1" >> /etc/sysctl.conf
sysctl -p # 执行sysctl.conf以启用配置
# 优化sshd_config配置文件
sed -i "s/#MaxAuthTries 6/MaxAuthTries 6/" /etc/ssh/sshd_config
sed -i "s/#UseDNS yes/UseDNS no/" /etc/ssh/sshd_config
# 限制重要命令的文件访问权限
chmod 700 /bin/ping
chmod 700 /usr/bin/finger
chmod 700 /usr/bin/who
chmod 700 /usr/bin/w
chmod 700 /usr/bin/locate
chmod 700 /usr/bin/whereis
chmod 700 /sbin/ifconfig
chmod 700 /usr/bin/pico
chmod 700 /bin/vi
chmod 700 /usr/bin/which
chmod 700 /usr/bin/gcc
chmod 700 /usr/bin/make
chmod 700 /bin/rpm
# 历史记录安全性增强
chattr +a /root/.bash_history
chattr +i /root/.bash_history
# 生成重要命令的MD5校验值列表
cat > list << "EOF" &&
/bin/ping
/bin/finger
/usr/bin/who
/usr/bin/w
/usr/bin/locate
/usr/bin/whereis
/sbin/ifconfig
/bin/pico
/bin/vi
/usr/bin/vim
/usr/bin/which
/usr/bin/gcc
/usr/bin/make
/bin/rpm
EOF
for i in `cat list`
do
if [ ! -x $i ];then
echo "$i not found,no md5sum!"
else
md5sum $i >> /var/log/`hostname`.log
fi
done
rm -f list