Super Tips - Free Windows Server Firewall with Brute Force

My VBS interactive Windows Free Firewall
(Advanced scripts for ipsec/windows 2003 server family and brute force intrusion detection)
USE AT YOUR OWN RISK!

Hi

If you don't have money to a complete server firewall solution this can be usefull. It is better than nothing and i would say it is a good server solution as you
can see the source code and know exactly what is going on

I have been running some windows and linux server for a while and always think about some Brute Force Detection
Scripts and free server firewall just to rest at night and know that nobody was trying to discover my Admin
Terminal service password or crack some ftp customer user

for linux besides the fact of having tons of softwares under open source we have http://www.rfxnetworks.com/proj.php
that kindly public their scripts for free and they have the iptables based firewall named APF (advanced policy firewall),
the BDF (brute force detection), LSM (linux socket monitor) and also PRM (process resource monitor)

this tools i use and approve as simple and cool... So i started to develop some tools analog to this ones and i will try to put this
as simple as i can (sorry for some English mistakes

if you take a look in this url:

http://www.windowsitpro.com/Article...ArticleID=41571

we can see that ipsec is very similar to the linux iptables, they work in a primary layer under windows kernels
so we have some commands to run in vbs and bat files that we can use to create a Deny Rule and apply it over our logs running like Schedule Tasks)

i don't use account lock policies because adminstrator account may be locked and i remote manage my machines...

PART I - configuring a firewall policies (open some ports deny all of the others)

this very popular url is a place to begin (almost mandatory):

http://www.analogx.com/contents/articles/ipsec.htm

1)you may want to download and install this ipsec template (before installing you can also open it at your notepad for instance and check that all entrys
will be added at the same place at your windows registry (regedit) and there is no hijack or stuff)

It came by default as disable so no need to be afraid of begin lock out of your box...

Obviously you'll also have to know something about the ipsec policies (locate at the Administrative Tools - Local Security Settings)
and after following analogx steps you will be able to customize your template

2)For helm control panel i added 8086 port, if you run webmail, awstats, mysql, sqlserver *under other port than 1433
you need to customize this to fit your needs, also changed telnet to deny, Windows Network to deny, etc...

browse thought their options and you will analise how it works before activating it

Now Passive Tranfer improvement (this analogx tutorial is to use with active transfer and this is bad cause it's too slow):

3)You can now define a very especific port range to your server:

http://www.support.microsoft.com/def...b;en-us;555022

Go back to the IPSEC Analogx Police

4)Edit the APS-ALL TCP TRAFFIC DENY FILTER double clicking it and then under Connection Type
change from all Network Connections to Remote Access only - doing this passive transfer will work. Also realize that the filter action is to Deny.

5)Now we are going to open the passive transfer ports to FTP:

Create inside of this Analogx Public Server Police a new filter named OPT (open passive transfer)
as it will ask you to create a new filtering rule put the first port you choosed for instance port 5500

Now use this cscript (edit and customize to fit your passive range)


Set WshShell = CreateObject("WScript.Shell")
For x = 5501 to 5700
WshShell.Run "netsh ipsec static add filter filterlist=OPT srcaddr=Me dstaddr=Any protocol=TCP mirrored=yes srcport=" & x & "dstport=0"
Next


it will open the other ports to passive transfer

*remember that if you click twice windows will accept and double place the rule (what is not cool - as simple it is as fast it will be)

6)Edit now the OPT- Open Passive Transfer double clicking it and then under Connection Type
change from all Network Connections to Remote Access only but this time make sure that the filter action is to Permit

7)Now create a filter named Firewall - in this new filtering rule (named firewall too) you will deny an ip adress *use one that dont compromise you or delete it after creating this filter.
This time you must use filter action as All Network Connection (as we are banning now) and DENY

this will be the place that the banned ips discovered by the Brute Force Detection Script will be placed and
you can easily do a task with a script to periodically clean this list.

In this following url we find all ipsec netsh commands:
http://www.microsoft.com/technet/pr...d443d5ed90.mspx


PART II - final ipsec tweaks and brute force detection based on event log and msftp log files:

Located at the Administrative Tools - Local Security Settings double click at local policies and then again at audit policy

make sure to have Failure enabled in all of then (because we need to log attempts that are brute force intrusions)


Finally the scripts

Script A is a Event Log to watch each 3 minutes and imediatly deny in case of 5 wrong passwords
the X10 error that means remote desktop terminal service attempt so is really an issue

tip. you can add a rule in your template to allow terminal service for your ips so you will never be locked out of the box
your better than this to only accept determined ips you will put in

Script B is based on LogParser and it needs logparser 2.2 and works watching MSFTP Logs to each 5 minutes searching for 10 wrong attempts and imediatly deny the ips
it will work even to anonymous connections that by default aren't logged at microsoft's event log

http://www.logparser.com/

also want to thanx to http://www.computerperformance.co.uk/ i learned a lot there regarding to wsh scripts
and used some of then as a base to this ones:


'beginning of Script A

Option Explicit
Dim strEventCode1
Dim strEventCode2
Dim strComputer
Dim dtmNow
Dim dtmStartDate
Dim dtmEndDate
Dim objWMIService
Dim strQueryString
Dim colEvents
Dim objEvent
Dim iThreshold
Dim iDuration
Dim strEmailRecipient
Dim body
dim countstr1
dim countstr2
dim countstr3
dim cc
dim WshShell

'---------Modify the following to suit your need------------
'Event Codes to monitor.
strEventCode1 = 529
strEventCode2 = 529
'Computer name to be monitored.
strComputer = "."
'Duration of the monitoring period, in hours.
iDuration = 1
'Threshold for the number of events.
iThreshold = 5
'Email address for notification.
strEmailRecipient = "your@email.com"
'at the end change the ip to CDOsys function
'---------Do not modify below--------------------------------

dtmNow = Now
'Convert the start and end date/time to UTC format.
dtmStartDate = UTC(Dateadd("n", -3 * iDuration, dtmNow),strComputer)
dtmEndDate = UTC(dtmNow,strComputer)
'Query for the events.
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate, (Security)}!\\" & strComputer & "\root\cimv2")
strQueryString = "Select * from Win32_NTLogEvent Where TimeWritten >= '" _
& dtmStartDate & "' and TimeWritten < '" & dtmEndDate & "'" _
& " and ((EventCode = '" & strEventCode1 & "') or " _
& " (EventCode = '" & strEventCode2 & "')) "
Set colEvents = objWMIService.ExecQuery _
(strQueryString)


dim x
dim x3
dim x8
dim x10
dim mark
dim mark1

countstr1 = 0
countstr2 = 0
countstr3 = 0
x = "Administrator"
x3 = "Type: 3"
x10 = "Type: 10"
mark=""

'extract the Ips using mid function
dim ip
dim leftover
dim find

DIM IPs : IPs = ARRAY(0)
DIM IPsA : IPsA = ARRAY(0)


DIM t
t = ""


DIM t1
t1 = ""

For each objEvent in colEvents

mark1 = "0"

If InStr(objEvent.Message,x) and InStr(ObjEvent.Message,x10) Then

countstr1 = countstr1 + 1

mark=instr(ObjEvent.Message,"Address:")
ip=mid(ObjEvent.Message,mark+8,17)
leftover=trim(ip)

body = body & "<br>Administrator flagged" & countstr1 & " " & leftover
mark1 = 1

else


If InStr(ObjEvent.Message,x10) Then

mark=instr(ObjEvent.Message,"Address:")
ip=mid(ObjEvent.Message,mark+8,17)
leftover=trim(ip)

countstr1 = countstr1 + 1

body = body & "<br>" & ObjEvent.User & "x10 flagged" & countstr1 & " " & leftover

mark1 = 1

end if


If InStr(ObjEvent.Message,x3) Then

'here you can improve a webmail control or application control if you want, i keep the email body enabled to silent know what is going on

'mark=instr(ObjEvent.Message,"Address:")
'ip=mid(ObjEvent.Message,mark+8,17)
'ip=mid(ObjEvent.Message,413,16)
'leftover=trim(ip)

countstr3 = countstr3 + 1

body = body & "<br>" & ObjEvent.User & " x3 flagged " & countstr3 & " " & ObjEvent.Message & "<br>"
'mark1 = 1

end if

end if

if mark1 <> 0 then

'rotine to compare and populate the arrays (it will distinct in array IPs and collect all occourences on array IPsA)
'then for each ip on array IPs it will search and count in array IPsA to check if it need to be Denied!

body = body & "-OK"

dim e
e = 0


if UBOUND(IPs) <= 0 or UBOUND(IPs) = "" then
'insert

REDIM PRESERVE IPs(UBOUND(IPs)+1)
IPs(UBOUND(IPs)-1) = leftover


else

'compare
for t=0 to UBOUND(IPs)-1
if IPs(t) = leftover then
e = e + 1
end if
next

if e = 0 then

REDIM PRESERVE IPs(UBOUND(IPs)+1)
IPs(UBOUND(IPs)-1) = leftover

end if

end if

REDIM PRESERVE IPsA(UBOUND(IPsA)+1)
IPsA(UBOUND(IPsA)-1) = leftover


end if
next

dim z
z = 0
cc = 0

'comment if you dont want debug report being retrived in body message
if UBOUND(IPs) > 0 then

for t=0 to UBOUND(IPs)-1
body = body & "<br>" & IPs(t) & "array IPs<br>"
cc = cc +1
next
else
body = body & "<br>END"
end if

if UBOUND(IPsA) > 0 then

for t=0 to UBOUND(IPsA)-1
body = body & "<br>" & IPsA(t) & "array IPsA<br>"
z = z + 1
next
else
body = body & "<br>END"
end if


dim y
y = 0

'validation and count


DIM ac
DIM fire

if UBOUND(IPs) > 0 then

do while y <= cc

fire = 0
ac = 0

for t1=0 to UBOUND(IPsA)-1
if IPs(y) = IPsA(t1) then

'count and flag as body message to debug purposes
ac = ac + 1
body = body & "<br>" & IPs(y) & "flagged" & ac

end if

if ac >= 5 and fire = 0 then

'deny it
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "cmd /c netsh ipsec static add filter filterlist=firewall srcaddr=Me dstaddr=" & IPs(y) & " protocol=any mirrored=yes",1,true
fire = 1
end if

next

y = y + 1


loop

end if



'If the number of events is greater than the threshold, email the notification.

If colEvents.Count >= iThreshold Then
Email strEmailRecipient, "[LOG] Security Event Log Alert", "There are " & _
colEvents.Count & " logs of Event Codes " & strEventCode1 & " and " & _
strEventCode2 & " at " & strComputer & " in the past 5 minutes<br>" & body
End If

WScript.Quit

Function UTC(dtmDate, strComputer)
'Function to convert the date/time to UTC format.
'
Dim objSWbemServices
Dim colTimeZone
Dim objTimeZone
Dim strBias
Dim dtmCurrentDate
Dim dtmTargetDate
Dim dtmMonth
Dim dtmDay
Dim dtmHour
Dim dtmMinute
Dim dtmSecond

Set objSWbemServices = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colTimeZone = objSWbemServices.ExecQuery _
("SELECT * FROM Win32_TimeZone")
For Each objTimeZone in colTimeZone
strBias = objTimeZone.Bias
Next

dtmCurrentDate = dtmDate
dtmTargetDate = Year(dtmCurrentDate)

dtmMonth = Month(dtmCurrentDate)
If Len(dtmMonth) = 1 Then
dtmMonth = "0" & dtmMonth
End If

dtmTargetDate = dtmTargetDate & dtmMonth

dtmDay = Day(dtmCurrentDate)
If Len(dtmDay) = 1 Then
dtmDay = "0" & dtmDay
End If

dtmTargetDate = dtmTargetDate & dtmDay

dtmHour = Hour(dtmCurrentDate)
If Len(dtmHour) = 1 Then
dtmHour = "0" & dtmHour
End If

dtmTargetDate = dtmTargetDate & dtmHour

dtmMinute = Minute(dtmCurrentDate)
If Len(dtmMinute) = 1 Then
dtmMinute = "0" & dtmMinute
End If

dtmTargetDate = dtmTargetDate & dtmMinute

dtmSecond = Second(dtmCurrentDate)
If Len(dtmSecond) = 1 Then
dtmSecond = "0" & dtmSecond
End If

dtmTargetDate = dtmTargetDate & dtmSecond

dtmTargetDate = dtmTargetDate & ".000000"
dtmTargetDate = dtmTargetDate & Cstr(strBias)
UTC = dtmTargetDate
End Function

Function Email(strTo, strSubject, strTextBody)
'Function to send email
'Default sender: email recipient
Dim objEmail
Set objEmail = CreateObject("CDO.Message")
objEmail.From = strTo
objEmail.To = strTo
objEmail.Subject = strSubject
objEmail.htmlbody = strTextBody
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
"0.0.0.0"
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update
objEmail.Send
Set objEmail = Nothing
End Function
'--------- end of script


the next script is based on LogParser and it is pretty cool, not only it will return the ips but also it counts the number of 530 ftp errors.
We don't need that arrays so it is simple than the other

It's different from the above because it will email you reporting for each ip denied and the Script A above will deliver
only a single email with a full report of x3, x10 and admin x10 attempts considering x10 as deniable.


'beginning of Script B
' This script uses logparser

DIM log
DIM ye
DIM ye1
DIM da
DIM mo

ye1 = year(now)
ye = replace(ye1,"20","")

if day(now) < 10 then
da = "0" & day(now)
else
da = day(now)
end if

if month(now) < 10 then
mo = "0" & month(now)
else
mo = month(now)
end if

log = "ex" & ye & mo & da & ".log"

DIM IPs : IPs = ARRAY(0)

DIM objLogQuery : SET objLogQuery = WScript.CreateObject("MSUtil.LogQuery")

DIM recordSet

DIM SelectStr

' Get the distinct IP addresses

SelectStr = "SELECT DISTINCT TO_LOWERCASE(c-ip) AS URL, Count(*) AS Hits FROM C:\WINDOWS\system32\LogFiles\MSFTPSVC1\" & log & " WHERE "
SelectStr = SelectStr & "SUB(TO_INT(TO_LOCALTIME(SYSTEM_TIMESTAMP())), "
SelectStr = SelectStr & "TO_INT(TO_LOCALTIME(TO_TIMESTAMP(date,time)))) < 300"
SelectStr = SelectStr & "AND sc-status=530 GROUP BY URL ORDER BY URL"


SET recordSet=objLogQuery.Execute(SelectStr)

DO WHILE NOT recordset.atEnd

IF recordSet.GetRecord().isNull(0) = FALSE THEN

REDIM PRESERVE IPs(UBOUND(IPs)+1)

if recordSet.GetRecord().getValue(1) >= 10 then


IPs(UBOUND(IPs)-1) = recordSet.GetRecord().getValue(0)

'else

' REDIM PRESERVE IPs(UBOUND(IPs)+1)


end if

END IF

recordset.MoveNext

LOOP

recordSet.close

dim body

IF UBOUND(IPs) > 0 THEN

' WScript.Echo("Blocking the following IP addresses:")

FOR t=0 TO UBOUND(IPs)-1
'se IPs(t) <> "" then deny

if IPs(t) <> "" and IPs(t) <> "0" then
'ipsec netsh add filter

Set WshShell = CreateObject("WScript.Shell")


WshShell.Run "netsh ipsec static add filter filterlist=firewall srcaddr=Me dstaddr=" & IPs(t) & " protocol=any mirrored=yes",1,true

body = IPs(t)

Email "my@email.com", "[LOG] Security Event Log Alert - FTP alarm", body

END IF
NEXT

ELSE

body = "No IP addresses to block"

END IF

WScript.Quit

' This function returns TRUE if the specified element is in the specified array

FUNCTION IsIn(element, arrayObj)

if UBOUND(arrayObj) = -1 THEN

IsIn = FALSE

END IF

FOR i=0 TO UBOUND(arrayObj)

DIM IPs

IPs = Split(arrayObj(i),",")

IF IPs(0)=element THEN

IsIn = TRUE

EXIT FUNCTION

END IF

NEXT

IsIn = FALSE

END FUNCTION


Function Email(strTo, strSubject, strTextBody)
'Function to send email
'Default sender: email recipient
Dim objEmail
Set objEmail = CreateObject("CDO.Message")
objEmail.From = strTo
objEmail.To = strTo
objEmail.Subject = strSubject
objEmail.htmlbody = strTextBody
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
"0.0.0.0"
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update
objEmail.Send
Set objEmail = Nothing
End Function
'end of the scripts


You know logparser cames with some cool scripts such as blocknimda.vbs that i changed to work in all IIS websites and
hackerScan.js that you can also modify.

I also made a script to report all sql attempts (trusted and failures) and some others such as an error report analiser
using find and findstr commands and the same hackerscan.str's list of bad requests such as "cmd.exe", "root.exe":


'sample script for watch error logs and look after a list of hacker attempts
'FIND

dim body

Set WshShell = CreateObject("WScript.Shell")

WshShell.Run "cmd /c findstr /i /g:/HackerScan.str C:\WINDOWS\system32\LogFiles\HTTPERR\* > c:\http.log",1,true

body = "email completed so send it"

Email "my@email.com", "[LOG] Security Event Log Alert - httperr TRIGGER", body

WScript.Quit

'Get computer name
Function getComputer()
Set objNet = WScript.CreateObject("WScript.Network")
getComputer= objNet.ComputerName
Set objNet = Nothing
End Function

Function Email(strTo, strSubject, strTextBody)
'Function to send email
'Default sender: email recipient
Dim objEmail
Set objEmail = CreateObject("CDO.Message")
objEmail.From = strTo
objEmail.To = strTo
ObjEMail.AddAttachment "c:\http.log"
objEmail.Subject = strSubject
objEmail.htmlbody = strTextBody
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
"0.0.0.0"
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update
objEmail.Send
Set objEmail = Nothing
End Function
'--------- end of script

Function Quote( sPath )
If InStr( sPath, " " ) > 0 Then
Quote = """" & sPath & """"
Else
Quote = """" & sPath & """"
End If
End Function
'end


An antidos can be a future development such as many other things

http://www.microsoft.com/technet/Se...satack.mspx#top


In the future i also plan to release a script to do something like PRM and LSM from http://www.rfxnetwork.com
as i state at the beginning of this article in order to monitor all process each one minute and kill some of then
such as Dr.Watson errors, etc.


To mailenable standard i am trying to finish a script that uses Spam control together with ClamAv in the same MTA pickup event


Security Hints

URLSCAN, Server Performance Advisor and Microsoft Baseline Security analiser are some handy tools for free

http://www.microsoft.com/technet/se...ls/default.mspx
http://www.microsoft.com/downloads/...&displaylang=en

Asp.net and Folder permissions VERY IMPORTANT dont run a windows server before doing this:

http://www.kb.servertastic.com/

http://www.php.net (other excelente resource)

http://www.webhostautomation.com - home of HELM Control Panel has an excelent board

After this when if you feel confortable and did some tests and stuff you can enable APS - Analog Public Server Policy and you are ready to go!

have fun : )

Claudio Szykman

 

 

 

 

Top