fangpsh's blog

OpenSSH的AuthorizedKeysCommand选项

openssh

Debian jessie 冻结了,今年就要release,openssh-server 包也从6.0 升到6.7,AuthorizedKeysCommand 和AuthorizedKeysCommandUser 这两个配置选项是在6.2的时候引入的,所以也能用上了。

  • wheezy (stable):1:6.0p1-4+deb7u2
  • wheezy-backports: 1:6.6p1-4~bpo70+1
  • jessie (testing) : 1:6.7p1-3
  • sid (unstable) : 1:6.7p1-3

AuthorizedKeysCommand 可以指定运行一个脚本,而这个脚本主要是寻找登录用户的publickey,默认传参为登录用户名,若未认证成功,将继续使用AuthorizedKeysFile文件来做认证。AuthorizedKeysCommandUser就是指定以什么用户来运行这个脚本。 这两个配置选项的一个用处就是在用户管理上可以不再依靠本地管理,而可以通过脚本读取远程数据库系统中的用户的publickey进行认证,例如MySQL或者LDAP,这样的话,更便于用户的集中管理。

更多参考 SSHD_CONFIG(5) File Formats Manual

MySQL

下面这个例子取自OpenSSH 6.2 で追加された機能を試す¶. 如果是Debian的系统需要确保服务器上的openssh-server版本在6.2之上。

mysql创建数据表:
mysql> create database authorizedkeys;
mysql> use authorizedkeys;
mysql> create table authorizedkeys(username text , publickey text);
mysql> insert into authorizedkeys values('fps','ssh-rsa AAA....xOr+WVPFsH/npVrvz/w== fangpeishi'); #添加用户的publickey到数据表中

AuthorizedKeysCommand调用的脚本:/etc/key.sh
#!/bin/sh
/usr/bin/mysql -uroot authorizedkeys -sNe "select publickey from authorizedkeys where username='$1'"

/etc/ssh/sshd_config配置文件:
...
AuthorizedKeysCommand /etc/key.sh
AuthorizedKeysCommandUser root #以root用户调用脚本
...

测试一下:

  # service ssh stop 停止服务
  # /usr/sbin/ssh -ddd 进行debug,运行之后尝试远程登录,查看日志信息如下
  ...
  ...
  debug1: temporarily_use_uid: 0/0 (e=0/0)
  debug3: Running AuthorizedKeysCommand: "/etc/ssh/key.sh fps" as "root"
  debug1: restore_uid: 0/0
  debug1: temporarily_use_uid: 0/0 (e=0/0)
  debug1: matching key found: file /etc/ssh/key.sh, line 1 RSA 00:11:26:ba:28:bc:fc:9c:da:f7:d0:ff:ee:64:fa:e2
  debug1: restore_uid: 0/0
  debug3: mm_answer_keyallowed: key 0x7fb2576727c0 is allowed
  ...
  ...

LDAP

这东西没折腾过,不熟悉,看两个例子吧: