OpenSSH的Match指令可基于用户、组、地址等条件差异化限制加密算法,如内网用兼容套件、公网强制强算法,且须置sshd_config末尾、顺序执行、首匹配生效。

可以利用 OpenSSH 的 Match 指令,为特定来源(如某段 IP、某个用户组或某类主机)单独限制其可使用的加密算法,实现“同服务、不同策略”的精细化控制。关键在于:Match 块内可覆盖 KexAlgorithms、Ciphers 和 Macs 等参数,且该限制仅对匹配连接生效,不影响其他用户或网络的全局配置。
按来源地址限定加密套件
适用于区分内网可信终端与公网不可信访问。例如,允许内网管理机使用较宽松但兼容性好的算法,而强制公网连接必须使用最强现代套件:
- 在
/etc/ssh/sshd_config末尾添加:
Match Address 192.168.10.0/24
KexAlgorithms ecdh-sha2-nistp256,diffie-hellman-group-exchange-sha256
Ciphers aes256-ctr,aes128-ctr,chacha20-poly1305@openssh.com
Macs hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com
- 再添加兜底规则,收紧公网连接:
Match Address 0.0.0.0/0,::/0
KexAlgorithms curve25519-sha256,ecdh-sha2-nistp384
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
Macs hmac-sha2-512-etm@openssh.com,umac-128-etm@openssh.com
- 注意:两个 Match 块顺序不能颠倒,否则公网规则可能被内网规则覆盖;Address 匹配支持 CIDR,多个网段用逗号分隔
按用户或组限制密钥交换方式
对高权限账户(如运维组)进一步约束,防止其因客户端配置宽松而协商出弱 KEX:
- 示例:禁止
devops组使用任何基于 SHA-1 的 DH 组,只允许 ECDH 或 Curve25519:
Match Group devops
KexAlgorithms curve25519-sha256,ecdh-sha2-nistp256,ecdh-sha2-nistp384
PubkeyAcceptedAlgorithms ssh-ed25519,ecdsa-sha2-nistp256
- 这样即使某台 devops 成员的笔记本仍装着旧版 SSH 客户端,默认尝试
diffie-hellman-group14-sha1也会被服务端直接拒绝,强制升级或手动指定算法 - 搭配
PubkeyAcceptedAlgorithms可同步限制可接受的公钥类型,避免 RSA-SHA1 主机密钥回退
组合条件实现更精准控制
Match 支持多条件“与”关系,可用于构建场景化策略。例如:仅对来自办公网的 root 用户启用双因子+强加密,其余 root 登录一律拒绝:
- Match User root Address 203.0.113.0/24
AuthenticationMethods publickey,keyboard-interactive:pam
KexAlgorithms curve25519-sha256,ecdh-sha2-nistp384
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
PermitRootLogin yes - Match User root
PermitRootLogin no - 第二条无 Address 条件,作为兜底规则,确保所有其他 root 连接都被拒
验证与注意事项
- 修改后务必运行
sudo sshd -t检查语法,再sudo systemctl reload sshd生效 - 测试时可用
ssh -vvv user@host查看实际协商的 KEX/Cipher/MAC,确认是否命中预期 Match 块 - Match 块中的算法列表是“完全替换”,不是追加;若写错导致空集(如拼写错误),连接将失败
- 不建议在 Match 中禁用全部算法来“彻底封锁”,而应明确列出允许项,兼顾安全与可用性

















