How to hook SSH Login and send notification (email or others)

When you first time login to Google, Facebook, It will send a notification email for you to improve security. I think many IT think “How to make SSH to same thing” right? If any user login ssh can send notify to system manager, It was help for security.

You have two way can do, write cmd in your .bashrc / .zshrc, or use pam (Pluggable Authentication Modules for Linux) to hook ssh login event, I recommend use pam to do this!

This post is write for Ubuntu / Debian.

Instruction

Use any text editor (ex. vim, nano) to open /etc/pam.d/sshd and move cursor to bottom. Type next line into file:

session optional pam_exec.so seteuid /root/notify.sh

It mean when you login/logout or do something about ssh session, ssh daemon will call “/root/notify.sh”, so you can replace the last parameter with any linux cmd or file.

The second parameter is optional, It mean if notify.sh return fail status code is ok, If you set as required, you can’t login when notify.sh return fail… so I recommend don’t set required!

And now create /root/notify.sh, put below content into file and set It as executable:

#! /bin/bash


if [ $PAM_TYPE == 'open_session' ]; then
    subject = "[$(hostname)] User $PAM_USER login from $PAM_RHOST at $(date)"
elif [ $PAM_TYPE == 'close_session' ]; then
    subject = "[$(hostname)] User $PAM_USER logout from $PAM_RHOST at $(date)"
fi

echo subject > mail -s $subject root

When pam exec notify.sh, It will set some environment variable, like:

  • PAM_TYPE: Use this to detect user login or logout
  • PAM_USER: Which user be login
  • PAM_RHOST: Remote user ip
  • PAM_SERVICE
  • PAM_TTY

You can use other notify way, ex: slack, telegram…etc to replace last line, currently I use mail to do notify.

I think pam is in sync model, so If you spend so many time to send notification, You login will be slow.

This post refer by:

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料