欢迎关注「全栈工程师修炼指南」公众号
点击 👇 下方卡片 即可关注我哟!
设为「星标⭐」每天带你 基础入门 到 进阶实践 再到 放弃学习!
“ 花开堪折直须折,莫待无花空折枝。 ”
作者主页:[ https://www.weiyigeek.top ]
博客:[ https://blog.weiyigeek.top ]
作者答疑学习交流群:请关注公众号后回复【学习交流群】
本章目录:
0x00 前言简述
0x01 常规配置
-
1.主机IP地址与网关设置
2.主机DNS配置
3.镜像源配置
4.常规运维工具安装及系统升级
5.系统时间时区同步配置
0x02 系统优化
-
1.创建swap系统分区配置
2.系统资源句柄数优化配置
3.系统常规内核参数优化配置
4.系统服务优化配置
0x03 安全加固
-
1.远程登录主机提示信息
2.远程登录主机系统信息
3.远程登录sshd服务安全策略配置
4.系统账户安全策略配置
5.系统账户密码更改及过期策略配置
6.系统用户密码复杂性策略配置
7.系统用户登录失败策略配置
8.系统用户su/sudo权限策略配置
8.系统文件权限策略配置
9.系统grub引导安全策略配置
10.系统用户历史命令记录策略配置
11.系统安全日志事件记录策略配置
12.系统审计规则安全策略配置
13.配置禁用系统非必须别名策略
14.配置禁用桌面系统策略
15.配置禁用Ctrl+Alt+Del重启系统
16.配置rm删除回收站策略
17.配置清除临时文件策略
18.配置系统防火墙策略
19.配置重启服务器策略
本文为作者原创文章,为尊重作者劳动成果禁止非授权转载,若需转载请在【全栈工程师修炼指南】公众号留言,或者发送邮件到 [master@weiyigeek.top] 中我将及时回复。
免责申明:本文分享旨在给网络安全从业人员、网站开发人员以及运维管理人员在日常工作中进行安全攻防测试以及防范恶意攻击, 请勿恶意使用下面介绍技术进行非法网络攻击,作者不为此承担任何责任,所有渗透都需获取授权,谨防从入门到入狱!
【中华人民共和国网络安全法】: http://www.npc.gov.cn/npc/c30834/201611/270b43e8b35e4f7ea98502b6f0e26f8a.shtml
0x00 前言简述
描述: 随着国家要求各政府部门及事企业单位服务器系统国产化,越来越多的的企业单位逐步引进国产化Linux操作系统(大趋势
),在众多国产操作系统中银河麒麟(KylinOS)、中科方德、统信UOS
,此三家持续版本迭代超15年的其生态市场及占有率最高, 除此之外红旗Linux、共创Linux、凝思磐石、新支点、深度Linux、Start OS、思普操作系统、云针OS、鸿蒙OS、YunOS、OpenCloudOS等国产操作系统。
此处由于我们企业中是试用的银河麒麟(KylinOS)V10 SP3 版本的国产系统,为了试用该系统是否可以承载现有业务,以及满足网络安全等保2.0主机安全配置要求,遂针对该系统进行安全加固及常规初始化操作,设置安全基线镜像,以保证基础业务运行环境安全。
这里作者就不在针对银河麒麟(KylinOS)的国产系统进行详细介绍与下载安装讲解,有兴趣的朋友可以参照【1.国产银河麒麟V10服务器操作系统基础知识与安装实践】( https://blog.weiyigeek.top/2023/3-21-725.html ) 此文。
好的废话不多说,此处我将其分为三个章节,第一个章节是初始化运维常规配置,第二个章节是系统内核优化,第三个章节安全加固,此处我已经将其写成shell脚本可以直接运行加固大大的节省了我们运维人的时间,最后我会将安全加固shell脚本(部分适用于CentOS7操作系统)文末获取下载链接, 以供各位看友使用实践参考,若有错误欢迎在【全栈工程师修炼指南】公众号留言。
若需观看视频实践演示,请在【全栈工程师修炼指南
】公众号中回复【kylinos安全脚本
】或【10002
】关键字。
温馨提示: 此处为了防止伸手党,以及尊重作者编写脚本及实践成果,象征性的设置为收费合集#网络安全攻防等保 ,付费后可直接联系作者发加固脚本或者文章末尾获取下载链接,希望大家理解支持!
温馨提示: 在进行操作时请注意备份操作文件,以便于异常时及时回退。
0x01 常规配置
1.主机IP地址与网关设置
描述: 一台新安装的主机必须配置IP地址才能方便我们通过远程连接,所以第一步肯定是把网络打通,主要根据配置的IP地址与网络地址环境变量进行对应设置,例如下述部分脚本片段。
# Modify the IP/MASK and Gateway
VAR_NETINTERFACE=ens192
VAR_IP=192.168.4.201/24
VAR_GATEWAY=192.168.4.1
if [ ! -f /opt/init/ ];then
mkdir -vp /opt/init/
sudo tee /opt/init/network.sh <<'EOF'
#!/bin/bash
# @Author: WeiyiGeek
# @Description: Configure KylinOS / CentOS Linux Server Network
# @E-mail: master@weiyigeek.top
# @Blog: https://www.weiyigeek.top
if [[ $# -lt 4 ]];then
echo "Usage: $0 NetInterface IP/NETMASK GATEWAY DNS"
echo "Example: $0 ens192 192.168.12.12/24 192.168.12.1 223.6.6.6"
echo "@Author: WeiyiGeek"
echo "@Blog: https://blog.weiyigeek.top"
exit
fi
echo "Setting Network interface card: ${1}, IP: ${2} , GATEWAY: ${3}"
CURRENT_IP=$(hostname -I | cut -f 1 -d " ")
CURRENT_GATEWAY=$(hostname -I | cut -f 1,2,3,4 -d ".")
CURRENT_FILE=/etc/sysconfig/network-scripts/ifcfg-${1}
CONFIG_IP=${2%%/*}
CONFIG_PREFIX=${2##*/}
echo "Original Network info: IP: ${CURRENT_IP} , GATEWAY: ${CURRENT_GATEWAY}"
echo "Setting Network interface card: ${1}, IP/NETMASK: ${2} , GATEWAY: ${3}, DNS: ${4}"
if [[ -f ${CURRENT_FILE} ]];then
# 已存在网卡配置文件的情况下
egrep -q "^\s*ONBOOT=.*$" ${CURRENT_FILE} && sed -ri "s/^\s*ONBOOT=.*$/ONBOOT=yes/" ${CURRENT_FILE}|| echo "ONBOOT=yes" >> ${CURRENT_FILE}
egrep -q "^\s*BOOTPROTO=.*$" ${CURRENT_FILE} && sed -ri "s/^\s*BOOTPROTO=.*$/BOOTPROTO=static/" ${CURRENT_FILE}|| echo "BOOTPROTO=static" >> ${CURRENT_FILE}
egrep -q "^\s*IPADDR=.*$" ${CURRENT_FILE} && sed -ri "s/^\s*IPADDR=.*$/IPADDR=${CONFIG_IP}/" ${CURRENT_FILE}|| echo "IPADDR=${CONFIG_IP}" >> ${CURRENT_FILE}
egrep -q "^\s*PREFIX=.*$" ${CURRENT_FILE} && sed -ri "s/^\s*PREFIX=.*$/PREFIX=${CONFIG_PREFIX}/" ${CURRENT_FILE}|| echo "PREFIX=${CONFIG_PREFIX}" >> ${CURRENT_FILE}
egrep -q "^\s*GATEWAY=.*$" ${CURRENT_FILE} && sed -ri "s/^\s*GATEWAY=.*$/GATEWAY=${3}/" ${CURRENT_FILE}|| echo "GATEWAY=${3}" >> ${CURRENT_FILE}
egrep -q "^\s*DNS1=.*$" ${CURRENT_FILE} && sed -ri "s/^\s*DNS1=.*$/DNS1=${4}/" ${CURRENT_FILE}|| echo "DNS1=${4}" >> ${CURRENT_FILE}
else
nmcli dev show ${1}
nmcli conn add connection.id ${1}-staic connection.interface-name ${1} connection.autoconnect yes type Ethernet ifname ${1} ipv4.method manual ipv4.address ${2} ipv4.gateway ${3} ipv4.dns ${4} ipv4.ignore-auto-dns true
fi
sudo nmcli c reload
read -t 5 -p "Heavy load network card, It is recommended to enter N during initialization (Y/N): " VERTIFY
if [[ ${VERIFY:="N"} == "Y" || ${VERIFY:="N"} == "y" ]]; then
sudo nmcli c up ${1}
sudo nmcli d reapply ${1}
else
echo "Please reload the network card manually, run sudo nmcli d reapply ${1}."
fi
EOF
# 权限赋予
sudo chmod +x /opt/init/network.sh
# 脚本执行
/opt/init/network.sh ${VAR_NETINTERFACE} ${VAR_IP} ${VAR_GATEWAY} ${VAR_DNS_SERVER}
2.主机DNS配置
描述: 完成IP地址的配置后,我便需要为主机配置私有DNS或者公共的DNS,以便可以解析外部域名。
# Show Script Execute result (Y/N)
VAR_VERIFY_RESULT=Y
# Modify the DNS server
# DNSPod: 119.29.29.29 Alidns: 223.5.5.5 223.6.6.6
# Google: 8.8.8.8 8.8.4.4 Cloudflare: 1.1.1.1 1.0.0.1
# Baidu: 114.114.114.114
# Internal : Your intranet domain name resolution server
VAR_DNS_SERVER=( "223.5.5.5" "114.114.114.114" "192.168.4.254")
local flag
# 此处配置的是百度IPV4 DNS与阿里云IPV6 DNS
sed -i -e "s/^#FallbackDNS=.*/FallbackDNS=114.114.114.114 2400:3200::1 2400:3200:baba::1/" -e "s/^#DNSSEC=.*/DNSSEC=allow-downgrade/" -e "s/^#DNSOverTLS=.*/DNSOverTLS=opportunistic/" /etc/systemd/resolved.conf
for dns in ${VAR_DNS_SERVER[@]};do
grep -q "${dns}" /etc/systemd/resolved.conf
if [ $? != 0 ];then
echo "nameserver ${dns}"
sed -i "/#DNS=/i DNS=${dns}" /etc/systemd/resolved.conf;
fi
done
systemctl restart systemd-resolved && systemctl enable systemd-resolved
find /etc/resolv.conf -delete
ln -s /run/systemd/resolve/resolv.conf /etc/resolv.conf
if [[ ${VERIFY:="N"} == "Y" || ${VERIFY:="N"} == "y" ]]; then
grep -Ev '^#|^$' /etc/resolv.conf | uniq
echo
grep -Ev '^#|^$' /etc/systemd/resolved.conf | uniq
fi
3.镜像源配置
描述: 使用国外的操作系统,例如CentOS、Ubuntu、Debian、Alpine
等操作系统,通常为了加快Linux系统中下载安装软件的速度,我们是需要配置软件镜像源,此处由于我们是国产操作系统,其软件更新源也肯定是在国内,所以通常无需调整。
但此处为了防止小伙伴们更改过该镜像源,我也将各发行版镜像源配置罗列出来。
local release
cp /etc/yum.repos.d/kylin_x86_64.repo ${BACKUPDIR}
# 1.根据主机发行版设置
# (Tercel) 版本是 麒麟 V10 SP1 版本,
# (Sword) 版本是 麒麟 V10 SP2 版本,
# (Lance) 版本是 麒麟 V10 SP3 版本,
release=$(grep -e "^VERSION=" /etc/os-release | cut -f 2 -d "=" | tr -d '[:punct:][:space:]')
if [ ${release} == "V10Lance" ];then
sudo tee /etc/yum.repos.d/kylin_x86_64.repo <<'EOF'
### Kylin Linux Advanced Server 10 (SP3) - os repo ###
[ks10-adv-os]
name = Kylin Linux Advanced Server 10 - Os
baseurl = https://update.cs2c.com.cn/NS/V10/V10SP3/os/adv/lic/base/$basearch/
gpgcheck = 1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-kylin
enabled = 1
[ks10-adv-updates]
name = Kylin Linux Advanced Server 10 - Updates
baseurl = https://update.cs2c.com.cn/NS/V10/V10SP3/os/adv/lic/updates/$basearch/
gpgcheck = 1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-kylin
enabled = 1
[ks10-adv-addons]
name = Kylin Linux Advanced Server 10 - Addons
baseurl = https://update.cs2c.com.cn/NS/V10/V10SP3/os/adv/lic/addons/$basearch/
gpgcheck = 1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-kylin
enabled = 0
EOF
# echo "7" > /etc/yum/vars/centos_version
# wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
elif [ ${release} == "V10Sword" ];then
echo "暂未使用麒麟 V10 Sword SP2 版本,请自行百度搜索,镜像源!"
elif [ ${release} == "V10Tercel" ];then
echo "暂未使用麒麟 V10 Tercel SP1 版本,请自行百度搜索,镜像源!"
else
echo "暂未使用麒麟除 V10 以外的系统版本,请自行百度搜索,镜像源!"
fi
sudo yum clean all -y && sudo yum makecache
read -t ${VAR_VERIFY_TIMEOUT} -p "Please input, Perform system software update and upgrade. (Y/N) : " VERIFY
if [[ ${VERIFY:="N"} == "Y" || ${VERIFY:="N"} == "y" ]]; then
sudo yum update -y && sudo yum upgrade -y
fi
PS: 虽然银河麒麟(KylinOS)V10 SP3 系统中可以使用CentOS7的镜像源,但是并不建议这样否则在镜像软件更新安装时,将会出现莫名错误。
4.常规运维工具安装及系统升级
描述: 完成软件镜像源配置后我们便可进行系统更新以及,常规的运维工具安装了。
# 1.系统更新
echo "[-] 系统软件源更新."
sudo yum update && sudo yum upgrade -y && dnf repolist
# 2.安装系统所需的常规软件
echo "[-] 安装系统所需的常规软件."
sudo dnf install -y gcc make
sudo dnf install -y nano vim git unzip unrar ftp wget ntpdate dos2unix net-tools tree htop sysstat psmisc bash-completion jq rpcbind dialog nfs-utils
# 补充:代理方式进行更新
# echo "proxy=http://127.0.0.1:8080/" >> /etc/yum.conf
# sudo yum clean all -y && sudo yum update -y && sudo yum upgrade -y
# sudo yum install -y 软件包
5.系统时间时区同步配置
描述: 更新系统及对应工具后,我们需要针对系统时间时区做同步配置,此步骤非常重要往往会影响应用程序时间,建议在服务器中必须进行配置。
# Show Script Execute result (Y/N)
VAR_VERIFY_RESULT=Y
# Modify the NTP server
# PS: "192.168.4.254" 为内部NTP服务器,若需要搭建NTP服务器请参考,此篇文章: https://blog.weiyigeek.top/2020/1-29-112.html
VAR_NTP_SERVER=( "ntp.aliyun.com" "ntp.tencent.com" "192.168.10.254")
# 安装配置 chrony 时间同步服务器
# 方式1.安装 Chrony 客户端配置
if [[ $(rpm -qa | grep -c "chrony") -eq 0 ]];then
dnf install -y chrony
fi
cp /etc/chrony.conf ${BACKUPDIR}
grep -E -q "^server" /etc/chrony.conf | sed -i 's/^server/# server/g' /etc/chrony.conf
grep -E -q "^pool" /etc/chrony.conf | sed -i 's/^pool/# pool/g' /etc/chrony.conf
for ntp in ${VAR_NTP_SERVER[@]};do
echo "ntp server => ${ntp}"
if [[ ${ntp} =~ "ntp" ]];then
echo "pool ${ntp} iburst maxsources 4" >> /etc/chrony.conf;
else
echo "pool ${ntp} iburst maxsources 1" >> /etc/chrony.conf;
fi
done
systemctl enable chronyd.service && systemctl restart chronyd.service
# chrony.conf 配置示例
# sudo tee /etc/chrony.conf <<'EOF'
# confdir /etc/conf.d
# server ntp.aliyun.com iburst maxsources 4
# server ntp.tencent.com iburst maxsources 4
# pool 192.168.10.254 iburst maxsources 1
# pool 192.168.12.254 iburst maxsources 2
# pool 192.168.4.254 iburst maxsources 3
# sourcedir /run/chrony-dhcp
# sourcedir /etc/sources.d
# keyfile /etc/chrony.keys
# driftfile /var/lib/chrony/chrony.drift
# ntsdumpdir /var/lib/chrony
# logdir /var/log/chrony
# maxupdateskew 100.0
# rtcsync
# makestep 1 3
# leapsectz right/UTC
# EOF
# 方式2.使用 ntpdate 工具定时同步
# sudo ntpdate 192.168.10.254 || sudo ntpdate 192.168.12.254 || sudo ntpdate ntp1.aliyun.com
# 方式3.使用系统 systemd-timesyncd
# echo 'NTP=192.168.10.254 192.168.4.254' >> /etc/systemd/timesyncd.conf
# echo 'FallbackNTP=ntp.aliyun.com' >> /etc/systemd/timesyncd.conf
# systemctl restart systemd-timesyncd.service
if [[ ${VAR_VERIFY_RESULT} == "Y" ]];then systemctl status chronyd.service -l --no-pager;fi
主机时间同步校准与时区设置
# Modify the timezone
VAR_TIMEZONE=Asia/Shanghai
# 1.时区设置
sudo timedatectl set-timezone ${VAR_TIMEZONE}
# sudo dpkg-reconfigure tzdata # 修改确认
# sudo bash -c "echo 'Asia/Shanghai' > /etc/timezone" # 与上一条命令一样
# 2.将当前的 UTC 时间写入硬件时钟 (硬件时间默认为UTC)
sudo timedatectl set-local-rtc 0
# 3.启用NTP时间同步:
sudo timedatectl set-ntp yes
# 4.校准时间服务器-时间同步(推荐使用chronyc进行平滑同步)
sudo chronyc tracking
# 5.手动校准-强制更新时间
# chronyc -a makestep
# 6.系统时钟同步硬件时钟
# sudo hwclock --systohc
sudo hwclock -w
echo "设置时间同步与时区后: $(date)"
# 7.重启依赖于系统时间的服务
sudo systemctl restart rsyslog.service crond.service
脚本执行效果:
0x02 系统优化
1.创建swap系统分区配置
描述: 当服务器系统内存过小时,我们可以划分一块磁盘空间作为swap交换分区以补充内存过小,无法运行某些程序,通常情况下会出现在VPS上,针对于企业中的服务器基本都是在64G以上,请根据业务需求划分,我们由于使用了K8S云原生通常情况下需要禁用SWAP交换分区,不过此处作者还是将方法其罗列出来以供需要的朋友使用。
# Show Script Execute result (Y/N)
VAR_VERIFY_RESULT=Y
# Modify Script vertify timeout (unit s)
VAR_VERIFY_TIMEOUT=8
echo "[${COUNT}] Create system swap partition."
read -t ${VAR_VERIFY_TIMEOUT} -p "Please input, Create swap partition. (Y/N) : " VERIFY
if [[ ${VERIFY:="N"} == "Y" || ${VERIFY:="N"} == "y" ]]; then
# 1.验证当前内存大小
MEM=$(free -m | awk '/Mem:/{print $2}')
if [ "$MEM" -le 1280 ]; then
MEM_LEVEL=1G
elif [ "$MEM" -gt 1280 ] && [ "$MEM" -le 2500 ]; then
MEM_LEVEL=2G
elif [ "$MEM" -gt 2500 ] && [ "$MEM" -le 3500 ]; then
MEM_LEVEL=3G
elif [ "$MEM" -gt 3500 ] && [ "$MEM" -le 4500 ]; then
MEM_LEVEL=4G
elif [ "$MEM" -gt 4500 ] && [ "$MEM" -le 8000 ]; then
MEM_LEVEL=6G
elif [ "$MEM" -gt 8000 ]; then
MEM_LEVEL=8G
fi
# 2.根据内存大小划分对应的swap分区并自动挂载
if [ "$(free -m | awk '/Swap:/{print $2}')" == '0' ]; then
fallocate -l "${MEM_LEVEL}" /swapfile
chmod 600 /swapfile
mkswap /swapfile >/dev/null 2>&1
swapon /swapfile
sed -i "/swap/d" /etc/fstab
echo "/swapfile swap swap defaults 0 0" >> /etc/fstab
fi
# 3.swap分区内核参数调整
egrep -q "^\s*vm.swappiness.*$" /etc/sysctl.conf && sed -ri "s/^\s*vm.swappiness.*$/vm.swappiness = 10/" /etc/sysctl.conf || echo "vm.swappiness = 10" >> /etc/sysctl.conf
egrep -q "^\s*vm.vfs_cache_pressure.*$" /etc/sysctl.conf && sed -ri "s/^\s*vm.vfs_cache_pressure.*$/vm.vfs_cache_pressure = 501/" /etc/sysctl.conf || echo "vm.vfs_cache_pressure = 50" >> /etc/sysctl.conf
sysctl -p >/dev/null 2>&1
if [[ $VAR_VERIFY_RESULT == "Y" ]]; then
swapon --show
echo .
free -h
echo .
grep -Ev '^#|^$' /etc/fstab | uniq
fi
fi
2.系统资源句柄数优化配置
描述: 为了提高系统的高并发以及防止程序报 Too many open file 错误,通常需要针对系统资源句柄数进行优化配置。
echo "[-] Linux 系统的最大进程数和最大文件打开数限制."
cp -a /etc/security/limits.conf ${BACKUPDIR}
egrep -q "^\s*ulimit -HSn\s+\w+.*$" /etc/profile && sed -ri "s/^\s*ulimit -HSn\s+\w+.*$/ulimit -HSn 655350/" /etc/profile || echo "ulimit -HSn 655350" >> /etc/profile
egrep -q "^\s*ulimit -HSu\s+\w+.*$" /etc/profile && sed -ri "s/^\s*ulimit -HSu\s+\w+.*$/ulimit -HSu 655350/" /etc/profile || echo "ulimit -HSu 655350" >> /etc/profile
if ! grep -qi "# OS Resources Limits Config" /etc/security/limits.conf; then
sed -i 's/^# End of file*//' /etc/security/limits.conf
{
echo '# OS Resources Limits Config'
echo '* soft nofile 655350'
echo '* hard nofile 655350'
echo '* soft nproc unlimited'
echo '* hard nproc unlimited'
echo '* soft core unlimited'
echo '* hard core unlimited'
echo '# End of file'
} >> /etc/security/limits.conf
fi
if [[ $VAR_VERIFY_RESULT == "Y" ]]; then grep -Ev '^#|^$' /etc/security/limits.conf | uniq;fi
3.系统常规内核参数优化配置
描述: 服务器内核参数的优化有助于系统以及应用程序提供更好的性能,但是通常需要针对应用程序特点以及应用场景进行相应配置,下述只是常规配置有侧重点的朋友们,可根据实际情况进行调整。
# Show Script Execute result (Y/N)
VAR_VERIFY_RESULT=Y
# Modify Script vertify timeout (unit s)
VAR_VERIFY_TIMEOUT=8
# 1.系统内核参数的配置文件/etc/sysctl.conf
echo "[-] 系统内核参数的优化配置 /etc/sysctl.conf"
# 启用IPV4数据包转发(业务需要)
egrep -q "^(#)?net.ipv4.ip_forward.*" /etc/sysctl.conf && sed -ri "s|^(#)?net.ipv4.ip_forward.*|net.ipv4.ip_forward = 1|g" /etc/sysctl.conf || echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
# egrep -q "^(#)?net.bridge.bridge-nf-call-ip6tables.*" /etc/sysctl.conf && sed -ri "s|^(#)?net.bridge.bridge-nf-call-ip6tables.*|net.bridge.bridge-nf-call-ip6tables = 1|g" /etc/sysctl.conf || echo "net.bridge.bridge-nf-call-ip6tables = 1" >> /etc/sysctl.conf
# egrep -q "^(#)?net.bridge.bridge-nf-call-iptables.*" /etc/sysctl.conf && sed -ri "s|^(#)?net.bridge.bridge-nf-call-iptables.*|net.bridge.bridge-nf-call-iptables = 1|g" /etc/sysctl.conf || echo "net.bridge.bridge-nf-call-iptables = 1" >> /etc/sysctl.conf
egrep -q "^(#)?net.ipv6.conf.all.disable_ipv6.*" /etc/sysctl.conf && sed -ri "s|^(#)?net.ipv6.conf.all.disable_ipv6.*|net.ipv6.conf.all.disable_ipv6 = 1|g" /etc/sysctl.conf || echo "net.ipv6.conf.all.disable_ipv6 = 1" >> /etc/sysctl.conf
egrep -q "^(#)?net.ipv6.conf.default.disable_ipv6.*" /etc/sysctl.conf && sed -ri "s|^(#)?net.ipv6.conf.default.disable_ipv6.*|net.ipv6.conf.default.disable_ipv6 = 1|g" /etc/sysctl.conf || echo "net.ipv6.conf.default.disable_ipv6 = 1" >> /etc/sysctl.conf
egrep -q "^(#)?net.ipv6.conf.lo.disable_ipv6.*" /etc/sysctl.conf && sed -ri "s|^(#)?net.ipv6.conf.lo.disable_ipv6.*|net.ipv6.conf.lo.disable_ipv6 = 1|g" /etc/sysctl.conf || echo "net.ipv6.conf.lo.disable_ipv6 = 1" >> /etc/sysctl.conf
egrep -q "^(#)?net.ipv6.conf.all.forwarding.*" /etc/sysctl.conf && sed -ri "s|^(#)?net.ipv6.conf.all.forwarding.*|net.ipv6.conf.all.forwarding = 1|g" /etc/sysctl.conf || echo "net.ipv6.conf.all.forwarding = 1" >> /etc/sysctl.conf
# 2.系统内核参数扩展优化配置
if ! grep -qi "# OS Resources Limits Config" /etc/sysctl.conf; then
tee -a /etc/sysctl.conf <<'EOF'
# Configuration of system kernel parameters
# 禁止 icmp 重定向报文
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
# 忽略 icmp echo 请求广播
net.ipv4.icmp_echo_ignore_broadcasts = 1
# 禁止 icmp 源路由
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
# 禁止发送重定向 (若非必须建议设置 0)
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
# 禁止对主机进行 IP 伪装
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# 限制一个进程可以拥有的VMA(虚拟内存区域)的数量
vm.max_map_count = 262144
# 设置内存分配策略,使用0表示内核将检查是否有足够的可用内存。
vm.overcommit_memory = 0
# 调整提升服务器负载能力之外,还能够防御小流量的Dos、CC和SYN攻击
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
# net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_fin_timeout = 60
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_fastopen = 3
# 优化TCP的可使用端口范围及提升服务器并发能力(注意一般流量小的服务器上没必要设置如下参数)
net.ipv4.tcp_keepalive_time = 7200
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_max_tw_buckets = 16384
net.ipv4.ip_local_port_range = 1024 65535
# 优化核套接字TCP的缓存区
net.core.netdev_max_backlog = 8192
net.core.somaxconn = 32768
net.core.rmem_max = 12582912
net.core.rmem_default = 6291456
net.core.wmem_max = 12582912
net.core.wmem_default = 6291456
# 内存缓存IO优化
vm.dirty_background_ratio = 5
vm.dirty_ratio = 10
EOF
fi
if [[ ${VAR_VERIFY_RESULT} == "Y" ]];then sysctl -p;fi
4.系统服务优化配置
描述: 针对我们新安装的KylinOS服务器中往往存在许多非必须服务,此处我们可以根据需求禁用相关服务。
# 1.用于关闭与禁用某些服务端口
echo "[-] 用于关闭与禁用某些服务端口。."
local VAR_APP_SERVICE VAR_SYSTEM_SERVICE
VAR_APP_SERVICE="telnet.socket printer sendmail nfs kshell lpd tftp ident time ntalk bootps klogin ypbind daytime nfslock echo discard chargen debug-shell.service"
VAR_SYSTEM_SERVICE="chargen-dgram daytime-stream echo-streamklogin tcpmux-server chargen-stream discard-dgram eklogin krb5-telnet tftp cvs discard-stream ekrb5-telnet kshell time-dgram daytime-dgram echo-dgram gssftp rsync time-stream"
for i in ${VAR_APP_SERVICE};do
echo "Status and Disable APP ${i} Service!"
# systemctl status ${i}
systemctl stop ${i};systemctl disable ${i};
done
for i in ${VAR_SYSTEM_SERVICE};do
echo "Status and Disable System ${i} Service!"
# systemctl status ${i}
systemctl stop ${i};systemctl disable ${i};
done
# 2.禁用烦人的apport错误报告
if [ -f /etc/default/apport ]; then
cp /etc/default/apport ${BACKUPDIR}
sed -i 's/enabled=.*/enabled=0/' /etc/default/apport
systemctl stop apport.service
systemctl disable apport.service
systemctl mask apport.service >/dev/null 2>&1
fi
read -t ${VAR_VERIFY_TIMEOUT} -p "Please input, is service verificating (Y/N) : " VERIFY
if [[ ${VERIFY:="N"} == "Y" || ${VERIFY:="N"} == "y" ]]; then
systemctl status apport.service --no-pager
else
log::success "[${COUNT}] This operation is completed!"
fi
# 3.非云的环境下禁用或者卸载多余的cloud-init软件及其服务
sudo systemctl stop cloud-init.target cloud-init.service cloud-config.service cloud-init-local.service cloud-final.service
sudo systemctl disable cloud-init.target cloud-init.service cloud-config.service cloud-init-local.service cloud-final.service
sudo systemctl mask cloud-init.service cloud-config.service cloud-init-local.service cloud-final.service >/dev/null 2>&1
# 禁用 Ubuntu 中的 cloud-init, 在 /etc/cloud 目录下创建 cloud-init.disable 文件(重启后生效)
if [ ! -f /etc/cloud/cloud-init.disable ];then sudo touch /etc/cloud/cloud-init.disable;fi
read -t ${VAR_VERIFY_TIMEOUT} -p "Please input, is Remove cloud-init related files and their directories (Y/N) : " VERIFY
if [[ ${VERIFY:="N"} == "Y" || ${VERIFY:="N"} == "y" ]]; then
sudo apt purge cloud-init -y
sudo rm -rf /etc/cloud && sudo rm -rf /var/lib/cloud/
fi
sudo systemctl daemon-reload
# 4.在系统启动时禁用debug-shell服务
systemctl stop debug-shell.service
systemctl mask debug-shell.service >/dev/null 2>&1
if [[ $VAR_VERIFY_RESULT == "Y" ]]; then
systemctl status debug-shell.service --no-pager
fi
0x03 安全加固
1.远程登录主机提示信息
描述: 配置提示信息可以提示运维人员以及恶意人员,在非权限授权时禁止访问。
# 1.设置SSH登录前警告Banner提示
egrep -q "^\s*(banner|Banner)\s+\W+.*$" /etc/ssh/sshd_config && sed -ri "s/^\s*(banner|Banner)\s+\W+.*$/Banner \/etc\/issue.net/" /etc/ssh/sshd_config || echo "Banner /etc/issue.net" >> /etc/ssh/sshd_config
sudo tee /etc/issue <<'EOF'
************************* [ 安全登陆 (Security Login) ] ************************
Authorized users only. All activity will be monitored and reported.By WeiyiGeek Security Center.
Author: WeiyiGeek
blog: https://blog.weiyigeek.top
EOF
sudo tee /etc/issue.net <<'EOF'
************************* [ 安全登陆 (Security Login) ] *************************
Authorized users only. All activity will be monitored and reported.By WeiyiGeek Security Center.
Author: WeiyiGeek
blog: https://blog.weiyigeek.top
EOF
# 2.本地控制台与SSH登录后提示自定义提示信息
tee /etc/motd <<'EOF'
Welcome to KylinOS Private Cloud Computer Service!
If the server is abnormal, please add WX weiyigeeker (WeiyiGeek-Security-Center)
_ooOoo_
o8888888o
88" . "88
(| -_- |)
O\ = /O
____/`---'\____
.' \\| |// `.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' | |
\ .-\__ `-` ___/-. /
___`. .' /--.--\ `. . __
."" '< `.___\_<|>_/___.' >'"".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `-. \_ __\ /__ _/ .-` / /
======`-.____`-.___\_____/___.-`____.-'======
`=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
佛祖保佑 永不死机
心外无法 法外无心
EOF
脚本执行效果:
2.远程登录主机系统信息
描述: 在登录到系统后及时的显示服务器系统相关信息,包括但不限于系统资源信息、登录时间、失败信息,以及各分区磁盘使用率。
脚本执行效果:
脚本片段如下: