作为Linux系统运维(SysOps)工程师,SSH访问控制是保障服务器安全的关键环节。以下是全面的SSH访问控制策略及应用方法:
# 编辑SSH配置文件
sudo vi /etc/ssh/sshd_config
# 修改Port行(建议使用1024-65535之间的端口)
Port 2222
PermitRootLogin no
Protocol 2
MaxAuthTries 3
LoginGraceTime 60
# 只允许特定用户登录
AllowUsers user1 user2 admin@192.168.1.*
# 或允许特定组
AllowGroups ssh-users
# 拒绝特定用户登录
DenyUsers baduser testuser
DenyGroups testers
# /etc/hosts.allow
sshd: 192.168.1.0/24, 10.0.0.5
# /etc/hosts.deny
sshd: ALL
# 使用iptables限制访问源IP
iptables -A INPUT -p tcp --dport 2222 -s 192.168.1.0/24 -j ACCEPT
iptables -A INPUT -p tcp --dport 2222 -j DROP
# 或使用firewalld
firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" port protocol="tcp" port="2222" accept'
# 禁用密码认证
PasswordAuthentication no
# 配置公钥认证
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
# 使用Google Authenticator
sudo apt install libpam-google-authenticator
google-authenticator
# 在sshd_config中添加
AuthenticationMethods publickey,keyboard-interactive
# 客户端空闲超时
ClientAliveInterval 300
ClientAliveCountMax 0
# 限制最大会话数
MaxSessions 5
# 修改日志级别
LogLevel VERBOSE
# 使用fail2ban防止暴力破解
sudo apt install fail2ban
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
- name: Configure SSH
hosts: all
tasks:
- name: Update sshd_config
template:
src: sshd_config.j2
dest: /etc/ssh/sshd_config
owner: root
group: root
mode: 0644
notify: restart sshd
handlers:
- name: restart sshd
service:
name: sshd
state: restarted
# 查看成功登录记录
last
# 查看失败尝试
grep "Failed password" /var/log/auth.log
# 或使用专用工具
sudo apt install auditd
# 定期更换主机密钥
sudo ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key -N ""
sudo systemctl restart sshd
通过实施这些策略,可以显著提高Linux服务器的SSH访问安全性,降低未授权访问风险。