접속 및 커맨드 입력 시 TelegramBot 알림 발송

mimic·2024년 4월 25일

※ Rocky Linux 9 (Kernel: 6.7.4-1.el9.elrepo.x86_64)에서 테스트 하였습니다.

👉 👩‍💻 스크립트 다운로드


사전 작업

텔레그램 봇 생성

👉 🤖 텔레그램 봇 생성 방법

패키지 설치

dnf install -y dnf-utils http://rpms.remirepo.net/enterprise/remi-release-9.rpm
dnf install -y GeoIP GeoIP-devel GeoIP-data zlib-devel
dnf install -y inotify-tools

/root/bin 폴더 생성

mkdir -p /root/bin

/etc/profile 설정

vi /etc/profile

remoteip=$(hostname -I)
if [[ -z $remoteip ]]; then remoteip=localhost; fi
export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "$(whoami) $remoteip [$$] [$RETRN_VAL] [$PWD]: $(history 1 | sed "s/^[ \t]*[0-9]\+[ \t]*//")"'
readonly PROMPT_COMMAND

VM이거나 사설 IP 때문에 텔레그램 알림이 사설 IP로 오는 경우

remoteip=$(curl ifconfig.me | awk '{print $1}')
if [[ -z $remoteip ]]; then remoteip=localhost; fi
export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "$(whoami) $remoteip [$$] [$RETRN_VAL] [$PWD]: $(history 1 | sed "s/^[ \t]*[0-9]\+[ \t]*//")"'
readonly PROMPT_COMMAND

sshd 로그인 알림 스크립트

vi /etc/profile.d/sshd-login-telegram.sh

#!/usr/bin/env bash
# Telegram Bot send
# Dev / jsh
# Update / 2018.08.30
#
#####################################################################
#
# 여러 사용자의 텔레그램 ID를 쉼표로 구분하여 추가합니다.
# 예: IDS="12345678,87654321,98765432"
IDS=""
KEY="" ## API Token Value
URL="https://api.telegram.org/bot${KEY}/sendMessage"
DATE="$(date "+%Y-%m-%d %H:%M")"
#
####################################################################
CLIENT_IP=$(echo $SSH_CLIENT | awk '{print $1}')
SRV_HOSTNAME=$(hostname -f)
SRV_IP=$(hostname -I | awk '{print $1}')
#PUB_IP=$(curl ifconfig.me | awk '{print $1}')
if [ -n "$CLIENT_IP" ]; then
    GEO=$(geoiplookup $CLIENT_IP | grep "Country" | awk -F, '{print $2}')
    TEXT="$SRV_IP SSH Connection / User=${USER} / Client IP *${CLIENT_IP}* $GEO / Date: ${DATE}"
else
    TEXT="$SRV_IP SSH Connection / User=${USER} / Date: ${DATE}"
fi
# 각각의 ID에 대해 알림을 보냅니다.
for ID in $(echo $IDS | tr ',' '\n'); do
    curl -s -d "chat_id=$ID&text=${TEXT}&disable_web_page_preview=true&parse_mode=markdown" $URL > /dev/null
done

VM이거나 사설 IP 때문에 텔레그램 알림이 사설 IP로 오는 경우

PUB_IP=$(curl ifconfig.me | awk '{print $1}')

if [ -n "$CLIENT_IP" ]; then
    GEO=$(geoiplookup $CLIENT_IP | grep "Country" | awk -F, '{print $2}')
    TEXT="$PUB_IP $SRV_IP SSH Connection / User=${USER} / Client IP *${CLIENT_IP}* $GEO / Date: ${DATE}"
else
    TEXT="$PUB_IP $SRV_IP SSH Connection / User=${USER} / Date: ${DATE}"
fi

chmod +x /etc/profile.d/sshd-login-telegram.sh

커맨드 입력 알림 스크립트

vi /root/bin/command-history-telegram.sh

#!/bin/bash
IDS=""
KEY="" ## API Token Value
URL="https://api.telegram.org/bot${KEY}/sendMessage"
# inotifywait로 파일 시스템 이벤트를 실시간으로 모니터링합니다.
tail -n0 -F /var/log/.cmd.log | while read -r line; do
    # 새로운 라인을 읽어와서 텔레그램으로 전송합니다.
    log="$line"
    # _ OK
    # log_escaped=$(printf '%s' "$log" | sed 's/\//\\\//g; s/_/\\_/g')
    log_escaped=$(printf '%s' "$log" | sed 's/_/\\_/g')
    # 로그를 전송합니다.
    for ID in $(echo $IDS | tr ',' '\n'); do
        curl -s -d "chat_id=$ID&text=${log_escaped}&disable_web_page_preview=true&parse_mode=markdown" $URL > /dev/null
    done
done

chmod +x /root/bin/command-history-telegram.sh

서비스 데몬 생성

vi /etc/systemd/system/command-history-telegram.service

[Unit]
Description=Command History Telegram Service
After=network.target
[Service]
Type=simple
ExecStart=/root/bin/command-history-telegram.sh
[Install]
WantedBy=multi-user.target
systemctl enable command-history-telegram
systemctl start command-history-telegram

커맨드 로그 파일 설정

vi /etc/rsyslog.conf

local6.*                        /var/log/.cmd.log
source /etc/profile
systemctl enable rsyslog
systemctl restart rsyslog

sshd 로그아웃 알림 스크립트

vi /etc/bash.bash_logout

#!/bin/bash
# Telegram Bot 설정
IDS=""
KEY="" ## API Token Value
URL="https://api.telegram.org/bot${KEY}/sendMessage"
# Get user information
USER=$(whoami)
#REMOTE_ADDR=$(who -m --ips | awk '{print $5}')
REMOTE_ADDR=$(curl -s ifconfig.me)
DATE="$(date "+%Y-%m-%d %H:%M")"
# Create message for Telegram
MESSAGE="User $USER logged out. Remote address: $REMOTE_ADDR / Date: ${DATE}"
# Send notification to Telegram for each user ID
for ID in $(echo $IDS | tr ',' '\n'); do
    curl -s -d "chat_id=$ID&text=${MESSAGE}&disable_web_page_preview=true&parse_mode=markdown" $URL > /dev/null
done
profile
Raiju Hantu Goryo Obake

0개의 댓글