/var/log/secure에는 ftp나 ssh 접속시 잘못된 아이디나 비밀번호를 사용하여 실패가 되는 경우를 로그로 남기고 있다.
아래 코드는 /var/log/secure 로그의 최근 1,000줄 중에 Failed password가 있는 로그 중 IP를 추출해서 3번 이상 로그가 남았다면, 해당 IP를 차단 후에 텔레그램으로 알람을 해주는 코드이다.
생각보다 굉장히 자주 접근을 시도하기 때문에 텔레그램 알람은 그냥 주석 처리하는 게 낫다.
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
BLOCK_IP_LIST_PATH = "/tmp/block_ip_list"
BLOCK_FAILED_COUNT = 3
KEY = "텔레그램API KEY"
CHATID = "텔레그램을 받을 대상"
block_ip_list = os.popen("cat {}".format(BLOCK_IP_LIST_PATH)).read().split("\n")
ssh_login_failed_list = os.popen("tail -n 1000 /var/log/secure | grep 'Failed password' | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'").read().split("\n")
temp = {}
for ip in ssh_login_failed_list:
ip = str(ip)
if ip in temp:
temp[ip] = temp[ip] + 1
else:
temp[ip] = 1
for ip in temp:
if temp[ip] >= BLOCK_FAILED_COUNT and ip not in block_ip_list:
os.popen("/usr/sbin/iptables -A INPUT -s {0} -j DROP".format(ip)).read()
os.popen("echo '{0}' >> {1}".format(ip, BLOCK_IP_LIST_PATH)).read()
os.popen('curl -d "chat_id={0}&text={1}" https://api.telegram.org/bot{2}/sendMessage'.format(CHATID, "BLOCK IP : "+ip, KEY))
크론을 1분 주기로 돌리겠다면, 해당 파일이 /tmp/block_ip.py에 있다고 가정하고 아래 내용을 crontab에 등록하면 된다.
* * * * * /tmp/block_ip.py >> /dev/null 2>&1
반응형