centos7主机安全检测脚本和初始化脚本

2023-05-19 20:11:40 浏览数 (2)

# 一、主机安全检查脚本

代码语言:javascript复制
#!/bin/bash
##Filename:     CentOS_Check_Script.sh
##Description:  Security detection script

echo "##########################################################################"
echo "#                                                                        #"
echo "#                         health check script                            #"
echo "#                                                                        #"
echo "#警告:本脚本只是一个检查的操作,未对服务器做任何修改,管理员可以根据此报告 #"
echo "#进行相应的安全整改                                                      #"
echo "##########################################################################"
echo " "
#read -p "=====================Are You Ready,Please press enter=================="
echo " "
echo "##########################################################################"
echo "#                                                                        #"
echo "#                               主机安全检测                             #"
echo "#                                                                        #"
echo "##########################################################################"
echo " "
echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>系统基本信息<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
hostname=$(uname -n)
system=$(cat /etc/os-release | grep "^NAME" | awk -F" '{print $2}')
version=$(cat /etc/redhat-release | awk '{print $4$5}')
kernel=$(uname -r)
platform=$(uname -p)
address=$(ip addr | grep inet | grep -v "inet6" | grep -v "127.0.0.1" | awk '{ print $2; }' | tr 'n' 't' )
cpumodel=$(cat /proc/cpuinfo | grep name | cut -f2 -d: | uniq)
cpu=$(cat /proc/cpuinfo | grep 'processor' | sort | uniq | wc -l)
machinemodel=$(dmidecode | grep "Product Name" | sed 's/^[ t]*//g' | tr 'n' 't' )
date=$(date)

echo "主机名:           $hostname"
echo "系统名称:         $system"
echo "系统版本:         $version"
echo "内核版本:         $kernel"
echo "系统类型:         $platform"
echo "本机IP地址:       $address"
echo "CPU型号:          $cpumodel"
echo "CPU核数:          $cpu"
echo "机器型号:         $machinemodel"
echo "系统时间:         $date"
echo " "
echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>资源使用情况<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
summemory=$(free -h |grep "Mem:" | awk '{print $2}')
freememory=$(free -h |grep "Mem:" | awk '{print $4}')
usagememory=$(free -h |grep "Mem:" | awk '{print $3}')
uptime=$(uptime | awk '{print $2" "$3" "$4" "$5}' | sed 's/,$//g')
loadavg=$(uptime | awk '{print $9" "$10" "$11" "$12" "$13}')

echo "总内存大小:           $summemory"
echo "已使用内存大小:       $usagememory"
echo "可使用内存大小:       $freememory"
echo "系统运行时间:         $uptime"
echo "系统负载:             $loadavg"
echo "=============================dividing line================================"
echo "内存状态:"
vmstat 2 5
echo "=============================dividing line================================"
echo "僵尸进程:"
ps -ef | grep zombie | grep -v grep
if [ $? == 1 ];then
    echo ">>>无僵尸进程"
else
    echo ">>>有僵尸进程------[需调整]"
fi
echo "=============================dividing line================================"
echo "耗CPU最多的进程:"
ps auxf |sort -nr -k 3 |head -5
echo "=============================dividing line================================"
echo "耗内存最多的进程:"
ps auxf |sort -nr -k 4 |head -5
echo "=============================dividing line================================"
echo  "环境变量:"
env
echo "=============================dividing line================================"
echo  "路由表:"
route -n
echo "=============================dividing line================================"
echo  "监听端口:"
netstat -tunlp
echo "=============================dividing line================================"
echo  "当前建立的连接:"
netstat -n | awk '/^tcp/ {  S[$NF]} END {for(a in S) print a, S[a]}'
echo "=============================dividing line================================"
echo "开机启动的服务:"
systemctl list-unit-files | grep enabled
echo " "
echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>系统用户情况<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
echo  "活动用户:"
w | tail -n  2
echo "=============================dividing line================================"
echo  "系统所有用户:"
cut -d: -f1,2,3,4 /etc/passwd
echo "=============================dividing line================================"
echo  "系统所有组:"
cut -d: -f1,2,3 /etc/group
echo "=============================dividing line================================"
echo  "当前用户的计划任务:"
crontab -l
echo " "
echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>身份鉴别安全<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
grep -i "^password.*requisite.*pam_cracklib.so" /etc/pam.d/system-auth  > /dev/null
if [ $? == 0 ];then
    echo ">>>密码复杂度:已设置"
else
    grep -i "pam_pwquality.so" /etc/pam.d/system-auth > /dev/null
    if [ $? == 0 ];then
	echo ">>>密码复杂度:已设置"
    else
	echo ">>>密码复杂度:未设置,请加固密码--------[需调整]"
    fi
fi
echo "=============================dividing line================================"
awk -F":" '{if($2!~/^!|^*/){print ">>>("$1")" " 是一个未被锁定的账户,请管理员检查是否是可疑账户--------[需调整]"}}' /etc/shadow
echo "=============================dividing line================================"
more /etc/login.defs | grep -E "PASS_MAX_DAYS" | grep -v "#" |awk -F' '  '{if($2!=90){print ">>>密码过期天数是"$2"天,请管理员改成90天------[需调整]"}}'
echo "=============================dividing line================================"
grep -i "^auth.*required.*pam_tally2.so.*$" /etc/pam.d/sshd  > /dev/null
if [ $? == 0 ];then
  echo ">>>登入失败处理:已开启"
else
  echo ">>>登入失败处理:未开启,请加固登入失败锁定功能----------[需调整]"
fi
echo " "
echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>访问控制安全<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
echo "系统中存在以下非系统默认用户:"
more /etc/passwd |awk -F ":" '{if($3>500){print ">>>/etc/passwd里面的"$1 "的UID为"$3",该账户非系统默认账户,请管理员确认是否为可疑账户--------[需调整]"}}'
echo "=============================dividing line================================"
echo "系统特权用户:"
awk -F: '$3==0 {print $1}' /etc/passwd
echo "=============================dividing line================================"
echo "系统中空口令账户:"
awk -F: '($2=="!!") {print $1"该账户为空口令账户,请管理员确认是否为新增账户,如果为新建账户,请配置密码-------[需调整]"}' /etc/shadow
echo " "
echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>安全审计<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
echo "正常情况下登录到本机30天内的所有用户的历史记录:"
last | head -n 30
echo "=============================dividing line================================"
echo "查看syslog日志审计服务是否开启:"
if service rsyslog status | egrep " active (running";then
  echo ">>>经分析,syslog服务已开启"
else
  echo ">>>经分析,syslog服务未开启,建议通过service rsyslog start开启日志审计功能---------[需调整]"
fi
echo "=============================dividing line================================"
echo "查看syslog日志是否开启外发:"
if more /etc/rsyslog.conf | egrep "@....|@...|@..|*.* @....|*.* @...|*.* @..";then
  echo ">>>经分析,客户端syslog日志已开启外发--------[需调整]"
else
  echo ">>>经分析,客户端syslog日志未开启外发---------[无需调整]"
fi
echo "=============================dividing line================================"
echo "审计的要素和审计日志:"
more /etc/rsyslog.conf  | grep -v "^[$|#]" | grep -v "^$"
echo "=============================dividing line================================"
echo "系统中关键文件修改时间:"
ls -ltr /bin/ls /bin/login /etc/passwd  /bin/ps /etc/shadow|awk '{print ">>>文件名:"$9"  ""最后修改时间:"$6" "$7" "$8}'
echo "
###############################################################################################
#   ls文件:是存储ls命令的功能函数,被删除以后,就无法执行ls命令                                 #
#   login文件:login是控制用户登录的文件,一旦被篡改或删除,系统将无法切换用户或登陆用户         #
#   /etc/passwd是一个文件,主要是保存用户信息                                                  #
#   /bin/ps 进程查看命令功能支持文件,文件损坏或被更改后,无法正常使用ps命令                    #
#   /etc/shadow是/etc/passwd的影子文件,密码存放在该文件当中,并且只有root用户可读              #
###############################################################################################"
echo "=============================dividing line================================"
echo "检查重要日志文件是否存在:"
log_secure=/var/log/secure
log_messages=/var/log/messages
log_cron=/var/log/cron
log_boot=/var/log/boot.log
log_dmesg=/var/log/dmesg
if [ -e "$log_secure" ]; then
  echo  ">>>/var/log/secure日志文件存在"
else
  echo  ">>>/var/log/secure日志文件不存在------[需调整]"
fi
if [ -e "$log_messages" ]; then
  echo  ">>>/var/log/messages日志文件存在"
else
  echo  ">>>/var/log/messages日志文件不存在------[需调整]"
fi
if [ -e "$log_cron" ]; then
  echo  ">>>/var/log/cron日志文件存在"
else
  echo  ">>>/var/log/cron日志文件不存在--------[需调整]"
fi
if [ -e "$log_boot" ]; then
  echo  ">>>/var/log/boot.log日志文件存在"
else
  echo  ">>>/var/log/boot.log日志文件不存在--------[需调整]"
fi
if [ -e "$log_dmesg" ]; then
  echo  ">>>/var/log/dmesg日志文件存在"
else
  echo  ">>>/var/log/dmesg日志文件不存在--------[需调整]"
fi
echo " "
echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>剩余信息保护<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
echo "分区情况:"
echo "如果磁盘空间利用率过高,请及时调整---------[需调整]"
df -h
echo "=============================dividing line================================"
echo "可用块设备信息:"
lsblk
echo "=============================dividing line================================"
echo "文件系统信息:"
more /etc/fstab  | grep -v "^#" | grep -v "^$"
echo " "
echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入侵防范安全<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
echo "系统入侵行为:"
more /var/log/secure |grep refused
if [ $? == 0 ];then
    echo "有入侵行为,请分析处理--------[需调整]"
else
    echo ">>>无入侵行为"
fi
echo "=============================dividing line================================"
echo "用户错误登入列表:"
lastb | head > /dev/null
if [ $? == 1 ];then
    echo ">>>无用户错误登入列表"
else
    echo ">>>用户错误登入--------[需调整]"
    lastb | head 
fi
echo "=============================dividing line================================"
echo "ssh暴力登入信息:"
more /var/log/secure | grep  "Failed" > /dev/null
if [ $? == 1 ];then
    echo ">>>无ssh暴力登入信息"
else
    more /var/log/secure|awk '/Failed/{print $(NF-3)}'|sort|uniq -c|awk '{print ">>>登入失败的IP和尝试次数: "$2"="$1"次---------[需调整]";}'
fi
echo " "
echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>恶意代码防范<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
echo "检查是否安装病毒软件:"
crontab -l | grep clamscan.sh > /dev/null
if [ $? == 0 ];then
  echo ">>>已安装ClamAV杀毒软件"
  crontab -l | grep freshclam.sh > /dev/null
  if [ $? == 0 ];then
    echo ">>>已部署定时更新病毒库"
  fi
else
  echo ">>>未安装ClamAV杀毒软件,请部署杀毒软件加固主机防护--------[无需调整]"
fi
echo " "
echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>资源控制安全<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
echo "查看是否开启了xinetd服务:"
if ps -elf |grep xinet |grep -v "grep xinet";then
  echo ">>>xinetd服务正在运行,请检查是否可以把xinetd服务关闭--------[无需调整]"
else
  echo ">>>xinetd服务未开启-------[无需调整]"
fi
echo "=============================dividing line================================"
echo  "查看是否开启了ssh服务:"
if service sshd status | grep -E "listening on|active (running)"; then
  echo ">>>SSH服务已开启"
else
  echo ">>>SSH服务未开启--------[需调整]"
fi
echo "=============================dividing line================================"
echo "查看是否开启了Telnet-Server服务:"
if more /etc/xinetd.d/telnetd 2>&1|grep -E "disable=no"; then
  echo ">>>Telnet-Server服务已开启"
else
  echo ">>>Telnet-Server服务未开启--------[无需调整]"
fi
echo "=============================dividing line================================"
ps axu | grep iptables | grep -v grep || ps axu | grep firewalld | grep -v grep 
if [ $? == 0 ];then
  echo ">>>防火墙已启用"
iptables -nvL --line-numbers
else
  echo ">>>防火墙未启用--------[需调整]"
fi
echo "=============================dividing line================================"
echo  "查看系统SSH远程访问设置策略(host.deny拒绝列表):"
if more /etc/hosts.deny | grep -E "sshd"; then
  echo ">>>远程访问策略已设置--------[需调整]"
else
  echo ">>>远程访问策略未设置--------[无需调整]"
fi
echo "=============================dividing line================================"
echo "查看系统SSH远程访问设置策略(hosts.allow允许列表):"
if more /etc/hosts.allow | grep -E "sshd"; then
  echo ">>>远程访问策略已设置--------[需调整]"
else
  echo ">>>远程访问策略未设置--------[无需调整]"
fi
echo "=============================dividing line================================"
echo "当hosts.allow和host.deny相冲突时,以hosts.allow设置为准"
echo "=============================dividing line================================"
grep -i "TMOUT" /etc/profile /etc/bashrc
if [ $? == 0 ];then
    echo ">>>已设置登入超时限制"
else
    echo ">>>未设置登入超时限制,请设置,设置方法:在/etc/profile或者/etc/bashrc里面添加参数TMOUT=600 --------[需调整]"
fi
echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>end<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"

# 主机初始化脚本

代码语言:javascript复制
#!/usr/bin/env bash
#

export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin

RGB_DANGER='33[31;1m'
RGB_WAIT='33[37;2m'
RGB_SUCCESS='33[32m'
RGB_WARNING='33[33;1m'
RGB_INFO='33[36;1m'
RGB_END='33[0m'

CHECK_CENTOS=$( cat /etc/redhat-release|sed -r 's/.* ([0-9] )..*/1/' )
CHECK_RAM=$( cat /proc/meminfo | grep "MemTotal" | awk -F" " '{ram=$2/1000000}{printf("%.0f",ram)}' )

LOCK=/var/log/init_centos7_record.log

tool_info() {
    echo -e "========================================================================================="
    echo -e "                              Init CentOS 7 Script                                       "
    echo -e "========================================================================================="
}

check_root(){
    if [[ $EUID -ne 0 ]]; then
        echo -e "${RGB_DANGER}This script must be run as root!${RGB_END}"
        exit 1
    fi
}

check_lock() {
    if [ ! -f "$LOCK" ];then
        touch $LOCK
    else
        echo -e "${RGB_DANGER}Detects that the initialization is complete and does not need to be initialized any further!${RGB_END}"
        exit 1
    fi
}

check_os() {
    if [ "${CHECK_CENTOS}" != '7' ]; then
        echo -e "${RGB_DANGER}This script must be run in CentOS 7!${RGB_END}"
        exit 1
    fi
}




function remote_login(){
    echo "#########################################################################################"
    echo -e "33[1;31m	   4、Set Remote Login Configuration(SSH)	33[0m"
    echo "#########################################################################################"
#set Protocol 2
    echo >> /etc/ssh/sshd_config
    grep -i '^Protocol' /etc/ssh/sshd_config > /dev/null
    if [ $? == 0 ];then
        sed -i 's/^Protocol.*$/Protocol 2/g' /etc/ssh/sshd_config
        if [ $? != 0 ];then
            echo -e "33[31;5m	    [##Error##]: Cannot to set Protocol to '2'	    33[0m"
        else
            echo -e "33[37;5m	    [Success: Set SSH Protocol to 2]	    33[0m"
         fi
    else
        echo 'Protocol 2' >> /etc/ssh/sshd_config
        echo -e "33[37;5m	    [Success: Set SSH Protocol to 2]	    33[0m"
    fi
    
	grep -i '^PermitRootLogin no' /etc/ssh/sshd_config > /dev/null
	if [ $? == 1 ];then
            grep -i '.*PermitRootLogin yes' /etc/ssh/sshd_config >/dev/null
            if [ $? == 0 ];then
                sed -i 's/.*PermitRootLogin yes/PermitRootLogin no/g' /etc/ssh/sshd_config
                if [ $? != 0 ];then
                    echo -e "33[31;5m	[##Error##]cannot to set PermitRootLogin to 'no'	33[0m"
                else
        	    echo -e "33[37;5m	    Disable root remote login[Success]	    33[0m"
        	    restart_flag=0
                fi
            else
                echo 'PermitRootLogin no' >> /etc/ssh/sshd_config
        	echo -e "33[37;5m	    Disable root remote login[Success]	    33[0m"
                restart_flag=0
            fi
	else
	    echo -e "33[37;5m	    Already disable root remote login	33[0m"
	fi
}





function create_user(){
    echo "#########################################################################################"
    echo -e "33[1;31m	   3、Create openroot account	33[0m"
    echo "#########################################################################################"
    read -p "Be sure to create an openroot account?[y/n]:"
    case $REPLY in 
    y)
	grep -i 'openroot' /etc/passwd
        if [ $? == 0 ];then
	    echo -e "33[1;31m		An openroot account has been created	33[0m"
        else
	    read -p "Please enter your password:" PASSWD
	    useradd -g root openroot;echo "$PASSWD" | passwd --stdin openroot  > /dev/null
	    if [ $? == 0 ];then
		echo -e "33[1;31m	openroot account created successfully	    33[0m"
		grep -i "openroot" /etc/sudoers
		if [ $? != 0 ];then
		    chmod u w /etc/sudoers > /dev/null 
		    sed -i '/^root.*ALL=(ALL).*$/aopenroot  ALL=(ALL)       NOPASSWD:ALL' /etc/sudoers > /dev/null
		    if [ $? == 0 ];then
			echo -e "33[37;5m	    [Permissions set success]	33[0m"
		    else
			echo -e "33[31;5m	    [Permissions set failed]	33[0m"
		    fi
		    chmod u-w /etc/sudoers > /dev/null 
		else
		    echo -e "33[1;31m	    Permissions have already been set	    33[0m"
		fi
	    else
		echo -e "33[1;31m	    openroot account created failed	    33[0m"
		exit 1 
	    fi
	fi
	;;
    n)
	;;
    *)
	create_user
    esac
}





###########################文件备份############################
function backup(){
if [ ! -x "backup" ]; then
    mkdir backup
    if [ -f /etc/pam.d/system-auth ];then
        cp /etc/pam.d/system-auth backup/system-auth.bak
    elif [ -f /etc/pam.d/common-password ];then
        cp /etc/pam.d/common-password backup/common-password.bak
    fi
    if [ -f ~/.ssh/authorized_keys ];then
        cp ~/.ssh/authorized_keys backup/authorized_keys.bak
    fi
    cp /etc/pam.d/sshd backup/sshd.bak
    cp /etc/sudoers backup/sudoers.bak
    cp /etc/ssh/sshd_config backup/sshd_config.bak
    cp /etc/profile backup/profile.bak
    cp /etc/pam.d/su backup/su.bak
    cp /etc/security/limits.conf backup/limits.conf.bak
    cp /etc/sysctl.conf  backup/sysctl.conf.bak
    cp /etc/login.defs backup/login.defs.bak
    echo -e "###########################################################################################"
    echo -e "33[1;31m     Auto backup successfully        33[0m"
    echo -e "###########################################################################################"
else
    echo -e "###########################################################################################"
    echo -e "33[1;31mBackup file already exist, to avoid overwriting these files, backup will not perform again33[0m "
    echo -e "###########################################################################################"
fi
}
###########################执行备份############################

###########################文件还原############################
function recover(){
if [ -f backup/system-auth.bak ];then
    cp -rf backup/system-auth.bak /etc/pam.d/system-auth
elif [ -f backup/common-password.bak ];then
    cp -rf backup/common-password.bak /etc/pam.d/common-password
fi
if [ -f backup/authorized_keys.bak ];then
    cp -rf backup/authorized_keys.bak ~/.ssh/authorized_keys
fi
    cp -rf backup/sshd.bak /etc/pam.d/sshd
    cp -rf backup/sudoers.bak /etc/sudoers
    cp -rf backup/sshd_config.bak /etc/ssh/sshd_config
    cp -rf backup/profile.bak /etc/profile
    cp -rf backup/limits.conf.bak /etc/security/limits.conf
    cp -rf backup/sysctl.conf.bak /etc/sysctl.conf 
    cp -rf backup/login.defs.bak /etc/login.defs
    source /etc/profile
    cp -rf backup/su.bak /etc/pam.d/su
    restart_flag=0
    echo -e "33[1;31m    8、 Recover success  33[0m"
}




new_swap() {
    echo "============= swap =============" >> ${LOCK} 2>&1
    if [ "${CHECK_RAM}" -le '2' ]; then
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    dd if=/dev/zero of=/swapfile bs=1024 count=1048576 >> ${LOCK} 2>&1
    chmod 600 /swapfile >> ${LOCK} 2>&1
    mkswap /swapfile >> ${LOCK} 2>&1
    swapon /swapfile >> ${LOCK} 2>&1
    echo '/swapfile swap swap defaults 0 0' >> /etc/fstab
    echo '# Swap' >> /etc/sysctl.conf
    echo 'vm.swappiness = 10' >> /etc/sysctl.conf
    sysctl -p >> ${LOCK} 2>&1
    sysctl -n vm.swappiness >> ${LOCK} 2>&1
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"
    else
    echo -e "${RGB_SUCCESS}Skip, no configuration needed${RGB_END}"
    fi
}

open_bbr() {
    echo "============= bbr =============" >> ${LOCK} 2>&1
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    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 >> ${LOCK} 2>&1
    sysctl -n net.ipv4.tcp_congestion_control >> ${LOCK} 2>&1
    lsmod | grep bbr >> ${LOCK} 2>&1
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"
}

disable_software() {
    echo "============= selinux firewalld =============" >> ${LOCK} 2>&1
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    setenforce 0 >> ${LOCK} 2>&1
    sed -i 's/^SELINUX=.*$/SELINUX=disabled/' /etc/selinux/config
    systemctl disable firewalld.service >> ${LOCK} 2>&1
 systemctl stop firewalld.service >> ${LOCK} 2>&1
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"
}

time_zone() {
    echo "============= time zone =============" >> ${LOCK} 2>&1
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    rm -rf /etc/localtime >> ${LOCK} 2>&1
    ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime >> ${LOCK} 2>&1
    ls -ln /etc/localtime >> ${LOCK} 2>&1
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"
}

custom_profile() {
    echo "============= custom profile =============" >> ${LOCK} 2>&1
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    cat > /etc/profile.d/centos7init.sh << EOF
PS1="[e[37;40m][[e[32;40m]u[e[37;40m]@h [e[35;40m]W[e[0m]]\\$ "
GREP_OPTIONS="--color=auto"
alias l='ls -AFhlt'
alias grep='grep --color'
alias egrep='egrep --color'
alias fgrep='fgrep --color'
export HISTTIMEFORMAT="%Y-%m-%d %H:%M:%S  "
EOF
    cat /etc/profile.d/centos7init.sh >> ${LOCK} 2>&1
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"
}

adjust_ulimit() {
    echo "============= adjust ulimit =============" >> ${LOCK} 2>&1
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    sed -i '/^# End of file/,$d' /etc/security/limits.conf
    cat >> /etc/security/limits.conf <<EOF
# End of file
* soft core unlimited
* hard core unlimited
* soft nproc 1000000
* hard nproc 1000000
* soft nofile 1000000
* hard nofile 1000000
root soft core unlimited
root hard core unlimited
root soft nproc 1000000
root hard nproc 1000000
root soft nofile 1000000
root hard nofile 1000000
EOF
    cat /etc/security/limits.conf >> ${LOCK} 2>&1
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"
}

kernel_optimum() {
    echo "============= kernel optimum =============" >> ${LOCK} 2>&1
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    [ ! -e "/etc/sysctl.conf_bak" ] && /bin/mv /etc/sysctl.conf{,_bak}
    cat > /etc/sysctl.conf << EOF
# Controls source route verification
net.ipv4.conf.default.rp_filter = 1
net.ipv4.ip_nonlocal_bind = 1
net.ipv4.ip_forward = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.accept_source_route = 0 
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.conf.all.log_martians = 1 
net.ipv4.conf.default.log_martians = 1
net.ipv4.conf.all.promote_secondaries = 1
net.ipv4.conf.default.promote_secondaries = 1

# Controls the use of TCP syncookies
# Number of pid_max
kernel.core_uses_pid = 1
kernel.pid_max = 1000000
net.ipv4.tcp_syncookies = 1

# Controls the maximum size of a message, in bytes
# Controls the default maxmimum size of a mesage queue
# Controls the maximum shared segment size, in bytes
# Controls the maximum number of shared memory segments, in pages
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
kernel.sysrq = 1
kernel.softlockup_panic = 1
kernel.printk = 5

# TCP kernel paramater
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_rmem = 4096 87380 4194304
net.ipv4.tcp_wmem = 4096 16384 4194304
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_sack = 1

# Socket buffer
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.netdev_max_backlog = 32768
net.core.somaxconn = 65535
net.core.optmem_max = 81920

# TCP conn
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_retries1 = 3
net.ipv4.tcp_retries2 = 15

# TCP conn reuse
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 5
net.ipv4.tcp_max_tw_buckets = 7000
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.tcp_synack_retries = 1

# keepalive conn
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.ip_local_port_range = 1024 65535

net.ipv6.neigh.default.gc_thresh3 = 4096
net.ipv4.neigh.default.gc_thresh3 = 4096
EOF
    sysctl -p >> ${LOCK} 2>&1
    cat /etc/sysctl.conf >> ${LOCK} 2>&1
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"
}


updatedb_optimum() {
    echo "============= updatedb optimum =============" >> ${LOCK} 2>&1
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    sed -i 's,media,media /data,' /etc/updatedb.conf
    cat /etc/updatedb.conf >> ${LOCK} 2>&1
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"
}

open_ipv6() {
    echo "============= open ipv6 =============" >> ${LOCK} 2>&1
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    echo '# IPV6' >> /etc/sysctl.conf
    echo 'net.ipv6.conf.all.disable_ipv6=0' >> /etc/sysctl.conf
    echo 'net.ipv6.conf.default.disable_ipv6=0' >> /etc/sysctl.conf
    echo 'net.ipv6.conf.lo.disable_ipv6=0' >> /etc/sysctl.conf
    sysctl -p >> ${LOCK} 2>&1
    cat /etc/sysctl.conf >> ${LOCK} 2>&1
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"
}

disable_cad() {
    echo "============= disable cad =============" >> ${LOCK} 2>&1
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    systemctl mask ctrl-alt-del.target >> ${LOCK} 2>&1
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"
}

remove_users() {
    echo "============= remove users =============" >> ${LOCK} 2>&1
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    for u in adm lp sync shutdown halt mail operator games ftp 
    do
    userdel ${u} >> ${LOCK} 2>&1
    done
    cut -d : -f 1 /etc/passwd >> ${LOCK} 2>&1
    for g in adm lp mail games ftp 
    do
    groupdel ${g} >> ${LOCK} 2>&1
    done
    cat /etc/group >> ${LOCK} 2>&1
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"
}

sys_permissions() {
    echo "============= sys permissions =============" >> ${LOCK} 2>&1
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    chmod 644 /etc/passwd >> ${LOCK} 2>&1
    chmod 644 /etc/group >> ${LOCK} 2>&1
    chmod 000 /etc/shadow >> ${LOCK} 2>&1
    chmod 000 /etc/gshadow >> ${LOCK} 2>&1
    ls -la /etc/passwd >> ${LOCK} 2>&1
    ls -la /etc/group >> ${LOCK} 2>&1
    ls -la /etc/shadow >> ${LOCK} 2>&1
    ls -la /etc/gshadow >> ${LOCK} 2>&1
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"
}

password_policy() {
    echo "============= password policy =============" >> ${LOCK} 2>&1
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    sed -i 's/^PASS_MAX_DAYS.*$/PASS_MAX_DAYS   90/' /etc/login.defs
    sed -i 's/^PASS_MIN_DAYS.*$/PASS_MIN_DAYS   10/' /etc/login.defs
    cat /etc/login.defs >> ${LOCK} 2>&1
    cat >>/etc/security/pwquality.conf << EOF
minlen = 8 
dcredit = -1
ucredit = -1
ocredit = -1
lcredit = -1
EOF
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"
}

change_useradd() {
    echo "============= change useradd =============" >> ${LOCK} 2>&1
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    sed -i 's/^INACTIVE.*$/INACTIVE=180/' /etc/default/useradd
    cat /etc/default/useradd >> ${LOCK} 2>&1
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"
}

sec_ssh() {
    echo "============= sec ssh =============" >> ${LOCK} 2>&1
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    sed -i 's/UseDNS.*$/UseDNS no/' /etc/ssh/sshd_config
    sed -i 's/^#LoginGraceTime.*$/LoginGraceTime 60/' /etc/ssh/sshd_config
    sed -i 's/^#PermitEmptyPasswords.*$/PermitEmptyPasswords no/' /etc/ssh/sshd_config
    sed -i 's/^#PubkeyAuthentication.*$/PubkeyAuthentication yes/' /etc/ssh/sshd_config
    sed -i 's/^#MaxAuthTries.*$/MaxAuthTries 3/' /etc/ssh/sshd_config
    sed -i "s/#ClientAliveInterval 0/ClientAliveInterval 300/g" /etc/ssh/sshd_config 
    sed -i "s/#ClientAliveCountMax 3/ClientAliveCountMax 3/g" /etc/ssh/sshd_config
    sed -i "s/X11Forwarding yes/X11Forwarding no/g" /etc/ssh/sshd_config
    sed -i "s/#Banner none/Banner /etc/issue.net/g" /etc/ssh/sshd_config
    echo "Authorized users only. All activity may be monitored and reported.">/etc/issue.net
    systemctl restart sshd.service >> ${LOCK} 2>&1
    cat /etc/ssh/sshd_config >> ${LOCK} 2>&1
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"
}

timeout_config() {
    echo "============= timeout config =============" >> ${LOCK} 2>&1
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    echo "export TMOUT=1800" >> /etc/profile.d/centos7init.sh
    cat /etc/profile.d/centos7init.sh >> ${LOCK} 2>&1
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"

}






#######################配置系统历史命令操作记录和定时帐户自动登出时间################################
function set_history_tmout(){
    echo "#########################################################################################"
    echo -e "33[1;31m	    5、set history and timeout	33[0m"
    echo "#########################################################################################"



	#history_size
        grep -i "^HISTSIZE=" /etc/profile >/dev/null
        if [ $? == 0 ];then
	#history记录保留一万条
            sed -i "s/^HISTSIZE=.*$/HISTSIZE=10000/g" /etc/profile
        else
            echo 'HISTSIZE=10000' >> /etc/profile
        fi
        echo -e "33[1;31m	    HISTSIZE has been set to 10000	    33[0m"
	#history_format
        grep -i "^export HISTTIMEFORMAT=" /etc/profile > /dev/null
        if [ $? == 0 ];then
            sed -i 's/^export HISTTIMEFORMAT=.*$/export HISTTIMEFORMAT="%F %T `whoami`"/g' /etc/profile
        else
            echo 'export HISTTIMEFORMAT="%F %T `whoami` "' >> /etc/profile
        fi
        echo -e '33[1;31m	    HISTTIMEFORMAT has been set to "Number-Time-User-Command"	    33[0m'
	#TIME_OUT
        #read -p "set shell TMOUT?[300-600]seconds:" tmout 
	#: ${tmout:=600}
        grep -i "^TMOUT=" /etc/profile	> /dev/null
        if [ $? == 0 ];then
            sed -i "s/^TMOUT=.*$/TMOUT=600/g" /etc/profile
        else
            echo "TMOUT=600" >> /etc/profile
        fi
        source /etc/profile
	echo -e "33[37;5m	    [Success]	    33[0m"

}



lockout_policy() {
    echo "============= lockout policy =============" >> ${LOCK} 2>&1
    echo -en "${RGB_WAIT}Configuring...${RGB_END}"
    [ ! -e "/etc/pam.d/system-auth_bak" ] && /bin/mv /etc/pam.d/system-auth{,_bak}
    cat > /etc/pam.d/system-auth << EOF
auth        required                                     pam_env.so
auth        required                                     pam_faillock.so preauth silent audit deny=3 unlock_time=900
auth        required                                     pam_faildelay.so delay=2000000
auth        [default=1 ignore=ignore success=ok]         pam_succeed_if.so uid >= 1000 quiet
auth        [default=1 ignore=ignore success=ok]         pam_localuser.so
auth        sufficient                                   pam_unix.so nullok try_first_pass
auth        [default=die]                                pam_faillock.so  authfail  audit  deny=3  unlock_time=900
auth        requisite                                    pam_succeed_if.so uid >= 1000 quiet_success
auth        sufficient                                   pam_sss.so forward_pass
auth        required                                     pam_deny.so

account     required                                     pam_unix.so
account     sufficient                                   pam_localuser.so
account     sufficient                                   pam_succeed_if.so uid < 1000 quiet
account     [default=bad success=ok user_unknown=ignore] pam_sss.so
account     required                                     pam_permit.so
account     required                                     pam_faillock.so

password    requisite                                    pam_pwquality.so try_first_pass local_users_only
password    sufficient                                   pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    sufficient                                   pam_sss.so use_authtok
password    required                                     pam_deny.so

session     optional                                     pam_keyinit.so revoke
session     required                                     pam_limits.so
-session    optional                                     pam_systemd.so
session     [success=1 default=ignore]                   pam_succeed_if.so service in crond quiet use_uid
session     required                                     pam_unix.so
session     optional                                     pam_sss.so
EOF
    [ ! -e "/etc/pam.d/password-auth_bak" ] && /bin/mv /etc/pam.d/password-auth{,_bak}
    cat > /etc/pam.d/password-auth << EOF
auth        required                                     pam_env.so
auth        required                                     pam_faillock.so preauth silent audit deny=3 unlock_time=900
auth        required                                     pam_faildelay.so delay=2000000
auth        [default=1 ignore=ignore success=ok]         pam_succeed_if.so uid >= 1000 quiet
auth        [default=1 ignore=ignore success=ok]         pam_localuser.so
auth        sufficient                                   pam_unix.so nullok try_first_pass
auth        [default=die]                                pam_faillock.so  authfail  audit  deny=3  unlock_time=900
auth        requisite                                    pam_succeed_if.so uid >= 1000 quiet_success
auth        sufficient                                   pam_sss.so forward_pass
auth        required                                     pam_deny.so

account     required                                     pam_unix.so
account     sufficient                                   pam_localuser.so
account     sufficient                                   pam_succeed_if.so uid < 1000 quiet
account     [default=bad success=ok user_unknown=ignore] pam_sss.so
account     required                                     pam_permit.so
account     required                                     pam_faillock.so

password    requisite                                    pam_pwquality.so try_first_pass local_users_only
password    sufficient                                   pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    sufficient                                   pam_sss.so use_authtok
password    required                                     pam_deny.so

session     optional                                     pam_keyinit.so revoke
session     required                                     pam_limits.so
-session    optional                                     pam_systemd.so
session     [success=1 default=ignore]                   pam_succeed_if.so service in crond quiet use_uid
session     required                                     pam_unix.so
session     optional                                     pam_sss.so
EOF
    systemctl restart sshd.service >> ${LOCK} 2>&1
    cat /etc/pam.d/etc/pam.d/system-auth >> ${LOCK} 2>&1
    cat /etc/pam.d/password-auth >> ${LOCK} 2>&1
    echo -e "r${RGB_SUCCESS}Configuration Success${RGB_END}"
}


#reboot_os() {
#    echo -e "n${RGB_WARNING}Please restart the server and see if the services start up fine.${RGB_END}"
#    echo -en "${RGB_WARNING}Do you want to restart OS ? [y/n]: ${RGB_END}"
#    while :; do
#        read REBOOT_STATUS
#        if [[ ! "${REBOOT_STATUS}" =~ ^[y,n]$ ]]; then
#            echo -en "${RGB_DANGER}Input error, please only input 'y' or 'n': ${RGB_END}"
#        else
#            break
#        fi
#    done
#    [ "${REBOOT_STATUS}" == 'y' ] && reboot
#}

main() {
    echo -e "n${RGB_INFO}1/18 : Start Init CentOS7 Script ${RGB_END}"

    echo -e "n${RGB_INFO}2/18 : Customize the profile (color and alias)${RGB_END}"
    custom_profile

    echo -e "n${RGB_INFO}3/18 : Time zone adjustment${RGB_END}"
#    time_zone

    echo -e "n${RGB_INFO}4/18 : Disable selinux and firewalld${RGB_END}"
#    disable_software

    echo -e "n${RGB_INFO}5/18 : Disable Ctrl Alt Del${RGB_END}"
    disable_cad

    echo -e "n${RGB_INFO}6/18 : Kernel parameter optimization${RGB_END}"
   # kernel_optimum

    echo -e "n${RGB_INFO}7/18 : The updatedb optimization${RGB_END}"
    updatedb_optimum

    echo -e "n${RGB_INFO}8/18 : Adding swap space${RGB_END}"
   # new_swap

    echo -e "n${RGB_INFO}9/18 : Adjustment of ulimit${RGB_END}"
    adjust_ulimit
    
    echo -e "n${RGB_INFO}10/18 : Enable tcp bbr congestion control algorithm${RGB_END}"
    #open_bbr

    echo -e "n${RGB_INFO}11/18 : Enable IPV6${RGB_END}"
    #open_ipv6

    echo -e "n${RGB_INFO}12/18 : Remove unnecessary users and user groups from the system${RGB_END}"
    remove_users

    echo -e "n${RGB_INFO}13/18 : System permissions for sensitive files${RGB_END}"
    sys_permissions

    echo -e "n${RGB_INFO}14/18 : Modify Account Password Survival Policy${RGB_END}"
    password_policy

    echo -e "n${RGB_INFO}15/18 : Maximum number of days an account is valid after password expiration strategy${RGB_END}"
#    change_useradd

    echo -e "n${RGB_INFO}16/18 : Secure configuration of SSH${RGB_END}"
    sec_ssh
    remote_login
    #create_user

    echo -e "n${RGB_INFO}17/18 : Timeout Auto-Logout Configuration${RGB_END}"
    #timeout_config
    set_history_tmout

    echo -e "n${RGB_INFO}18/18 : Configure account login failure lockout policy${RGB_END}"
    lockout_policy


}

#clear

case $1 in
     all)
        backup
	tool_info
	check_root
	check_os
#	check_lock
     	main
      	 ;;

     recover)
     	 recover
     	 ;;
     *)
      echo "输入错误"
esac

0 人点赞