SSH

SSH(Secure Shell)是一种用于安全远程登录和其他网络服务的协议。它通过加密的方式在不安全的网络上提供安全的通信通道。SSH广泛应用于系统管理、远程操作和文件传输等场景。

ssh 配置加固、防爆破与二次验证

配置加固

文件位置:/etc/ssh/sshd_config

Port 22                     # 修改默认端口,防止被扫描
PermitRootLogin no          # 禁止root用户远程登录
PasswordAuthentication no   # 禁止密码登录,使用密钥登录
AllowUsers user1 user2  # 只允许指定用户登录
MaxAuthTries 3            # 限制最大认证尝试次数
LoginGraceTime 30s        # 登录宽限时间
X11Forwarding no          # 禁止X11转发
AllowTcpForwarding no      # 禁止TCP转发

修改后执行 systemctl restart sshd 使配置生效。

基于 IP 的访问控制(hosts.allow/hosts.deny)

文件位置:

  • /etc/hosts.allow

  • /etc/hosts.deny

这两份文件属于 TCP Wrapper 控制机制(sshd 默认支持)。

默认拒绝所有外部访问:

# /etc/hosts.deny
sshd: ALL

允许指定源 IP 地址访问:

# /etc/hosts.allow
sshd: 10.10.10.0/24,10.188.188.188

# 支持配置网段和单个 IP 地址,无论你是一行写多个地址,还是分行列出来,hosts.allow 都能正常识别,效果完全一样。配置方式可以根据你自己的习惯来。

sshd: 10.10.10.0/24
sshd: 10.188.188.188

fail2ban: 动态防御暴力破解

fail2ban 是一个基于日志文件的入侵防御软件,可以监控系统日志文件中的登录尝试,并根据预设的规则自动禁止多次失败的登录尝试的 IP 地址,从而防止暴力破解攻击。

安装 fail2ban:

sudo apt-get install fail2ban  # Debian/Ubuntu
sudo yum install fail2ban      # CentOS/RHEL

新建 /etc/fail2ban/jail.local 配置文件:

[sshd]
enabled  = true
port     = 22
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 3
findtime = 10m
bantime  = 1h

启动与验证

sudo systemctl start fail2ban
sudo systemctl enable fail2ban
sudo fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed: 0
|  |- Total failed: 5
|  `- File list: /var/log/auth.log
`- Actions
   |- Currently banned: 2
   |- Total banned: 2
   `- Banned IP list: 192.168.1.100, 192.168.1.101

Google Authenticator:二次认证(2FA)

Google Authenticator 是一种基于时间的一次性密码(TOTP)生成器,可以为 SSH 登录提供二次认证(2FA),增强系统的安全性。 不需要联网即可使用,适合在没有网络环境下的场景。

安装 Google Authenticator 并初始化:

sudo apt-get install libpam-google-authenticator  # Debian/Ubuntu
sudo yum install google-authenticator              # CentOS/RHEL

google-authenticator
# 扫描生成的二维码并保存应急码。

修改 PAM 验证模块

# 编辑 /etc/pam.d/sshd:
# 在顶部添加:
auth required pam_google_authenticator.so

启用查询响应 编辑 /etc/ssh/sshd_config:

ChallengeResponseAuthentication yes

重启 SSH 服务使配置生效:

sudo systemctl restart sshd