Send telegram message on every ssh login
Add script
Create file /etc/login-notify.sh
Modify TELEGRAM_BOT_TOKEN and TELEGRAM_SEND_TO variables. Optional set EXCLUDE_USERS for users about whom a message will not be sent.
#!/bin/sh
TELEGRAM_SEND_TO=123456789
TELEGRAM_BOT_TOKEN=123456789:someLETTERS
EXCLUDE_USERS="some_excluded_user another_excluded_user"
if ! echo "${EXCLUDE_USERS}" | grep -q "\<${PAM_USER}\>"; then
if [ "$PAM_TYPE" != "close_session" ]; then
SSH_KEY=$(grep "Accepted publickey" /var/log/auth.log | tail -n 1 | awk '{print $NF}')
WHERE_KEY=$(grep "found at" /var/log/auth.log | tail -n 1 | awk '{print $NF}')
KEYS_PATH=$(echo "$WHERE_KEY" | cut -d ':' -f 1)
KEYS_LINE=$(echo "$WHERE_KEY" | cut -d ':' -f 2)
KEY_LINE=$(sed -n "${KEYS_LINE}p" "$KEYS_PATH")
KEY_NAME=$(echo "$KEY_LINE" | cut -d ' ' -f 3)
MESSAGE="Server: ${PAM_USER}@`hostname`%0ALogin: ${PAM_RHOST} ${KEY_NAME}"
curl -s -X POST https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage -d chat_id=${TELEGRAM_SEND_TO} -d text="$MESSAGE" > /dev/null
fi
fi
Modify to make it executable
chmod +x /etc/login-notify.sh
Add script to execute for every login
Do it by modifying file /etc/pam.d/sshd, just add line to end of file by echo:
echo 'session optional pam_exec.so seteuid /etc/login-notify.sh' >> /etc/pam.d/sshd
Increase a log level
Script search for fingerprint, but doesn't know witch authorized_keys file used for auth. For get authorized_keys file location, we need to print location to /var/log/auth.log
Increase log level:
echo 'LogLevel VERBOSE' >> /etc/ssh/sshd_config
Restart ssh for updated log level:
sudo systemctl restart ssh
No Comments