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

2016년 10월 12일 수요일

vpopmail(pop3) brute force 공격 차단

qmail vpopmail 을 쓰고 있다.

서버 점검 중 pop3로 접속시도를 하는 로그를 발견했다.

없는 아이디로 계속 시도하는 것과 계정은 있지만 패스워드를 계속 틀리게 입력하는 유형 2가지.
Oct 11 11:27:54 mail vpopmail[27836]: vchkpw-pop3: vpopmail user not found admin12@domain.com:109.104.203.62

Oct 11 15:02:11 mail vpopmail[15277]: vchkpw-pop3: password fail (pass: 'e603f6c507b3993651f0439553584c50') acount@domain.com:110.70.15.59

한두개가 아니라 같은 아이피가 계정만 바꿔서 계속 시도하고 있다.
fail2ban으로 vpopmail 차단을설정하면 좋은데, 실 운영서버라 fail2ban 설치하기가 쉽지 않다.

그래서 스크립트 작성.
#/bin/bash


help()
{
echo ""
echo "/var/log/maillog is default"
echo "iptable apply is not default"
echo "banCount 100 is default"
echo "-a : iptable applied"
echo "-f : maillog FILE PATH"
echo "-c : ban count"
echo ""
echo "Usae : $0 -a -c 100 -f /var/log/maillog "
exit 0
}


ignoreIPs=("222.222.222.222" "111.111.111.111")
maillog="/var/log/maillog"
banCount=100
fw=false


while getopts ac:f: opt
do
case $opt in
a)
fw=true
;;
c)
banCount=$OPTARG
;;
f)
maillog=$OPTARG
;;
*)
help
exit 0
;;
esac
done


banIPs=`grep -E 'user not found|password fail' ${maillog} | awk -F: '{print $NF}' | sort | uniq -dc | awk '{if ($1 > '"${banCount}"') print $NF}'`

for banIP in $banIPs
do
for ignoreIP in ${ignoreIPs[@]}
do
if [ $ignoreIP == $banIP ]
then
# echo "ignore IP: ${ignoreIP}"
# echo "ban IP : $banIP"
break
fi
done

echo "ban IP : $banIP ,whois : $(geoiplookup $banIP)"
if [ $fw = true ] ; then
iptables -A INPUT -s ${banIP}/24 -j DROP
fi

done


if [ $fw = true ] ; then
#remove duplicate iptables rules
#http://www.krazyworks.com/remove-duplicate-iptables-rules/
/sbin/service iptables save
/sbin/iptables-save | awk '!x[$0]++' > /tmp/iptables.conf
/sbin/iptables -F
/sbin/iptables-restore < /tmp/iptables.conf
/sbin/service iptables save
/sbin/service iptables restart
if [ -f /tmp/iptables.conf ] ; then /bin/rm -f /tmp/iptables.conf ; fi
fi


 

1. banCount 는 같은 IP가 해당 값이상일 경우만 가져온다.
실제사용자가 실패할 경우도 있기 때문에 100정도면 적당한 것 같다.

2. ignoreIPs는 차단하지 않을 IP를 적어준다.

3. iptable에 적용하는 데, 중복으로 계속 적용된다.
마지막 부분이 중복을 없애고 다시 설정하는 부분이다.

maillog 파일의 생성을 살펴보면 매일 오전 4시 마다 rotate 되고 있다
cron으로 4시 30분 부터 실행되게끔 걸어주면 되겠다.

2014년 1월 28일 화요일

원격데스크탑,MSSQL 공격 자동 차단 스크립트

원격데스크탑 과 mssql 의 기본 포트를 바꾸지 않는 이상, BRUTE FORCE 공격이 지속적으로 들어온다.

해당 포트를 바꾸는 게 가장 최선이지만, 사정상 바꾸기 힘든 경우는 이벤트로그를 보고 해당 IP를 차단하는 방법 밖에 없다.

리눅스 같은 경우 fail2ban 이라는 훌륭한 오픈소스가 존재하여 사용가능 하나 윈도우 같은 경우 그런 프로그램이 없다.

소스포지에서 검색 해보면 비슷한 프로그램들이 나오나, 동작도 제대로 안 되고 에러 투성이 프로그램들만 있어서 사용할 수 있는 게 없다.

물론 상용프로램은 제외.

RDP 공격 같은 경우 EvlWatcher 라는 프로그램이 있는데, 아주 잘 동작 된다.

주의 할점은 관리자 권한으로 설치 해야 서비스 등록 및 방화벽 룰 셋팅이 제대로 설정 된다.

그러나 MSSQL BRUTE FORCE 공격은 따로 막아 주지 않아 조금 아쉽다.

ps.2014.05.21 윈도우2012에서는 동작을 안한다.

-------------------------------------------------------------------------------------

그러다 파워셀 스크립트로 해당 기능을 수행 할 수 있지 않을 까 해서 검색 해 보니, 역시 있었다.

해당 스크립트를 약간 변형 하여 mssql 도 막을 수 있게끔 처리 하였다.

이 스크립트는 이벤트 로그 기록을 참조하여 현재 접속 중인 아이피만 확인 한다.
#$regex1,$regex2값을 서버 아이피로 변경한다.
#예를 들어 서버 아이피가 222.222.222.222 이면
# $regex1 = [regex] "222\.222\.222\.(?:222|51):3389\s+(\d+\.\d+\.\d+\.\d+)";
#제일 마지막은 or 연산이기 때문에 신경 안써도 된다. 한개만 들어가도 됨.

###################### Config ######################
$regex1 = [regex] "111\.222\.333\.(?:140|51):3389\s+(\d+\.\d+\.\d+\.\d+)";
$regex2 = [regex] "원본 네트워크 주소:\t(\d+\.\d+\.\d+\.\d+)";

$regex1_mssql = [regex] "111\.222\.333\.(?:140|51):1433\s+(\d+\.\d+\.\d+\.\d+)";
$regex2_mssql = [regex] "클라이언트: (\d+\.\d+\.\d+\.\d+)";

$MyIp = "123.123.123.123"; #현재 내가 접속한 IP 차단하지 않는다.
$deny_count = 5; #임계값
$loop_time = 30; #loop_time 마다 재 실행.(초)
###################### Config ######################

$tick = 0;
"Start to run at: " + (get-date);

while($True) {
$blacklist = @();

#Port 3389 RDP
"Running... (tick:" + $tick + ")"; $tick+=1;

$a = @()
netstat -no | Select-String ":3389" | ? { $m = $regex1.Match($_);
$ip = $m.Groups[1].Value; if ($m.Success -and $ip -ne $MyIp) {$a = $a + $ip;} }

if ($a.count -gt 0) {
$ips = get-eventlog Security -Newest 1000 | Where-Object {$_.EventID -eq 4625 } | foreach {
$m = $regex2.Match($_.Message); $ip = $m.Groups[1].Value; $ip; } | Sort-Object | Tee-Object -Variable list | Get-Unique

foreach ($ip in $a) { if ($ips -contains $ip) {
if (-not ($blacklist -contains $ip)) {
$attack_count = ($list | Select-String $ip -SimpleMatch | Measure-Object).count;
"Found RDP attacking IP on 3389: " + $ip + ", with count: " + $attack_count;
if ($attack_count -ge $deny_count) {$blacklist = $blacklist + $ip;}
}
}
}
}

#Port 1433 MSSQL

$a = @()
netstat -no | Select-String ":1433" | ? { $m = $regex1_mssql.Match($_);
$ip = $m.Groups[1].Value;
if ($m.Success -and $ip -ne $MyIp) {$a = $a + $ip;} }

if ($a.count -gt 0) {
$ips = get-eventlog Application -Newest 1000 | Where-Object {$_.EventID -eq 18456 -and ($_.Message -like "*sa*" ) } | foreach {
$m = $regex2_mssql.Match($_.Message); $ip = $m.Groups[1].Value; $ip; echo $m; } | Sort-Object | Tee-Object -Variable list | Get-Unique

foreach ($ip in $a) { if ($ips -contains $ip) {
if (-not ($blacklist -contains $ip)) {
$attack_count = ($list | Select-String $ip -SimpleMatch | Measure-Object).count;
"Found MSSQL attacking IP on 1433: " + $ip + ", with count: " + $attack_count;
if ($attack_count -ge $deny_count) {$blacklist = $blacklist + $ip;}
}
}
}
}

<# 주석처리. 사용안함. 미 테스트
#FTP
$MyFtpLogFile1 = "";
$now = (Get-Date).AddMinutes(-5); #check only last 5 mins.
#Get-EventLog has built-in switch for EventID, Message, Time, etc. but using any of these it will be VERY slow.
$count = (Get-EventLog Security -Newest 1000 | Where-Object {$_.EventID -eq 4625 -and $_.Message -match "Logon Type:\s+8" -and
$_.TimeGenerated.CompareTo($now) -gt 0} | Measure-Object).count;
if ($count -gt 50) #threshold
{
$ips = @();
$ips1 = dir "C:\inetpub\logs\LogFiles\FPTSVC2" | Sort-Object -Property LastWriteTime -Descending
| select -First 1 | gc | select -Last 200 | where {$_ -match "An\+error\+occured\+during\+the\+authentication\+process."}
| Select-String -Pattern "(\d+\.\d+\.\d+\.\d+)" | select -ExpandProperty Matches | select -ExpandProperty value | Group-Object
| where {$_.Count -ge 10} | select -ExpandProperty Name;

$ips2 = dir "C:\inetpub\logs\LogFiles\FTPSVC3" | Sort-Object -Property LastWriteTime -Descending
| select -First 1 | gc | select -Last 200 | where {$_ -match "An\+error\+occured\+during\+the\+authentication\+process."}
| Select-String -Pattern "(\d+\.\d+\.\d+\.\d+)" | select -ExpandProperty Matches | select -ExpandProperty value | Group-Object
| where {$_.Count -ge 10} | select -ExpandProperty Name;
$ips += $ips1; $ips += $ips2; $ips = $ips | where {$_ -ne "10.0.0.1"} | Sort-Object | Get-Unique;

foreach ($ip in $ips) {
if (-not ($blacklist -contains $ip)) {
"Found attacking IP on FTP: " + $ip;
$blacklist = $blacklist + $ip;
}
}
}
#>

#Firewall change

<# $current = (netsh advfirewall firewall show rule name="MY BLACKLIST" | where {$_ -match "RemoteIP"}).replace("RemoteIP:", "").replace(" ","").replace("/255.255.255.255",""); #inside $current there is no \r or \n need remove. foreach ($ip in $blacklist) { if (-not ($current -match $ip) -and -not ($ip -like "10.0.0.*")) {"Adding this IP into firewall blocklist: " + $ip; $c= 'netsh advfirewall firewall set rule name="MY BLACKLIST" new RemoteIP="{0},{1}"' -f $ip, $current; Invoke-Expression $c; } } #>

foreach ($ip in $blacklist) {

$fw=New-object -comObject HNetCfg.FwPolicy2; # http://blogs.technet.com/b/jamesone/archive/2009/02/18/how-to-manage-the-windows-firewall-settings-with-powershell.aspx
$myrule = $fw.Rules | where {$_.Name -eq "MY BLACKLIST"} | select -First 1; # Potential bug here?

if (-not ($myrule.RemoteAddresses -match $ip) -and -not ($ip -like "123.123.123.*"))
{"Adding this IP into firewall blocklist: " + $ip;
$myrule.RemoteAddresses+=(","+$ip);
#echo $ip > C:\BlackListIP.txt
}
}

"__________________________________________________________________________________"
Wait-Event -Timeout $loop_time #pause 30 secs

} # end of top while loop.

해당 코드를 Windows PowerShell ISE 실행하여 붙여넣고 실행하면 된다.
실행하기 전에 자기에게 맡게 IP,포트번호 등의 셋팅을 해야 하며, 윈도우 방화벽 규칙(MY BLACKLIST)이 추가 되어 있어야 한다.

 

#등록된 IP 전부를 deny 시키는 방화벽 룰 생성.
netsh advfirewall firewall add rule name="MY BLACKLIST" dir=in action=block localip=any remoteip=107.160.158.70

 107.160.158.70 아이피는 미국 어태커 IP.

 

1. 2008에서만 검증 확인. 2012에서도 가능 할 것으로 보임
2. 2003이하에서는 방화벽 동작 방식이 아예 달라서 사용 할 수 가 없다.
3. MY BLACKLIST 이름으로 차단 규칙 추가해야 한다.
4. FTP 스크립트는 테스트 안 해봄
5. 이벤트 로그가 있어야 하며, 현재 사용자가 계속 공격을 시도하고 있어야지 차단목록에 등록된다.
6. 공격자가 접속을 시도하는 상황에서만 차단 동작을 한다.

해당 스크립트를 저장하여 사용할 경우

오류: 이 시스템에서 스크립트를 실행할 수 없으므로 <Script name> 파일을 로드할 수 없습니다.  라는 메시지가 나타난다.

이럴 경우 파워셀을 관리자 권한으로 실행 후 아래의 명령어를 실행하면 된다.

Set-ExecutionPolicy RemoteSigned

출처

auto_blocking.ps1