#!/usr/bin/sh
group=$1
host_name=$2
hostip=`hostname -I|xargs -n 1`

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

set_hostname() {
    if [[ $host_name = P* ]] || [[ $host_name = p* ]] || [[ $host_name = T* ]] || [[ $host_name = v* ]] || [[ $host_name = V* ]] || [[ $host_name = GY* ]] || [[ $host_name = gy* ]];then
        hostnamectl set-hostname $host_name
    fi
}

ssh_config_file() {
	# 修改sshd配置文件权限
	chown root:root /etc/ssh/sshd_config
    chmod 0600 /etc/ssh/ssh_host_*
    cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
    # 修改端口
	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
    # 允许root登录
    cat /etc/ssh/sshd_config|grep '^PermitRootLogin yes' >/dev/null 2>&1
    if [[ $? -ne 0 ]];then
        sed -i '$a PermitRootLogin yes' /etc/ssh/sshd_config 
    fi
    # 关闭逆向解析
    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 
    fi
    # 开启rsa证书验证
    cat /etc/ssh/sshd_config|grep '^PubkeyAcceptedKeyTypes=+ssh-rsa' >/dev/null 2>&1
    if [[ $? -ne 0 ]];then
        sed -i '$a PubkeyAcceptedKeyTypes=+ssh-rsa' /etc/ssh/sshd_config 
    fi
    # 关闭GSS认证，开启会导致登录缓慢
    cat /etc/ssh/sshd_config|grep '^GSSAPIAuthentication no' >/dev/null 2>&1
    if [[ $? -ne 0 ]];then
        sed -i '$a GSSAPIAuthentication no' /etc/ssh/sshd_config  
    fi
    # 确保SSH MaxAuthTries设置为4或更低(小)
    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  '^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
	# 确保SSH_LogLevel为适当得
	cat /etc/ssh/sshd_config |grep -w  '^LogLevel' >/dev/null 2>&1
    if [[ $? -ne 0 ]];then
        sed -i '$a LogLevel INFO' /etc/ssh/sshd_config
    else
        sed -i 's/^LogLevel.*/LogLevel INFO/' /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

    systemctl restart sshd
    if [[ $? -eq 0 ]];then
        echo "------------ssh文件修改完成：端口、root登录、关闭逆向解析、开启rsa证书验证、关闭GSS认证、最大登录失败次数、SSH超时、禁用空密码登录--------"
    else
        echo "------------ssh文件修改完成：sshd服务重启失败--------"
    fi
}

# 设置历史命令数量和
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\` \"" >> /etc/profile
        . /etc/profile
        if [[ $? -eq 0 ]];then
            echo "------------设置历史命令保留条目和显示格式完成--------"
        else
            echo "------------设置历史命令保留条目和显示格式失败--------"
        fi
    fi
}

# 添加堡垒机公钥
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 "------------添加堡垒机公钥完成--------"
}

# 设置10分钟内用户无操作就自动断开终端
timeout_fun(){
    cp /etc/profile /etc/profile.bak && cp /etc/bash.bashrc /etc/bash.bashrc.bak
    cat /etc/profile | egrep -w "^export TMOUT=600" >/dev/null 2>&1
    if [[ $? -ne 0 ]];then
        echo "export TMOUT=600" >> /etc/profile
        . /etc/profile
    else
        /bin/sed -i "s/^export TMOUT.*/export TMOUT=600/1" /etc/profile
        . /etc/profile
    fi

    cat /etc/bash.bashrc | egrep -w "^export TMOUT=600" >/dev/null 2>&1
    if [[ $? -ne 0 ]];then
        echo "export TMOUT=600" >> /etc/bash.bashrc
        . /etc/bash.bashrc
    else
        /bin/sed -i "s/^export TMOUT.*/export TMOUT=600/1" /etc/bash.bashrc
        . /etc/bash.bashrc
    fi
    echo "------------设置十分钟内用户无法操作自动断开--------"
}

# 设置系统dns
dns_fun(){
    # if [ ${hostname:0:1} != 'T' ];then
    #     echo "DNS=183.60.83.19 183.60.82.98" >> /etc/systemd/resolved.conf
    # elif [ ${hostname:0:1} != 'A' ];then
    #     echo "DNS=223.5.5.5 223.6.6.6" >> /etc/systemd/resolved.conf
    if [[ $host_name = P* ]] || [[ $host_name = p* ]] || [[ $host_name = v* ]] || [[ $host_name = V* ]] || [[ $host_name = GY* ]] || [[ $host_name = gy* ]];then
        echo "DNS=119.29.29.29 223.5.5.5" >> /etc/systemd/resolved.conf
    fi 
    systemctl restart systemd-resolved
    systemctl enable systemd-resolved
    mv /etc/resolv.conf /etc/resolv.conf.bak
    ln -s /run/systemd/resolve/resolv.conf /etc/resolv.conf
    chmod 644 /etc/resolv.conf
    echo "------------设置系统DNS完成--------"
}

# 设置ntp时间服务
ntp_fun(){
    if [[ $host_name = P* ]] || [[ $host_name = p* ]] || [[ $host_name = v* ]] || [[ $host_name = V* ]] || [[ $host_name = GY* ]] || [[ $host_name = gy* ]];then
        apt install -y ntp >/dev/null 2>&1
        cp /etc/ntp.conf /etc/ntp.conf.bak
        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 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 s2c.time.edu.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
        timedatectl set-timezone Asia/Shanghai
        systemctl restart ntp
        if [[ $? -eq 0 ]];then
            echo "------------A502机器ntp设置完成--------"
        else
            echo "------------A502机器ntp设置失败--------"
        fi
    else
        systemctl unmask ntp
        systemctl start ntp
        if [[ $? -eq 0 ]];then
            echo "------------云服务器ntp设置完成--------"
        else
            echo "------------云服务器ntp设置失败--------"
        fi
    fi  
}

# 内核参数优化
kernel_config() {
    free_mem_total=`free -b |grep -wi  'mem:' |awk '{print $2}'`
    mem_50=`echo $(($free_mem_total / 2))`
    cp /etc/sysctl.conf /etc/sysctl.conf.bak
    cat > /etc/sysctl.conf <<EOF
# 关闭/开启内核路由转发
net.ipv4.ip_forward = 1

# 开启源地址校验：从某个网卡进来的数据包，会校验通过默认路由到源地址是否可达，不通则丢弃数据包
net.ipv4.conf.all.rp_filter=1
net.ipv4.conf.default.rp_filter=1

# 处理没有源路由的数据包
net.ipv4.conf.default.accept_source_route = 0

# 设置pid为文件扩展名
kernel.core_uses_pid = 1

# 计算syn的cookie，然后返回syn+ack时当作序列号，再根据返沪ideack计算包头信息cookie，然后判断是否是一个正常连接，然后分配资源建立连接，可以防止syn flood攻击
net.ipv4.tcp_syncookies = 1

# 表示单个消息队列的最大容量
kernel.msgmnb = 65536 
# 表示消息队列中单个消息的最大容量，进程间的消息传递是在内核的内存中进行的，不会交换到硬盘上，增加该值将增加系统所用内存
kernel.msgmax = 65536

# 主备IP地址切换控制机制：0当接口的主IP地址被移除时，删除所有次IP地址；1当接口的主IP地址被移除时，将次IP地址提升为主IP地址
net.ipv4.conf.all.promote_secondaries = 1
net.ipv4.conf.default.promote_secondaries = 1

# 保存在 ARP 高速缓存中的最多记录的硬限制， 一旦高速缓存中的数目高于此， 垃圾收集器将马上运行
net.ipv6.neigh.default.gc_thresh3 = 4096
net.ipv4.neigh.default.gc_thresh3 = 4096

# 设置产生softlockup时是否抛出一个内核严重错误（kernel panic）。Softlockup用于检测CPU可以响应中断，但是在长时间内不能调度（比如禁止抢占时间太长）的死锁情况。这个机制运行在一个hrtimer的中断上下文，每隔一段时间检测一下是否发生了调度，如果过长时间没发生调度，说明系统被死锁。
kernel.softlockup_panic = 1

# 激活键盘上的sysrq按键。这个按键用于给内核传递信息，用于紧急情况下重启系统。当遇到死机或者没有响应的时候，甚至连 tty 都进不去，可以尝试用 SysRq 重启计算机。
kernel.sysrq = 1  # 是否和发生panic后按照时间重启的参数配合使用

# IPV6用不上的禁用
net.ipv6.conf.all.disable_ipv6=1      #在所有接口上禁用IPv6 （XenServer虚机禁用无效）
net.ipv6.conf.default.disable_ipv6=1  #默认在lo接口上禁用IPv6 （XenServer虚机禁用无效）
net.ipv6.conf.lo.disable_ipv6=1       #在lo接口上禁用IPv6 （XenServer虚机禁用无效）

# 关闭自动协调本地内存和原地内存的操作
kernel.numa_balancing = 0

# 系统所允许的最大共享内存段的大小（以字节为单位），最好设置为物理内存的50% 
kernel.shmmax = ${mem_50}

# 系统日志级别 0-7
kernel.printk = 5

# 表示是否启用有选择的应答（Selective Acknowledgment），这可以通过有选择地应答乱序接收到的报文来提高性能（这样可以让发送者只发送丢失的报文段）；（对于广域网通信来说）这个选项应该启用，但是这会增加对 CPU 的占用
net.ipv4.tcp_sack=0

#控制物理内存剩余%多少时使用SWAP（建议值0，但0并非禁用SWAP，只是充分利用物理内存）
vm.swappiness = 1

# 定义了一个进程能拥有的最多的内存区域
vm.max_map_count = 262144

# kernel panic后，会一直夯住，此参数为自动从panic中自动重启，时间为20秒
kernel.panic = 20

# 确保启用了地址空间布局随机化（ASLR）
kernel.randomize_va_space = 2
EOF
    sysctl -p >/dev/null 2>&1
    if [[ $? -eq 0 ]];then
        echo "------------内核参数已修改--------"
    else
        echo "------------内核参数生效失败--------"
    fi
}

# 启动rc-local服务,Ubuntu 16以后需要自建rc.local文件
start_rc_local() {
    if [[ $group != "tke" ]]; then
    echo '#!/bin/bash' > /etc/rc.local
    fi
    #echo -e '\n[Install]\nWantedBy=multi-user.target' >> /usr/lib/systemd/system/rc-local.service
    #systemctl daemon-reload
    chmod +x /etc/rc.local
    #systemctl enable --now rc-local
    systemctl start rc-local
    if [[ $? -eq 0 ]];then
        echo "------------rc-local服务已启动--------"
    else
        echo "------------rc-local服务启动失败--------"
    fi
}

# 替换apt的软件包源：阿里
replace_apt_source() {
    if [[ $host_name = P* ]] || [[ $host_name = p* ]] || [[ $host_name = v* ]] || [[ $host_name = V* ]] || [[ $host_name = GY* ]] || [[ $host_name = gy* ]];then
        cp /etc/apt/sources.list /etc/apt/sources.list.bak
        cat > /etc/apt/sources.list <<EOF
deb http://mirrors.aliyun.com/ubuntu/ focal main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-proposed main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal-proposed main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ focal-backports main restricted universe multiverse
EOF
        echo "---------正在更新apt的软件库-------"
        apt update
        echo "---------更新apt的软件库完成-------"
    fi
}

# 安装依赖软件
install_devel() {
    echo "------------正在安装依赖软件------------"
	# 预装密码管理工具
	apt install -y libpam-pwquality
    # 判断如果为gop的机器，则安装特定软件包
    if [[ $group = 'gop' ]] || [[ $group = 'GOP' ]];then
        dpkg --add-architecture i386
    fi  
    apt-get -y update
    if [[ $group = 'gop' ]] || [[ $group = 'GOP' ]];then
        apt install -y glibc-source libcrypt1:i386 lib32stdc++6
    fi
    # 判断如果为gop的机器，则添加dss算法到sshd配置文件中
    if [[ $group = 'gop' ]] || [[ $group = 'GOP' ]];then
        echo 'HostKeyAlgorithms +ssh-rsa,ssh-dss' >> /etc/ssh/sshd_config
        sed -i '/^Subsystem/ c Subsystem sftp internal-sftp' /etc/ssh/sshd_config
        systemctl restart sshd
    fi
    # 此操作是关闭apt安装过程中要求交互式的重启服务
    echo "\$nrconf{restart} = 'l';" >>/etc/needrestart/needrestart.conf
    apt install -y unzip zip gcc g++ lrzsz auditd >/dev/null 2>&1
    result=$?
    apt install -y tcpdump telnet  wget bind9-utils  net-tools >/dev/null 2>&1
    if [[ $? -eq 0  && $result -eq 0 ]];then
        echo "------------安装依赖软件完成------------"
    else
        echo "------------安装依赖软件出错------------"
    fi
}

# 开启定时任务日志、messages日志
open_cron_log() {
     sed -i 's/#cron\.\*/cron\.\*/g' /etc/rsyslog.d/50-default.conf
     sed -i '$a \*\.info;mail\.none;authpriv\.none -\/var\/log\/messages' /etc/rsyslog.d/50-default.conf
     systemctl restart rsyslog
     if [[ $? -eq 0 ]];then
        echo "------------cron日志和系统messages日志已开启,重启rsyslog服务成功------------"
    else
        echo "------------cron日志和系统messages日志已开启,重启rsyslog服务失败------------"
    fi
}

# 确保密码规定次数内不能重用
disable_userpass_reuse() {
    cp /etc/pam.d/common-password /etc/pam.d/common-password.bak
    sed -i '/^password.*required.*pam_pwhistory.so.*remember=.*/d' /etc/pam.d/common-password  
    echo 'password required pam_pwhistory.so remember=5' >> /etc/pam.d/common-password
    if [[ $? -eq 0 ]];then
        echo "------------已设置密码至少5次内不能重复使用------------"
    else
        echo "------------设置密码重复限制失败------------"
    fi
}

#密码尝试五次冻结15分钟
passwd_forgen_15min(){
	cp /etc/pam.d/common-auth /etc/pam.d/common-auth.bak
	sed -i '/^password.*required.*pam_tally2.so.*deny=.*/d' /etc/pam.d/common-auth
	echo 'password required pam_tally2.so deny=5 unlock_time=900' >> /etc/pam.d/common-auth
	if [[ $? -eq 0 ]];then
        echo "------------已设置密码尝试五次后冻结十五分钟------------"
    else
        echo "------------设置密码尝试冻结失败------------"
    fi
}

#设置密码更改最短间隔天数
modify_passwd_time_interval(){
	cp /etc/login.defs /etc/login.defs.bak
	sed i '/^PASS_MIN_DAYS.*/d' /etc/login.defs
	echo 'PASS_MIN_DAYS 1' >> /etc/login.defs
	if [[ $? -eq 0 ]];then
        echo "------------已设置密码更改最短时间间隔为一天------------"
    else
        echo "------------设置密码更改时间最短间隔失败------------"
    fi
	sed i '/^PASS_MAX_DAYS.*/d' /etc/login.defs
	echo 'PASS_MAX_DAYS 99999' >> /etc/login.defs
	if [[ $? -eq 0 ]];then
        echo "------------已设置密码永不过期------------"
    else
        echo "------------设置密码永不过期失败------------"
    fi
}

# 确保已配置/etc/passwd和备份文件(passwd-)的权限
passwd_file_mode() {
    chown root:root /etc/passwd /etc/passwd-
    chmod u-x,go-xw /etc/passwd /etc/passwd-
    if [[ $? -eq 0 ]];then
        echo "------------已设置/etc/passwd和备份文件(passwd-)的权限------------"
    else
        echo "------------设置/etc/passwd和备份文件(passwd-)的权限失败------------"
    fi
}

# 确保已配置/etc/group和备份文件(group-)的权限
group_file_mode() {
    chown root:root /etc/group /etc/group-
    chmod 644 /etc/group /etc/group-
    if [[ $? -eq 0 ]];then
        echo "------------已设置/etc/group和备份文件(group-)的权限------------"
    else
        echo "------------设置/etc/group和备份文件(group-)的权限失败------------"
    fi
}

# 用户和组的shadow文件的权限
user_and_group_shadowfilemode() {
    chown root:root /etc/shadow /etc/shadow- /etc/gshadow /etc/gshadow-
    chmod u-x,g-wx,o-rwx /etc/shadow /etc/shadow- /etc/gshadow /etc/gshadow-
    if [[ $? -eq 0 ]];then
        echo "------------已设置用户和组的shadow文件的权限------------"
    else
        echo "------------设置用户和组的shadow文件的权限失败------------"
    fi
}

# grub配置文件的权限
grub_file_mode() {
    chown root:root /boot/grub/grub.cfg
    chmod u-wx,og-rwx /boot/grub/grub.cfg
    if [[ $? -eq 0 ]];then
        echo "------------已设置grub配置文件的权限------------"
    else
        echo "------------设置grub配置文件的权限失败------------"
    fi
}

# audit审计服务配置文件修改部分
audit_conf_rulesfile() {
    cp /etc/audit/rules.d/audit.rules /etc/audit/rules.d/audit.rules.bak

    # 确保收集了修改用户/组信息的事件
    sed -i '/^.*os一致化：确保收集了修改用户\/组信息的事件\|^-w.*\/etc\/group.*-p.*wa.*-k.*\|^-w.*\/etc\/passwd.*-p.*wa.*-k.*\|^-w.*\/etc\/gshadow.*-p.*wa.*-k.*\|^-w.*\/etc\/shadow.*-p.*wa.*-k.*\|^-w.*\/etc\/security\/opasswd.*-p.*wa.*-k.*/d' /etc/audit/rules.d/audit.rules
    echo -e '\n# os一致化：确保收集了修改用户/组信息的事件\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' >> /etc/audit/rules.d/audit.rules
    
    # 确保系统管理范围（sudoers）更改的收集
    sed -i '/^.*os一致化：确保系统管理范围（sudoers）更改的收集\|^-w.*\/etc\/sudoers.*-p.*wa.*-k.*\|^-w.*\/etc\/sudoers.d\/.*-p.*wa.*-k.*/d' /etc/audit/rules.d/audit.rules
    echo -e '\n# os一致化：确保系统管理范围（sudoers）更改的收集\n-w /etc/sudoers -p wa -k scope\n-w /etc/sudoers.d/ -p wa -k scope' >> /etc/audit/rules.d/audit.rules
    
    # 确保审核配置是不变的
    sed -i '/^.*os一致化：确保审核配置是不变的\|^-e.*/d' /etc/audit/rules.d/audit.rules
    echo -e '\n# os一致化：确保审核配置是不变的\n-e 2' >> /etc/audit/rules.d/audit.rules

    # 确保收集了会话启动信息
    sed -i '/^.*os一致化：确保收集了会话启动信息\|^-w.*\/var\/run\/utmp.*-p.*wa.*-k.*\|^-w.*\/var\/log\/wtmp.*-p.*wa.*-k.*\|^-w.*\/var\/log\/btmp.*-p.*wa.*-k.*/d' /etc/audit/rules.d/audit.rules
    echo -e '\n# os一致化：确保收集了会话启动信息\n-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' >> /etc/audit/rules.d/audit.rules
    
    # 确保审核日志不会自动删除
    cp /etc/audit/auditd.conf /etc/audit/auditd.conf.bak
	#确保审核日志存储大小
	sed -i '/^.*os一致化：确保审核日志存储大小\|^max_log_file/d' /etc/audit/auditd.conf && echo -e '\n# os一致化：确保审核日志存储大小\nmax_log_file = 100' >> /etc/audit/auditd.conf
	# 确保审核日志轮转
    sed -i '/^.*os一致化：确保审核日志不会自动删除\|^max_log_file_action/d' /etc/audit/auditd.conf && echo -e '\n# os一致化：确保审核日志自动转\nmax_log_file_action = rotate' >> /etc/audit/auditd.conf
	# 确保轮转30个日志自动删除
	sed -i 's#^num_logs.*#num_logs = 30#g' /etc/audit/auditd.conf
	# 请确保系统在审核日志满时被禁用
	sed -i '/^.*os一致化：确保系统在审计日志满时被禁用\|^\s*space_left_action/d' /etc/audit/auditd.conf && echo -e '\n# os一致化：确保系统在审计日志满时被禁用\nspace_left_action = SUSPEND' >> /etc/audit/auditd.conf

    # 确保收集了修改系统的强制访问控制的事件
    sed -i '/^.*os一致化：确保收集了修改系统的强制访问控制的事件\|^-w.*\/etc\/apparmor\/.*-p.*wa.*-k.*\|^-w.*\/etc\/apparmor.d\/.*-p.*wa.*-k.*/d' /etc/audit/rules.d/audit.rules
    echo -e '\n# os一致化：确保收集了修改系统的强制访问控制的事件\n-w /etc/apparmor/ -p wa -k MAC-policy\n-w /etc/apparmor.d/ -p wa -k MAC-policy' >> /etc/audit/rules.d/audit.rules

    # 确保收集了登录和注销事件
    sed -i '/^.*os一致化：确保收集了登录和注销事件\|^-w.*\/var\/log\/faillog.*-p.*wa.*-k.*\|^-w.*\/var\/log\/lastlog.*-p.*wa.*-k.*\|^-w.*\/var\/log\/tallylog.*-p.*wa.*-k.*/d' /etc/audit/rules.d/audit.rules
    echo -e '\n# os一致化：确保收集了登录和注销事件\n-w /var/log/faillog -p wa -k logins\n-w /var/log/lastlog -p wa -k logins\n-w /var/log/tallylog -p wa -k logins' >> /etc/audit/rules.d/audit.rules

    # 重启audit服务
    systemctl restart auditd
    if [[ $? -eq 0 ]];then
        echo "------------audit相关配置已完成：确保收集了修改用户/组信息的事件、确保系统管理范围（sudoers）更改的收集、确保审核配置是不变的、确保收集了会话启动信息、确保审核日志不会自动删除、确保收集了修改系统的强制访问控制的事件、确保收集了登录和注销事件--------"
    else
        echo "------------audit相关配置已完成：重启audit服务失败"
    fi
}

# 关闭定时任务发送调用sendmail发送邮件的功能
close_cron_sendmail() {
    sed -i '/^MAILTO=/d' /etc/crontab && sed -i '/SHELL/aMAILTO=""' /etc/crontab
    systemctl restart cron
    if [[ $? -eq 0 ]];then
        echo "------------定时任务的sendmail功能已关闭--------"
    else
        echo "------------定时任务的sendmail功能已关闭，cron服务重启失败--------"
    fi
}

# 设置umask为027或更大
set_umask() {
    if [[ $group != "gop" && $group != "GOP" ]]; then
    echo 'umask 027' >> /etc/profile
    echo 'umask 027' >> /etc/bash.bashrc
    source /etc/profile
    source /etc/bash.bashrc
    echo "------------umask设置完成：umask 027--------"
    fi
}

# 刷新tty终端，显示修改后的主机名
bash_tty() {
    if [[ $host_name = P* ]] || [[ $host_name = p* ]] || [[ $host_name = v* ]] || [[ $host_name = V* ]] || [[ $host_name = GY* ]] || [[ $host_name = gy* ]];then
        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
    set_hostname
    ssh_config_file
    history_num_fun
    jumpserver_fun
    timeout_fun
    # dns_fun
    ntp_fun
    kernel_config
    start_rc_local
    # replace_apt_source
    install_devel
    open_cron_log
    disable_userpass_reuse
	modify_passwd_time_interval
    passwd_file_mode
    group_file_mode
    user_and_group_shadowfilemode
    grub_file_mode
    audit_conf_rulesfile
    close_cron_sendmail
    set_umask
    # bash_tty
    gyservice
}

main
