718 字
4 分钟
VPS保护流程
以下操作均在debian12中操作
创建普通用户
useradd -m -s /usr/bin/bash <username># -m: 创建用户目录# -s <shell>: 指定shell# 若没有添加-s参数使用以下命令# user -s /usr/bin/bash <username>添加密码
passwd <username>使用root权限
如果没有sudo,先安装
vim /etc/sudoers找到root ALL=(ALL:ALL) ALL这行,复制粘贴到下一行,把root改为
使用su <username>可切换用户
上传公共密钥
客户端
创建.ssh目录
在“C:\Users<username>或/home/
# Windowsmd .ssh# Mac or Linuxmkdir .ssh生成密钥
# key name随便填ssh-keygen -t ed25519 -C "<key name>"按三次回车,密钥即可创建成功
上传密钥到服务器
ssh默认端口为22
# Windowsscp -P <port> C:\Users\<username>\.ssh\id_ed25519.pub <普通用户名>@<域名或服务器IP>:~/.ssh/authorized_keys# Linux or Macscp -P <port> ~/.ssh/id_ed25519.pub <普通用户名>@<域名或服务器IP>:~/.ssh/authorized_keys服务端
赋予密钥文件权限
chmod 600 authorized_keys到这里已经可以使用密钥登陆了
SSH修改端口
端口共有35536个,范围0-65535
sudo vim /etc/ssh/sshd_config修改以下内容
Port <随机ssh端口>PermitRootLogin no #禁用root用户登录PasswordAuthentication no #禁用密码登录PubkeyAuthentication yes #允许公钥认证AddressFamily inet #sshd不监听ipv6端口重启服务
sudo systemctl restart sshUFW 防火墙配置
启用防火墙
sudo ufw enable允许端口
sudo ufw limit from 0.0.0.0/0 to any port <ssh端口> proto tcp # 只开放ipv4端口,limit限速sudo ufw allow 443/tcpsudo ufw allow 80/tcp禁用端口
sudo ufw deny <port>/<udp or tcp>载入规则
sudo ufw reload查看规则
Terminal window sudo ufw status删除规则
Terminal window sudo ufw status numberedsudo ufw delete <序号>禁用防火墙
Terminal window sudo ufw disable
禁用Ping
sudo vim /etc/ufw/before.rules搜echo-request,这有两个,把有input的那行的ACCEPT改成DROP
载入规则
sudo ufw reload创建虚拟内存
sudo fallocate -l 512M /swapsudo chmod 600 /swapsudo mkswap /swapsudo swapon /swapecho '/swap none swap sw 0 0' | sudo tee -a /etc/fstab验证
free -hsudo swapon --show在/etc/sysctl.conf里追加vm.swappiness=10
使用以下命令载入规则
sudo sysctl -p添加Sysctl规则
sudo vim /etc/sysctl.conf追加规则
net.core.default_qdisc = fqnet.ipv4.tcp_congestion_control = bbrnet.ipv4.tcp_mtu_probing = 1net.ipv4.tcp_slow_start_after_idle = 0net.ipv4.tcp_syncookies = 1载入规则
sudo sysctl -pFail2ban
防止ssh被暴力破解
安装fail2ban
sudo apt update && sudo apt install fail2ban复制文件
cd /etc/fail2bancp fail2ban.conf fail2ban.localvim fail2ban.local添加内容
[sshd]enabled = trueport = <SSH port>filter = sshdlogpath = /var/log/auth.logbackend = auto
maxretry = 3findtime = 10mbantime = 7d
bantime.increment = truebantime.factor = 2bantime.maxtime = 30d创建日志文件
sudo mkdir /var/log/auth.log重启fail2ban
sudo systemctl enable fail2bansudo systemctl restart fail2ban查看状态
sudo fail2ban-client statussudo fail2ban-client status sshd解除指定IP
Terminal window sudo fail2ban-client set sshd unbanip <被禁用的IP>
修改日志大小上限
sudo vim /etc/systemd/journald.conf修改以下参数
SystemMaxUse=200MSystemKeepFree=500MMaxRetentionSec=7day重启服务
sudo systemctl restart systemd-journaldsudo systemctl status systemd-journald时间同步
sudo apt update && sudo apt install chrony
sudo systemctl enable --now chronychronyc tracking自动安全更新
小型VPS不建议,占资源
sudo dpkg-reconfigure -plow unattended-upgrades