2023-01-18

OpenSSHのsshd_configでのMatchの使い方

 OpenSSHほどお世話になっているアプリは少ないと思う。世の中、ある意味これなくしては成り立たないサービスが乱立しているのにも拘らず無料で使える。
2006年だったか、OpenBSDプロジェクトの資金不足からOpenSSHの存続も危惧された事があったが、これからも大丈夫なんだろうか?

1月14日に岸田総理が国際研究に500億円の寄付をしていたが、そんな所へ寄付する前に、IT利用の基本である日本語IMEの公的な開発プロジェクトを立ち上げるとか、OpenSSHに寄付するとかしてみろよ!

表題のsshd_configでのMatchの使い方だが、今までうまく出来なかった動的にセットする方法をついに見つけたのでメモ。

UbuntuのOpenSSHのsshd_configはのmanには、

     Note that the Debian openssh-server package sets several options as standard in
     /etc/ssh/sshd_config which are not the default in sshd(8):

           •   Include /etc/ssh/sshd_config.d/*.conf

 /etc/ssh/sshd_config.d/*.conf files are included at the start of the configuration file,
 so options set there will override those in /etc/ssh/sshd_config.

と書かれている。つまり、オリジナルを変えたい場合は、sshd_config.dフォルダ以下に拡張子がconfのファイルをセットすれば読み込むという事だ。サンプルのsshd_configファイルは

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

Include /etc/ssh/sshd_config.d/*.conf

#Port 22

と先頭部分でカスタムファイルを読み込む設定になっている。
ならば、こいつを使ってMatch条件を動的にセットしてしまうのもアリなんじゃないか?
という事で、sshd_configファイルの 末尾に Include /etc/ssh/sshd_config.d/*.conf をつけてMatchを記述したカスタムファイルをセットする事にした所、思うように動いてくれた。

Matchは、次のMatchが出現するか、Match All の記述が出るまでは条件を加算して解釈される。webのsshd_configの書き込みを見ていると、sshd_configの最後に

Match Address xxx.xxx.xxx.xxx
  PermitRootLogin prohibit-password
  AllowUsers user1 user2 

Include /etc/ssh/sshd_config.d/*.conf

------ ex1.conf -----
Match Address yyy.yyy.yyy.yyy
  PermitRootLogin prohibit-password
  AllowUsers user3 user4 

みたいな書き方をしているのをみかけるが、ssh-serverは、これを

Match Address xxx.xxx.xxx.xxx
  PermitRootLogin prohibit-password
  AllowUsers user1 user2 
  Match Address yyy.yyy.yyy.yyy
    PermitRootLogin prohibit-password
    AllowUsers user3 user4 

と、Matchの中のMatchとして解釈するようだ。

独立した2つのMatchとして解釈させるには、sshd_configの末尾に、

Include /etc/ssh/sshd_config.d/*.conf

とだけ書き、sshd_config.d 以下に以下のような2つのファイルとしてセットすると上手くいく。

------ ex0.conf -----
Match Address xxx.xxx.xxx.xxx
  PermitRootLogin prohibit-password
  AllowUsers user1 user2 

------ ex1.conf -----
Match Address yyy.yyy.yyy.yyy
  PermitRootLogin prohibit-password
  AllowUsers user3 user4