ssh-hardening
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSSH Hardening Skill
SSH安全加固技能
Secure SSH access to VPS servers by implementing industry-standard hardening practices.
通过实施行业标准的加固实践,保障VPS服务器的SSH访问安全。
What This Skill Does
本技能的作用
This skill helps AI agents harden SSH configuration on VPS servers. SSH is the primary entry point for server management, making it a critical attack vector. Proper SSH hardening prevents unauthorized access, brute-force attacks, and credential theft.
Key capabilities:
- Create non-root users with sudo privileges
- Generate and configure SSH key authentication
- Disable password-based authentication
- Disable root login over SSH
- Configure security settings in sshd_config
- Test configuration before applying
本技能可帮助AI Agent加固VPS服务器上的SSH配置。SSH是服务器管理的主要入口,因此成为了关键的攻击面。正确的SSH加固可防止未授权访问、暴力破解攻击和凭证窃取。
核心功能:
- 创建拥有sudo权限的非root用户
- 生成并配置SSH密钥认证
- 禁用基于密码的认证
- 禁用SSH的root登录
- 在sshd_config中配置安全设置
- 应用前测试配置
When to Use
使用场景
Use this skill when you need to:
- Set up a new VPS server with secure SSH access
- Replace password authentication with SSH keys
- Disable root login for security compliance
- Harden an existing server against brute-force attacks
- Fix security audit findings related to SSH
- Implement principle of least privilege
Critical understanding: Root can do anything. One typo, one compromised session, and your entire system is gone. Passwords can be guessed. SSH keys can't be brute-forced in any practical timeframe.
在以下场景中使用本技能:
- 为新VPS服务器配置安全的SSH访问
- 用SSH密钥替换密码认证
- 为符合安全合规要求禁用root登录
- 加固现有服务器以抵御暴力破解攻击
- 修复与SSH相关的安全审计问题
- 实施最小权限原则
关键认知: Root用户拥有完全权限。一个输入错误、一次会话泄露,都可能导致整个系统沦陷。密码容易被猜测,而SSH密钥在实际场景中无法被暴力破解。
Prerequisites
前置条件
- Root or existing sudo user access to the server
- SSH access to the server (keep current session open!)
- SSH client on local machine (ssh, ssh-keygen, ssh-copy-id)
- Terminal access to local machine
- 拥有服务器的Root或现有sudo用户访问权限
- 服务器的SSH访问权限(请保持当前会话处于打开状态!)
- 本地机器上的SSH客户端(ssh、ssh-keygen、ssh-copy-id)
- 本地机器的终端访问权限
SSH Hardening Steps
SSH加固步骤
Step 1: Create Non-Root User
步骤1:创建非Root用户
CRITICAL: Complete this step and test before disabling root login!
Create a new user for daily operations:
bash
undefined重要提示: 完成此步骤并测试后,再禁用root登录!
创建用于日常操作的新用户:
bash
undefinedCreate user (replace 'deployer' with desired username)
创建用户(将'deployer'替换为你想要的用户名)
sudo adduser deployer
Enter a strong password when prompted.
Add user to sudo group:
```bash
sudo usermod -aG sudo deployerTest sudo access before proceeding:
bash
undefinedsudo adduser deployer
按提示输入强密码。
将用户添加到sudo组:
```bash
sudo usermod -aG sudo deployer继续前测试sudo权限:
bash
undefinedSwitch to new user
切换到新用户
su - deployer
su - deployer
Test sudo
测试sudo
sudo whoami
sudo whoami
Should output: root
应输出:root
Exit back to original user
退出回到原用户
exit
undefinedexit
undefinedStep 2: Generate SSH Key Pair (Local Machine)
步骤2:生成SSH密钥对(本地机器)
On your local machine (not the server), generate an SSH key:
bash
ssh-keygen -t ed25519 -C "your-email@example.com"Key type explained:
- - Modern, secure, fast (recommended)
ed25519 - Alternative: for older systems
rsa -b 4096
When prompted:
- Press Enter to save to default location ()
~/.ssh/id_ed25519 - Enter a strong passphrase (recommended) or leave empty
在本地机器(而非服务器)上生成SSH密钥:
bash
ssh-keygen -t ed25519 -C "your-email@example.com"密钥类型说明:
- - 现代、安全、快速(推荐使用)
ed25519 - 替代方案:针对旧系统使用
rsa -b 4096
当出现提示时:
- 按回车键保存到默认位置()
~/.ssh/id_ed25519 - 输入强密码短语(推荐)或留空
Step 3: Copy SSH Key to Server
步骤3:将SSH密钥复制到服务器
From your local machine, copy the public key to the server:
bash
ssh-copy-id deployer@your-server-ipEnter the user's password when prompted.
Manual alternative (if ssh-copy-id is unavailable):
bash
undefined从本地机器将公钥复制到服务器:
bash
ssh-copy-id deployer@your-server-ip按提示输入用户密码。
手动替代方案(如果ssh-copy-id不可用):
bash
undefinedOn local machine, display public key
在本地机器上显示公钥
cat ~/.ssh/id_ed25519.pub
cat ~/.ssh/id_ed25519.pub
On server, as the new user
在服务器上,以新用户身份执行
mkdir -p ~/.ssh
chmod 700 ~/.ssh
nano ~/.ssh/authorized_keys
mkdir -p ~/.ssh
chmod 700 ~/.ssh
nano ~/.ssh/authorized_keys
Paste the public key, save and exit
粘贴公钥,保存并退出
chmod 600 ~/.ssh/authorized_keys
undefinedchmod 600 ~/.ssh/authorized_keys
undefinedStep 4: Test SSH Key Authentication
步骤4:测试SSH密钥认证
CRITICAL: Test in a NEW terminal window, keep existing session open!
bash
ssh deployer@your-server-ipYou should connect without entering a password (or only your SSH key passphrase).
If connection fails, DO NOT proceed to Step 5! Debug the issue first.
重要提示: 在新的终端窗口中测试,保持现有会话处于打开状态!
bash
ssh deployer@your-server-ip你应该无需输入密码即可连接(或仅需输入SSH密钥的密码短语)。
如果连接失败,请勿继续执行步骤5! 先调试问题。
Step 5: Harden SSH Configuration
步骤5:加固SSH配置
WARNING: Make these changes carefully. Test in a new terminal before closing existing sessions!
Edit SSH daemon configuration:
bash
sudo nano /etc/ssh/sshd_configUpdate or add these settings:
undefined警告: 请谨慎进行这些更改。关闭现有会话前,先在新终端中测试!
编辑SSH守护进程配置:
bash
sudo nano /etc/ssh/sshd_config更新或添加以下设置:
undefinedDisable root login
禁用root登录
PermitRootLogin no
PermitRootLogin no
Disable password authentication
禁用密码认证
PasswordAuthentication no
PasswordAuthentication no
Disable empty passwords
禁用空密码
PermitEmptyPasswords no
PermitEmptyPasswords no
Limit authentication attempts
限制认证尝试次数
MaxAuthTries 3
MaxAuthTries 3
Allow only specific users (optional but recommended)
仅允许特定用户(可选但推荐)
AllowUsers deployer
AllowUsers deployer
Use only SSH protocol 2
仅使用SSH协议2
Protocol 2
Protocol 2
Disable X11 forwarding (unless needed)
禁用X11转发(除非需要)
X11Forwarding no
X11Forwarding no
Set login grace time
设置登录宽限时间
LoginGraceTime 60
LoginGraceTime 60
Disable host-based authentication
禁用基于主机的认证
HostbasedAuthentication no
**Optional advanced settings:**
HostbasedAuthentication no
**可选高级设置:**
Change default port (security through obscurity, optional)
修改默认端口(通过隐匿实现安全,可选)
Port 2222
Port 2222
Disable agent forwarding (unless needed)
禁用Agent转发(除非需要)
AllowAgentForwarding no
AllowAgentForwarding no
Disable TCP forwarding (unless needed)
禁用TCP转发(除非需要)
AllowTcpForwarding no
AllowTcpForwarding no
Set idle timeout
设置空闲超时
ClientAliveInterval 300
ClientAliveInterval 300
ClientAliveCountMax 2
ClientAliveCountMax 2
undefinedundefinedStep 6: Test Configuration
步骤6:测试配置
Test the configuration file for syntax errors:
bash
sudo sshd -tNo output means the configuration is valid.
测试配置文件是否存在语法错误:
bash
sudo sshd -t无输出表示配置有效。
Step 7: Restart SSH Service
步骤7:重启SSH服务
CRITICAL: Test in a new terminal BEFORE restarting!
bash
undefined重要提示: 重启前先在新终端中测试!
bash
undefinedTest connection in NEW terminal first
先在新终端中测试连接
ssh deployer@your-server-ip
ssh deployer@your-server-ip
If successful, restart SSH (in original terminal)
如果连接成功,在原终端中重启SSH
sudo systemctl restart sshd
**Verification:**
```bash
sudo systemctl status sshdsudo systemctl restart sshd
**验证:**
```bash
sudo systemctl status sshdStep 8: Verify Root Login is Disabled
步骤8:验证Root登录已禁用
Try to connect as root (should fail):
bash
ssh root@your-server-ipExpected result:
Permission denied (publickey)尝试以root身份连接(应失败):
bash
ssh root@your-server-ip预期结果:
Permission denied (publickey)Configuration Reference
配置参考
AllowUsers vs AllowGroups
AllowUsers vs AllowGroups
Restrict SSH access to specific users or groups:
undefined限制SSH访问到特定用户或组:
undefinedOption 1: Specific users
选项1:特定用户
AllowUsers deployer admin
AllowUsers deployer admin
Option 2: Users in specific group
选项2:特定组中的用户
AllowGroups sshusers
undefinedAllowGroups sshusers
undefinedPort Changes
端口修改
Changing the default SSH port (22) reduces noise from automated scanners:
Port 2222Remember to:
- Update firewall rules before restarting SSH
- Use the new port when connecting:
ssh -p 2222 user@host
修改默认SSH端口(22)可减少自动化扫描的干扰:
Port 2222请记住:
- 重启SSH前更新防火墙规则
- 连接时使用新端口:
ssh -p 2222 user@host
Key-Based Authentication Only
仅启用密钥认证
Ensure these settings work together:
PubkeyAuthentication yes
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM yes确保以下设置协同工作:
PubkeyAuthentication yes
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM yesSecurity Best Practices
安全最佳实践
- Always test before closing sessions - Keep one session open until verified
- Use SSH key passphrases - Adds another layer of security
- Limit user access - Use AllowUsers or AllowGroups
- Monitor authentication logs - Check regularly
/var/log/auth.log - Use fail2ban - Add automated banning for repeated failed attempts
- Regular key rotation - Periodically generate new keys
- Disable unused features - X11Forwarding, TCP forwarding, etc.
- 测试后再关闭会话 - 验证前保持一个会话处于打开状态
- 使用SSH密钥密码短语 - 添加额外的安全层
- 限制用户访问 - 使用AllowUsers或AllowGroups
- 监控认证日志 - 定期检查
/var/log/auth.log - 使用fail2ban - 自动封禁多次失败尝试的来源
- 定期轮换密钥 - 定期生成新密钥
- 禁用未使用的功能 - 如X11Forwarding、TCP转发等
Troubleshooting
故障排除
Locked Out of Server
被锁定在服务器外
Prevention is key:
- Always keep one session open when making changes
- Test in a new terminal before closing existing sessions
- Have console access via hosting provider's control panel
Recovery:
- Use hosting provider's console/VNC access
- Revert changes to
/etc/ssh/sshd_config - Restart sshd service
预防是关键:
- 进行更改时始终保持一个会话处于打开状态
- 关闭现有会话前在新终端中测试
- 通过托管提供商的控制面板获取控制台访问权限
恢复方法:
- 使用托管提供商的控制台/VNC访问
- 还原中的更改
/etc/ssh/sshd_config - 重启sshd服务
SSH Key Not Working
SSH密钥无法工作
bash
undefinedbash
undefinedCheck file permissions on server
检查服务器上的文件权限
ls -la ~/.ssh/
ls -la ~/.ssh/
Should show:
应显示:
drwx------ .ssh/
drwx------ .ssh/
-rw------- authorized_keys
-rw------- authorized_keys
Fix permissions if needed
如有需要修复权限
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
Check SSH logs
查看SSH日志
sudo tail -f /var/log/auth.log
undefinedsudo tail -f /var/log/auth.log
undefinedConnection Refused After Changes
修改后连接被拒绝
bash
undefinedbash
undefinedCheck SSH service status
检查SSH服务状态
sudo systemctl status sshd
sudo systemctl status sshd
View recent errors
查看最近的错误
sudo journalctl -u sshd -n 50
sudo journalctl -u sshd -n 50
Test configuration
测试配置
sudo sshd -t
undefinedsudo sshd -t
undefinedCommon Mistakes to Avoid
需避免的常见错误
- ❌ Closing all SSH sessions before testing new configuration
- ❌ Disabling password auth before setting up SSH keys
- ❌ Not testing sudo access for new user
- ❌ Typos in sshd_config causing service failure
- ❌ Forgetting to restart sshd after changes
- ❌ Not updating firewall when changing SSH port
- ❌ 测试新配置前关闭所有SSH会话
- ❌ 配置SSH密钥前禁用密码认证
- ❌ 未测试新用户的sudo权限
- ❌ sshd_config中的输入错误导致服务故障
- ❌ 修改后忘记重启sshd
- ❌ 修改SSH端口后未更新防火墙规则
Additional Resources
额外资源
See references/sshd-config.md for complete sshd_config reference.
See scripts/setup-ssh-hardening.sh for automated setup script.
完整的sshd_config参考请查看references/sshd-config.md。
自动化安装脚本请查看scripts/setup-ssh-hardening.sh。
Related Skills
相关技能
- - Restrict SSH port access
firewall-configuration - - Auto-ban brute-force attempts
fail2ban-setup - - Keep SSH patched against vulnerabilities
auto-updates
- - 限制SSH端口访问
firewall-configuration - - 自动封禁暴力破解尝试
fail2ban-setup - - 保持SSH补丁更新以抵御漏洞
auto-updates