第6章 sshd_config 深入解析
第6章 sshd_config 深入解析
6.1 配置文件基础
文件位置与加载顺序
# 主配置文件
/etc/ssh/sshd_config
# 包含的子配置文件(OpenSSH 7.4+)
Include /etc/ssh/sshd_config.d/*.conf
# 主机密钥配置
HostKey /etc/ssh/ssh_host_ed25519_key
HostKey /etc/ssh/ssh_host_rsa_key
配置文件语法
# 注释行
# This is a comment
# 空行被忽略
# 指令格式(大小写敏感的 key,大小写敏感的 value)
Keyword Arguments
# 多个值用空格分隔
AllowUsers admin deploy monitor
# Match 块(缩进不是必须的,但推荐)
Match User admin
X11Forwarding yes
AllowTcpForwarding yes
注意: 指令的关键字不区分大小写,但参数值区分大小写。每个指令只有第一个生效(后面的同名指令被忽略,除非在 Match 块内)。
语法检查
# 检查配置语法
sudo sshd -t
# 详细检查(显示已弃用的选项)
sudo sshd -T
# 检查特定配置文件
sudo sshd -t -f /etc/ssh/sshd_config.test
# 查看当前生效的完整配置(包含默认值)
sudo sshd -T
# 过滤特定配置项
sudo sshd -T | grep -i password
sudo sshd -T | grep -i permit
配置重载方式
# 方式一:systemctl reload(推荐,不断开现有连接)
sudo systemctl reload sshd
# 方式二:发送 SIGHUP 信号
sudo kill -HUP $(cat /var/run/sshd.pid)
# 方式三:重启服务(会断开所有连接)
sudo systemctl restart sshd
6.2 全局配置参数详解
网络与监听
| 参数 | 默认值 | 说明 |
|---|
Port | 22 | 监听端口 |
AddressFamily | any | 地址族:any/inet/inet6 |
ListenAddress | 0.0.0.0 | 监听地址 |
Protocol | 2 | SSH 协议版本(仅支持 2) |
# 监听多个地址和端口
Port 22
Port 2222
ListenAddress 0.0.0.0
ListenAddress ::
主机密钥
| 参数 | 默认值 | 说明 |
|---|
HostKey | 系统默认 | 主机私钥路径 |
HostCertificate | 无 | 主机证书路径 |
HostKeyAgent | 无 | 主机密钥 Agent |
# 推荐的主机密钥配置
HostKey /etc/ssh/ssh_host_ed25519_key
HostKey /etc/ssh/ssh_host_rsa_key
# 可选:主机证书
# HostCertificate /etc/ssh/ssh_host_ed25519_key-cert.pub
日志与审计
| 参数 | 默认值 | 说明 |
|---|
SyslogFacility | AUTH | 日志设施 |
LogLevel | INFO | 日志级别 |
# 日志级别对照
# QUIET - 仅致命错误
# FATAL - 致命错误
# ERROR - 错误
# INFO - 一般信息(推荐生产)
# VERBOSE - 详细信息(排查时使用)
# DEBUG - 调试信息(极详细)
# DEBUG1/2/3 - 更深层调试
LogLevel INFO
# 生产环境排查临时调高
LogLevel VERBOSE
认证控制
| 参数 | 默认值 | 说明 |
|---|
PubkeyAuthentication | yes | 公钥认证 |
PasswordAuthentication | yes | 密码认证 |
KbdInteractiveAuthentication | no | 键盘交互认证 |
ChallengeResponseAuthentication | no | 质询响应认证 |
PermitEmptyPasswords | no | 允许空密码 |
AuthenticationMethods | any | 认证方法列表 |
MaxAuthTries | 6 | 最大认证尝试次数 |
LoginGraceTime | 120 | 登录宽限时间(秒) |
PubkeyAuthOptions | none | 公钥认证选项 |
# 安全的认证配置
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitEmptyPasswords no
MaxAuthTries 3
LoginGraceTime 60
用户与会话控制
| 参数 | 默认值 | 说明 |
|---|
PermitRootLogin | prohibit-password | root 登录策略 |
AllowUsers | 所有用户 | 允许登录的用户列表 |
DenyUsers | 无 | 禁止登录的用户列表 |
AllowGroups | 所有组 | 允许登录的组 |
DenyGroups | 无 | 禁止登录的组 |
MaxSessions | 10 | 最大并发会话数 |
MaxStartups | 10:30:60 | 并发未认证连接限制 |
ClientAliveInterval | 0 | 客户端活跃检测间隔 |
ClientAliveCountMax | 3 | 活跃检测失败次数 |
# PermitRootLogin 选项
PermitRootLogin no # 禁止 root 登录
PermitRootLogin prohibit-password # 允许 root 密钥登录
PermitRootLogin yes # 允许 root 密码登录(不推荐)
PermitRootLogin forced-commands-only # 仅允许执行命令
# 用户访问控制
AllowUsers admin deploy monitoring
DenyUsers guest test
# 或使用组
AllowGroups ssh-users admins
DenyGroups visitors
# 保活配置
ClientAliveInterval 300 # 每 300 秒发送心跳
ClientAliveCountMax 2 # 2 次失败后断开
TCPKeepAlive yes # TCP 层保活
功能限制
| 参数 | 默认值 | 说明 |
|---|
AllowTcpForwarding | yes | TCP 端口转发 |
X11Forwarding | no | X11 图形转发 |
PermitTunnel | no | tun/tap 设备转发 |
GatewayPorts | no | 远程转发监听地址 |
AllowStreamLocalForwarding | yes | Unix 域套接字转发 |
PermitUserEnvironment | no | 允许用户设置环境变量 |
DisableForwarding | no | 禁用所有转发 |
# 限制转发功能
AllowTcpForwarding no
X11Forwarding no
PermitTunnel no
GatewayPorts no
AllowStreamLocalForwarding no
DisableForwarding yes # 最严格,覆盖其他转发设置
环境与执行
| 参数 | 默认值 | 说明 |
|---|
PermitUserEnvironment | no | 读取 ~/.ssh/environment |
AcceptEnv | LANG LC_* | 接受的客户端环境变量 |
SetEnv | 无 | 强制设置的环境变量 |
Banner | none | 登录前显示的横幅文件 |
PrintMotd | yes | 显示 /etc/motd |
PrintLastLog | yes | 显示上次登录时间 |
# 接受客户端环境变量
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE
AcceptEnv LC_MONETARY LC_MESSAGES LC_PAPER LC_NAME
AcceptEnv LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL
AcceptEnv EDITOR VISUAL
# 自定义环境变量
SetEnv SSH_SESSION_ID=session001
# 登录横幅
Banner /etc/ssh/banner.txt
PrintMotd no
6.3 chroot 配置
限制用户在指定目录下活动:
# /etc/ssh/sshd_config
# 全局 chroot
ChrootDirectory /var/chroot
# 或使用 Match 按用户/组设置
Match Group sftponly
ChrootDirectory /home/%u
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding no
chroot 目录要求
# chroot 目录必须满足以下条件:
# 1. 由 root 拥有
# 2. root 是唯一有写权限的用户
# 3. 目录权限为 755
sudo chown root:root /home/sftpuser
sudo chmod 755 /home/sftpuser
# 在 chroot 内创建可写子目录
sudo mkdir /home/sftpuser/uploads
sudo chown sftpuser:sftpuser /home/sftpuser/uploads
sudo chmod 755 /home/sftpuser/uploads
6.4 Match 块详解
Match 语法
Match [User username] [Group groupname] [Host hostname] [Hostaddress ip] [LocalAddress ip] [LocalPort port] [RDomain domain]
# 缩进的配置指令
# ...
Match 条件:
| 条件 | 说明 | 支持通配符 |
|---|
User | 用户名 | ✅ |
Group | 组名(主组或附加组) | ✅ |
Host | 客户端主机名 | ✅ |
Hostaddress | 客户端 IP | ✅ |
LocalAddress | 服务器本地地址 | ✅ |
LocalPort | 服务器本地端口 | ✅ |
RDomain | 路由域 | ✅ |
Match 块中的可用指令
以下指令可以在 Match 块中使用:
AllowAgentForwarding, AllowGroups, AllowStreamLocalForwarding,
AllowTcpForwarding, AllowUsers, AuthenticationMethods,
AuthorizedKeysCommand, AuthorizedKeysCommandUser, AuthorizedKeysFile,
AuthorizedPrincipalsCommand, AuthorizedPrincipalsCommandUser,
AuthorizedPrincipalsFile, Banner, ChrootDirectory, ClientAliveCountMax,
ClientAliveInterval, DenyGroups, DenyUsers, DisableForwarding,
ExposeAuthInfo, ForceCommand, GatewayPorts, GSSAPIAuthentication,
HostbasedAcceptedAlgorithms, HostbasedAuthentication, HostbasedUsesNameFromPacketOnly,
IgnoreRhosts, Include, IPQoS, KbdInteractiveAuthentication,
KerberosAuthentication, LogLevel, MaxAuthTries, MaxSessions,
PasswordAuthentication, PermitEmptyPasswords, PermitListen,
PermitOpen, PermitRootLogin, PermitTTY, PermitUserEnvironment,
PubkeyAcceptedAlgorithms, PubkeyAcceptedKeyTypes, PubkeyAuthOptions,
PubkeyAuthentication, RekeyLimit, RDomain, RequiredRSASize,
RevokedKeys, StreamLocalBindMask, StreamLocalBindUnlink,
TrustedUserCAKeys, X11DisplayOffset, X11MaxDisplays, X11Forwarding,
XAuthLocation
Match 块使用示例
示例一:按用户区分配置
# 全局配置
PasswordAuthentication no
AllowTcpForwarding no
# 管理员
Match User admin
PasswordAuthentication no
AllowTcpForwarding yes
X11Forwarding yes
MaxSessions 20
# 部署用户
Match User deploy
ForceCommand /opt/deploy/run.sh
AllowTcpForwarding no
X11Forwarding no
PermitTTY no
# 监控用户
Match User monitoring
ForceCommand /opt/monitor/health-check.sh
AllowTcpForwarding no
PermitTTY no
示例二:按组区分配置
# SFTP 用户组
Match Group sftponly
ChrootDirectory /home/%u
ForceCommand internal-sftp -l INFO
AllowTcpForwarding no
X11Forwarding no
PermitTTY no
PermitRootLogin no
# 开发团队
Match Group developers
AllowTcpForwarding yes
X11Forwarding yes
PermitOpen localhost:3000 localhost:8080
# VPN 用户(只能通过 VPN 网段访问)
Match Group vpnusers Hostaddress 10.8.0.*
AllowTcpForwarding yes
PermitOpen 192.168.1.0/24:*
示例三:按来源 IP 区分
# 来自内网
Match Hostaddress 192.168.1.* 10.0.0.*
AllowTcpForwarding yes
X11Forwarding yes
PasswordAuthentication yes
# 来自公网
Match Hostaddress !192.168.1.* !10.0.0.*
PasswordAuthentication no
AllowTcpForwarding no
X11Forwarding no
MaxAuthTries 2
示例四:多条件组合
# 管理员从管理网段访问
Match User admin Hostaddress 10.0.100.*
AllowTcpForwarding yes
X11Forwarding yes
MaxSessions 50
LogLevel VERBOSE
# 特定用户特定端口
Match User backup LocalPort 2222
ForceCommand /opt/backup/start.sh
PermitTTY no
AllowTcpForwarding no
Match 块注意事项
# 1. Match 块之后的所有指令都属于该 Match
# 直到下一个 Match 或文件结尾
# 2. 如果需要恢复"默认"行为,使用以下方式
Match all
# 之后的配置适用于所有连接
# 注意:Match all 不是官方关键字
# 实际上你需要把全局配置放在 Match 块之前
# 3. 条件取反使用 !
Match User !admin
# 匹配非 admin 用户
# 4. 多个条件是 AND 关系
Match User admin Hostaddress 192.168.1.*
# 必须同时满足:用户名是 admin 且来自 192.168.1.*
6.5 Include 指令
将配置文件拆分为多个文件:
# /etc/ssh/sshd_config
# 主配置文件
Port 22
UsePAM yes
# 包含子配置目录(OpenSSH 7.4+)
Include /etc/ssh/sshd_config.d/*.conf
# Match 块放在最后
Match User admin
...
推荐的配置文件拆分
/etc/ssh/sshd_config # 主配置
/etc/ssh/sshd_config.d/
├── 00-hardening.conf # 安全加固
├── 10-auth.conf # 认证配置
├── 20-sftp.conf # SFTP 配置
├── 30-tunnel.conf # 隧道配置
└── 99-custom.conf # 自定义配置
# /etc/ssh/sshd_config.d/00-hardening.conf
Protocol 2
MaxAuthTries 3
LoginGraceTime 60
PermitEmptyPasswords no
PermitRootLogin prohibit-password
ClientAliveInterval 300
ClientAliveCountMax 2
X11Forwarding no
AllowTcpForwarding no
# /etc/ssh/sshd_config.d/10-auth.conf
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
AuthenticationMethods publickey
注意: 每个 Include 的文件中也可以使用 Match 块。Match 块的范围仅限于当前文件。但使用 Include 可能导致配置解析复杂化,建议保持简单的配置结构。
6.6 加密算法配置
推荐的安全配置
# /etc/ssh/sshd_config
# 密钥交换算法
KexAlgorithms curve25519-sha256,[email protected],diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha256
# 加密算法
Ciphers [email protected],[email protected],[email protected],aes256-ctr,aes192-ctr,aes128-ctr
# MAC 算法
MACs [email protected],[email protected],[email protected]
# 主机密钥算法
HostKeyAlgorithms ssh-ed25519,[email protected],rsa-sha2-512,rsa-sha2-256
# 公钥接受的算法
PubkeyAcceptedAlgorithms ssh-ed25519,[email protected],rsa-sha2-512,rsa-sha2-256
# 主机密钥接受的算法
HostbasedAcceptedAlgorithms ssh-ed25519,rsa-sha2-512,rsa-sha2-256
使用 Mozilla 配置生成器
# https://infosec.mozilla.org/guidelines/openssh
# 现代配置(OpenSSH 6.7+)
KexAlgorithms curve25519-sha256,[email protected],diffie-hellman-group-exchange-sha256
Ciphers [email protected],[email protected],[email protected]
MACs [email protected],[email protected]
# 中等配置(兼容性更好)
KexAlgorithms curve25519-sha256,[email protected],diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256
Ciphers [email protected],[email protected],[email protected],aes256-ctr,aes192-ctr,aes128-ctr
MACs [email protected],[email protected],[email protected]
6.7 完整的生产配置模板
# /etc/ssh/sshd_config
# Production SSH Server Configuration
# Last updated: 2025-01-01
# ===== 网络 =====
Port 22
AddressFamily inet
ListenAddress 0.0.0.0
# ===== 主机密钥 =====
HostKey /etc/ssh/ssh_host_ed25519_key
HostKey /etc/ssh/ssh_host_rsa_key
# ===== 协议与加密 =====
Protocol 2
KexAlgorithms curve25519-sha256,[email protected],diffie-hellman-group16-sha512
Ciphers [email protected],[email protected],[email protected]
MACs [email protected],[email protected]
# ===== 认证 =====
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitEmptyPasswords no
MaxAuthTries 3
LoginGraceTime 60
AuthenticationMethods publickey
# ===== 用户控制 =====
PermitRootLogin prohibit-password
AllowGroups ssh-users
# ===== 会话 =====
MaxSessions 10
MaxStartups 10:30:60
ClientAliveInterval 300
ClientAliveCountMax 2
TCPKeepAlive yes
# ===== 功能限制 =====
X11Forwarding no
AllowTcpForwarding no
PermitTunnel no
GatewayPorts no
AllowStreamLocalForwarding no
PermitUserEnvironment no
# ===== 日志 =====
SyslogFacility AUTH
LogLevel INFO
# ===== 杂项 =====
UsePAM yes
UseDNS no
GSSAPIAuthentication no
PrintMotd no
Banner /etc/ssh/banner.txt
# ===== 子配置文件 =====
Include /etc/ssh/sshd_config.d/*.conf
# ===== 条件配置 =====
# 部署用户
Match User deploy
AllowGroups deploy
ForceCommand /opt/deploy/entry.sh
AllowTcpForwarding no
X11Forwarding no
PermitTTY no
# SFTP 用户
Match Group sftp-only
ChrootDirectory /home/%u
ForceCommand internal-sftp -l INFO
AllowTcpForwarding no
X11Forwarding no
PermitRootLogin no
# 管理员(仅从内网)
Match User admin Hostaddress 10.0.0.0/8
AllowTcpForwarding yes
X11Forwarding yes
PermitTunnel yes
6.8 配置参数速查表
| 参数 | 安全值 | 说明 |
|---|
PermitRootLogin | no 或 prohibit-password | root 登录策略 |
PasswordAuthentication | no | 禁用密码 |
PermitEmptyPasswords | no | 禁止空密码 |
X11Forwarding | no | 禁用 X11 |
AllowTcpForwarding | no | 禁用转发 |
MaxAuthTries | 3 | 认证尝试限制 |
LoginGraceTime | 60 | 登录超时 |
ClientAliveInterval | 300 | 心跳间隔 |
UseDNS | no | 加速登录 |
GSSAPIAuthentication | no | 除非用 Kerberos |
MaxStartups | 10:30:60 | 防止连接洪泛 |
AllowGroups | 指定组 | 细粒度访问控制 |
扩展阅读
下一章: 第7章 SSH 隧道与端口转发 → 学习本地转发、远程转发和 SOCKS 动态代理。