限制ssh免密秘钥ssh命令的执行

Restrict to single command in authorized_keys

背景

先说下背景

就是希望 服务器 上配置的这个 免密的公钥 只能执行 特定的命令。
例如,只能执行 rsync 命令,把我这台主机下面的 某个目录的数据备份出去,
只能出,不能进,就是防止 rsync 命令用反了我这台关键服务器上的数据冲掉。

如何实现

在公钥前面加上一个 command 配置

1
2
3
4
5
6
: ~ $ cat .ssh / authorized_keys 
ssh-rsa AAAAB3NzaC1yc2EAAAAAABABAAABAQCj98R [ ... ]

: ~ $ cat .ssh / authorized_keys
command = "date" ssh-rsa AAAA [ ... ]

rrsync 工具

这个工具 就是专门用来 我之前的那种需求的。这个工具好像是一个 perl 脚本。

https://serverfault.com/questions/965053/restricting-a-ssh-key-to-only-allow-rsync-file-transfer

https://download.samba.org/pub/rsync/rrsync.1

https://opensource.apple.com/source/rsync/rsync-52/rsync/support/rrsync.auto.html

1
command="/path/to/rrsync -wo /allowed/directory/",restrict,from="a.b.c.d" ecdsa-sha2-nistp521 AAAAE...

实际用例

备份 gerrit 代码服务器

使用这个 限制 其他机器只能用这个公钥去 rsync 备份 个 review_site 下面的数据
不能登录gerrit, 不能执行其他命令,只能读取  review_site 下面的数据,不能往
这个路径下面写入数据,防止 rsync 命令弄反了数据被破坏掉。