From 08e91883b3909ce03c1bad59faf1caed115090b5 Mon Sep 17 00:00:00 2001 From: Felix Stupp Date: Wed, 29 Sep 2021 12:33:33 +0200 Subject: [PATCH] misc/ssh_tg_notify: Added cache to send fewer notifications - per IP only once in the next 4 hours --- roles/misc/ssh_tg_notify/defaults/main.yml | 4 +++- roles/misc/ssh_tg_notify/tasks/main.yml | 7 +++++-- roles/misc/ssh_tg_notify/templates/notify.sh | 9 +++++++++ 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/roles/misc/ssh_tg_notify/defaults/main.yml b/roles/misc/ssh_tg_notify/defaults/main.yml index a8c22ab..1adff65 100644 --- a/roles/misc/ssh_tg_notify/defaults/main.yml +++ b/roles/misc/ssh_tg_notify/defaults/main.yml @@ -1,6 +1,8 @@ --- -notify_script: "{{ global_deployment_directory }}/ssh_notify/telegram.sh" +notify_directory: "{{ global_deployment_directory }}/ssh_notify" +notify_script: "{{ notify_directory }}/telegram.sh" +notify_cache_directory: "{{ notify_directory }}/cache" # recipient_id bot_key: "{{ global_telegram_server_bot_key }}" diff --git a/roles/misc/ssh_tg_notify/tasks/main.yml b/roles/misc/ssh_tg_notify/tasks/main.yml index 15c68f7..890898c 100644 --- a/roles/misc/ssh_tg_notify/tasks/main.yml +++ b/roles/misc/ssh_tg_notify/tasks/main.yml @@ -7,13 +7,16 @@ - curl - gawk -- name: Create directory for notify script +- name: Create directories for notify script file: state: directory - path: "{{ notify_script | dirname }}" + path: "{{ item }}" owner: root group: root mode: u=rwx,g=rx,o= + loop: + - "{{ notify_directory }}" + - "{{ notify_cache_directory }}" - name: Install notify script template: diff --git a/roles/misc/ssh_tg_notify/templates/notify.sh b/roles/misc/ssh_tg_notify/templates/notify.sh index d859910..8a4309c 100644 --- a/roles/misc/ssh_tg_notify/templates/notify.sh +++ b/roles/misc/ssh_tg_notify/templates/notify.sh @@ -1,13 +1,22 @@ #!/bin/bash # Modified version, original source: https://gitlab.com/snippets/1871482#note_188602535 +CACHE_DIR={{ notify_cache_directory | quote }} USERID={{ recipient_id | quote }} KEY={{ bot_key | quote }} TIMEOUT={{ timeout | quote }} + URL="https://api.telegram.org/bot$KEY/sendMessage" if [[ "$PAM_SERVICE" == "sshd" && "$PAM_TYPE" == "open_session" && "$PAM_USER" != "git" && -z "$TMUX" ]]; then IP="$PAM_RHOST" + cache_file="$CACHE_DIR/$IP" + cache_mtime=$(stat --format="%Y" "$cache_file") + current_time=$(date +%s) + touch "$cache_file" + if (( cache_mtime > (current_time - 4*60*60) )); then + exit 0 + fi HOSTNAME=$(hostname --fqdn) TEXT="Successful login from [$IP](https://ipinfo.io/$IP) for ${PAM_USER} @ ${HOSTNAME} ($(date "+%Y-%m-%d %H:%M"))" curl -s --max-time "$TIMEOUT" -d "chat_id=$USERID" -d "disable_web_page_preview=1" -d "parse_mode=Markdown" -d "text=$TEXT" "$URL" > /dev/null