You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
1.6 KiB
Bash

#!/bin/bash
# Modified version, original source: https://gitlab.com/snippets/1871482#note_188602535
USER_ID_DIR={{ notify_users_directory | quote }}
CACHE_DIR={{ notify_cache_directory | quote }}
KEY={{ bot_key | quote }}
VPN_SUBNET={{ trusted_vpn_subnet | quote }}
TIMEOUT={{ timeout | quote }}
getUserId() {
USER_CONF="${USER_ID_DIR}/$1"
[[ -r "$USER_CONF" ]] && head -n 1 "$USER_CONF"
}
URL="https://api.telegram.org/bot$KEY/sendMessage"
sendMessage() {
curl -s --max-time "$TIMEOUT" -H "Content-Type: application/x-www-form-urlencoded" -d "chat_id=$1" -d "disable_web_page_preview=1" -d "parse_mode=Markdown" -d "text=$2" "$URL" >/dev/null
}
if [[ "$PAM_SERVICE" == "sshd" && "$PAM_TYPE" == "open_session" && "$PAM_USER" != "git" && -z "$TMUX" && -n "$PAM_RHOST" ]] && ! /ansible/helpers/check_subnet.py "$PAM_RHOST" "$VPN_SUBNET"; then
IP="$PAM_RHOST"
cache_file="${CACHE_DIR}/${IP}-${PAM_USER}"
cache_mtime=$(stat --format="%Y" "$cache_file" 2>/dev/null)
current_time=$(date +%s)
touch "$cache_file"
if (( cache_mtime > (current_time - 4*60*60) )); then
exit 0
fi
# define message text
HOSTNAME=$(hostname --fqdn)
TEXT="Successful login from [$IP](https://stat.ripe.net/app/$IP) for ${PAM_USER} @ ${HOSTNAME} ($(date "+%Y-%m-%d %H:%M"))"
# send to root
ROOT_USER_ID="$(getUserId root)"
sendMessage "$ROOT_USER_ID" "$TEXT (This message was sent to you because you are the admin.)"
# send to user if id is known
USER_ID="$(getUserId "$PAM_USER")"
if [[ -n "$USER_ID" ]]; then
sendMessage "$USER_ID" "$TEXT"
fi
fi