How To Block Hackers and Remote Desktop Attempts In Windows Server 2008 or newer
Is your Windows server getting hacked? Do you need to block ip addresses in Windows? Dealing with a brute force attack? This article is for you.
The last month or so I noticed a disturbing trend in the event viewer on one of our dedicated windows servers. We were getting thousands of failed login attempts to terminal services (remote desktop). I decided I would enable the terminal services auto-ban, so after 5 login attempts the ip address would get banned for 24 hours. This only solved part of the problem, as the attacker continued to flood our server with requests, causing the windows logon process (csrss.exe kept appearing and disappearing in task manager) to continually spin up and shut down. This actually caused significant CPU (10%+) and disk IO as the event viewer continually wrote failed login attempts.
After searching the Interwebs for a better way, I did not find anything that I liked or that didn’t spike my CPU usage, so I decided to make a free tool in C# to auto-ban ip addresses. This tool is constantly improving. Right now it can block ip addresses as found in the event log for audit-failure events. It is very configurable as well.
Features include:
- Duration to ban ip address
- Number of failed login attempts before ban
- Whitelist of comma separated ip addresses or regex to never ban
- Blacklist of comma separated ip addresses or regex to always ban
- Custom prefix to windows firewall rules
- Custom keywords, XPath and Regex to parse event viewer logs for failed login attempts
- Refreshes config so no need to restart the service when you change something
- Highly configurable, ban anything that comes through Windows Event Viewer
- A GREAT and FREE alternative to RdpGuard or Syspeace. Don’t pay for something that should be free!
Ships with Windows login failure and MSSQLSERVER login failures by default.
Here’s how to create a Windows service from command prompt:
sc create IPBAN type= own start= auto binPath= d:\system\ipban\ipban.exe DisplayName= IPBAN
*** Requires Windows Vista or Windows Server 2008 or newer ***
*** Make sure to right click on the .zip file you download and select properties, then unblock ***
Jeffrey N. Johnson (
Hi JJXtra,
I’ll give that new version a go. I had seen it not unban after the set time, and used the above reset task script to do it. Plus I like how a reset flushes all the firewall rules, and brings it all back to zero. White listing wasn’t being cooperative either, and with 300+ users, my potential for grief was high so a 15min flush kept the legit users working while balancing the security aspect. Also incrementing the version numbers in the exe so folks know what ver they’re running would be helpful, it seems they’re all stamped as 1.0.0.
PS.. Not sure if this is relevant to the newer vers, but what is the time frame for looking at the security log? I noticed today I banned an IP with a single invalid login, I confirmed this by resetting the service and again one single bad login got me banned. Now I may have had a number of older entries from days/weeks ago, but it seems to me it may be looking cumulatively throughout the log history. Can it auto filter perhaps only the last 24 hours? No hacker is going to try one login per day to break in.
Tim
Hi Tim,
There was a bug with unbanning that was recently fixed. I have tested whitelisting and it seems to work at least in my simple tests. The exe now has a version that increments. It does not reset failed login attempt counts ever until the ip is banned (unless you restart the service), but that may be something useful to do, I will consider adding it. What is the ban count in your configuration file (FailedLoginAttemptsBeforeBan)? I believe the default is 5.
Thanks!
Greetings all, please download the latest version from github. It has a critical bug fix for not un-banning ip addresses properly.
This has been working so well! I added a cmd task to reset the service every 15mins, this clears previously banned IP’s, and inserts into a long term log any blocked IP in that segment of time. Haven’t tried the newer vers but here’s my reset script if anyone is interested. Cheers to JJXTRA for this tool.
net stop “ipban”
echo %date% %time% >> C:\apps\IPBan\log\IPBANLog.txt
type C:\apps\IPBan\banlog.txt >> C:\apps\IPBan\log\IPBANLog.txt
sleep 2
net start “ipban”
The tool does have a configuration item that allows you to specify how long to ban ip addresses for. They are un-banned automatically after that time. Do you need a feature to keep track of all banned ip addresses for all time?
Hi, great script! I can’t seem to get it to go run unfortunately. It’s a 2008R2 server with .NET 4 Framework Extended running on it. Here’s the debug output…
C:\IPBan>ipban.exe debug
Unhandled Exception: System.TypeInitializationException: The type initializer for ‘IPBan.Log’ threw an exception. —> S
ystem.Configuration.ConfigurationErrorsException: An error occurred creating the configuration section handler for nlog:
Request failed. (C:\IPBan\IPBan.exe.Config line 5) —> System.Security.SecurityException: Request failed.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCache
d, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckTh
is, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Configuration.TypeUtil.CreateInstanceWithReflectionPermission(Type type)
at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.Init(RuntimeConfigurationRecord config
Record, FactoryRecord factoryRecord)
at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.InitWithRestrictedPermissions(RuntimeC
onfigurationRecord configRecord, FactoryRecord factoryRecord)
at System.Configuration.RuntimeConfigurationRecord.CreateSectionFactory(FactoryRecord factoryRecord)
at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String configKey, Boolean& isRootDeclaredH
ere)
— End of inner exception stack trace —
at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String configKey, Boolean& isRootDeclaredH
ere)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPe
rmission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(Stri
ng sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at NLog.Config.XmlLoggingConfiguration.get_AppConfig()
at NLog.LogFactory.get_Configuration()
at NLog.LogFactory.GetLogger(LoggerCacheKey cacheKey)
at NLog.LogFactory.GetLogger(String name)
at NLog.LogManager.GetLogger(String name)
at IPBan.Log..cctor() in C:\Users\Jeff\Desktop\Personal\DigitalRuby\DEV\SVN\trunk\Utilities\IPBan\Logger.cs:line 22
— End of inner exception stack trace —
at IPBan.Log.Write(LogLevel level, String text, Object[] args) in C:\Users\Jeff\Desktop\Personal\DigitalRuby\DEV\SVN\
trunk\Utilities\IPBan\Logger.cs:line 29
at IPBan.IPBanService.OnStart(String[] args) in C:\Users\Jeff\Desktop\Personal\DigitalRuby\DEV\SVN\trunk\Utilities\IP
Ban\IPBanService.cs:line 363
at IPBan.IPBanService.RunConsole(String[] args) in C:\Users\Jeff\Desktop\Personal\DigitalRuby\DEV\SVN\trunk\Utilities
\IPBan\IPBanService.cs:line 390
at IPBan.IPBanService.Main(String[] args) in C:\Users\Jeff\Desktop\Personal\DigitalRuby\DEV\SVN\trunk\Utilities\IPBan
\IPBanService.cs:line 402
C:\IPBan>
The application crashes so it doesn’t parse the whole output so it stops after line 402.
Any help would be great.
Many thanks,
Chris.
Looks like it may not have permission to write the log file. Can you verify you are running under the system account?
Hi, I can confirm the service is running as the Local System account. When I try and manually start the service I get the error: ‘The IPBAN service on local computer started then stopped. Some services stop automatically if they are not in use by other services or programs.’
Any ideas?
What is the path to your log file? From your exception stack it looks like it’s failing to initialize the logger…
Also try downloading the latest from github.
Same error again unfortunately when I try to run the debug with the newer version.
The log is in the same location as the .exe file.
C:\IPBan\IPBan.Log
&
C:\IPBan\banlog.txt
I have even given ‘Everyone’ security permissions to write to it, just incase.
Still no joy.
Many thanks for your help so far.
Just to confirm are you running the service as SYSTEM? What about user account control, is that on at all? What if you start command prompt as administrator and then run “ipban debug”, does it work then?
First of all I would like to say Thank you for your great work!
I am new to windows server and was looking for a secure solution for my windows server that I recently installed.
I uploaded .exe file from the downloads folder and created a service as below. Unfortunately the service doesn’t start as it stopped itself after the service started.
sc create IPBAN type= own start= auto binPath= c:\path\IPBan.exe DisplayName= IPBAN
I installed .NET framework 4.0 before create a service. Can you please advise?
Harry
Try running “IPBAN.exe debug” on the command line and let me know what it says. Also, right click on all the files and select properties and then “unblock” if it’s available.
Sorry, the locale is not set to English but you may guess what type of errors I have had. The error is related to the exception which is not completed and the next error message in Korean means “a file or one of the assemblies could not be loaded. Can not find the file specified.”
C:\bin\IPBan>IPBan.exe debug
처리되지 않은 예외: System.IO.FileNotFoundException: 파일이나 어셈블리 ‘NLog, Ve
rsion=2.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c’ 또는 여기에 종
속되어 있는 파일이나 어셈블리 중 하나를 로드할 수 없습니다. 지정된 파일을 찾을
수 없습니다.
위치: IPBan.Log.Write(LogLevel level, String text, Object[] args)
위치: IPBan.IPBanService.OnStart(String[] args) 파일 C:\Users\Jeff\Desktop\Pe
rsonal\DigitalRuby\DEV\SVN\trunk\Utilities\IPBan\IPBanService.cs:줄 400
위치: IPBan.IPBanService.RunConsole(String[] args) 파일 C:\Users\Jeff\Desktop
\Personal\DigitalRuby\DEV\SVN\trunk\Utilities\IPBan\IPBanService.cs:줄 427
위치: IPBan.IPBanService.Main(String[] args) 파일 C:\Users\Jeff\Desktop\Perso
nal\DigitalRuby\DEV\SVN\trunk\Utilities\IPBan\IPBanService.cs:줄 439
Try the latest download from github. It should have NLog.dll in the same directory. If it still fails to load, it must have something to do with the locale of the system you are on, in which case I will need to troubleshoot further. What is the system locale of your server? Korean I assume?
Yes, the system locale is Korean. I will download it again and will let you know whether it works or not.
Many thanks!
I have uploaded NLog.dll into the same folder. The service started without any errors and it seems working fine. Thanks again for your great work!
Just FYI I added a whitelist config option which is a comma separated list of ips to never ban
This is a simple and awesome tool..works perfect on my VPS, almost no cpu impact, very simple and effective, really man you made a perfect and simple tool for a simple but very important function.
You’re welcome, glad it’s helping you out
Hey JJxtra
The software is working great blocking the IP’s of hax0rz. But it doesn’t appear to be doing housekeeping removing previously banned IP’s. The problem being that we’ve got some legit users that have banned themselves, and while it’s simple to remove them by hand, I’m wondering if you’ve had the same results with banned IP’s not being cleansed after the the ban period has elapsed.
I appreciate your effort, once the word gets out on this tool everyone will be using it =)
Tim
I’ll look into it, it’s supposed to check every minute for expired banned ip addresses, but I’ll write some tests to make sure it’s working and update github soon. Also I’ve added more flexibility in the config file to support different kind of events (such as MSSQLSERVER failed logings).
You can try the latest version to see if you have more luck, it’s definitely more beta feeling since I’ve added so many new features, but it seems to still be working on my dedicated web server.
Also, you can edit the WhiteList property in the config file to specify a comma separated list of ip addresses to never ban.
I loaded it up on a test box and it is working as described. Simple and effective. Thanks for your work on putting this together. I appreciate it.
You’re welcome
Hi, I came upon your tool for banning IP’s based upon failed logon attempts. I am curious if you would provide the .exe file, as I don’t have the tools to compile the source.
I appreciate this effort and would like to try it out.
Tim ONeill
Sure thing, I added it under downloads in github. Let me know how it goes…
https://github.com/jjxtra/Windows-IP-Ban-Service/downloads
Try right clicking on the extracted files and select unblock. You can also run “ipban.exe debug” to run it as a console app. Let me know how it goes.