学shell之新vps配置初始化脚本(简单安全加固)

314
#!/bin/bash

sshd_conf="/etc/ssh/sshd_config"
selinux_conf="/etc/selinux/config"
sudoers_conf="/etc/sudoers"

function blue() {
    echo -e "\033[34m\033[01m$1\033[0m"
}
function green() {
    echo -e "\033[32m\033[01m$1\033[0m"
}
function red() {
    echo -e "\033[31m\033[01m$1\033[0m"
}

function get_system_type() {
    issue=$(cat /etc/issue)
    if [[ $issue == *"Debian"* ]]; then
        echo "Debian"
    elif [[ $issue == *"Kernel"* ]]; then
        echo "Redhat"
    fi
}

# check sshd_config exist, if not, install it
function install_sshd() {
    if [[ $(get_system_type) == "Debian" ]]; then
        apt update -y
    elif [[ $(get_system_type) == "Redhat" ]]; then
        yun update -y
    fi
}

function key_file_permissions() {
    chown root:root /etc/passwd /etc/shadow /etc/group /etc/gshadow
    chmod 0644 /etc/group
    chmod 0644 /etc/passwd
    chmod 0400 /etc/shadow
    chmod 0400 /etc/gshadow
}

function check_sshd_config_exist() {
    if [ ! -f $sshd_conf ]; then
        blue "sshd not install, start install..."
        install_sshd
    else
        green "sshd_config exist, do next job"
    fi
}

function modify_sshd_config() {
    blue "=========================modify ssh config========================="

    cp $sshd_conf "$sshd_conf" + "_bak"

    while true; do
        read -p "please input new ssh port: " sshport

        if [ "$sshport" -ge 0 ] && [ "$sshport" -le 65535 ]; then
            break
        else
            red "plese input number in 1-65535, recommended >10,000"
            continue
        fi
    done

    sed -i -e "/#Port[\s\S]*/ c Port $sshport" $sshd_conf
    sed -i -e "/#LogLevel[\s\S]*/ c LogLevel INFO" $sshd_conf
    sed -i -e "/#PermitRootLogin[\s\S]*/ c PermitRootLogin no" $sshd_conf
    sed -i -e "/PermitRootLogin[\s\S]*/ c PermitRootLogin no" $sshd_conf
    sed -i -e "/#MaxAuthTries[\s\S]*/ c MaxAuthTries 5" $sshd_conf
    sed -i -e "s/#AuthorizedKeysFile/AuthorizedKeysFile/g" $sshd_conf
    sed -i -e "s/#PubkeyAuthentication/PubkeyAuthentication/g" $sshd_conf
    sed -i -e "/#PermitEmptyPasswords[\s\S]*/ c PermitEmptyPasswords no" $sshd_conf
    sed -i -e "/#PasswordAuthentication[\s\S]*/ c PasswordAuthentication no" $sshd_conf
    sed -i -e "/PasswordAuthentication[\s\S]*/ c PasswordAuthentication no" $sshd_conf
    sed -i -e "/#ClientAliveInterval[\s\S]*/c ClientAliveInterval 600" $sshd_conf
    sed -i -e "/#ClientAliveCountMax[\s\S]*/ c ClientAliveCountMax 0" $sshd_conf
    green "========================modify ssh config done===================="
}

# disabled selinux
function disable_selinux() {
    blue "===========disabled selinux if system was Redhat line=============="
    if [[ "$(get_system_type)" == "Redhat" ]]; then
        sed -i -e "/SELINUX[\s\S]*/ c SELINUX diabled" $selinux_conf
    fi
    green "========================disabled selinux done====================="
}

function add_new_user() {
    blue "========================add new user==============================="
    while true; do
        read -p "please input new user name: " username

        if id "$username" &>/dev/null; then
            red 'user exists'
            continue
        else
            break
        fi
    done

    # add user
    /usr/sbin/adduser "$username"
    if [ $? -eq 0 ]; then
        green "user $username is created successfully!!!"
    else
        red "user {username is created failly!!!"
        exit 1
    fi
    green "=======================add new user done=========================="
}


function create_ssh_key_file() {
    blue "========================create ssh key============================="

    if [ ! -d "/home/$username/.ssh" ]; then
        green "current user ssh path not exist, create it now"
        mkdir -p "/home/$username/.ssh"
    fi

    ssh-keygen -t rsa -b 2048 -N '' -f "/home/$username/.ssh/id_rsa" -q

    if [ -f "/home/$username/.ssh/id_rsa" ]; then
        cat /home/"$username"/.ssh/id_rsa
        red "Note: Please backup your private key and delete it in time! (private key path: /home/$username/.ssh/id_rsa)"
        mv /home/"$username"/.ssh/id_rsa.pub /home/"$username"/.ssh/authorized_keys
        chmod 600 /home/"$username"/.ssh/authorized_keys
        chown -R "$username":"$username" /home/"$username"
    fi

    green "=======================create ssh key down========================"

}

function update_system() {
    if [ "$(get_system_type)" == "Redhat" ]; then
        yum update -y
    elif [ "$(get_system_type)" == "Debian" ]; then
        apt update -y
    fi
}

function check_sudoer_install() {
    blue "========================check sudoer status========================"
    if [ ! -f "/etc/sudoers" ]; then
        if [ "$(get_system_type)" == "Debian" ]; then
            apt install sudo -y
        elif [ "$(get_system_type)" == "Redhat" ]; then
            yum install sudo -y
        fi
    fi
    green "=======================check sudoer status done==================="
}

function user_rights_to_root() {
    blue "========================grant root rights=========================="

    read -p "grant $username to root? Y/N  " grantroot
    if [[ "${grantroot}" == "Y" || "${grantroot}" == "y" ]]; then
        check_sudoer_install

        if [ "$(get_system_type)" == "Debian" ]; then
            sed -i -e "/^root[\s]*/a $username  ALL=(ALL:ALL) ALL" $sudoers_conf
        elif [ "$(get_system_type)" == "Redhat" ]; then
            sed -i -e "/^root[\s]*/a $username  ALL=(ALL)       ALL" $sudoers_conf
        fi
    elif [[ "${grantroot}" == "N" || "${grantroot}" == "n" ]]; then
        green "skip grant root rights to ${username}"
    fi

    green "=======================grant root rights done====================="
}

function check_firewall_install() {
    if [ "$(get_system_type)" == "Debian" ]; then
        if [[ "$(ufw status)" == *"command not found"* ]]; then
            apt install ufw -y
            systemctl enable ufw
        fi
    elif [ "$(get_system_type)" == "Redhat" ]; then
        if [[ "$(firewall-cmd --state)" == *"command not found"* ]]; then
            yum install firewalld -y
            systemctl enable firewalld
        fi
    fi
}

function firewalld_allowed_ssh_port() {
    blue "========================allowed ssh port==========================="
    check_firewall_install
    if [ "$(get_system_type)" == "Debian" ]; then
        ufw allow "$sshport/tcp"
    elif [ "$(get_system_type)" == "Redhat" ]; then
        if [ "$(firewall-cmd --state)" == "running" ]; then
            firewall-cmd --zone=public --add-port="$sshport/tcp" --permanent
        elif [ "$(firewall-cmd --state)" == "not running" ]; then
            firewall-offline-cmd --zone=public --add-port="$sshport/tcp"
        fi
    fi
    green "========================allowed ssh port done====================="
}

main() {
    check_sshd_config_exist
    modify_sshd_config
    firewalld_allowed_ssh_port
    disable_selinux
    add_new_user
    user_rights_to_root
    create_ssh_key_file
    key_file_permissions
    update_system
}

main
green "===========================all operation done========================="