#!/bin/sh

#检测系统版本
os_check=`cat /etc/redhat-release | awk -F '.' '{print $1}' | awk '{print $NF}'`

#获取服务器内网信息
host_ip=`ip ad | grep eth0 | grep inet |awk '{print $2}' | awk  -F '/' '{print $1}'`



# 如果已安装selinux则禁用
disable_selinux() {
    [ -f /etc/selinux/config ] && sed  -i 's/^SELINUX=.*/SELINUX=disabled/g' /etc/selinux/config && echo "--------禁用selinux完成--------" &&  setenforce 0
}

group=$1
host_name=$2

#下面是针对阿里云6系统的yum源做的特殊处理办法，镜像里已带云上推荐的6yum源，带上系统自带的yum源无法通过yum下载资源。
if [[ $host_ip == 10.11.* ]] && [[ $os_check == "6" ]];then
    rm -f /etc/yum.repos.d/{CentOS-Base.repo,epel.repo} 
fi

mkdir -p /usr/local/elves-agent/apps

#修改ssh默认登录端口为63008
ssh_port_fun(){

    cat /etc/ssh/sshd_config|grep '^ListenAddress 0.0.0.0' >/dev/null 2>&1
    if [[ $? -eq 0 ]];then
        /bin/sed -i 's/ListenAddress 0.0.0.0:/Port /g' /etc/ssh/sshd_config
    fi
    cat /etc/ssh/sshd_config|grep '^ListenAddress' >/dev/null 2>&1
    if [[ $? -eq 0 ]];then
        echo "please add # before ListenAddress"
        return 1
    fi
    cat /etc/ssh/sshd_config|grep '^Port 63008' >/dev/null 2>&1
    if [[ $? -ne 0 ]];then
        sed -i '$a Port 63008' /etc/ssh/sshd_config   
    fi
    cat /etc/ssh/sshd_config|grep '#ListenAddress 10.53.69.13' >/dev/null 2>&1
    if [[ $? -eq 0 ]];then
        /bin/sed -i 's/#Port 22/Port 63008/g' /etc/ssh/sshd_config
    fi
    if [[ $os_check == "7" ]];then
        /usr/bin/systemctl restart sshd.service >/dev/null 2>&1
    elif [[ $os_check == "6" ]];then
        /etc/init.d/sshd restart >/dev/null 2>&1
    fi
    echo "--------ssh端口修改完成--------"
sleep 1
}

#修改sshdns
ssh_dns_fun(){

    cat /etc/ssh/sshd_config|grep '^UseDNS no' >/dev/null 2>&1
    if [[ $? -ne 0 ]];then
        sed -i '$a UseDNS no' /etc/ssh/sshd_config
    else
        /bin/sed -i '/^UseDNS/d' /etc/ssh/sshd_config
        sed -i '$a UseDNS no' /etc/ssh/sshd_config
    fi
    if [[ $os_check == "7" ]];then
        /usr/bin/systemctl restart sshd.service >/dev/null 2>&1
    elif [[ $os_check == "6" ]];then
        /etc/init.d/sshd restart >/dev/null 2>&1
    fi 

	nuber=`cat  /etc/ssh/sshd_config  | grep '#PermitEmptyPasswords' |wc -l`
	if [[ $nuber -eq 1 ]];then
        sed -i '/#PermitEmptyPasswords no/d' /etc/ssh/sshd_config 
		echo 'PermitEmptyPasswords no' >>  /etc/ssh/sshd_config
	fi
	
    cat /etc/ssh/sshd_config  | grep '#KexAlgorithms'
	if [[ $? -ne 0 ]];then
		sed  -i  '/KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256/d' /etc/ssh/sshd_config
		echo "#KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256" >> /etc/ssh/sshd_config
	fi
    echo "--------sshdns修改完成--------"
sleep 1   
}


#关闭GSS认证，开启会导致登录缓慢。
ssh_auth_fun(){

    cat /etc/ssh/sshd_config|grep '^GSSAPIAuthentication' >/dev/null 2>&1
    if [[ $? -ne 0 ]];then
        sed -i '$a GSSAPIAuthentication no' /etc/ssh/sshd_config
    else
        /bin/sed -i '/^GSSAPIAuthentication/d' /etc/ssh/sshd_config
        sed -i '$a GSSAPIAuthentication no' /etc/ssh/sshd_config       
    fi
    if [[ $os_check == "7" ]];then
        /usr/bin/systemctl restart sshd.service  >/dev/null 2>&1 
    elif [[ $os_check == "6" ]];then
        /etc/init.d/sshd restart >/dev/null 2>&1
    fi
    echo "--------GSS认证修改完成--------"
sleep 3
}


#设置历史命令保留条数
history_num_fun(){

    cat /etc/profile | grep "HISTTIMEFORMAT" >/dev/null 2>&1
    if [[ $? -ne 0 ]];then
        echo -e "USER_IP=\`who -u am i 2>/dev/null| awk '{print \$NF}'|sed -e 's/[()]//g'\`\n\tHISTFILESIZE=4000\n\tHISTSIZE=4000\n\tHISTTIMEFORMAT=\"%F %T \${USER_IP} \`whoami\` \"\nexport HISTTIMEFORMAT" >> /etc/profile
        source /etc/profile
    fi
    echo "--------设置历史命令保留条目--------"
sleep 1
}


#添加堡垒机公钥
jumpserver_fun(){
        mkdir -p /root/.ssh  && touch /root/.ssh/authorized_keys
		echo "ssh-rsa [payload removed: 372 characters] root@jumpserver" >>/root/.ssh/authorized_keys
		echo "ssh-rsa [payload removed: 372 characters] gop@ansible_public_key" >> /root/.ssh/authorized_keys
		chmod 600 /root/.ssh/authorized_keys
		

    echo "--------添加堡垒机公钥--------"
sleep 1
}


#设置十分钟内用户无操作就自动断开终端
timeout_fun(){
    egrep 'TMOUT=[0-9]{3}' /etc/profile >/dev/null 2>&1
    if [[ $? -ne 0 ]];then
        echo "export TMOUT=600" >> /etc/profile
        source /etc/profile
    else
        /bin/sed -i "s/^export TMOUT=.*/export TMOUT=600/1" /etc/profile
        source /etc/profile 
    fi
    egrep 'TMOUT=[0-9]{3}' /etc/bashrc >/dev/null 2>&1
    if [[ $? -ne 0 ]];then
        echo "export TMOUT=600" >> /etc/bashrc
        source /etc/bashrc
    else
        /bin/sed -i "s/^export TMOUT=.*/export TMOUT=600/1" /etc/bashrc
        source /etc/bashrc
    fi
    echo "--------设置用户600秒无操作自动断开--------"
sleep 1  
}



#设置系统dns
dns_fun(){
    idc=`/bin/hostname | awk -F 'M' '{print $1}'`
    if [[ "$host_name" == 'T' ]];then
        echo "" > /etc/resolv.conf 
		echo "nameserver 183.60.83.19" >> /etc/resolv.conf 
		echo "nameserver 183.60.82.98" >> /etc/resolv.conf 
    fi 
	
	if [[ "$host_name" == 'A' ]];then
        echo "" > /etc/resolv.conf 
		echo "nameserver 100.100.2.136" >> /etc/resolv.conf 
		echo "nameserver 100.100.2.138" >> /etc/resolv.conf 
    fi
	
    if [[ $host_ip == 10.12* ]] || [[ $host_ip == 192.168* ]];then
        echo "" > /etc/resolv.conf 
		echo "nameserver 119.29.29.29" >> /etc/resolv.conf 
		echo "nameserver 223.5.5.5" >> /etc/resolv.conf     	
    fi

    chmod 644 /etc/resolv.conf 
    echo "--------设置系统DNS--------"
sleep 1
}


#同步系统时间
ntp_fun(){

if [[ $host_name = P* ]] || [[ $host_name = p* ]] || [[ $host_name = v* ]] || [[ $host_name = V* ]] || [[ $host_name = GY* ]] || [[ $host_name = gy* ]];then
    echo "" > /etc/ntp.conf 
    cat>>/etc/ntp.conf <<EOF
driftfile  /var/lib/ntp/drift
restrict default kod nomodify notrap nopeer noquery
restrict -6 default kod nomodify notrap nopeer noquery
restrict 127.0.0.1 
restrict -6 ::1

server ntp.aliyun.com minpoll minpoll 4 maxpoll 4
server ntp.tencent.com minpoll 4 maxpoll 4
server ntp1.tencent.com minpoll 4 maxpoll 4

server cn.pool.ntp.org minpoll 4 maxpoll 4
server edu.ntp.org.cn minpoll 4 maxpoll 4
server time1.cloud.tencent.com minpoll 4 maxpoll 4
server time2.cloud.tencent.com minpoll 4 maxpoll 4
server ntp1.aliyun.com minpoll 4 maxpoll 4
server ntp2.aliyun.com minpoll 4 maxpoll 4
EOF
    if [[ "$os_check" == "7" ]];then
        /usr/bin/systemctl enable  ntpd >/dev/null 2>&1
        /usr/bin/systemctl restart  ntpd >/dev/null 2>&1
    elif [[ "$os_check" == "6" ]];then
        /sbin/chkconfig ntpd on  >/dev/null 2>&1
        /sbin/service ntpd restart >/dev/null 2>&1       
    fi
    echo "--------设置系统同步时间--------"
fi
sleep 1
}

#内核参数优化
sysctl_fun(){
    sysctl -w net.ipv4.tcp_sack=0 >/dev/null 2>&1
    cat /etc/sysctl.conf | grep "net.ipv4.tcp_sack=0" >/dev/null 2>&1
    if [[ $? -ne 0 ]];then
        echo "net.ipv4.tcp_sack=0" >> /etc/sysctl.conf
    fi 
    echo "--------内核参数优化--------"
sleep 1
}


#清除信息
QingChu() {
    if [[ $host_name = P* ]] || [[ $host_name = p* ]] || [[ $host_name = v* ]] || [[ $host_name = V* ]] || [[ $host_name = GY* ]] || [[ $host_name = gy* ]];then
        rm -f /etc/rc.local 
        ln -s /etc/rc.d/rc.local /etc/rc.local
        chmod +x /etc/rc.d/rc.local
        chmod +x /etc/rc.local
        chmod +s /bin/netstat
        #del histroy
        /bin/echo "" > .bash_history
        #del packages
        cd /root/
        rm -rf  sys_consistency.sh
        echo "--------清除信息--------"
    fi
sleep 1
}

#配置yum源
yum_fun(){
	if [[ $host_name = P* ]] || [[ $host_name = p* ]] || [[ $host_name = v* ]] || [[ $host_name = V* ]] || [[ $host_name = GY* ]] || [[ $host_name = gy* ]];then
	    rm -f /etc/yum.repos.d/gyyx.repo
    	touch /etc/yum.repos.d/gyyx.repo
        if [[ $os_check == "7" ]];then
            cat >>/etc/yum.repos.d/gyyx.repo <<EOF
[base]
name=CentOS-7
enabled=1
failovermethod=priority
baseurl=http://mirrors.cloud.aliyuncs.com/centos/7/os/\$basearch/
    http://mirrors.aliyun.com/centos/7/os/\$basearch/
gpgcheck=1
gpgkey=http://mirrors.cloud.aliyuncs.com/centos/RPM-GPG-KEY-CentOS-7
    http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7

[updates]
name=CentOS-7
enabled=1
failovermethod=priority
baseurl=http://mirrors.cloud.aliyuncs.com/centos/7/updates/\$basearch/
    http://mirrors.aliyun.com/centos/7/updates/\$basearch/
gpgcheck=1
gpgkey=http://mirrors.cloud.aliyuncs.com/centos/RPM-GPG-KEY-CentOS-7
    http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7

[extras]
name=CentOS-7
enabled=1
failovermethod=priority
baseurl=http://mirrors.cloud.aliyuncs.com/centos/7/extras/\$basearch/
    http://mirrors.aliyun.com/centos/7/extras/\$basearch/
gpgcheck=1
gpgkey=http://mirrors.cloud.aliyuncs.com/centos/RPM-GPG-KEY-CentOS-7
    http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
[epel]
name=Extra Packages for Enterprise Linux 7 - \$basearch
enabled=1
failovermethod=priority
baseurl=http://mirrors.cloud.aliyuncs.com/epel/7/\$basearch
    http://mirrors.aliyun.com/epel/7/\$basearch
gpgcheck=0
gpgkey=http://mirrors.cloud.aliyuncs.com/epel/RPM-GPG-KEY-EPEL-7
    http://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-7
EOF
        elif [[ $os_check == "6" ]];then
            cat >>/etc/yum.repos.d/gyyx.repo <<EOF
[base]
name=CentOS-6.10
enabled=1
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos-vault/6.10/os/\$basearch/
gpgcheck=0
gpgkey=http://mirrors.aliyun.com/centos-vault/RPM-GPG-KEY-CentOS-6

[updates]
name=CentOS-6.10
enabled=1
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos-vault/6.10/updates/\$basearch/
gpgcheck=0
gpgkey=http://mirrors.aliyun.comm/centos-vault/RPM-GPG-KEY-CentOS-6

[extras]
name=CentOS-6.10
enabled=1
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos-vault/6.10/extras/\$basearch/
gpgcheck=0
gpgkey=http://mirrors.aliyun.com/centos-vault/RPM-GPG-KEY-CentOS-6

[epel]
name=Extra Packages for Enterprise Linux 6 - \$basearch
enabled=1
failovermethod=priority
baseurl=http://mirrors.aliyun.com/epel-archive/6/\$basearch
gpgcheck=0
gpgkey=http://mirrors.aliyun.com/epel-archive/RPM-GPG-KEY-EPEL-6
EOF
        fi
        echo "--------软件源设置完成，正在生成缓存，较慢"
        yum clean all  >/dev/null 2>&1
        yum makecache >/dev/null 2>&1
        if [[ $? -ne 0 ]];then
            if [[ $os_check == "7" ]];then
                sed -i "s/^#\!.*/#\!\/usr\/bin\/python2.7/" /usr/bin/yum
            elif [[ $os_check == "6" ]];then
                sed -i "s/^#\!.*/#\!\/usr\/bin\/python2.6/" /usr/bin/yum
            fi
        fi   
        echo "--------A502机器设置yum源信息完成--------"
fi
sleep 1
}

yum_devel() {
    echo "--------准备安装依赖软件--------"
    # if [[ $host_name = A* ]] && [[ $os_check == "7" ]];then
    # # 阿里云7.9镜像安装依赖时需要安装Deltarpm包（增量 RPM 套件）
    #     yum install deltarpm -y
    # fi
    yum install -y -q unzip zip kernel-devel
    yum install -y -q gcc fuse-devel glibc-utils iptables-devel iptraf 
    yum install -y -q iptraf-ng libcap-devel mrtg net-snmp-perl net-snmp-python nmap 
    yum install -y -q python-dmidecode telnet tftp watchdog lrzsz openssl openssl-devel 
    yum install -y -q screen freetds vim-enhanced  net-tools tmpwatch tcpdump mlocate 
    yum install -y -q expect ftp libpcap-devel nc  psutils-perl ncurses-devel wget 
    yum install -y -q bzip2 patch bind-utils cyrus-sasl-devel gcc-c++ libev subversion 
    yum install -y -q zlib-devel libstdc++-devel libpcap ntp mysql-devel sysstat numactl-libs 
    yum install -y -q perl-DBD-MySQL yum-utils  psutils dos2unix libmnl 
    echo "------安装依赖软件完成--------"
    sleep 1
}


sshd_config() {
 # 确保SSH MaxAuthTries设置为4或更低(小)
 cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
 cat /etc/ssh/sshd_config |grep -w  '^MaxAuthTries' >/dev/null 2>&1
 if [[ $? -ne 0 ]];then
    sed -i '$a MaxAuthTries 4' /etc/ssh/sshd_config
 else
    sed -i 's/^MaxAuthTries.*/MaxAuthTries 4/' /etc/ssh/sshd_config
 fi

 # 确保已禁用SSH空密码登录(默认就是，但检测需要把注释打开)
 cat /etc/ssh/sshd_config |grep -w  '^PermitEmptyPasswords' >/dev/null 2>&1
 if [[ $? -ne 0 ]];then
    sed -i '$a PermitEmptyPasswords no' /etc/ssh/sshd_config
 else
    sed -i 's/^PermitEmptyPasswords.*/PermitEmptyPasswords no/' /etc/ssh/sshd_config
 fi

 # 配置SSH空闲超时间隔
 cat /etc/ssh/sshd_config |grep -w  '^ClientAliveInterval' >/dev/null 2>&1
 if [[ $? -ne 0 ]];then
    sed -i '$a ClientAliveInterval 300' /etc/ssh/sshd_config
 else
    sed -i 's/^ClientAliveInterval.*/ClientAliveInterval 300/' /etc/ssh/sshd_config
 fi
 cat /etc/ssh/sshd_config |grep -w  '^ClientAliveCountMax' >/dev/null 2>&1
 if [[ $? -ne 0 ]];then
    sed -i '$a ClientAliveCountMax 0' /etc/ssh/sshd_config
 else
    sed -i 's/^ClientAliveCountMax.*/ClientAliveCountMax 0/' /etc/ssh/sshd_config
 fi

 # 重启服务
 if [[ $os_check == "7" ]];then
    /usr/bin/systemctl restart sshd.service >/dev/null 2>&1
 elif [[ $os_check == "6" ]];then
    /etc/init.d/sshd restart >/dev/null 2>&1
 fi
 if [[ $? -eq 0 ]];then
    echo "------ssd_config文件修改完成:MaxAuthTries 4、禁用SSH空密码登录、配置SSH空闲超时间隔--------"
 else
    echo "ssd_config文件修改失败:MaxAuthTries 4、禁用SSH空密码登录、配置SSH空闲超时间隔"
 fi
}

local_pass() {
 # 确保配置了密码尝试失败的锁定(连续5次失败登录尝试后锁定用户)
 if [[ $os_check == "7" ]];then
    result_line=`egrep -w '^auth.*required.*pam_faillock.so preauth audit silent deny=5 unlock_time=900$|^auth.*[success=1 default=bad].*pam_unix.so$|^auth.*[default=die].*pam_faillock.so authfail audit deny=5 unlock_time=900$|^auth.*sufficient.*pam_faillock.so authsucc audit deny=5 unlock_time=900$' /etc/pam.d/password-auth  |wc -l`
    if [[ $result1_line -ne 4 ]];then
       cp /etc/pam.d/password-auth /etc/pam.d/password-auth.bak
       sed -i '/^auth.*required.*pam_faillock.so preauth audit silent deny=5 unlock_time=900$\|^auth.*[success=1 default=bad].*pam_unix.so$\|^auth.*[default=die].*pam_faillock.so authfail audit deny=5 unlock_time=900$\|^auth.*sufficient.*pam_faillock.so authsucc audit deny=5 unlock_time=900$/d'  /etc/pam.d/password-auth
       sed_line=`egrep -w -n '^auth' /etc/pam.d/password-auth |awk 'END {print}' |awk -F : '{print $1}'`
       sed -i "${sed_line}a auth required pam_faillock.so preauth audit silent deny=5 unlock_time=900\nauth [success=1 default=bad] pam_unix.so\nauth [default=die] pam_faillock.so authfail audit deny=5 unlock_time=900\nauth sufficient pam_faillock.so authsucc audit deny=5 unlock_time=900" /etc/pam.d/password-auth
       if [[ $? -eq 0 ]];then
          echo "------/etc/pam.d/password-auth修改完成：配置连续5次失败登录后锁定用户--------"
       else
          echo "/etc/pam.d/password-auth修改失败：配置连续5次失败登录后锁定用户"
       fi
    fi
    result2_line=`egrep -w '^auth.*required.*pam_faillock.so preauth audit silent deny=5 unlock_time=900$|^auth.*[success=1 default=bad].*pam_unix.so$|^auth.*[default=die].*pam_faillock.so authfail audit deny=5 unlock_time=900$|^auth.*sufficient.*pam_faillock.so authsucc audit deny=5 unlock_time=900$' /etc/pam.d/system-auth  |wc -l`
    if [[ $result2_line -ne 4 ]];then
       cp /etc/pam.d/system-auth /etc/pam.d/system-auth.bak
       sed -i '/^auth.*required.*pam_faillock.so preauth audit silent deny=5 unlock_time=900$\|^auth.*[success=1 default=bad].*pam_unix.so$\|^auth.*[default=die].*pam_faillock.so authfail audit deny=5 unlock_time=900$\|^auth.*sufficient.*pam_faillock.so authsucc audit deny=5 unlock_time=900$/d'  /etc/pam.d/system-auth
       sed_line=`egrep -w -n '^auth' /etc/pam.d/system-auth |awk 'END {print}' |awk -F : '{print $1}'`
       sed -i "${sed_line}a auth required pam_faillock.so preauth audit silent deny=5 unlock_time=900\nauth [success=1 default=bad] pam_unix.so\nauth [default=die] pam_faillock.so authfail audit deny=5 unlock_time=900\nauth sufficient pam_faillock.so authsucc audit deny=5 unlock_time=900" /etc/pam.d/system-auth
       if [[ $? -eq 0 ]];then
          echo "------/etc/pam.d/system-auth修改完成：配置连续5次失败登录后锁定用户--------"
       else
          echo "/etc/pam.d/system-auth修改失败：配置连续5次失败登录后锁定用户"
       fi
    fi
 fi
}


cron_mem() {
 # 确保核心转储受到限制
 if [[ $os_check == "7" ]];then
    cp /etc/security/limits.conf /etc/security/limits.bak
    cat /etc/security/limits.conf |egrep -w '^\* hard core' >/dev/null 2>&1
    if [[ $? -ne 0 ]];then
        sed -i '$a \* hard core 0' /etc/security/limits.conf
    else
        sed -i 's/^\* hard core.*/\* hard core 0/' /etc/security/limits.conf
    fi
    cp /etc/sysctl.conf /etc/sysctl.bak
    cat /etc/sysctl.conf |egrep -w '^fs.suid_dumpable' >/dev/null 2>&1   
    if [[ $? -ne 0 ]];then
        sed -i '$a fs.suid_dumpable = 0' /etc/sysctl.conf
    else
        sed -i 's/^fs.suid_dumpable.*/fs.suid_dumpable = 0/' /etc/sysctl.conf
    fi
    if sysctl -w fs.suid_dumpable=0 >/dev/null 2>&1;then
       echo "------确保核心转储受到限制:配置成功------"
    else
       echo "确保核心转储受到限制:配置失败"
    fi
 fi
}

grub_file_user() {
 # 确保配置了bootloader配置的权限(grub配置文件权限)
 if [[ $os_check == "7" ]];then
    if ! chown root:root /boot/grub2/grub.cfg || ! chmod og-rwx /boot/grub2/grub.cfg;then
       echo "grub文件更改为root用户或修改权限失败"
    else
       echo "------grub文件所属用户和权限修改成功------"
    fi
 else
    if ! chown root:root /boot/grub/grub.conf || ! chmod og-rwx /boot/grub/grub.conf;then
       echo "grub文件更改为root用户或修改权限失败"
    else
       echo "------grub文件所属用户和权限修改成功------"
    fi
 fi
}

ASLR_enable() {
 # 确保启用了地址空间布局随机化（ASLR）
 cp /etc/sysctl.conf /etc/sysctl.bak2
 cat /etc/sysctl.conf  |egrep -w '^kernel.randomize_va_space' >/dev/null 2>&1
 if [[ $? -ne 0 ]];then
    sed -i '$a kernel.randomize_va_space = 2' /etc/sysctl.conf
 else
    sed -i 's/^kernel.randomize_va_space.*/kernel.randomize_va_space = 2/' /etc/sysctl.conf
 fi
 if sysctl -w kernel.randomize_va_space=2 >/dev/null 2>&1;then
    echo "------启用地址空间布局随机化（ASLR）成功------"
 else
    echo "启用地址空间布局随机化（ASLR）失败"
 fi
}

audit_file() {
 # 确保收集了会话启动信息
 if [[ $os_check == "7" ]];then
    cp /etc/audit/rules.d/audit.rules /etc/audit/rules.d/audit.bak
    sed -i '/^-w\|^-e/d' /etc/audit/rules.d/audit.rules
    result_line=`wc -l /etc/audit/rules.d/audit.rules |awk '{print $1}'`
    sed -i "${result_line}a -w /var/run/utmp -p wa -k session\n-w /var/log/wtmp -p wa -k logins\n-w /var/log/btmp -p wa -k logins\n-w /var/log/sudo.log -p wa -k actions\n-w /var/log/lastlog -p wa -k logins\n-w /var/run/faillock/ -p wa -k logins\n-w /etc/sudoers -p wa -k scope\n-w /etc/sudoers.d/ -p wa -k scope\n-w /etc/group -p wa -k identity\n-w /etc/passwd -p wa -k identity\n-w /etc/gshadow -p wa -k identity\n-w /etc/shadow -p wa -k identity\n-w /etc/security/opasswd -p wa -k identity\n-w /etc/selinux/ -p wa -k MAC-policy\n-w /usr/share/selinux/ -p wa -k MAC-policy\n-e 2" /etc/audit/rules.d/audit.rules
 else
    cp /etc/audit/audit.rules /etc/audit/audit.bak
    sed -i '/^-w\|^-e/d' /etc/audit/audit.rules
    result_line=`wc -l /etc/audit/audit.rules |awk '{print $1}'`
    sed -i "${result_line}a -w /var/run/utmp -p wa -k session\n-w /var/log/wtmp -p wa -k session\n-w /var/log/btmp -p wa -k session\n-w /var/log/sudo.log -p wa -k actions\n-w /var/log/lastlog -p wa -k logins\n-w /var/run/faillock/ -p wa -k logins\n-w /etc/sudoers -p wa -k scope\n-w /etc/sudoers.d -p wa -k scope\n-w /etc/group -p wa -k identity\n-w /etc/passwd -p wa -k identity\n-w /etc/gshadow -p wa -k identity\n-w /etc/shadow -p wa -k identity\n-w /etc/security/opasswd -p wa -k identity\n-w /etc/selinux/ -p wa -k MAC-policy\n-e 2" /etc/audit/audit.rules
 fi   
 if [ ! -d "/var/log/audit" ]; then
     mkdir -p /var/log/audit
 fi
 if service auditd restart >/dev/null 2>&1;then
     echo -e "------确保收集了会话启动信息------\n------确保收集了系统管理员操作（sudolog）------\n------确保收集了会话启动信息------\n------确保收集了登录和注销事件------\n------确保系统管理范围（sudoers）更改的收集------\n------确保收>集了修改用户/组信息的事件------\n------确保收集了修改系统的强制访问控制的事件------"
 else
    echo "auditd服务重启失败：确保收集了会话启动信息、确保收集了系统管理员操作（sudolog）、确保收集了会话启动信息、确保收集了登录和注销事件、确保系统管理范围（sudoers）更改的收集、确保收集了修改用户/组信息的事件、确保收集了修改系统的强制访问控制的事件"
 fi
}

audit_log() {
 # 确保审核日志不会自动删除
 cp /etc/audit/auditd.conf /etc/audit/auditd.bak
 cat /etc/audit/auditd.conf  |egrep -w '^max_log_file_action' >/dev/null 2>&1
 if [[ $? -ne 0 ]];then
    sed -i '$a max_log_file_action = keep_logs' /etc/audit/auditd.conf
 else
    sed -i 's/^max_log_file_action.*/max_log_file_action = keep_logs/' /etc/audit/auditd.conf
 fi
 echo "------确保审核日志不会自动删除配置成功------"
}

etc_passwd() {
 # 确保已配置/etc/passwd-的权限
 if [[ $os_check == "6" ]];then
    if ! chown root:root /etc/passwd- || ! chmod 600 /etc/passwd-;then
       echo "修改/etc/passwd-文件的所属主或权限失败"
    else
       echo "------/etc/passwd-的文件权限和所属主修改完成------"   
    fi
 fi
}

etc_group() {
 # 确保已配置/etc/group-的权限
 if [[ $os_check == "6" ]];then
    if ! chown root:root /etc/group- || ! chmod 600 /etc/group-;then
       echo "修改/etc/group-文件的所属主或权限失败"
    else
       echo "------/etc/group-的文件权限和所属主修改完成------"   
    fi  
 fi
}

elves_ip_check() {
 echo -e "\n# 用于检测elves配置文件中的ip和/server.info中是否一致\n1 8 * * * ip=\`grep -w '^ip' /server.info |awk -F = '{print \$2}'\` && if [[ \`grep -w \$ip /usr/local/elves-agent/conf/cfg.json |wc -l\` -ne 2  ]];then sed -i  's/\(\"asset\": \"\).*/\1'\"\$ip\"'\",/g'   /usr/local/elves-agent/conf/cfg.json && sed -i  's/\(\"ip\": \"\).*/\1'\"\$ip\"'\",/g'   /usr/local/elves-agent/conf/cfg.json && /usr/local/elves-agent/control  restart; fi >/dev/null" >>/var/spool/cron/root
 echo "------添加检测elves_ip的定时任务完成------"
}

cronMAILTO() {
    [ -f /etc/crontab ] && sed -i '/SHELL/aMAILTO=""' /etc/crontab
}

set_umask() {
 # 确保默认用户(etc/passwd中)的umask限制为027或更高
  if [[ $group != "gop" ]] && [[ $group != "GOP" ]];then
        sed  -i 's/umask [0-9]\{3\}/umask 027/g' /etc/profile
        sed  -i 's/umask [0-9]\{3\}/umask 027/g' /etc/bashrc
        # 生效文件
        if !source /etc/profile >/dev/null 2>&1;then
            echo "/etc/profile文件source失败"
        elif !source /etc/bashrc >/dev/null 2>&1;then
            echo "/etc/bashrc文件source失败"
        else
            echo "------设置umask为027完成------"
        fi
    fi
}

# 如果是阿里的6版本镜像，则需要重置下主机名
bash_tty() {
    if [[ $host_name = A* ]] && [[ $os_check == "6" ]];then
        sed -i "s/^HOSTNAME=.*/HOSTNAME=$host_name/" /etc/sysconfig/network
        hostname $host_name
        bash
    fi
}
gyservice() {
ps -ef | grep -Ev "grep|check" | grep gyservice | awk '{print $2}' | xargs kill -9;rm -rf /usr/local/gyservice/* && rm -rf /etc/cron.d/gyserviceCron && mkdir -p /usr/local/gyservice/ && cd /usr/local/gyservice/ && wget http://gyservice.download.gyyx.cn/gyservice.tgz && tar -xvf gyservice.tgz && nohup ./gyservice >/dev/null 2>&1 &
}


#函数调用
main() {
 disable_selinux
 ssh_port_fun
 ssh_dns_fun
 ssh_auth_fun
 history_num_fun
 jumpserver_fun
 timeout_fun
 dns_fun
 ntp_fun
 sysctl_fun
 QingChu
 yum_fun
 yum_devel
 sshd_config
 local_pass
 cron_mem
 grub_file_user
 ASLR_enable
 audit_file
 audit_log
 etc_passwd
 etc_group
 elves_ip_check
 cronMAILTO
 set_umask
 bash_tty
 gyservice
}


main
