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/8
CHECK_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 版本是否为 7
check_os() {
    if [ "${CHECK_VER}" != '7' ]; then
        RGB_DANGER "This script must be run on Linux 7!"
        exit 1
    fi
}

# 启用 BBR,防止网络拥塞,需要内核版本>=4.9
open_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"
}

# 设置禁用 SELinux
disable_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 <<EOF
PS1="\[\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 = 8
difok = 3
dcredit = -1
ucredit = -1
ocredit = -1
lcredit = -1
EOF
    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, reboot
reboot_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
}
clear
check_root
check_os
main

特立独行
0 声望2 粉丝

技术需要分享。