DevTech
2024년 6월 21일 · 7 min read

나만의 서버를 모니터링해보자(SNMP Trap) (1)

이 글은 2024년 6월 21일 예전 네이버 블로그에 올렸던 글을 옮겨 온 것입니다.

Ubuntu 서버에서 SNMP 트랩을 설정하고 다양한 시스템 이벤트를 모니터링하여 에러 메시지를 여러 NMS(네트워크 관리 시스템)로 전송하는 방법을 단계별로 설명합니다.

세팅 환경

 Static hostname: server
       Icon name: computer-laptop
         Chassis: laptop 💻
      Machine ID: secret
         Boot ID: secret
Operating System: Ubuntu 24.04 LTS
          Kernel: Linux 6.8.0-35-generic
    Architecture: x86-64
 Hardware Vendor: LG Electronics Inc.
  Hardware Model: R570-KE1BK
Firmware Version: secret
   Firmware Date: Wed 2010-01-06
    Firmware Age: 14y 5month 2w

NMS 1 : Windows11

NMS 2 : macOS Sonoma 14.5

1단계: 필수 패키지 설치

먼저, SNMP 트랩을 보내기 위해 필요한 패키지를 설치합니다.

sudo apt-get update
sudo apt-get install snmp snmpd snmp-mibs-downloader

2단계: SNMP 설정 파일 구성

SNMP 설정 파일을 편집하여 트랩 설정을 구성합니다.

sudo nano /etc/snmp/snmpd.conf

snmpd.conf 파일에 다음 설정을 추가합니다:

rocommunity public
trap2sink 192.0.2.10 public
trap2sink 192.0.2.11 public  # 두 번째 NMS 서버

3단계: SNMP 데몬 재시작

SNMP 데몬을 재시작하여 설정을 적용합니다.

sudo systemctl restart snmpd

4단계: 모니터링 스크립트 작성

모니터링할 시스템 이벤트를 감지하고 SNMP 트랩을 보내는 스크립트를 작성합니다. 예를 들어, /usr/local/bin/monitor_system.sh 파일에 스크립트를 작성합니다.

sudo nano /usr/local/bin/monitor_system.sh
#!/bin/bash

# NMS 서버 주소
NMS1="192.0.2.10"
NMS2="192.0.2.11"  # 두 번째 NMS 주소
COMMUNITY="MyNMS"

CPU_THRESHOLD=80
MEMORY_THRESHOLD=90
DISK_THRESHOLD=90

# SNMP 트랩 메시지를 보내는 함수
function send_snmp_trap() {
    local message=$1
    snmptrap -v 2c -c $COMMUNITY $NMS1 '' .1.3.6.1.2.1.1.3.0 0 s "$message"
    snmptrap -v 2c -c $COMMUNITY $NMS2 '' .1.3.6.1.2.1.1.3.0 0 s "$message"
}

# 보안 로그 모니터링
function monitor_security_logs() {
    tail -Fn0 /var/log/auth.log | while read line; do
        if echo "$line" | grep -qE "Failed password for"; then
            user=$(echo "$line" | grep -oP '(?<=Failed password for )\S+')
            ip=$(echo "$line" | grep -oP '(?<=from )\S+')
            send_snmp_trap "Security Alert: Failed login attempt for user $user from IP $ip"
        elif echo "$line" | grep -qE "Accepted password for"; then
            user=$(echo "$line" | grep -oP '(?<=Accepted password for )\S+')
            ip=$(echo "$line" | grep -oP '(?<=from )\S+')
            send_snmp_trap "Security Alert: Successful login for user $user from IP $ip"
        elif echo "$line" | grep -qE "session opened for user"; then
            user=$(echo "$line" | grep -oP '(?<=session opened for user )\S+')
            ip=$(echo "$line" | grep -oP '(?<=from )\S+')
            send_snmp_trap "Security Alert: Session opened for user $user from IP $ip"
        elif echo "$line" | grep -qE "session closed for user"; then
            user=$(echo "$line" | grep -oP '(?<=session closed for user )\S+')
            send_snmp_trap "Security Alert: Session closed for user $user"
        fi
    done
}

# CPU 사용량 모니터링
function monitor_cpu_usage() {
    while true; do
        cpu_usage=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')
        if (( $(echo "$cpu_usage > $CPU_THRESHOLD" | bc -l) )); then
            send_snmp_trap "CPU Usage Alert: CPU usage is at $cpu_usage%"
        fi
        sleep 10  # 10초마다 체크
    done
}

# 메모리 사용량 모니터링
function monitor_memory_usage() {
    while true; do
        memory_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
        if (( $(echo "$memory_usage > $MEMORY_THRESHOLD" | bc -l) )); then
            send_snmp_trap "Memory Usage Alert: Memory usage is at $memory_usage%"
        fi
        sleep 10  # 10초마다 체크
    done
}

# 디스크 사용량 모니터링
function monitor_disk_usage() {
    while true; do
        df -h | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output; do
            usage=$(echo $output | awk '{ print $1}' | sed 's/%//g')
            partition=$(echo $output | awk '{ print $2 }')
            if [ $usage -ge $DISK_THRESHOLD ]; then
                send_snmp_trap "Disk Usage Alert: $partition usage is at ${usage}%"
            fi
        done
        sleep 10  # 10초마다 체크
    done
}

# 네트워크 인터페이스 상태 변화 모니터링
function monitor_network_interface() {
    declare -A interface_status
    while true; do
        for iface in $(ls /sys/class/net/); do
            if [ "$iface" != "lo" ]; then
                current_status=$(cat /sys/class/net/$iface/operstate)
                previous_status=${interface_status[$iface]}
                if [ "$previous_status" == "up" ] && [ "$current_status" == "down" ]; then
                    send_snmp_trap "Network Interface Alert: $iface is down"
                fi
                interface_status[$iface]=$current_status
            fi
        done
        sleep 10  # 10초마다 체크
    done
}

# 시스템 재부팅 모니터링
function monitor_system_reboot() {
    last_reboot=$(last reboot | head -n 1)
    while true; do
        new_reboot=$(last reboot | head -n 1)
        if [ "$new_reboot" != "$last_reboot" ]; then
            send_snmp_trap "System Alert: System reboot detected"
            last_reboot=$new_reboot
        fi
        sleep 10  # 10초마다 체크
    done
}

# 모든 모니터링 함수를 병렬로 실행
monitor_security_logs &
monitor_cpu_usage &
monitor_memory_usage &
monitor_disk_usage &
monitor_network_interface &
monitor_system_reboot &
wait

이 스크립트는 CPU 과부하, 메모리 부족, 디스크 사용량 초과, 로그인 시도 등을 모니터링하고 NMS 서버로 SNMP 트랩을 전송합니다.

5단계: 스크립트에 실행 권한 부여

작성한 스크립트에 실행 권한을 부여합니다.

sudo chmod +x /usr/local/bin/monitor_system.sh

6단계: 시스템 서비스 파일 작성

스크립트를 시스템 서비스로 등록하여 자동으로 실행되도록 설정합니다. /etc/systemd/system/monitor_system.service 파일을 작성합니다.

sudo nano /etc/systemd/system/monitor_system.service

다음 내용을 추가합니다:

[Unit]
Description=Monitor System and Send SNMP Traps

[Service]
ExecStart=/usr/local/bin/monitor_system.sh

[Install]
WantedBy=multi-user.target

7단계: 서비스 등록 및 시작

서비스를 등록하고 시작합니다.

sudo systemctl daemon-reload
sudo systemctl enable monitor_system.service
sudo systemctl start monitor_system.service

8단계: 수신 확인

wireshark를 통해 트랩이 무사히 수신되었는지 확인합니다.

이를 보면 잘 수신되는 것을 확인할 수 있다.

이렇게 모니터링을 하다보면 무작위로 root로그인을 시도하는 공격들을 간간히 확인할 수 있다.

이 ip를 추적해보면

user@server:~$ curl ipinfo.io/203.0.113.5
{
  "ip": "203.0.113.5",
  "city": "Beijing",
  "region": "Beijing",
  "country": "CN",
  "loc": "39.9075,116.3972",
  "org": "AS23724 IDC, China Telecommunications Corporation",
  "postal": "100000",
  "timezone": "Asia/Shanghai",
  "readme": "https://ipinfo.io/missingauth"
}

curl로 ipinfo.io에서 확인해보면 위와 같이 확인할 수 있는데 대충 중국에서 공격 같다.

나도 모르는 사이에 무차별적인 로그인시도가 전세계 곧곧에서 일어나고 있다. 이는 중국이라서 공격이 온것이 아니라 확인해보면 정말 어디서든 오지만 대부분 중국, 싱가폴로 보이긴 하다.

직접 IP주소로 시도하는 것은 현재 fail2ban으로 3회이상 시도시 600초를 밴하는 방법으로 차단하고 있다.

이 방법은 다음 글에 정리하겠다.

그 외의 것들은 현재 CloudFlare로 방어중이다.

이건 내가 구입한 도메인에 대한 접속시도인데 아마 모든 문자열을 가지고 무차별 랜덤접속시도를 돌리는 듯 하다.

우리는 항상 보안에 취약해있으며 언제 어디서 올지 모르는 해킹공격에 대비해야한다.

그 방법은 어렵지 않다. 조금만 찾아보다보면 굉장히 다양한 방법들이 존재하며 돈을 지불하고 방어를 하는 방법도 있지만 이렇게 손수 방어구축시스템을 조금씩 갖춰나가는 방법도 있다.

그럼 1편 끝

댓글