목적#
- SSH는 누군가 로그인을 시도할 때 원하는 명령을 실행하게 만들 수 있습니다. 이 글에서는 Slack과 연동하면서 PAM 실행 순서를 제어하는 방법을 소개합니다.
Slack API 웹훅#
앱 만드는 방법은 여기에 잘 정리되어 있습니다.
Slack 앱을 만들고 웹훅을 활성화한 뒤, 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 이벤트도 받고 싶다면#
- 로그인 성공 같은 다른 이벤트까지 알림을 받고 싶다면 파일을 두 개 만드는 걸 추천합니다.
- 각 파일에 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]는 로그인에 성공하면 두 줄을 건너뛴다는 뜻이라, 실패 알림이 실행되지 않고 넘어갑니다.
파일: /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감사합니다!#
- 궁금한 점이나 의견이 있으면 편하게 연락 주세요

