目的#
- SSHでは、ログイン試行があったタイミングで任意のコマンドを実行できます。この記事では、Slackと連携させつつPAMの実行順序を制御する方法を紹介します。
Slack APIのWebhook#
アプリの作り方はこちらにまとまっています。
Slackアプリを作成してWebhookを有効にし、SSHからの通知を受け取るためのIncoming Webhookを用意してください。
ログイン失敗時の通知スクリプト#
- スクリプトはどこに置いても構いません。私は
/var/opt/notify-attempt.shに置きました。
#!/bin/bash
if [ "$PAM_TYPE" != "close_session" ]; then
url="<YOUR SLACK WEBHOOK>"
channel="#channel"
host="$(hostname)"
content="\"attachments\": [ { \"mrkdwn_in\": [\"text\", \"fallback\"], \"fallback\": \"SSH login: $PAM_USER connected to \`$host\`\", \"text\": \"SSH login to \`$host\`\", \"fields\": [ { \"title\": \"User\", \"value\": \"$PAM_USER\", \"short\": true }, { \"title\": \"IP Address\", \"value\": \"$PAM_RHOST\", \"short\": true } ], \"color\": \"#F35A00\" } ]"
curl -X POST --data-urlencode "payload={\"channel\": \"$channel\", \"mrkdwn\": true, \"username\": \"SSH Notifications\", $content, \"icon_emoji\": \":inbox-tray:\"}" "$url" &
fi
exit他のSSHイベントについて#
- ログイン成功など、他のイベントも通知したい場合はファイルを2つ作るのがおすすめです。
- それぞれのファイルに、Slackへ送るJSONを書いておきます。
fallback\": \"SSH login: $PAM_USER connected to \$host`"` の行はイベントに合わせて書き換えてください。- OpenSSHがこれらのスクリプトをどう使うかは、下の設定を見れば分かります。
sshの設定#
ログイン成功時の通知はコメントアウトしてあります。使いたい場合はコメントを外せば、成功時にもSlackへ通知が飛びます。
該当行:# auth optional pam_exec.so /var/opt/notify-login.sh
[success=2] は「ログインに成功したら2行スキップする」という意味で、これで失敗時の通知を飛ばしています。
ファイル:/etc/pam.d/common-auth
# /etc/pam.d/common-auth - authentication settings common to all services
#
# This file is included from other service-specific PAM config files,
# and should contain a list of the authentication modules that define
# the central authentication scheme for use on the system
# (e.g., /etc/shadow, LDAP, Kerberos, etc.). The default is to use the
# traditional Unix authentication mechanisms.
#
# As of pam 1.0.1-6, this file is managed by pam-auth-update by default.
# To take advantage of this, it is recommended that you configure any
# local modules either before or after the default block, and use
# pam-auth-update to manage selection of other modules. See
# pam-auth-update(8) for details.
# here are the per-package modules (the "Primary" block)
auth [success=2 default=ignore] pam_unix.so nullok
auth optional pam_exec.so /var/opt/notify-attempt.sh
# here's the fallback if no module succeeds
auth requisite pam_deny.so
# prime the stack with a positive return value if there isn't one already;
# this avoids us returning an error just because nothing sets a success code
# since the modules above will each just jump around
# For successful login, uncomment the below line, ensure the file exists.
# auth optional pam_exec.so /var/opt/notify-login.sh
# auth required pam_permit.so
# and here are more per-package modules (the "Additional" block)
auth optional pam_cap.so
# end of pam-auth-update configありがとうございました!#
- 質問やコメントがあれば、気軽に直接連絡してください

