Linux SSH安全加固完整指南

Linux SSH安全加固完整指南

一、SSH基础配置

1.1 SSH配置文件位置


# 主配置文件
/etc/ssh/sshd_config

# 用户配置
~/.ssh/config

1.2 常用配置项


# 编辑SSH配置
sudo vim /etc/ssh/sshd_config

# 常用配置:
Port 2222                  # 更改默认端口
PermitRootLogin no         # 禁止root登录
PasswordAuthentication no    # 禁用密码登录
PubkeyAuthentication yes    # 启用公钥认证
PermitEmptyPasswords no    # 禁止空密码
ClientAliveInterval 300      # 客户端存活检测
ClientAliveCountMax 2      # 最大检测次数
MaxAuthTries 3             # 最大认证次数
LoginGraceTime 60          # 登录宽限期

1.3 重启服务


# 重启SSH服务
sudo systemctl restart sshd

# 检查配置语法
sudo sshd -t

二、密钥认证配置

2.1 生成密钥对


# 生成ED25519密钥(推荐)
ssh-keygen -t ed25519 -C "your@email.com"

# 或生成RSA密钥
ssh-keygen -t rsa -b 4096 -C "your@email.com"

2.2 复制公钥到服务器


# 方法1:使用ssh-copy-id
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server

# 方法2:手动复制
mkdir -p ~/.ssh
chmod 700 ~/.ssh
cat id_ed25519.pub >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys

2.3 SSH客户端配置


# 编辑 ~/.ssh/config
Host myserver
    HostName server.example.com
    User username
    Port 2222
    IdentityFile ~/.ssh/id_ed25519
    ServerAliveInterval 300
    ServerAliveCountMax 2

三、防火墙配置

3.1 UFW防火墙


# 安装UFW
sudo apt install ufw

# 配置规则
sudo ufw allow 2222/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# 启用防火墙
sudo ufw enable

# 查看状态
sudo ufw status numbered

3.2 iptables


# 允许SSH
sudo iptables -A INPUT -p tcp --dport 2222 -j ACCEPT

# 限制连接频率
sudo iptables -A INPUT -p tcp --dport 2222 -m limit --limit 3/min --limit-burst 3 -j ACCEPT

# 禁止非法连接
sudo iptables -A INPUT -p tcp --dport 2222 -j DROP

四、Fail2ban配置

4.1 安装Fail2ban


sudo apt install fail2ban

4.2 创建本地配置


# 创建配置文件
sudo vim /etc/fail2ban/jail.local

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600

[sshd-ddos]
enabled = true
port = ssh
filter = sshd-ddos
logpath = /var/log/auth.log
maxretry = 6
bantime = 3600

4.3 管理命令


# 查看状态
sudo fail2ban-client status

# 查看被ban的IP
sudo fail2ban-client status sshd

# 手动unban IP
sudo fail2ban-client set sshd unbanip 

# 重启服务
sudo systemctl restart fail2ban

五、SSH密钥安全

5.1 密钥权限设置


# 设置正确的权限
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub

5.2 使用SSH Agent


# 启动agent
eval "$(ssh-agent -s)"

# 添加密钥
ssh-add ~/.ssh/id_ed25519

# 查看已添加的密钥
ssh-add -l

# 从agent中删除密钥
ssh-add -d ~/.ssh/id_ed25519

六、双因素认证

6.1 安装Google Authenticator


sudo apt install libpam-google-authenticator

6.2 配置PAM


# 编辑PAM配置
sudo vim /etc/pam.d/sshd

# 添加:
auth required pam_google_authenticator.so

6.3 SSH配置


# 编辑sshd_config
sudo vim /etc/ssh/sshd_config

# 添加:
ChallengeResponseAuthentication yes
AuthenticationMethods password,keyboard-interactive

七、总结

本文介绍了SSH安全加固的完整方案。

核心要点:

安全等级提升:

  • 基本配置 → 中级配置 → 高安全配置

发表回复

后才能评论