centos7 初始化 内核调优 安全加固脚本

分类:运维日常    发布时间:2020-02-27 22:41:30
#!/bin/bash

cat << EOF
+------------------------------------------------------------------+
| ** Welcome to CentOS 7 System init ** |
+------------------------------------------------------------------+
EOF

set -o nounset     # Treat unset variables as an error

# 初始化设置
echo "初始化设置"
# 修改主机名
#read -p "请输入要修改的主机名:" name
#hostnamectl set-hostname ${name}

yum install wget -y

# 配置系统使用阿里云yum源和EPEL源
mkdir /etc/yum.repos.d/bak
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/bak/
wget -P /etc/yum.repos.d http://mirrors.aliyun.com/repo/Centos-7.repo
wget -P /etc/yum.repos.d http://mirrors.aliyun.com/repo/epel-7.repo
yum clean all  # 清除缓存
yum makecache # 生成缓存

# 关闭SELINUX和防火墙
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
systemctl stop firewalld.service
systemctl disable firewalld.service
setenforce 0

# 禁用不需要的服务
systemctl stop postfix.service
systemctl disable postfix.service

# 时间定时同步及时区设置
yum -y install ntp
timedatectl set-timezone Asia/Shanghai
mv /etc/localtime  /etc/localtime.bak_$(date +"%Y%m%d%H%M%S")
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime 
echo  "*/5 * * * * /usr/sbin/ntpdate ntp1.aliyun.com > /dev/null 2>&1" >>/var/spool/cron/root

# 历史记录设置
echo "export HISTTIMEFORMAT='%Y-%m-%d %H:%M:%S `whoami` '" >> /etc/profile #显示执行命令的用户和时间
sed -i 's/HISTSIZE=1000/HISTSIZE=100/g' /etc/profile #历史记录条数

# 挂载磁盘(如需要)

# 创建常用目录

# 创建用户

# 安装常用命令
yum -y install vim ntpdate lrzsz expect unzip autoconf

# 安装网络及性能监控工具
yum -y install telnet net-tools sysstat iftop lsof iotop htop dstat

# 安装源码编译工具及开发组件
yum -y install cmake gcc gcc-c++ zib zlib-devel open openssl-devel pcre pcre-devel curl


# 安全设置
echo "安全设置"
echo "TMOUT=300" >> /etc/profile #登录后不活动则300秒超时

# 给系统文件加锁,防止未经许可的删除或添加,注意执行以下权限修改之后,就无法添加删除用户了。
# chattr +ia /etc/passwd
# chattr +ia /etc/shadow
# chattr +ia /etc/group
# chattr +ia /etc/gshadow
# chattr +ia /etc/services
# lsattr /etc/passwd /etc/shadow /etc/group /etc/gshadow /etc/services #显示文件的属性
# 注意:如果再要添加删除用户,需要先取消上面的设置,等用户添加删除完成之后,再执行上面的操作
# chattr -ia /etc/passwd
# chattr -ia /etc/shadow
# chattr -ia /etc/group
# chattr -ia /etc/gshadow
# chattr -ia /etc/services
# 使用chattr命令后,为了安全我们需要将其改名.
#mv /usr/bin/chattr /usr/bin/任意名称

# 隐藏系统版本信息
mv /etc/issue /etc/issue.bak
mv /etc/issue.net /etc/issue.net.bak_$(date +"%Y%m%d%H%M%S")

# 修改密码时效及长度
cp /etc/login.defs /etc/login.defs.bak_$(date +"%Y%m%d%H%M%S") #备份配置文件
sed -i '/^PASS_MAX_DAYS/c\PASS_MAX_DAYS   60' /etc/login.defs
sed -i '/^PASS_MIN_DAYS/c\PASS_MIN_DAYS   30'  /etc/login.defs
sed -i '/^PASS_MIN_LEN/c\PASS_MIN_LEN     16'  /etc/login.defs
sed -i '/^PASS_WARN_AGE/c\PASS_WARN_AGE   3'   /etc/login.defs

# 设定新密码的复杂度
cp /etc/pam.d/system-auth /etc/pam.d/system-auth.bak_$(date +"%Y%m%d%H%M%S") #备份配置文件
sed -i '/pam_pwquality.so/c\password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=  difok=3 minlen=12 ucredit=-1 lcredit=-1 dcredit=-1' /etc/pam.d/system-auth
# 参数含义:
# difok        定义新密码中必须要有几个字符和旧密码不同
# minlen       定义新密码的最小长度
# ucredit      定义新密码中可以包含的大写字母的最大数目(-1代表最少1个)
# lcredit      定义新密码中可以包含的小写字母的最大数目(-1代表最少1个)
# dcredit      定义新密码中可以包含的数字的最大数目 (-1代表最少1个)

# 登陆失败次数限定
cp /etc/pam.d/login /etc/pam.d/login.bak_$(date +"%Y%m%d%H%M%S") #备份配置文件
sed -i '/%PAM-1.0/a\auth required pam_tally2.so deny=5 unlock_time=300 even_deny_root root_unlock_time=300'  /etc/pam.d/login
# 参数含义:
# pam_tally2.so deny                定义密码失败次数
# lock_time                         定义普通用户失败后锁定时间(单位秒)
# even_deny_root root_unlock_time   定义root用户失败后锁定时间(单位秒)

# 删除不必要账户
UnusefulAccounts=("adm" "sync" "shutdown" "halt" "operator" "lp" "mail" "games" "ftp" "postfix" )
for Username in ${UnusefulAccounts[@]} ; 
    do
        userdel -f $Username >& /dev/null
            if [ $? -eq 0 ] ; then 
                echo "The account $Username has been deleted!"
            else
                echo "Deleting the account $Username ERROR! Please try again!"
            fi
    done

# 删除不必要的组
UnusefulGroups=("adm" "sync" "shutdown" "halt" "operator" "lp" "mail" "games" "ftp" "postfix" )
for Groups in ${UnusefulGroups[@]} ;
    do
        groupdel $Groups >& /dev/null
                         if [ $? -eq 0 ] ; then
                                 echo "The group $Groups has been deleted!"
                        else
                                 echo "Deleting the group $Groups ERROR! Please try again!"
                         fi
    done


# ssh服务安全设置
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak_$(date +"%Y%m%d%H%M%S")

sed -i  's/#Port 22/port 60000/'  /etc/ssh/sshd_config #修改默认端口
sed -i  's/#PermitRootLogin yes/PermitRootLogin no/'  /etc/ssh/sshd_config #禁止root用户ssh登录
sed -i  's/PasswordAuthentication no/PasswordAuthentication yes/'  /etc/ssh/sshd_config #禁止使用证书登录
sed -i "s/#PermitEmptyPasswords no/PermitEmptyPasswords no/g" /etc/ssh/sshd_config  #禁止SSH空密码用户登录

# 设置SSH LogLevel设置为INFO,记录登录和注销活动
sed -i "s/#LogLevel INFO/LogLevel INFO/g" /etc/ssh/sshd_config

# 设置SSH空闲超时退出时间
sed -i "s/^#ClientAliveInterval.*$/ClientAliveInterval 600/g" /etc/ssh/sshd_config
sed -i "s/^#ClientAliveCountMax.*$/ClientAliveCountMax 0/g" /etc/ssh/sshd_config

# SSHD强制使用V2安全协议
if [[ `grep "Protocol 2" /etc/ssh/sshd_config |wc -l` == "0" ]];then
        echo "Protocol 2" >>/etc/ssh/sshd_config
fi

# 确保SSH MaxAuthTries设置为3到6之间,降低SSH服务器被暴力攻击成功的风险。
sed -i "s/#MaxAuthTries/MaxAuthTries/g" /etc/ssh/sshd_config
sed -i "s/^MaxAuthTries.*$/MaxAuthTries 4/g" /etc/ssh/sshd_config

source /etc/profile>&/dev/null


echo "内核设置"
# 更新内核
# yum -y update # 此更新会升级系统版本和内核版本,请确认是否需要

# 内核调优
echo "Set sysctl.conf"

# 避免放大攻击
echo -e "net.ipv4.icmp_echo_ignore_broadcasts = 1" >> /etc/sysctl.conf 

# 开启恶意icmp错误消息保护
echo -e "net.ipv4.icmp_ignore_bogus_error_responses = 1" >> /etc/sysctl.conf

# 应对DDOS***
echo -e "net.ipv4.tcp_max_orphans = 3276800" >> /etc/sysctl.conf

# 开启SYN洪水攻击保护
echo -e "net.ipv4.tcp_syncookies = 1" >> /etc/sysctl.conf
echo -e "net.ipv4.tcp_synack_retries = 1" >> /etc/sysctl.conf
echo -e "net.ipv4.tcp_syn_retries = 1" >> /etc/sysctl.conf
echo -e "net.ipv4.tcp_max_syn_backlog = 262144" >> /etc/sysctl.conf
echo -e "net.ipv4.tcp_timestamps = 0" >> /etc/sysctl.conf

#开启重用。允许将TIME-WAIT sockets 重新用于新的TCP 连接
echo -e "net.ipv4.tcp_tw_reuse = 1" >> /etc/sysctl.conf
echo -e "net.ipv4.tcp_mem = 94500000 915000000 927000000" >> /etc/sysctl.conf
echo -e "net.ipv4.tcp_fin_timeout = 5" >> /etc/sysctl.conf

# 设置TCP发送keepalive的频率,默认为2小时,修改为600秒,表示服务器以10分钟发送keepalive消息
echo -e "net.ipv4.tcp_keepalive_time = 600" >> /etc/sysctl.conf
# 探测包发送的时间间隔设置为3秒,默认75秒
echo -e "net.ipv4.tcp_keepalive_intvl = 3" >> /etc/sysctl.conf
# 如果对方不给予应答,探测包发送的次数,默认9次
echo -e "net.ipv4.tcp_keepalive_probes = 3" >> /etc/sysctl.conf

#开启反向路径过滤
echo -e "net.ipv4.conf.all.rp_filter = 1" >> /etc/sysctl.conf
echo -e "net.ipv4.conf.default.rp_filter = 1" >> /etc/sysctl.conf

# 处理无源路由的包
echo -e "net.ipv4.conf.all.accept_source_route = 0" >> /etc/sysctl.conf
echo -e "net.ipv4.conf.default.accept_source_route = 0" >> /etc/sysctl.conf

# 关闭sysrq功能
echo -e "kernel.sysrq = 0" >> /etc/sysctl.conf

# core文件名中添加pid作为扩展名
echo -e "kernel.core_uses_pid = 1" >> /etc/sysctl.conf

# timewait的数量,默认180000
echo -e "net.ipv4.tcp_max_tw_buckets = 6000" >> /etc/sysctl.conf
echo -e "net.ipv4.tcp_sack = 1" >> /etc/sysctl.conf
echo -e "net.ipv4.tcp_window_scaling = 1" >> /etc/sysctl.conf

# 每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许送到队列的数据包的最大数目
echo -e "net.core.netdev_max_backlog = 262144" >> /etc/sysctl.conf

# 内存资源使用相关设定 
echo -e "net.core.wmem_default = 8388608" >> /etc/sysctl.conf
echo -e "net.core.rmem_default = 8388608" >> /etc/sysctl.conf
echo -e "net.core.rmem_max = 16777216" >> /etc/sysctl.conf
echo -e "net.core.wmem_max = 16777216" >> /etc/sysctl.conf
echo -e "net.ipv4.tcp_wmem = 8192 131072 16777216" >> /etc/sysctl.conf
echo -e "net.ipv4.tcp_rmem = 32768 131072 16777216" >> /etc/sysctl.conf
echo -e "net.ipv4.tcp_mem = 94500000 915000000 927000000" >> /etc/sysctl.conf

# 设置最大内存共享段大小bytes
echo -e "kernel.shmmax = 68719476736" >> /etc/sysctl.conf
echo -e "kernel.shmall = 4294967296" >> /etc/sysctl.conf

# 修改消息队列长度
echo -e "kernel.msgmnb = 655360" >> /etc/sysctl.conf
echo -e "kernel.msgmax = 655360" >> /etc/sysctl.conf
echo -e "kernel.msgmni = 20480" >> /etc/sysctl.conf

# 允许系统打开的端口范围
echo -e "net.ipv4.ip_local_port_range = 1025 65535" >> /etc/sysctl.conf

# 其他TCP相关调节
echo -e "net.core.somaxconn = 65535" >> /etc/sysctl.conf
echo -e "net.ipv4.tcp_retries2 = 5" >> /etc/sysctl.conf

/sbin/sysctl -p #使配置立即生效
cat /var/log/secure #查看系统设置是否正确,没有error提示说明设置正确

# 文件最大打开数与最大进程数优化
ulimit -SHn 65535
echo "ulimit -SHn 65535" >> /etc/rc.local
echo "*                     soft    nofile             65535" >>/etc/security/limits.conf
echo "*                     hard    nofile             65535" >>/etc/security/limits.conf
echo "*                     soft    nproc             65535" >>/etc/security/limits.conf
echo "*                     hard    nproc             65535" >>/etc/security/limits.conf
#noproc   代表最大进程数
#nofile   代表最大文件打开数

reboot # 重启系统使设置生效


标签: linux

阅读(52)┆ 评论(0) ┆ (0) ┆ 返回博客首页


发表我的评论

欢迎您: | 退出登录


文章评论