快捷搜索:  汽车  科技

centos7 安全加固脚本(CentOS7一键安全加固及系统优化脚本)

centos7 安全加固脚本(CentOS7一键安全加固及系统优化脚本)再次执行脚本会提示已经做了安全加固优化,无须再次执行

点击上方"walkingcloud"关注

centos7 安全加固脚本(CentOS7一键安全加固及系统优化脚本)(1)

CentOS7一键安全加固及系统优化脚本

init_centos7.sh 脚本内容如下

脚本说明:本脚本在 https://github.com/vtrois/spacepack上下载,并在其脚本基础上做了调整,根据前期CentOS7安全加固系列文章,添加了部分加固项

#!/usr/bin/envbash # #Author:SeatonJiang<seaton@vtrois.com> #GithubURL:https://github.com/vtrois/spacepack #License:MIT #Date:2020-08-13 exportPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin RGB_DANGER='\033[31;1m' RGB_WAIT='\033[37;2m' RGB_Success='\033[32m' RGB_WARNING='\033[33;1m' RGB_INFO='\033[36;1m' RGB_END='\033[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"InitCentOS7Script" echo-e"Formoreinformationpleasevisithttps://github.com/vtrois/spacepack" echo-e"=========================================================================================" } check_root(){ if[[$EUID-ne0]];then echo-e"${RGB_DANGER}Thisscriptmustberunasroot!${RGB_END}" exit1 fi } check_lock(){ if[!-f"$LOCK"];then touch$LOCK else echo-e"${RGB_DANGER}Detectsthattheinitializationiscompleteanddoesnotneedtobeinitializedanyfurther!${RGB_END}" exit1 fi } check_os(){ if["${CHECK_CENTOS}"!='7'];then echo-e"${RGB_DANGER}ThisscriptmustberuninCentOS7!${RGB_END}" exit1 fi } new_swap(){ echo"=============swap=============">>${LOCK}2>&1 if["${CHECK_RAM}"-le'2'];then echo-en"${RGB_WAIT}Configuring...${RGB_END}" ddif=/dev/zeroof=/swapfilebs=1024count=1048576>>${LOCK}2>&1 chmod600/swapfile>>${LOCK}2>&1 mkswap/swapfile>>${LOCK}2>&1 swapon/swapfile>>${LOCK}2>&1 echo'/swapfileswapswapdefaults00'>>/etc/fstab echo'#Swap'>>/etc/sysctl.conf echo'vm.swappiness=10'>>/etc/sysctl.conf sysctl-p>>${LOCK}2>&1 sysctl-nvm.swappiness>>${LOCK}2>&1 echo-e"\r${RGB_SUCCESS}ConfigurationSuccess${RGB_END}" else echo-e"${RGB_SUCCESS}Skip noconfigurationneeded${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-nnet.ipv4.tcp_congestion_control>>${LOCK}2>&1 lsmod|grepbbr>>${LOCK}2>&1 echo-e"\r${RGB_SUCCESS}ConfigurationSuccess${RGB_END}" } disable_software(){ echo"=============selinuxfirewalld=============">>${LOCK}2>&1 echo-en"${RGB_WAIT}Configuring...${RGB_END}" setenforce0>>${LOCK}2>&1 sed-i's/^SELINUX=.*$/SELINUX=disabled/'/etc/selinux/config systemctldisablefirewalld.service>>${LOCK}2>&1 systemctlstopfirewalld.service>>${LOCK}2>&1 echo-e"\r${RGB_SUCCESS}ConfigurationSuccess${RGB_END}" } time_zone(){ echo"=============timezone=============">>${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}ConfigurationSuccess${RGB_END}" } custom_profile(){ echo"=============customprofile=============">>${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" aliasl='ls-AFhlt' aliasgrep='grep--color' aliasegrep='egrep--color' aliasfgrep='fgrep--color' exportHISTTIMEFORMAT="%Y-%m-%d%H:%M:%S" EOF cat/etc/profile.d/centos7init.sh>>${LOCK}2>&1 echo-e"\r${RGB_SUCCESS}ConfigurationSuccess${RGB_END}" } adjust_ulimit(){ echo"=============adjustulimit=============">>${LOCK}2>&1 echo-en"${RGB_WAIT}Configuring...${RGB_END}" sed-i'/^#Endoffile/ $d'/etc/security/limits.conf cat>>/etc/security/limits.conf<<EOF #Endoffile *softcoreunlimited *hardcoreunlimited *softnproc1000000 *hardnproc1000000 *softnofile1000000 *hardnofile1000000 rootsoftcoreunlimited roothardcoreunlimited rootsoftnproc1000000 roothardnproc1000000 rootsoftnofile1000000 roothardnofile1000000 EOF cat/etc/security/limits.conf>>${LOCK}2>&1 echo-e"\r${RGB_SUCCESS}ConfigurationSuccess${RGB_END}" } kernel_optimum(){ echo"=============kerneloptimum=============">>${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 #Controlssourcerouteverification 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 #ControlstheuseofTCPsyncookies #Numberofpid_max kernel.core_uses_pid=1 kernel.pid_max=1000000 net.ipv4.tcp_syncookies=1 #Controlsthemaximumsizeofamessage inbytes #Controlsthedefaultmaxmimumsizeofamesagequeue #Controlsthemaximumsharedsegmentsize inbytes #Controlsthemaximumnumberofsharedmemorysegments inpages kernel.msgmnb=65536 kernel.msgmax=65536 kernel.shmmax=68719476736 kernel.shmall=4294967296 kernel.sysrq=1 kernel.softlockup_panic=1 kernel.printk=5 #TCPkernelparamater net.ipv4.tcp_mem=94500000915000000927000000 net.ipv4.tcp_rmem=4096873804194304 net.ipv4.tcp_wmem=4096163844194304 net.ipv4.tcp_window_scaling=1 net.ipv4.tcp_sack=1 #Socketbuffer 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 #TCPconn net.ipv4.tcp_max_syn_backlog=262144 net.ipv4.tcp_syn_retries=1 net.ipv4.tcp_retries1=3 net.ipv4.tcp_retries2=15 #TCPconnreuse 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 #keepaliveconn net.ipv4.tcp_keepalive_time=300 net.ipv4.tcp_keepalive_intvl=30 net.ipv4.tcp_keepalive_probes=3 net.ipv4.ip_local_port_range=102465535 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}ConfigurationSuccess${RGB_END}" } updatedb_optimum(){ echo"=============updatedboptimum=============">>${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}ConfigurationSuccess${RGB_END}" } open_ipv6(){ echo"=============openipv6=============">>${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}ConfigurationSuccess${RGB_END}" } disable_cad(){ echo"=============disablecad=============">>${LOCK}2>&1 echo-en"${RGB_WAIT}Configuring...${RGB_END}" systemctlmaskctrl-alt-del.target>>${LOCK}2>&1 echo-e"\r${RGB_SUCCESS}ConfigurationSuccess${RGB_END}" } remove_users(){ echo"=============removeusers=============">>${LOCK}2>&1 echo-en"${RGB_WAIT}Configuring...${RGB_END}" foruinadmlpsyncshutdownhaltmailoperatorgamesftp do userdel${u}>>${LOCK}2>&1 done cut-d:-f1/etc/passwd>>${LOCK}2>&1 forginadmlpmailgamesftp do groupdel${g}>>${LOCK}2>&1 done cat/etc/group>>${LOCK}2>&1 echo-e"\r${RGB_SUCCESS}ConfigurationSuccess${RGB_END}" } sys_permissions(){ echo"=============syspermissions=============">>${LOCK}2>&1 echo-en"${RGB_WAIT}Configuring...${RGB_END}" chmod644/etc/passwd>>${LOCK}2>&1 chmod644/etc/group>>${LOCK}2>&1 chmod000/etc/shadow>>${LOCK}2>&1 chmod000/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}ConfigurationSuccess${RGB_END}" } password_policy(){ echo"=============passwordpolicy=============">>${LOCK}2>&1 echo-en"${RGB_WAIT}Configuring...${RGB_END}" sed-i's/^PASS_MAX_DAYS.*$/PASS_MAX_DAYS90/'/etc/login.defs sed-i's/^PASS_MIN_DAYS.*$/PASS_MIN_DAYS10/'/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}ConfigurationSuccess${RGB_END}" } change_useradd(){ echo"=============changeuseradd=============">>${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}ConfigurationSuccess${RGB_END}" } sec_ssh(){ echo"=============secssh=============">>${LOCK}2>&1 echo-en"${RGB_WAIT}Configuring...${RGB_END}" sed-i's/UseDNS.*$/UseDNSno/'/etc/ssh/sshd_config sed-i's/^#LoginGraceTime.*$/LoginGraceTime60/'/etc/ssh/sshd_config sed-i's/^#PermitEmptyPasswords.*$/PermitEmptyPasswordsno/'/etc/ssh/sshd_config sed-i's/^#PubkeyAuthentication.*$/PubkeyAuthenticationyes/'/etc/ssh/sshd_config sed-i's/^#MaxAuthTries.*$/MaxAuthTries3/'/etc/ssh/sshd_config sed-i"s/#ClientAliveInterval0/ClientAliveInterval30/g"/etc/ssh/sshd_config sed-i"s/#ClientAliveCountMax3/ClientAliveCountMax3/g"/etc/ssh/sshd_config sed-i"s/X11Forwardingyes/X11Forwardingno/g"/etc/ssh/sshd_config sed-i"s/#Bannernone/Banner\/etc\/issue.net/g"/etc/ssh/sshd_config echo"Authorizedusersonly.Allactivitymaybemonitoredandreported.">/etc/issue.net systemctlrestartsshd.service>>${LOCK}2>&1 cat/etc/ssh/sshd_config>>${LOCK}2>&1 echo-e"\r${RGB_SUCCESS}ConfigurationSuccess${RGB_END}" } timeout_config(){ echo"=============timeoutconfig=============">>${LOCK}2>&1 echo-en"${RGB_WAIT}Configuring...${RGB_END}" echo"exportTMOUT=1800">>/etc/profile.d/centos7init.sh cat/etc/profile.d/centos7init.sh>>${LOCK}2>&1 echo-e"\r${RGB_SUCCESS}ConfigurationSuccess${RGB_END}" } lockout_policy(){ echo"=============lockoutpolicy=============">>${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 authrequiredpam_env.so authrequiredpam_faillock.sopreauthsilentauditdeny=3unlock_time=300 authrequiredpam_faildelay.sodelay=2000000 auth[default=1ignore=ignoresuccess=ok]pam_succeed_if.souid>=1000quiet auth[default=1ignore=ignoresuccess=ok]pam_localuser.so authsufficientpam_unix.sonulloktry_first_pass auth[default=die]pam_faillock.soauthfailauditdeny=3unlock_time=300 authrequisitepam_succeed_if.souid>=1000quiet_success authsufficientpam_sss.soforward_pass authrequiredpam_deny.so accountrequiredpam_unix.so accountsufficientpam_localuser.so accountsufficientpam_succeed_if.souid<1000quiet account[default=badsuccess=okuser_unknown=ignore]pam_sss.so accountrequiredpam_permit.so accountrequiredpam_faillock.so passwordrequisitepam_pwquality.sotry_first_passlocal_users_only passwordsufficientpam_unix.sosha512shadownulloktry_first_passuse_authtok passwordsufficientpam_sss.souse_authtok passwordrequiredpam_deny.so sessionoptionalpam_keyinit.sorevoke sessionrequiredpam_limits.so -sessionoptionalpam_systemd.so session[success=1default=ignore]pam_succeed_if.soserviceincrondquietuse_uid sessionrequiredpam_unix.so sessionoptionalpam_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 authrequiredpam_env.so authrequiredpam_faillock.sopreauthsilentauditdeny=3unlock_time=300 authrequiredpam_faildelay.sodelay=2000000 auth[default=1ignore=ignoresuccess=ok]pam_succeed_if.souid>=1000quiet auth[default=1ignore=ignoresuccess=ok]pam_localuser.so authsufficientpam_unix.sonulloktry_first_pass auth[default=die]pam_faillock.soauthfailauditdeny=3unlock_time=300 authrequisitepam_succeed_if.souid>=1000quiet_success authsufficientpam_sss.soforward_pass authrequiredpam_deny.so accountrequiredpam_unix.so accountsufficientpam_localuser.so accountsufficientpam_succeed_if.souid<1000quiet account[default=badsuccess=okuser_unknown=ignore]pam_sss.so accountrequiredpam_permit.so accountrequiredpam_faillock.so passwordrequisitepam_pwquality.sotry_first_passlocal_users_only passwordsufficientpam_unix.sosha512shadownulloktry_first_passuse_authtok passwordsufficientpam_sss.souse_authtok passwordrequiredpam_deny.so sessionoptionalpam_keyinit.sorevoke sessionrequiredpam_limits.so -sessionoptionalpam_systemd.so session[success=1default=ignore]pam_succeed_if.soserviceincrondquietuse_uid sessionrequiredpam_unix.so sessionoptionalpam_sss.so EOF systemctlrestartsshd.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}ConfigurationSuccess${RGB_END}" } reboot_os(){ echo-e"\n${RGB_WARNING}Pleaserestarttheserverandseeiftheservicesstartupfine.${RGB_END}" echo-en"${RGB_WARNING}DoyouwanttorestartOS?[y/n]:${RGB_END}" while:;do readREBOOT_STATUS if[[!"${REBOOT_STATUS}"=~^[y n]$]];then echo-en"${RGB_DANGER}Inputerror pleaseonlyinput'y'or'n':${RGB_END}" else break fi done ["${REBOOT_STATUS}"=='y']&&reboot } main(){ echo-e"\n${RGB_INFO}1/18:StartInitCentOS7Script${RGB_END}" echo-e"\n${RGB_INFO}2/18:Customizetheprofile(colorandalias)${RGB_END}" custom_profile echo-e"\n${RGB_INFO}3/18:Timezoneadjustment${RGB_END}" time_zone echo-e"\n${RGB_INFO}4/18:Disableselinuxandfirewalld${RGB_END}" disable_software echo-e"\n${RGB_INFO}5/18:DisableCtrl Alt Del${RGB_END}" disable_cad echo-e"\n${RGB_INFO}6/18:Kernelparameteroptimization${RGB_END}" kernel_optimum echo-e"\n${RGB_INFO}7/18:Theupdatedboptimization${RGB_END}" updatedb_optimum echo-e"\n${RGB_INFO}8/18:Addingswapspace${RGB_END}" new_swap echo-e"\n${RGB_INFO}9/18:Adjustmentofulimit${RGB_END}" adjust_ulimit echo-e"\n${RGB_INFO}10/18:Enabletcpbbrcongestioncontrolalgorithm${RGB_END}" open_bbr echo-e"\n${RGB_INFO}11/18:EnableIPV6${RGB_END}" open_ipv6 echo-e"\n${RGB_INFO}12/18:Removeunnecessaryusersandusergroupsfromthesystem${RGB_END}" remove_users echo-e"\n${RGB_INFO}13/18:Systempermissionsforsensitivefiles${RGB_END}" sys_permissions echo-e"\n${RGB_INFO}14/18:ModifyAccountPasswordSurvivalPolicy${RGB_END}" password_policy echo-e"\n${RGB_INFO}15/18:Maximumnumberofdaysanaccountisvalidafterpasswordexpirationstrategy${RGB_END}" change_useradd echo-e"\n${RGB_INFO}16/18:SecureconfigurationofSSH${RGB_END}" sec_ssh echo-e"\n${RGB_INFO}17/18:TimeoutAuto-LogoutConfiguration${RGB_END}" timeout_config echo-e"\n${RGB_INFO}18/18:Configureaccountloginfailurelockoutpolicy${RGB_END}" lockout_policy reboot_os } clear tool_info check_root check_os check_lock main

测试执行截图如下

centos7 安全加固脚本(CentOS7一键安全加固及系统优化脚本)(2)

再次执行脚本会提示已经做了安全加固优化,无须再次执行

centos7 安全加固脚本(CentOS7一键安全加固及系统优化脚本)(3)

猜您喜欢: