Linux 平安设置脚本,局部配置按需批改

#!/bin/bash# Filename:     security_setting.sh# Author:       Jeff.Cui# Date:         2023-05-22############### 平安设置次要批改性能 ################ 批改禁止 root ssh 登录,如只有root用户,则增加用户:dbaadmin/DBA_Test1 用户;# 批改 ssh 端口为 922 ;# 批改明码最大可用工夫180天,起码8位大写字母、小写字母、数字、特殊字符;# 批改限度IP网段拜访,hosts.allow 和 firewalld# 批改超时限度 1800s;# 红字、高亮RGB_DANGER() {    echo -e "\n\033[31;1m# $1 \033[0m\n"}# 白字、半亮RGB_WAIT() {    echo -e "\n\033[37;2m# $1 \033[0m\n"}# 绿字、高亮RGB_SUCCESS() {    echo -e "\n\033[32;1m# $1 \033[0m\n"}# 黄字、半亮RGB_WARNING() {    echo -e "\n\033[33;2m# $1 \033[0m\n"}# 天蓝字、半亮RGB_INFO() {    echo -e "\n\033[36;2m# $1 \033[0m"}# 查看操作系统大版本,如6/7/8CHECK_VER=$(egrep "^VERSION_ID" /etc/os-release | cut -d\" -f2 | cut -d\. -f1)# 查看 RAM 大小,此处未应用CHECK_RAM=$(cat /proc/meminfo | grep "MemTotal" | awk -F" " '{ram=$2/1024/1024}{printf("%.0f",ram)}')# 设置日志名字,脚本同目录下conflog=linux_security_$(date +'%Y%m%d').log# 查看 kernel 版本,用以同 4.9 比拟大小,BBR 要求 4.9 及以上版本KERN=$(uname -r | awk -F. '{ printf("%d.%d\n",$1,$2); }')kern_int=$(echo $KERN|cut -d\. -f1)kern_dec=$(echo $KERN|cut -d\. -f2)if [ $kern_int -gt 4 ];then    cansue_bbr = "Y"elif [ $kern_int -eq 4 ] && [ $kern_dec -ge 9 ];then    cansue_bbr = "Y"fi# 查看是否 root 执行check_root() {    if [[ $EUID -ne 0 ]]; then        RGB_DANGER "This script must be run as root!"        exit 1    fi}# 查看 OS 版本是否为 7check_os() {    if [ "${CHECK_VER}" != '7' ]; then        RGB_DANGER "This script must be run on Linux 7!"        exit 1    fi}# 启用 BBR,防止网络拥塞,须要内核版本>=4.9open_bbr() {    echo "============= bbr =============" >>${conflog} 2>&1    RGB_WAIT "Configuring..."    sed -i '/default_qdisc\|BBR\|tcp_congestion_control/d' /etc/sysctl.conf    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 >>${conflog} 2>&1    sysctl -n net.ipv4.tcp_congestion_control >>${conflog} 2>&1    lsmod | grep bbr >>${conflog} 2>&1    RGB_SUCCESS "Configuration Success"}# 设置禁用 SELinuxdisable_selinux() {    echo "============= selinux =============" >>${conflog} 2>&1    RGB_WAIT "Configuring..."    seconf=$(grep -i ^selinux= /etc/selinux/config | sed 's/ //g' | cut -d\= -f2)    seconf=$(echo $seconf | tr [:upper:] [:lower:])    if [ "${seconf}" != "disabled" ];then        sed -i 's/^SELINUX=.*$/SELINUX=disabled/g' /etc/selinux/config        setenforce 0    else        RGB_INFO "SELinux already configed to 'disabled',see /etc/selinux/config:$(grep -i ^selinux= /etc/selinux/config)"    fi    # systemctl disable firewalld.service >>${conflog} 2>&1    # systemctl stop firewalld.service >>${conflog} 2>&1    RGB_SUCCESS "Configuration Success"}# 设置仅容许指定 IP 能够 ssh 登录limit_sshIP() {    sed -i '/10.10.212.89/d' /etc/hosts.allow    echo "sshd:10.10.212.89/255.255.252.0" >>/etc/hosts.allow    sed -i '/sshd:/d' /etc/hosts.deny    echo 'sshd:ALL' /etc/hosts.deny    systemctl restart firewalld # 开启防火墙    systemctl enable firewalld # 开机自启动防火墙    firewall-cmd --zone=public --list-rich-rules    firewall-cmd --permanent --remove-service=ssh    firewall-cmd --permanent --zone=public --remove-service=ssh # 勾销没有限度的ssh服务,限度近程登录    firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.56.0/23" port protocol="tcp" port="922" accept' #增加 192.168.56.0/23 网段 拜访 922号端口白名单    firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.10.212.89/22" port protocol="tcp" port="922" accept' #增加 10.10.212.89/22 网段 拜访 922号端口白名单    firewall-cmd --reload # 失效设置    firewall-cmd --zone=public --list-rich-rules}# 设置时区为东八区 'Asia/Shanghai' "+0800"time_zone() {    echo "============= time zone =============" >>${conflog} 2>&1    RGB_WAIT "Configuring..."    if [ "$(date +%z)" != "+0800" ];then        rm -rf /etc/localtime >>${conflog} 2>&1        ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime >>${conflog} 2>&1        ls -ln /etc/localtime >>${conflog} 2>&1    else        tz=$(echo " $(ls -l /etc/localtime | awk -F"/" '{print $(NF-1)"/"$NF}') ($(date +'%Z, %z'))" | sed 's/^ //g')        RGB_INFO "Time Zone already set to 'Asia/Shanghai', like $tz,see /etc/localtime"    fi    RGB_SUCCESS "Configuration Success"}# 可选,测试环境可用custom_profile() {    echo "============= custom profile =============" >>${conflog} 2>&1    RGB_WAIT "Configuring..."    cat >/etc/profile.d/secu.sh <<EOFPS1="\[\e[37;40m\][\[\e[31;40m\]\u\[\e[37;40m\]@\h \[\e[35;40m\]\W\[\e[37;40m\]]\\\\$ \[\e[0m\]"GREP_OPTIONS="--color=auto"alias l='ls -AFhlt'alias grep='grep --color'alias egrep='egrep --color'alias fgrep='fgrep --color'export HISTTIMEFORMAT="%F %T"EOF    cat /etc/profile.d/custom.conf >>${conflog} 2>&1    RGB_SUCCESS "Configuration Success"}# 禁用 ctrl-alt-del 重启组合键disable_cad() {    echo "============= disable cad =============" >>${conflog} 2>&1    RGB_WAIT "Configuring..."    if [ -h /etc/systemd/system/ctrl-alt-del.target ];then        rm -rf /usr/lib/systemd/system/ctrl-alt-del.target        RGB_INFO "removed ctrl-alt-del.target link"    else        RGB_INFO "Already removed ctrl-alt-del.target link"    fi    # systemctl mask ctrl-alt-del.target >>${conflog} 2>&1 # 创立或批改软连贯指向 /dev/null    RGB_SUCCESS "Configuration Success"}# 锁定没有登录权限的账户lock_user() {    echo "============= Lock users =============" >>${conflog} 2>&1    RGB_WAIT "Configuring..."    for account in $(egrep "/sbin/nologin" /etc/passwd | cut -f 1 -d ":"); do        passwd -l $account 2>&1 >/dev/null    done    # 如果只有 root 账户可登录零碎,则建设其余管理员账户,如:dbaadmin/DBA_Test1    if [ $(egrep "/bin/bash|/bin/csh|/bin/sh" /etc/passwd | cut -f 1 -d ":" | grep -v root| wc -l) -eq 0 ];then        useradd dbaadmin -g wheel -G wheel        echo "DBA_Test1" | passwd --stdin dbaadmin    fi    # cut -d : -f 1 /etc/passwd >>${conflog} 2>&1    # for g in adm lp mail games ftp; do    #     groupdel ${g} >>${conflog} 2>&1    # done    # cat /etc/group >>${conflog} 2>&1    RGB_SUCCESS "Configuration Success"}# 系统文件权限sys_permissions() {    echo "============= sys permissions =============" >>${conflog} 2>&1    RGB_WAIT "Configuring..."    chmod 644 /etc/passwd >>${conflog} 2>&1    chmod 644 /etc/group >>${conflog} 2>&1    chmod 000 /etc/shadow >>${conflog} 2>&1    chmod 000 /etc/gshadow >>${conflog} 2>&1    ls -la /etc/passwd >>${conflog} 2>&1    ls -la /etc/group >>${conflog} 2>&1    ls -la /etc/shadow >>${conflog} 2>&1    ls -la /etc/gshadow >>${conflog} 2>&1    RGB_SUCCESS "Configuration Success"}#批改曾经存在的账户的明码过期工夫exist_account_pwd_policy() {    name=$(egrep "/bin/bash|/bin/csh|/bin/sh" /etc/passwd | grep -v root | awk -F ":" '{print $1}')    echo "Check exist account and change expire time for password..."    if [ -n "$name" ]; then        for i in $name; do            passwd -n 2 -x 180 -w 7 $i 2>&1 >/dev/null        done        printf "OK\n"    else        printf "Do not exist account,OK\n"    fi}# 批改默认明码策略,对后加账户失效password_policy() {    echo "============= default password policy =============" >>${conflog} 2>&1    RGB_WAIT "Configuring..."    passwd_maxdays=$(grep -i ^PASS_MAX_DAYS /etc/login.defs | awk '{print $2}')    if [ $passwd_maxdays -gt 180 ];then        cp /etc/login.defs /etc/login.defs.$(date +'%F')        sed -i 's/^PASS_MAX_DAYS.*$/PASS_MAX_DAYS   180/' /etc/login.defs        sed -i 's/^PASS_MIN_DAYS.*$/PASS_MIN_DAYS   0/' /etc/login.defs        sed -i  's/^PASS_MIN_LEN.*$/PASS_MIN_LEN    8/' /etc/login.defs        sed -i 's/^PASS_WARN_AGE.*$/PASS_WARN_AGE   7/' /etc/login.defs    else        RGB_INFO "Default Password lifetime policy already changed, do nothing"    fi    grep -Ev "^$|^#" /etc/login.defs >>${conflog} 2>&1    # 批改明码复杂度    plnum=$(grep -Ei "^minlen|^difok|^dcredit|^ucredit|^ocredit|^lcredit" /etc/security/pwquality.conf| wc -l)    if [ $plnum -eq 0 ];then        cat >>/etc/security/pwquality.conf <<EOF # 8位以上蕴含数字\大写字母\特殊字符\小写字母4种,且同旧明码差别3位以上minlen = 8difok = 3dcredit = -1ucredit = -1ocredit = -1lcredit = -1EOF    else        RGB_INFO "There already has policy like:\n$(grep -Ei "^minlen|^difok|^dcredit|^ucredit|^ocredit|^lcredit" /etc/security/pwquality.conf)"    fi    RGB_SUCCESS "Configuration Success"}# 批改 useradd 默认到期change_useradd() {    echo "============= change useradd =============" >>${conflog} 2>&1    RGB_WAIT "Configuring..."    sed -i 's/^INACTIVE.*$/INACTIVE=180/' /etc/default/useradd    cat /etc/default/useradd >>${conflog} 2>&1    RGB_SUCCESS "Configuration Success"}# 配置 ssh 策略sec_ssh() {    echo "============= ssh 平安设置(禁止root登录、批改ssh默认端口为922) =============" >>${conflog} 2>&1    RGB_WAIT "Configuring..."    cp /etc/ssh/sshd_config /etc/ssh/sshd_config_$(date +'%F')    sed -i '/^UseDNS\|^Port\|^AllowTcpForwarding\|^X11UseLocalhost\|^X11Forwarding\|^LoginGraceTime\|^PermitEmptyPasswords\|^PubkeyAuthentication\|^MaxAuthTries\|^ClientAlive\|^PermitRootLogin/d' /etc/ssh/sshd_config    sed -i '/^#UseDNS/a\UseDNS no' /etc/ssh/sshd_config    sed -i '/^#Port/a\Port 922' /etc/ssh/sshd_config    sed -i '/^#AllowTcpForwarding/a\AllowTcpForwarding yes' /etc/ssh/sshd_config    sed -i '/^#X11UseLocalhost/a\X11UseLocalhost no' /etc/ssh/sshd_config    sed -i '/X11Forwarding/a\X11Forwarding yes' /etc/ssh/sshd_config    sed -i '/^#LoginGraceTime/a\LoginGraceTime 90' /etc/ssh/sshd_config    sed -i '/^#PermitEmptyPasswords/a\PermitEmptyPasswords no' /etc/ssh/sshd_config    sed -i '/^#PubkeyAuthentication/a\PubkeyAuthentication yes' /etc/ssh/sshd_config    sed -i '/^#MaxAuthTries/a\MaxAuthTries 5' /etc/ssh/sshd_config    sed -i '/^#ClientAliveInterval/a\ClientAliveInterval 60' /etc/ssh/sshd_config    sed -i '/^#ClientAliveCountMax/a\ClientAliveCountMax 3' /etc/ssh/sshd_config    sed -i '/^#PermitRootLogin/a\PermitRootLogin no' /etc/ssh/sshd_config    sed -i "s/#Banner none/Banner \/etc\/issue.net/g" /etc/ssh/sshd_config    echo "ATTENTION:You have logged onto a secured server, ONLY Authorized users can access..." > /etc/issue    echo "ATTENTION:You have logged onto a secured server, ONLY Authorized users can access..." > /etc/issue.net    echo "ATTENTION:You have logged onto a secured server, ONLY Authorized users can access..." > /etc/motd    systemctl restart sshd >/dev/null 2>&1    grep -Ev "^$|^#" /etc/ssh/sshd_config >>${conflog} 2>&1    RGB_SUCCESS "Configuration Success"}# 禁用 USB 设施dsiable_usb() {    echo "============= 禁用 USB 设施 =============" >>${conflog} 2>&1    RGB_WAIT "Configuring..."    echo "install usb-storage /bin/true" >/etc/modprobe.d/block_usb.conf    cat /etc/modprobe.d/block_usb.conf >>${conflog} 2>&1    RGB_SUCCESS "Configuration Success"}# 超时设置timeout_config() {    echo "============= timeout config =============" >>${conflog} 2>&1    RGB_WAIT "Configuring..."    echo "export TMOUT=1800" >>/etc/profile.d/custom.conf    cat /etc/profile.d/custom.conf >>${conflog} 2>&1    RGB_SUCCESS "Configuration Success"}# 询问是否重启 OS, rebootreboot_os() {    RGB_WARNING "Please restart the server and see if the services start up fine."    RGB_WARNING "Do you want to restart OS ? [y/n]: "    while :; do        read REBOOT_STATUS        if [[ ! "${REBOOT_STATUS}" =~ ^[y,n]$ ]]; then            echo -en "${RGB_DANGER}Input error, please only input 'y' or 'n': "        else            break        fi    done    REBOOT_STATUS=$(echo $REBOOT_STATUS | tr [:upper:] [:lower:])    [ "${REBOOT_STATUS}" == 'y' ] && reboot}# 主步骤main() {    RGB_INFO "1/13 : Customize the profile (color and alias)"    custom_profile    RGB_INFO "2/13 : Time zone adjustment,设置时区"    time_zone    RGB_INFO "3/13 : Disable selinux,禁用 SELinux"    disable_selinux    RGB_INFO "4/13 : Configure Limit IP login,限度 IP 近程拜访"    limit_sshIP    RGB_INFO "5/13 : Disable Ctrl+Alt+Del"    disable_cad    if [ "$cansue_bbr" = "Y" ];then        RGB_INFO "6/13 : Enable Google bbr congestion control algorithm,启用 Google BBR 防拥挤,内核版本≥4.9"        open_bbr    else        RGB_INFO "6/13 : 不反对 Google BBR 防拥挤配置,内核版本<4.9,Not support Google bbr congestion control algorithm, do nothing..."    fi    RGB_INFO "7/13 : 锁定(Lock)没有登录权限的账户 ( $(egrep "/sbin/nologin" /etc/passwd | cut -d: -f1 | paste -s -d ","s) )"    lock_user    RGB_INFO "8/13 : System permissions for sensitive files,批改passwd/group等系统文件读写权限"    exist_account_pwd_policy    RGB_INFO "9/13 : System permissions for sensitive files,批改passwd/group等系统文件读写权限"    sys_permissions    RGB_INFO "10/13 : Modify Account Password Survival Policy,设置明码最大可用天数、最小长度等"    password_policy    RGB_INFO "11/13 : Maximum number of days an account is valid after password expiration strategy"    change_useradd    RGB_INFO "12/13 : SSH 平安设置,禁用 root 近程登录,批改默认端口为 922"    sec_ssh    RGB_INFO "13/13 : Timeout Auto-Logout Configuration, 设置 30 分钟超时退出"    timeout_config    reboot_os}clearcheck_rootcheck_osmain