Japan
サイト内の現在位置
SSHの公開鍵認証のオプション設定で機能制限の実現について
NECセキュリティブログ2025年3月14日
NECサイバーセキュリティ戦略統括部 セキュリティ技術センターの長浜です。
今回は、SSHのauthorized_keysの設定についてご紹介したいと思います。SSHは多くのシステムで利用されているかと思います。しかし、authorized_keysのオプション設定を使ったことがある方は少ないのではないでしょうか。
本ブログでは、SSHのauthorized_keysで設定可能なオプションの一部を紹介します[1]。私自身も、社内CTFの問題を作成する際に、authorized_keysのオプションを利用して問題を作成しました。リモート監視システムの構築や制限したターミナルの提供など様々な場面に利用可能でセキュア実装を高める効果があると考えています。
目次
Authorized_keys設定について
SSH接続で公開鍵認証を用いる際authorized_keysに公開鍵を登録するケースが多いと思います。その際に、公開鍵をそのまま記入して利用されている方は多いと思います。実は、authorized_keysのオプション機能を利用することで、公開鍵を利用したアクセスに対して機能制限が可能となります。
機能制限の一例としては、実行可能なコマンドの制限やポートフォワード先の制限、鍵の有効期限の設定などがあります。
これらの制限はsshd_configに記載することでも実現可能ですが、authorized_keysを用いることでユーザごと、公開鍵ごとに異なる設定が可能となります。
設定デモ
実行可能なコマンドの制限とポートフォワーディング先制限のオプション機能を利用した際の挙動をご紹介します。
接続先設定
接続対象となる端末に対して、authorized_keysの設定をしていきたいと思います。今回のデモでは、接続元の公開鍵を3ペア作成し、制限なし、command、ポートフォワーディング先制限を設定していきます。
実際に設定した際のコマンドが以下の通りです。
test2@ubuntu:~$ vi .ssh/authorized_keys
test2@ubuntu:~$ cat .ssh/authorized_keys
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINP7p4jW/rIP1uRcgxyMv8oQsAfdgSPDZyxnEGx2X+R2 test1@ubuntu
restrict,command="ps" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINhdhozqMh3kYsImDFdwOrt/b3PtWCPW0LYkNPxCFeKT test1@ubuntu
restrict,port-forwarding,permitopen="192.168.40.130:8000" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPbKxERppDjXpEUi/atNmHbAV6CHDv5t97ji1sP7CclO test1@ubuntu
command オプション
commandオプションを利用することで、SSH接続後設定したコマンドを実行後セッションが終了されます。例えば、リモートからdateコマンドなどの状態監視コマンドを実行する際に利用することができます。
以下に接続デモを表示します。デモでは、接続先に接続すると、psコマンドのみを実行し、そのままセッションが終了されます。
test1@ubuntu:~/.ssh$ ssh test2@localhost -i command
PTY allocation request failed on channel 0
PID TTY TIME CMD
356810 ? 00:00:13 systemd
356811 ? 00:00:00 (sd-pam)
357202 ? 00:00:00 bash
357294 ? 00:00:00 python3
440153 ? 00:00:00 sshd
440154 ? 00:00:00 ps
Connection to localhost closed.
commandに設定するものは、実行可能なファイルであれば設定が可能なため、コマンドをまとめたshファイルでも指定が可能です。
その際のデモが以下のようになります。このshファイルでは、dateコマンドとpsコマンドを実行してくれます。
以下が変更後の接続先の設定となります。
test2@ubuntu:~$ vi test.sh
test2@ubuntu:~$ chmod +x test.sh
test2@ubuntu:~$ cat test.sh
#/bin/bash
date
ps
test2@ubuntu:~$ vi .ssh/authorized_keys
test2@ubuntu:~$ cat .ssh/authorized_keys
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINP7p4jW/rIP1uRcgxyMv8oQsAfdgSPDZyxnEGx2X+R2 test1@ubuntu
restrict,command="./test.sh" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINhdhozqMh3kYsImDFdwOrt/b3PtWCPW0LYkNPxCFeKT test1@ubuntu
restrict,port-forwarding,permitopen="192.168.40.130:8000" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPbKxERppDjXpEUi/atNmHbAV6CHDv5t97ji1sP7CclO test1@ubuntu
変更後、改めて、接続試行してみると以下のようにdateコマンドとpsコマンドがまとめて実行されていることが確認できます。
test1@ubuntu:~/.ssh$sh test2@localhost -i command
PTY allocation request failed on channel 0
Mon Mar 3 05:37:15 AM UTC 2025
PID TTY TIME CMD
356810 ? 00:00:13 systemd
356811 ? 00:00:00 (sd-pam)
357202 ? 00:00:00 bash
357294 ? 00:00:00 python3
440492 ? 00:00:00 sshd
440599 ? 00:00:00 sshd
440600 ? 00:00:00 bash
440602 ? 00:00:00 ps
Connection to localhost closed.
本オプションを利用することで、利用可能なコマンドをユーザレベルで制限が可能となります。状態監視のためリモート監視ユーザを作成したい場合には本オプションの利用もご検討ください。
ポートフォワーディング制限
port-forwardingオプションとpermitopenオプションを利用することでポートフォワーディング先を制限することも可能です。permitopenオプションは、’host:port’でマッチする先への`-L`でのポートフォワーディングを可能とするオプションです。
許可された接続先に接続した際の挙動が以下の画像のようになります。
今回は、192.168.40.130のサーバに8000ポートと18000ポートにそれぞれWebサーバを起動しています。
正しくポートフォワードでき、テストページにアクセスすることができています。一方、許可されていない接続先にフォワードした際には、` administratively prohibited`という表示があり、ポートフォワードが失敗していることが確認できます。


活用方法例
SSH経由でデータ取得(コマンド監視)
Linuxなどのサーバをリモートから監視する際に、Zabbixを利用することが多いかと思います。Zabbixを利用するためには、Linuxホストにアプリケーションのインストールが必要となります。
そこで、SSH経由で、必要なコマンドをまとめたshファイルを用意してcommandで実行されることによりコマンドによる稼働状況の可視化も可能となります。今回のコマンド実行のデモのような環境を構築することで、実現可能です。
rbash回避防止
よく制限されたSSHの提供方法として、rbashといわれる手法が用いられるかと思いますが、rbashのみでは回避方法が知られています。しかし、authorized_keysの設定を導入することによりSSH接続時のrbashの回避を防止できるようになります。
rbashが設定されている環境に対して、SSHで接続する際にtオプションを使うことでrbashは回避することが可能です。ただ、このtオプションを利用するためには接続先でttyへの紐づけが可能なことが条件となります。
そこで、authorized_keysのオプションのno-ttyまたはrestrict(すべての制限)を利用して、ttyへの紐づけを制限することにより回避が困難となります。sshd_configでもユーザ単位で設定することができるため、rbashの回避対策という観点であれば、管理者権限でしか変更のできない制約のあるsshd_configで設定するほうが良いかもしれません。ただし、管理者権限がない環境下でrbashを作成する際にはauthorized_keysのオプションで設定する必要があります。
まとめ
authorized_keysで設定することにより、ユーザが任意の接続元の制限やポートフォワード先の制限を実施することが可能となります。同様な設定はsshd_configでも実行は可能かと思いますが、管理者権限が必要となります。 authorized_keys のオプション設定の方が、管理者権限がなくても設定できるため、都合がよいケースがありそうです。ツールの仕様を理解し、選べる選択肢を増やしておくことは、技術者として重要なことと考えています。今後も役に立ちそうな情報がありましたら随時展開していきたいと考えています。
authorize_keysのオプション設定、ぜひシステムのセキュア化やリモート監視などにご活用ください。
参考文献
- [1]Ubuntu Manpage: sshd — OpenSSH SSH daemon
https://manpages.ubuntu.com/manpages/xenial/man8/sshd.8.html
備考
sshdの中マニュアルの中からauthorized_keysに関する部分の抜粋
AUTHORIZED_KEYS FILE FORMAT
AuthorizedKeysFile specifies the files containing public keys for public key authentication; if this option is not specified, the default is ~/.ssh/authorized_keys and ~/.ssh/authorized_keys2. Each line of the file contains one key (empty lines and lines starting with a ‘#’ are ignored as comments). Protocol 1 public keys consist of the following space-separated fields: options, bits, exponent, modulus, comment. Protocol 2 public key consist of: options, keytype, base64-encoded key, comment. The options field is optional; its presence is determined by whether the line starts with a number or not (the options field never starts with a number). The bits, exponent, modulus, and comment fields give the RSA key for protocol version 1; the comment field is not used for anything (but may be convenient for the user to identify the key). For protocol version 2 the keytype is “ecdsa-sha2-nistp256”, “ecdsa-sha2-nistp384”, “ecdsa-sha2-nistp521”, “ssh-ed25519”, “ssh-dss” or “ssh-rsa”.
Note that lines in this file are usually several hundred bytes long (because of the size of the public key encoding) up to a limit of 8 kilobytes, which permits DSA keys up to 8 kilobits and RSA keys up to 16 kilobits. You don't want to type them in; instead, copy the identity.pub, id_dsa.pub, id_ecdsa.pub, id_ed25519.pub, or the id_rsa.pub file and edit it.
sshd enforces a minimum RSA key modulus size for protocol 1 and protocol 2 keys of 768 bits.
The options (if present) consist of comma-separated option specifications. No spaces are permitted, except within double quotes. The following option specifications are supported (note that option keywords are case-insensitive):
agent-forwarding
Enable authentication agent forwarding previously disabled by the restrict option.
cert-authority
Specifies that the listed key is a certification authority (CA) that is trusted to validate signed certificates for user authentication.
Certificates may encode access restrictions similar to these key options. If both certificate restrictions and key options are present, the most restrictive union of the two is applied.
command="command"
Specifies that the command is executed whenever this key is used for authentication. The command supplied by the user (if any) is ignored. The command is run on a pty if the client requests a pty; otherwise it is run without a tty. If an 8-bit clean channel is required, one must not request a pty or should specify no-pty. A quote may be included in the command by quoting it with a backslash. This option might be useful to restrict certain public keys to perform just a specific operation. An example might be a key that permits remote backups but nothing else. Note that the client may specify TCP and/or X11 forwarding unless they are explicitly prohibited. The command originally supplied by the client is available in the SSH_ORIGINAL_COMMAND environment variable. Note that this option applies to shell, command or subsystem execution. Also note that this command may be superseded by either a sshd_config(5) ForceCommand directive or a command embedded in a certificate.VNJN3511
environment="NAME=value"
Specifies that the string is to be added to the environment when logging in using this key. Environment variables set this way override other default environment values. Multiple options of this type are permitted. Environment processing is disabled by default and is controlled via the PermitUserEnvironment option. This option is automatically disabled if UseLogin is enabled.
from="pattern-list"
Specifies that in addition to public key authentication, either the canonical name of the remote host or its IP address must be present in the comma-separated list of patterns. See PATTERNS in ssh_config(5) for more information on patterns.
In addition to the wildcard matching that may be applied to hostnames or addresses, a from stanza may match IP addresses using CIDR address/masklen notation.
The purpose of this option is to optionally increase security: public key authentication by itself does not trust the network or name servers or anything (but the key); however, if somebody somehow steals the key, the key permits an intruder to log in from anywhere in the world. This additional option makes using a stolen key more difficult (name servers and/or routers would have to be compromised in addition to just the key).
no-agent-forwarding
Forbids authentication agent forwarding when this key is used for authentication.
no-port-forwarding
Forbids TCP forwarding when this key is used for authentication. Any port forward requests by the client will return an error. This might be used, e.g. in connection with the command option.
no-pty
Prevents tty allocation (a request to allocate a pty will fail).
no-user-rc
Disables execution of ~/.ssh/rc.
no-X11-forwarding
Forbids X11 forwarding when this key is used for authentication. Any X11 forward requests by the client will return an error.
permitopen="host:port"
Limit local port forwarding with ssh(1) -L such that it may only connect to the specified host and port. IPv6 addresses can be specified by enclosing the address in square brackets. Multiple permitopen options may be applied separated by commas. No pattern matching is performed on the specified hostnames, they must be literal domains or addresses. A port specification of * matches any port.
port-forwarding
Enable port forwarding previously disabled by the restrict
principals="principals"
On a cert-authority line, specifies allowed principals for certificate authentication as a comma- separated list. At least one name from the list must appear in the certificate's list of principals for the certificate to be accepted. This option is ignored for keys that are not marked as trusted certificate signers using the cert-authority option.
pty
Permits tty allocation previously disabled by the restrict option.
restrict
Enable all restrictions, i.e. disable port, agent and X11 forwarding, as well as disabling PTY allocation and execution of ~/.ssh/rc. If any future restriction capabilities are added to authorized_keys files they will be included in this set.
tunnel="n"
Force a tun(4) device on the server. Without this option, the next available device will be used if the client requests a tunnel.
user-rc
Enables execution of ~/.ssh/rc previously disabled by the restrict option.
X11-forwarding
Permits X11 forwarding previously disabled by the restrict option.
An example authorized_keys file:
# Comments allowed at start of line
ssh-rsa AAAAB3Nza...LiPk== user@example.net
from="*.sales.example.net,!pc.sales.example.net" ssh-rsa
AAAAB2...19Q== john@example.net
command="dump /home",no-pty,no-port-forwarding ssh-dss
AAAAC3...51R== example.net
permitopen="192.0.2.1:80",permitopen="192.0.2.2:25" ssh-dss
AAAAB5...21S==
tunnel="0",command="sh /etc/netstart tun0" ssh-rsa AAAA...==
jane@example.net
restrict,command="uptime" ssh-rsa AAAA1C8...32Tv==
user@example.net
restrict,pty,command="nethack" ssh-rsa AAAA1f8...IrrC5==
user@example.net
執筆者プロフィール
長浜 佑介(ながはま ゆうすけ)
セキュリティ技術センター リスクハンティング・アナリシスチーム
主にペネトレーションテスト、脆弱性診断などを担当しNECグループのセキュア開発・運用を推進。
2020年6月にIPA 産業サイバーセキュリティセンター中核人材育成プログラムを修了。
CISSP、GIAC(GXPN)、情報処理安全確保支援士(RISS)を保持。

執筆者の他の記事を読む
アクセスランキング
2025年3月16日~3月22日に読まれた記事のランキング