跳过正文
  1. 文章/

有人SSH登录你的服务器时,让Slack通知你

· loading · loading ·
仁才德
作者
仁才德
居住在韩国首尔的领导者和软件工程师

目的
#

  • SSH可以在有人尝试登录时执行命令。这篇文章介绍怎么接入Slack,同时控制PAM的执行顺序。

Slack API的Webhook
#

  • 怎么创建应用,看这里就行。

  • 你需要先建一个Slack应用,启用Webhook,再创建一个Incoming Webhook,用来接收SSH发来的通知。

登录失败的通知脚本
#

  • 脚本放在哪里都行,我放在了/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

谢谢!
#

  • 有任何问题或想法,欢迎直接联系我