Ban IP address on Hmail with Password proxy

This section contains scripts that hMailServer has contributed with. hMailServer 5 is needed to use these.
Post Reply
insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-09 06:50

I know this has been done many times, in many different ways. One thing that I believe is always consistent, is that in order to do so, you must pass a plain text password. Attached is an executable that will allow you to avoid just that.

I know this could cause some "Well if you are worried about plain test in a file, then you have larger concerns" flame fest. Just know that this is not an option in my world. There can never be any plain text passwords in any flat file on out network (Well none that we own :))

Description:

ProxyBan.exe is called from your EventHandlers.vbs whenever some criteria is met which warrants a ban. It takes a simple command syntax, which then calls the "Interop.hMailServer.dll" which is included in your installation. The offending IP address is now banned for 1 day.

In order to avoid passing plain text from script, ProxyBan.exe is designed to use a "secret". If the secret is correct, it will accept a ban request, and on-the-fly decrypt your hmailserver password and ban the IP that you passed.

e.g. a command line syntax for a ban would be: "C:\Program Files (x86)\hMailServer\Bin\ProxyBan.exe" -secret=mySecret 1.1.1.1

a vbs syntax would be:
Set oShell = CreateObject("WScript.Shell")
oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyBan.exe"" -secret=mySecret " & oClient.IPAddress

BE CAREFUL with the above VB. If you don't call it properly, you will start soft banning everything. You must call it only when something meets a criteria that you would want to ban an IP address for

Setup:

copy ProxyBan.exe to: "C:\Program Files (x86)\hMailServer\Bin\" - folder

Edit your hMailServer.INI file with the following ([Security]should already be there):

[Security]
secretWord=mySecret

Note: mySecret should be whatever you want your secret word to be

You now need to setup you encrypted password. In order to do this, you will need to key in your real Hmailserver's Administrator password. This is a one time thing so that it can proxy the password moving forward

"C:\Program Files (x86)\hMailServer\Bin\ProxyBan.exe" -secret=mySecret -setPass=RealPassword

After you do this, a new line will be created in your hMailServer.INI:
proxyPass=<obscurepassword>

That's it. You are now sending your password to Hmailserver without having to hard code your password in plain text.

So here's how i use it:

I use this with RvdH's fantastic OnClientConnect(oClient) spamrats checker. If you don't know what that is, look here. It allows you to ban a known spammer before they even pass data. Of course, you can call this ban proxy for whatever you want.

Reference: https://vdhout.nl/2017/08/using-spamrat ... mailserver

Here is how you can call it from your EventHandlers.vbs:

Code: Select all

Sub OnClientConnect(oClient)
        If SpamRatsAuthHacker(oClient.IPAddress) Then
		REM call AutobanIP(oClient.IPAddress)
		Set oShell = CreateObject("WScript.Shell") 
		oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyBan.exe"" -secret=mySecret " & oClient.IPAddress
		Result.Value = 1
		REM Debug
		EventLog.Write("Message from: " & oClient.IPAddress & " Blocked as authentication hacker") 
		Exit Sub
	End If	
End Sub

Function SpamRatsAuthHacker(strIP)
	SpamRatsAuthHacker = false
	Dim a : a = Split(strIP, ".")
	On Error Resume Next
	With CreateObject("DNSLibrary.DNSResolver")
		strIP = .DNSLookup(a(3) & "." & a(2) & "." & a(1) & "." & a(0) & ".auth.spamrats.com")
	End With
	On Error Goto 0
	Dim strRegEx : strRegEx = "^(127\.0\.0\.43)$"
	SpamRatsAuthHacker = Lookup(strRegEx, strIP)
End Function

Function Lookup(strRegEx, strMatch)
	With CreateObject("VBScript.RegExp")
		.Global = False
		.Pattern = strRegEx
		.IgnoreCase = True
		Lookup = .Test(strMatch)
	End With
End Function
Bans will be indicated in your IP range as the following:

added from script - Auth Hacker BAN for 1 day - ipaddress

You will also see reference to this ban in C:\Program Files (x86)\hMailServer\Logs\hmailserver_events.log if you copied to above verbatim.


Again, the above is not my work. I just use it verbatim to what RvdH has shared!

I just wrote the executable to meet my companies (and mine) requirements. If you find that it could be useful for you, give it a go and let me know :)

P.S. ProxyBan.exe /? will give you some minor syntax help
Attachments
ProxyBan.zip
(6.12 KiB) Downloaded 519 times

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-09 22:21

I came to realize that hard coding just a 1 day ban will be a little too limited for most peoples standards. I added the ability to accept a day parameter as well. If nothing is passed, it will default to 1 day.

vbs code would change to this:

Code: Select all

Set oShell = CreateObject("WScript.Shell") 

Code: Select all

oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyBan.exe"" -secret=mySecret " & oClient.IPAddress & " " & 10
10 stands for 10 days. Change the number accordingly.

Command line code would look like this:

Code: Select all

"C:\Program Files (x86)\hMailServer\Bin\ProxyBan.exe" -secret=mySecret 1.1.1.1 10
Same as above.

Attached is the newest exe.
Attachments
ProxyBan.zip
(6.29 KiB) Downloaded 506 times

User avatar
RvdH
Senior user
Senior user
Posts: 3231
Joined: 2008-06-27 14:42
Location: The Netherlands

Re: Ban IP address on Hmail with Password proxy

Post by RvdH » 2017-10-12 12:41

Nice one, had some difficulties understanding it's purpose

I use much more scripting, for example auto-whitelisting, greylist whitelisting and user validation, these all require to have the password passed via the Authenticate API in the script

I like the idea though....maybe you could make it so it can be used in a much wider scenario? Just to do the Authenticate part and let the actual autoban procedure over to the user/script
CIDR to RegEx: d-fault.nl/cidrtoregex
DNS Lookup: d-fault.nl/dnstools
DKIM Generator: d-fault.nl/dkimgenerator
DNSBL Lookup: d-fault.nl/dnsbllookup
GEOIP Lookup: d-fault.nl/geoiplookup

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-12 18:35

Thanks. For me, the purpose is singular. I needed to be able to ban without having a password in plain text. I also do not like the scripting dependencies on the front end of the server. e.g. script hangs, and thread locks. This is where the interop comes in for me 2 full. I am much more proficient in c#, and I can control script failure much easier by just passing the task off to an executable that does the job for me. Failure or success does not harm hmail.

Being that it is using the interop, its very easily adaptable to do any other function by just adding command line variables(I make quite a few other calls to interop for other reasons as well). The dilema that I ran into is that i'm not entirely sure that I could just pass auth, and then hand it back to vbs to continue. If you are interested, i can strip down the executable just to handle auth and you can try it out.
RvdH wrote:Nice one, had some difficulties understanding it's purpose

I use much more scripting, for example auto-whitelisting, greylist whitelisting and user validation, these all require to have the password passed via the Authenticate API in the script

I like the idea though....maybe you could make it so it can be used in a much wider scenario? Just to do the Authenticate part and let the actual autoban procedure over to the user/script

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-12 19:18

I made a quick modification. If you would like to try it just for the auth call, syntax would look like this:

Code: Select all

"C:\Program Files (x86)\hMailServer\Bin\ProxyBan.exe" -secret=mySecret
Don't forget that you still need to create your "secret" in the ini file and set your password to be encrypted (as in original instructions)

Code: Select all

"C:\Program Files (x86)\hMailServer\Bin\ProxyBan.exe" -secret=mySecret -setPass=RealPassword
Anyway, feel free to give that a try. I'm still trying to figure out if this would work. I was assuming that if you pass auth to hmail, that you would have to do it in the same session that you are calling a function from. If not, then this would be a great addition to any hardened server (IMO).
Attachments
ProxyBan.zip
(6.41 KiB) Downloaded 504 times

User avatar
RvdH
Senior user
Senior user
Posts: 3231
Joined: 2008-06-27 14:42
Location: The Netherlands

Re: Ban IP address on Hmail with Password proxy

Post by RvdH » 2017-10-12 21:19

Thx, i will give it a go whenever i find some free time
CIDR to RegEx: d-fault.nl/cidrtoregex
DNS Lookup: d-fault.nl/dnstools
DKIM Generator: d-fault.nl/dkimgenerator
DNSBL Lookup: d-fault.nl/dnsbllookup
GEOIP Lookup: d-fault.nl/geoiplookup

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-12 21:26

I dont think you will have any luck. I have made several attempts, and it didnt work (As expected). The only way i think this will work is if the VB script were to open a socket and receive a buffer value.
RvdH wrote:Thx, i will give it a go whenever i find some free time

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-13 03:07

Hmm. I dabbled a little. I was able to create a listener that would accept connections on a port and accept the "secret string". If the secret string is correct, then the listener will return the unencrypted password.

So that works... Problem is that i am beating my head against the wall trying to create ANYTHING vbs based that is capable of connecting, passing a string and receiving the output. I really hate vbs :)

I'm not entirely sure that its possible without winsock.

Anyway. I can successfully telnet to 127.0.0.1 <port>

and pass mySecret

I receive the correct password back. So if you can create some sort of TCP connection with vbs, i can make this work easy.

User avatar
jimimaseye
Moderator
Moderator
Posts: 10053
Joined: 2011-09-08 17:48

Re: Ban IP address on Hmail with Password proxy

Post by jimimaseye » 2017-10-13 08:51

Ive been reading with interest but would like to ask a question. Im not doubting anything but would like to know in simple terms:

Whats the difference in having the official password that lets you do anything with Hmailserver (in the INI and and vbs scripts) coded and visible to any user that has been given access to do so
to
having the official 'secret string' that lets you do anything with Hmailserver (in the INI and and vbs scripts) coded and visible to any user that has been given access to do so?

Im seeing "dont open the door with the key under the mat, use the one out the plant pot".
5.7 on test.
SpamassassinForWindows 3.4.0 spamd service
AV: Clamwin + Clamd service + sanesecurity defs : https://www.hmailserver.com/forum/viewtopic.php?f=21&t=26829

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-13 16:15

I cannot argue with the logic. All i can present is my perspective.

Passwords in plain text are an open invite for brute force and dumb luck. In my experience, i find that most all breaches happen from poor admin decisions which lead to someone simply turning the key that they left in the front door. Not from elaborate, and intelligent hacks at process. Security by obscurity is always my front line of defense.

So my example is this:

plain text:
Box is compromised. Hacker has browse access. "Hacker" looks around for a bit and finds scripts. "Hey, look, the password is in plain text. Lets go take a look."

encoded text:
Box is compromised. Hacker has browse access. "Hacker" looks around a bit and finds scripts. Hacker finds encoded lines seem like passwords. The hacker is now posed with questions and has to choose a direction.
1. Passwords to what?
2. How are they used?
3. What do they give them access too?
4. Syntax?
Is it worth their time?

Don't get me wrong. It's not really hard. But are they willing to spend the time to learn the process, crack the executable, and then do their 0 day damage to your server? In my experience, no. They will move onto the guy the left the keys in the lock.

I've also been known to explain it as such: If someone peels the first layer of an onion in a small room, are you interested in sticking around for them to peel the second layer? Is it worth it?

This is why i'm also a fan of not allowing the script to call for just auth and then to continue on. It makes it much more "insecure", in comparison to passing off just a single function to another application. Granted, not by much. It's just another layer. That said, my curiosity really wants to see if i can pull it off..

Here is my question to this whole thing: Who is going to want to hack an hmail server? I wonder what those responses would look like.

jimimaseye wrote:Ive been reading with interest but would like to ask a question. Im not doubting anything but would like to know in simple terms:

Whats the difference in having the official password that lets you do anything with Hmailserver (in the INI and and vbs scripts) coded and visible to any user that has been given access to do so
to
having the official 'secret string' that lets you do anything with Hmailserver (in the INI and and vbs scripts) coded and visible to any user that has been given access to do so?

Im seeing "dont open the door with the key under the mat, use the one out the plant pot".

User avatar
mattg
Moderator
Moderator
Posts: 22435
Joined: 2007-06-14 05:12
Location: 'The Outback' Australia

Re: Ban IP address on Hmail with Password proxy

Post by mattg » 2017-10-13 23:02

insomniac2k2 wrote:3. What do they give them access too?
Seems a moot point when this is added to "C:\Program Files (x86)\hMailServer\Bin\"

TBH, as well as jimimaseye's, comment of 'What's the difference ...', I'm also wondering WHO would download an .exe, that you can't see the source of, and run it on their system, and whether or not this .exe could be leaking my admin password to someone outside of my control...
insomniac2k2 wrote:Here is my question to this whole thing: Who is going to want to hack an hmail server?
From the outside of my network, many people try, normally more than a dozen attempts each day.
Their success is limited, due to their only access really being username + password, or perhaps a flaw in the phpwebadmin module, and admin access via that.

Someone with access to my administrator password, perhaps gained by a leak caused by an untrustworthy .exe, could easily do stuff to my server / send mail from my server / high jack other programs on my server (webserver, DNS ??).

My logs show that attackers are ever more crafty, just last week I had someone sniffing my SSL cipher protocols from across the world. Most of my attacks are not port 25 SMTP any more (because I block AUTH on port 25), now many more try to gain user credentials via IMAP or POP3 connections, even via ports 993 and 995. My wordpress websites each get about 5 attempts each day to guess my passwords. There are a number of hacking programs freely available on the internet, and stuff like SPARTA can tell what mailserver I run behind my firewall, and even finds this on custom (not standard) ports.

So now the who?
-script kiddies for sure (I get an increase in traffic in northern hemisphere summer holidays)
-Bored wanna-be computer gurus, who don't have full time work, and are looking at showing their skills (and aside from the hacking aspect, this is someone like me I guess)
-Governments of foreign nations (This is very real, and the USA is a foreign government to me, not that they are the only ones)
-Governments of your own country. Many counties including my country (Australia) have legislation that prevents government employees from hacking businesses or homes in their own country, but if you host on an overseas saerver...
-your business opposition (I've seen my business opposition change account details to my domain Registrar account, trying to steal my domains, and therefore my business. Very nearly got away with it. I've changed domain Registrar a couple of times since.)
-criminal gangs / organised crime. Selling drugs on the street corner is so 1990. These days they sell them from web sites, and from email links, and post the product to you (and sometimes keep charging your credit card for repeats, whether you get the repeats or not)
-people with a political agenda. Don't like religion, don't like conservative views on same sex marriage, don't like gay rights, don't like abortions, don't like guns, do like guns, etc (you get the picture)
-SPAMMERS. These people will do anything to upload malware, and send millions of emails to unsuspecting people who will give over their credit card details. These are often related to the organised crime above...Sometimes SPAMMERS will pretend to be nice software engineers offering their trojan horse via some .exe pretending to offer better security, but in reality being part of the problem. Anyone ever used a registry cleaner app and then get LESS spam. I my experience these apps always increase the spam received.

So my question to you is, how do we know that you are NOT trying to compromise our hmailservers?
Just 'cause I link to a page and say little else doesn't mean I am not being nice.
https://www.hmailserver.com/documentation

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-13 23:58

The exe, as well the ini that it reads can go anywhere. I only put them there for ease of use whilst calling the interop. I shared the exe and what it did to spawn the idea. And to gauge if anyone would have use for it. If you have use for it, ask for the source. If you don't, then don't.

I disagree with it being moot, when its sole function is to ban IP addresses when called (We have talked about expanding this, but maybe its a good reason to limit it to specific calls.). By providing your password in plain text, you are giving everyone that has access to the box full control, as well as anyone that "hacks" the box. When the password is decrypted, it is passed to the interop via com. IMO, that's a hell of a lot more secure than having it sit unencrypted at rest in file and passed in plain text thousands of times a day. I could be wrong i suppose..

In any case, I can just bow out and use it for my purposes.


mattg wrote:
insomniac2k2 wrote:3. What do they give them access too?
Seems a moot point when this is added to "C:\Program Files (x86)\hMailServer\Bin\"

TBH, as well as jimimaseye's, comment of 'What's the difference ...', I'm also wondering WHO would download an .exe, that you can't see the source of, and run it on their system, and whether or not this .exe could be leaking my admin password to someone outside of my control...
insomniac2k2 wrote:Here is my question to this whole thing: Who is going to want to hack an hmail server?
From the outside of my network, many people try, normally more than a dozen attempts each day.
Their success is limited, due to their only access really being username + password, or perhaps a flaw in the phpwebadmin module, and admin access via that.

Someone with access to my administrator password, perhaps gained by a leak caused by an untrustworthy .exe, could easily do stuff to my server / send mail from my server / high jack other programs on my server (webserver, DNS ??).

My logs show that attackers are ever more crafty, just last week I had someone sniffing my SSL cipher protocols from across the world. Most of my attacks are not port 25 SMTP any more (because I block AUTH on port 25), now many more try to gain user credentials via IMAP or POP3 connections, even via ports 993 and 995. My wordpress websites each get about 5 attempts each day to guess my passwords. There are a number of hacking programs freely available on the internet, and stuff like SPARTA can tell what mailserver I run behind my firewall, and even finds this on custom (not standard) ports.

So now the who?
-script kiddies for sure (I get an increase in traffic in northern hemisphere summer holidays)
-Bored wanna-be computer gurus, who don't have full time work, and are looking at showing their skills (and aside from the hacking aspect, this is someone like me I guess)
-Governments of foreign nations (This is very real, and the USA is a foreign government to me, not that they are the only ones)
-Governments of your own country. Many counties including my country (Australia) have legislation that prevents government employees from hacking businesses or homes in their own country, but if you host on an overseas saerver...
-your business opposition (I've seen my business opposition change account details to my domain Registrar account, trying to steal my domains, and therefore my business. Very nearly got away with it. I've changed domain Registrar a couple of times since.)
-criminal gangs / organised crime. Selling drugs on the street corner is so 1990. These days they sell them from web sites, and from email links, and post the product to you (and sometimes keep charging your credit card for repeats, whether you get the repeats or not)
-people with a political agenda. Don't like religion, don't like conservative views on same sex marriage, don't like gay rights, don't like abortions, don't like guns, do like guns, etc (you get the picture)
-SPAMMERS. These people will do anything to upload malware, and send millions of emails to unsuspecting people who will give over their credit card details. These are often related to the organised crime above...Sometimes SPAMMERS will pretend to be nice software engineers offering their trojan horse via some .exe pretending to offer better security, but in reality being part of the problem. Anyone ever used a registry cleaner app and then get LESS spam. I my experience these apps always increase the spam received.

So my question to you is, how do we know that you are NOT trying to compromise our hmailservers?

User avatar
mattg
Moderator
Moderator
Posts: 22435
Joined: 2007-06-14 05:12
Location: 'The Outback' Australia

Re: Ban IP address on Hmail with Password proxy

Post by mattg » 2017-10-14 00:21

insomniac2k2 wrote:In any case, I can just bow out and use it for my purposes.
Please don't

Sharing is great, and alternate opinions and ideas are what makes open source software work.

insomniac2k2 wrote: If you have use for it, ask for the source. If you don't, then don't.
Great answer... :D

Whilst I think that anyone having even just read only access to scripts is likely to lead to bigger issues, I certainly see a point in not including passwords (and usernames) in them.
Your idea of an .exe that requires a 'secret' and does just one thing is a plausible solution, and I don't know of many solutions...

FWIW you've certainly made me think about the security of my PHPwebAdmin, among other things
Just 'cause I link to a page and say little else doesn't mean I am not being nice.
https://www.hmailserver.com/documentation

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-16 03:55

Sooo. Curiosity got the best of me. I decided to run with Rvdh's suggestion/comment on opening up the Proxy to multiple tasks. So while attempting to preserve the original purpose of the Proxy in the first place, I decided to add Auto-Whitelisting w/ auto purging as a POC. Not only that, but i decided to rewrite the argument syntax to a more standard Microsoft structure.

New syntax should look very familiar with todays standards:

command line syntax:

Code: Select all

"C:\Program Files (x86)\hMailServer\Bin\ProxyAuth.exe" -secret <secretphrase>
options:
/? (help)
-help
-whitelist <emailaddress>
-purge <num days to purge old while list records. 180 is default>
-secret <mySecret>
-setpass <Actual Hmail Password>
-ban <100.100.100.10>
-bandays <number ban days. 1 is default>

So in order to auto add a user that you send to to your whitelist, it would look like this:

Code: Select all

Set oShell = CreateObject("WScript.Shell")
oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyAuth.exe"" -secret mySecret -whitelist " & oMessage.Recipients(oRecipient)
In order to Add users to whitelist while utilizing auto purge (remove any users from whitelist older than x days):

Code: Select all

Set oShell = CreateObject("WScript.Shell")
oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyAuth.exe"" -secret mySecret -whitelist " & oMessage.Recipients(oRecipient) & " -purge 180"
To ban an ip address:
In order to Add users to whitelist while utilizing auto purge (remove any users from whitelist older than x days):

Code: Select all

Set oShell = CreateObject("WScript.Shell")
oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyAuth.exe"" -secret mySecret -ban " & oClient.IPAddress"
To ban an ip address optional ban days:

Code: Select all

Set oShell = CreateObject("WScript.Shell")
oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyAuth.exe"" -secret mySecret -ban " & oClient.IPAddress" & " -bandays 60"
My favorite:

Ban auth hackers and purge whitelist (less frequent whitelist checking, since bans are much less frequent than whitelist users):

Code: Select all

Set oShell = CreateObject("WScript.Shell")
oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyAuth.exe"" -secret mySecret -ban " & oClient.IPAddress" & " -bandays 60 -purge"

So in order to replace most of the whitelist code and use ProxyAuth instead. It would look like this:

'--------------------------------------------------------
' Auto Whitelist recipients from auth'd senders
'--------------------------------------------------------
If oClient.Port = 25 Then ' set your smtp sending port number here
If oClient.Username <> "" Then
Dim oRecipient
Set oShell = CreateObject("WScript.Shell")
For oRecipient = 0 to oMessage.Recipients.Count-1
If Not oMessage.Recipients(oRecipient).IsLocalUser Then
For oWhitelistAddress = 0 to oWhitelistAddresses.Count-1
oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyAuth.exe"" -secret mySecret -whitelist " & oClient.IPAddress & " -purge 180" 'user will add if not in list already. List will be read and old users will be purged.
Exit For
End If
End If
End If

Of course you could do whatever you want. It doesnt matter how you call ProxyAuth. It will ban or whitelist whatever you tell it to :)
Attachments
ProxyAuth.zip
(8.51 KiB) Downloaded 498 times

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-16 04:25

Hmm. The above syntax for the EventHandlers.vbs is broken. Maybe someone that is better with VBS can sort it out. I was assuming that whitelisting is called on Sub OnAcceptMessage(oClient, oMessage).

I could be wrong with that as well.

User avatar
mattg
Moderator
Moderator
Posts: 22435
Joined: 2007-06-14 05:12
Location: 'The Outback' Australia

Re: Ban IP address on Hmail with Password proxy

Post by mattg » 2017-10-16 04:40

the FOR loops should be for >> next

Code: Select all

'--------------------------------------------------------
' Auto Whitelist recipients from auth'd senders
'--------------------------------------------------------
If oClient.Port = 25 Then ' set your smtp sending port number here
   If oClient.Username <> "" Then
      Dim oRecipient, oShell
      Set oShell = CreateObject("WScript.Shell")
      For oRecipient = 0 to oMessage.Recipients.Count-1
         If Not oMessage.Recipients(oRecipient).IsLocalUser Then
             'user will add if not in list already. List will be read and old users will be purged.
            oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyAuth.exe"" -secret mySecret -whitelist " & oMessage.Recipients(oRecipient).Address & " -purge 180"
         End If
      Next
   End If
End If
And yes, this would need to be part of probably be OnAcceptMessage sub.
Just 'cause I link to a page and say little else doesn't mean I am not being nice.
https://www.hmailserver.com/documentation

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-16 04:47

Thanks. I was just coming back to correct it. Your's looks better anyway :)
mattg wrote:the FOR loops should be for >> next

Code: Select all

'--------------------------------------------------------
' Auto Whitelist recipients from auth'd senders
'--------------------------------------------------------
If oClient.Port = 25 Then ' set your smtp sending port number here
   If oClient.Username <> "" Then
      Dim oRecipient, oShell
      Set oShell = CreateObject("WScript.Shell")
      For oRecipient = 0 to oMessage.Recipients.Count-1
         If Not oMessage.Recipients(oRecipient).IsLocalUser Then
             'user will add if not in list already. List will be read and old users will be purged.
            oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyAuth.exe"" -secret mySecret -whitelist " & oMessage.Recipients(oRecipient).Address & " -purge 180"
         End If
      Next
   End If
End If
And yes, this would need to be part of probably be OnAcceptMessage sub.

User avatar
SorenR
Senior user
Senior user
Posts: 6308
Joined: 2006-08-21 15:38
Location: Denmark

Re: Ban IP address on Hmail with Password proxy

Post by SorenR » 2017-10-22 17:28

I still get viruses from friends that never should have been given access to electronic equipment. If I whitelist them ... :roll: Geezzzuss ... That is the main reason I gave up on Percepts' old script from 2013 doing the same as your binary Whitelist thingy. Original script dates back to 2008.
viewtopic.php?p=155530#p155530

Whitelisted addresses are NOT virus/spam checked... Just saying... :!:

I favor using the Whitelist in Greylisting to allow known servers immediate access as an alternative.

Eg. like this ... BTW, "LockFile" is used as a kind of record lock since VBS do not natively support record locking. I experience quite often 5-10 concurrent connections from spammers and unless I control the sequence in which things are done, I get errors.

"Sub ExpireGreyList" is included here but I actually run it from a separate script via Windows Scheduler.

Code: Select all

   Sub OnHELO(oClient)
   '
   ' BEGIN
   '

   Dim strRegEx
   strRegEx = "^[a-z]+[0-9]{2}(-)[a-z]{2}[0-9](-obe\.outbound\.protection\.outlook\.com)$|"     &_
              "^(a)[0-9]{1,2}(-)[0-9]{1,3}(\.smtp-out\.amazonses\.com)$|"                       &_
              "^(mail-)[a-z]{2}[0-9](-f)[0-9]{1,3}(\.google\.com)$|"                            &_
              "^(spring-chicken-)[a-z]{2}(\.twitter\.com)$|"                                    &_
              "^(mail)[a-z](-)[a-z]{2}(\.linkedin\.com)$|"                                      &_
              "^(mx)[0-9](\.)[a-z]{3}(\.paypal\.com)$|"                                         &_
              "^(mx-out\.facebook\.com)$|"                                                      &_
              "^(relay99\.mysmtp\.com)$|"                                                       &_
              "(\.lifewavemembers\.com)$|"                                                      &_
              "(\.companymobile\.dk)$|"                                                         &_
              "(\.gratisdns\.dk)$|"                                                             &_
              "(\.electric\.net)$|"                                                             &_
              "(\.jobindex\.dk)$|"                                                              &_
              "(\.anpdm\.com)$|"                                                                &_
              "(\.exigo\.com)$|"                                                                &_
              "(\.post\.dk)$"
   If Lookup(strRegEx, oClient.HELO) Then
      Call GreyWhiteList(oClient.IPAddress, oClient.HELO)
      Exit Sub
   End If

   '
   ' END
   '
   End Sub

   Function Wait(sec)
      With CreateObject("WScript.Shell")
         .Run "timeout /T " & Int(sec), 0, True
'        .Run "sleep -m " & Int(sec * 1000), 0, True
'        .Run "powershell Start-Sleep -Milliseconds " & Int(sec * 1000), 0, True
      End With
   End Function

   Function Lookup(strRegEx, strMatch)
      With CreateObject("VBScript.RegExp")
         .Global = False
         .Pattern = strRegEx
         .IgnoreCase = True
         If .Test(strMatch) Then
            Lookup = True
         Else
            Lookup = False
         End If
      End With
   End Function

   Function LockFile(strPath)
      Const Append = 8
      Const Unicode = -1
      With CreateObject("Scripting.FileSystemObject")
         Dim oFile, i
         For i = 0 To 30
            On Error Resume Next
            Set oFile = .OpenTextFile(strPath, Append, True, Unicode)
            If (Not Err.Number = 70) Then
               Set LockFile = oFile
               On Error Goto 0
               Exit For
            End If
            On Error Goto 0
            Wait(1)
         Next
      End With
      Set oFile = Nothing
      If (Err.Number = 70) Then
         EventLog.Write("ERROR: EventHandlers.vbs")
         EventLog.Write("File " & strPath & " is locked and timeout was exceeded.")
         Err.Clear
      ElseIf (Err.Number <> 0) Then
         EventLog.Write("ERROR: EventHandlers.vbs : Function LockFile")
         EventLog.Write("Error       : " & Err.Number)
         EventLog.Write("Error (hex) : 0x" & Hex(Err.Number))
         EventLog.Write("Source      : " & Err.Source)
         EventLog.Write("Description : " & Err.Description)
         Err.Clear
      End If
   End Function

   Sub GreyWhiteList(strIP, strDesc)
      Dim oApp : Set oApp = CreateObject("hMailServer.Application")
      Call oApp.Authenticate(ADMIN, PASSWORD)
      With LockFile("c:\hmailserver\temp\greywhitelist.lck")
         On Error Resume Next
         oApp.Settings.AntiSpam.GreyListingWhiteAddresses.Refresh
         If (oApp.Settings.AntiSpam.GreyListingWhiteAddresses.ItemByName(strIP) Is Nothing) Then
            With oApp.Settings.AntiSpam.GreyListingWhiteAddresses.Add
               .Description = "# " & Date & " " & strDesc
               .IPAddress = strIP
               .Save
            End With
         Else
            With oApp.Settings.AntiSpam.GreyListingWhiteAddresses.ItemByName(strIP)
               .Description = "# " & Date & " " & strDesc
               .Save
            End With
         End If
         On Error Goto 0
         .Close
      End With
   End Sub

   Sub ExpireGreyList
      Dim j, m_Days : m_Days = 30
      Dim oApp : Set oApp = CreateObject("hMailServer.Application")
      Call oApp.Authenticate(ADMIN, PASSWORD)
      For j = oApp.Settings.AntiSpam.GreyListingWhiteAddresses.Count-1 To 0 Step -1
         If (Left(oApp.Settings.AntiSpam.GreyListingWhiteAddresses(j).Description, 1) = "#") Then
            If (DateDiff("d", Mid(oApp.Settings.AntiSpam.GreyListingWhiteAddresses(j).Description,3,10), Date) > m_Days) Then
               oApp.Settings.AntiSpam.GreyListingWhiteAddresses(j).Delete
            End If
         End If
      Next
   End Sub
SørenR.

Woke is Marxism advancing through Maoist cultural revolution.

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-28 17:17

I wont be using it either, i just wanted to see how easy it would be to add it as an interop function. Needless to say, it would be pretty easy to add anything to this if you were motivated. I also think that its very important to scan all emails. Especially from my friends :)
SorenR wrote:I still get viruses from friends that never should have been given access to electronic equipment. If I whitelist them ... :roll: Geezzzuss ... That is the main reason I gave up on Percepts' old script from 2013 doing the same as your binary Whitelist thingy. Original script dates back to 2008.
viewtopic.php?p=155530#p155530

Whitelisted addresses are NOT virus/spam checked... Just saying... :!:

I favor using the Whitelist in Greylisting to allow known servers immediate access as an alternative.

Eg. like this ... BTW, "LockFile" is used as a kind of record lock since VBS do not natively support record locking. I experience quite often 5-10 concurrent connections from spammers and unless I control the sequence in which things are done, I get errors.

"Sub ExpireGreyList" is included here but I actually run it from a separate script via Windows Scheduler.

Code: Select all

   Sub OnHELO(oClient)
   '
   ' BEGIN
   '

   Dim strRegEx
   strRegEx = "^[a-z]+[0-9]{2}(-)[a-z]{2}[0-9](-obe\.outbound\.protection\.outlook\.com)$|"     &_
              "^(a)[0-9]{1,2}(-)[0-9]{1,3}(\.smtp-out\.amazonses\.com)$|"                       &_
              "^(mail-)[a-z]{2}[0-9](-f)[0-9]{1,3}(\.google\.com)$|"                            &_
              "^(spring-chicken-)[a-z]{2}(\.twitter\.com)$|"                                    &_
              "^(mail)[a-z](-)[a-z]{2}(\.linkedin\.com)$|"                                      &_
              "^(mx)[0-9](\.)[a-z]{3}(\.paypal\.com)$|"                                         &_
              "^(mx-out\.facebook\.com)$|"                                                      &_
              "^(relay99\.mysmtp\.com)$|"                                                       &_
              "(\.lifewavemembers\.com)$|"                                                      &_
              "(\.companymobile\.dk)$|"                                                         &_
              "(\.gratisdns\.dk)$|"                                                             &_
              "(\.electric\.net)$|"                                                             &_
              "(\.jobindex\.dk)$|"                                                              &_
              "(\.anpdm\.com)$|"                                                                &_
              "(\.exigo\.com)$|"                                                                &_
              "(\.post\.dk)$"
   If Lookup(strRegEx, oClient.HELO) Then
      Call GreyWhiteList(oClient.IPAddress, oClient.HELO)
      Exit Sub
   End If

   '
   ' END
   '
   End Sub

   Function Wait(sec)
      With CreateObject("WScript.Shell")
         .Run "timeout /T " & Int(sec), 0, True
'        .Run "sleep -m " & Int(sec * 1000), 0, True
'        .Run "powershell Start-Sleep -Milliseconds " & Int(sec * 1000), 0, True
      End With
   End Function

   Function Lookup(strRegEx, strMatch)
      With CreateObject("VBScript.RegExp")
         .Global = False
         .Pattern = strRegEx
         .IgnoreCase = True
         If .Test(strMatch) Then
            Lookup = True
         Else
            Lookup = False
         End If
      End With
   End Function

   Function LockFile(strPath)
      Const Append = 8
      Const Unicode = -1
      With CreateObject("Scripting.FileSystemObject")
         Dim oFile, i
         For i = 0 To 30
            On Error Resume Next
            Set oFile = .OpenTextFile(strPath, Append, True, Unicode)
            If (Not Err.Number = 70) Then
               Set LockFile = oFile
               On Error Goto 0
               Exit For
            End If
            On Error Goto 0
            Wait(1)
         Next
      End With
      Set oFile = Nothing
      If (Err.Number = 70) Then
         EventLog.Write("ERROR: EventHandlers.vbs")
         EventLog.Write("File " & strPath & " is locked and timeout was exceeded.")
         Err.Clear
      ElseIf (Err.Number <> 0) Then
         EventLog.Write("ERROR: EventHandlers.vbs : Function LockFile")
         EventLog.Write("Error       : " & Err.Number)
         EventLog.Write("Error (hex) : 0x" & Hex(Err.Number))
         EventLog.Write("Source      : " & Err.Source)
         EventLog.Write("Description : " & Err.Description)
         Err.Clear
      End If
   End Function

   Sub GreyWhiteList(strIP, strDesc)
      Dim oApp : Set oApp = CreateObject("hMailServer.Application")
      Call oApp.Authenticate(ADMIN, PASSWORD)
      With LockFile("c:\hmailserver\temp\greywhitelist.lck")
         On Error Resume Next
         oApp.Settings.AntiSpam.GreyListingWhiteAddresses.Refresh
         If (oApp.Settings.AntiSpam.GreyListingWhiteAddresses.ItemByName(strIP) Is Nothing) Then
            With oApp.Settings.AntiSpam.GreyListingWhiteAddresses.Add
               .Description = "# " & Date & " " & strDesc
               .IPAddress = strIP
               .Save
            End With
         Else
            With oApp.Settings.AntiSpam.GreyListingWhiteAddresses.ItemByName(strIP)
               .Description = "# " & Date & " " & strDesc
               .Save
            End With
         End If
         On Error Goto 0
         .Close
      End With
   End Sub

   Sub ExpireGreyList
      Dim j, m_Days : m_Days = 30
      Dim oApp : Set oApp = CreateObject("hMailServer.Application")
      Call oApp.Authenticate(ADMIN, PASSWORD)
      For j = oApp.Settings.AntiSpam.GreyListingWhiteAddresses.Count-1 To 0 Step -1
         If (Left(oApp.Settings.AntiSpam.GreyListingWhiteAddresses(j).Description, 1) = "#") Then
            If (DateDiff("d", Mid(oApp.Settings.AntiSpam.GreyListingWhiteAddresses(j).Description,3,10), Date) > m_Days) Then
               oApp.Settings.AntiSpam.GreyListingWhiteAddresses(j).Delete
            End If
         End If
      Next
   End Sub

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-28 17:53

I notice in your script that you are using OnHELO. As far as i understand, this is superseded by OnClientConnect, correct?

I want to give the greywhitelist a go but just wanted to verify before i start testing.

User avatar
SorenR
Senior user
Senior user
Posts: 6308
Joined: 2006-08-21 15:38
Location: Denmark

Re: Ban IP address on Hmail with Password proxy

Post by SorenR » 2017-10-28 18:20

insomniac2k2 wrote:I notice in your script that you are using OnHELO. As far as i understand, this is superseded by OnClientConnect, correct?

I want to give the greywhitelist a go but just wanted to verify before i start testing.
They are two different things...

OnClientConnect will only give you the IP address and IP Port.

ALL initial connections do a EHLO/HELO to identify themselves regardless of protocol. This "greeting" is used by many to filter out SPAM and bots, as do I, and it is also used to identify the sender.

I COULD do the GreyWhitelist by doing IP lookups and dissect the SPF information for each server - but it's a TON of work and not that easy to do. Filtering on EHLO/HELO is so much easier :mrgreen:

This is what I do... Not the complete code, but you'll get the idea :mrgreen:

PS. My IDS code is using a local SQLite database, not the hMailServer database.

Code: Select all

   Sub OnClientConnect(oClient)
      Dim strRegEx

      '
      ' Exclude Backup-MX & local LAN from test
      '
      If (Left(oClient.IPAddress, 10) = "80.160.77.") Then Exit Sub
      If (Left(oClient.IPAddress, 10) = "192.168.0.") Then Exit Sub

      '
      ' Only allow non-SMTP connect from "Rigsfællesskabet"/"Naalagaaffeqatigiit"/"Ríkisfelagsskapurin" = The Danish Realm.
      '
      If (oClient.Port <> 25) Then
         Dim strPort : strPort = Trim(Mid("SMTP IMAP SMTPSSUBM IMAPS", InStr("25   143  465  587  993  ", oClient.Port), 5))
         strRegEx = "999|208|304|234" ' 999 = N/A, 208 = Denmark, 304 = Greenland, 234 = Faroe Islands
         If Not Lookup(strRegEx, NerdLookup(oClient.IPAddress)) Then
            Result.Value = 1
            Call AutoBan(oClient.IPAddress, strPort, 7, "d")
         End If
      End If

      '
      ' Only test SMTP traffic
      '
      strRegEx = "(25|587|465)"
      If Lookup(strRegEx, oClient.Port) Then
         If (oClient.Port = 25) Then Wait(20)

         '
         ' IDS test for SYN flood etc.
         '
         If IDSCheck(oClient.IPAddress) Then
            Result.Value = 1
            Call AutoBan(oClient.IPAddress, "IDS", 2, "d")
         End If
      End If
   End Sub

   Sub OnHELO(oClient)

      '
      ' Exclude Backup-MX & local LAN from test
      '
      If (Left(oClient.IPAddress, 10) = "80.160.77.") Then Exit Sub
      If (Left(oClient.IPAddress, 10) = "192.168.0.") Then Exit Sub

      '
      ' Dynamic GreyListing
      '
      Dim strRegEx
      strRegEx = "^[a-z]+[0-9]{2}(-)[a-z]{2}[0-9](-obe\.outbound\.protection\.outlook\.com)$|"     &_
                 "^(a)[0-9]{1,2}(-)[0-9]{1,3}(\.smtp-out\.amazonses\.com)$|"                       &_
                 "^(mail-)[a-z]{2}[0-9](-f)[0-9]{1,3}(\.google\.com)$|"                            &_
                 "^(spring-chicken-)[a-z]{2}(\.twitter\.com)$|"                                    &_
                 "^(mail)[a-z](-)[a-z]{2}(\.linkedin\.com)$|"                                      &_
                 "^(mx)[0-9](\.)[a-z]{3}(\.paypal\.com)$|"                                         &_
                 "^(mx-out\.facebook\.com)$|"                                                      &_
                 "^(relay99\.mysmtp\.com)$|"                                                       &_
                 "(\.lifewavemembers\.com)$|"                                                      &_
                 "(\.companymobile\.dk)$|"                                                         &_
                 "(\.gratisdns\.dk)$|"                                                             &_
                 "(\.electric\.net)$|"                                                             &_
                 "(\.jobindex\.dk)$|"                                                              &_
                 "(\.anpdm\.com)$|"                                                                &_
                 "(\.exigo\.com)$|"                                                                &_
                 "(\.post\.dk)$"
      If Lookup(strRegEx, oClient.HELO) Then
         Call GreyWhiteList(oClient.IPAddress, oClient.HELO)
         Exit Sub
      End If

      '
      ' SnowShoe SPAM detection
      '
      If IsSnowShoe(oClient.IPAddress) Then
         Result.Value = 2
         Result.Message = "5.7.1 CODE01 Your access to this mail system has been rejected due to "  &_
                          "the sending MTA's poor reputation. If you believe that this failure is " &_
                          "in error, please contact the intended recipient via alternate means."
         Exit Sub
      End If

      '
      ' Deny servers with specific HELO/EHLO greetings
      '
      ' ^(\[87\.58\.176\.150\])$ and ^(lolle\.org)$ are my public IP and domain !!
      '
      strRegEx = "(localhost)$|(127(?:\.[0-9]{1,3}){3})|^(\[87\.58\.176\.150\])$|^(lolle\.org)$|"  &_
                 "(\.top)$|(\.xyz)$|(\.stream)$|(\.bid)$|(\.date)$|(\.win)$|(\.men)$|(\.vn)$|"     &_
                 "(userdb\.info)$|(\.host\.com)$|(api\.ru)$|(\.faith)$|(\.loan)$|(\.trade)$|"      &_
                 "(\.shop)$"
      If Lookup(strRegEx, oClient.HELO) Then
         Result.Value = 2
         Result.Message = "5.7.1 CODE02 Your access to this mail system has been rejected due to "  &_
                          "the sending MTA's poor reputation. If you believe that this failure is " &_
                          "in error, please contact the intended recipient via alternate means."
         Call AutoBan(oClient.IPAddress, oClient.HELO, 2, "d")
         Exit Sub
      End If

      '
      ' Validate HELO/EHLO greeting
      '
      Const strFQDN = "^(?=^.{1,254}$)(^(?:(?!\.|-)([a-z0-9\-\*]{1,63}|([a-z0-9\-]{1,62}[a-z0-9]))\.)+(?:[a-z]{2,})$)$"
      Const strIPv4 = "^\[(?:[0-9]{1,3}\.){3}[0-9]{1,3}\]$"
      Const strIPv6 = "^\[(IPv6)((?:[0-9A-Fa-f]{0,4}:){1,7}(?:(?:(>25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|[0-9A-Fa-f]{1,4}))\]$"
      strRegEx = strFQDN & "|" & strIPv4 & "|" & strIPv6
      If (Lookup(strRegEx, oClient.HELO) = False) Then
         Result.Value = 2
         Result.Message = "5.7.1 CODE03 Your access to this mail system has been rejected due to "  &_
                          "the sending MTA's poor reputation. If you believe that this failure is " &_
                          "in error, please contact the intended recipient via alternate means."
         Call AutoBan(oClient.IPAddress, oClient.HELO, 2, "d")
         Exit Sub
      End If
   End Sub

   Sub OnSMTPData(oClient, oMessage)

      '
      ' Exclude Backup-MX & local LAN from test
      '
      If (Left(oClient.IPAddress, 10) = "80.160.77.") Then Exit Sub
      If (Left(oClient.IPAddress, 10) = "192.168.0.") Then Exit Sub

      '
      ' Cleanup IDS registry
      '
      IDSDelete(oClient.IPAddress)
   End Sub
SørenR.

Woke is Marxism advancing through Maoist cultural revolution.

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-28 18:51

Ok, thanks for clarification. I'll do some reading, but if you read this, feel free to beat me to the answer. I'm running 5.6.5-B2367. I'm guessing that OnHelo a burned-in unsupported feature in my version? I know i've seen an OnHelo thread, so i will go take a look as well.

I've already added the code to add greywhitelist to ProxyPass, and at first glance it looks like it will work without issue. I just have to test the call real fast to verify.


Thanks for the code snips. It helps with some ideas on how to clamp things down a bit :)

SorenR wrote:
insomniac2k2 wrote:I notice in your script that you are using OnHELO. As far as i understand, this is superseded by OnClientConnect, correct?

I want to give the greywhitelist a go but just wanted to verify before i start testing.
They are two different things...

OnClientConnect will only give you the IP address and IP Port.

ALL initial connections do a EHLO/HELO to identify themselves regardless of protocol. This "greeting" is used by many to filter out SPAM and bots, as do I, and it is also used to identify the sender.

I COULD do the GreyWhitelist by doing IP lookups and dissect the SPF information for each server - but it's a TON of work and not that easy to do. Filtering on EHLO/HELO is so much easier :mrgreen:

This is what I do... Not the complete code, but you'll get the idea :mrgreen:

PS. My IDS code is using a local SQLite database, not the hMailServer database.

Code: Select all

   Sub OnClientConnect(oClient)
      Dim strRegEx

      '
      ' Exclude Backup-MX & local LAN from test
      '
      If (Left(oClient.IPAddress, 10) = "80.160.77.") Then Exit Sub
      If (Left(oClient.IPAddress, 10) = "192.168.0.") Then Exit Sub

      '
      ' Only allow non-SMTP connect from "Rigsfællesskabet"/"Naalagaaffeqatigiit"/"Ríkisfelagsskapurin" = The Danish Realm.
      '
      If (oClient.Port <> 25) Then
         Dim strPort : strPort = Trim(Mid("SMTP IMAP SMTPSSUBM IMAPS", InStr("25   143  465  587  993  ", oClient.Port), 5))
         strRegEx = "999|208|304|234" ' 999 = N/A, 208 = Denmark, 304 = Greenland, 234 = Faroe Islands
         If Not Lookup(strRegEx, NerdLookup(oClient.IPAddress)) Then
            Result.Value = 1
            Call AutoBan(oClient.IPAddress, strPort, 7, "d")
         End If
      End If

      '
      ' Only test SMTP traffic
      '
      strRegEx = "(25|587|465)"
      If Lookup(strRegEx, oClient.Port) Then
         If (oClient.Port = 25) Then Wait(20)

         '
         ' IDS test for SYN flood etc.
         '
         If IDSCheck(oClient.IPAddress) Then
            Result.Value = 1
            Call AutoBan(oClient.IPAddress, "IDS", 2, "d")
         End If
      End If
   End Sub

   Sub OnHELO(oClient)

      '
      ' Exclude Backup-MX & local LAN from test
      '
      If (Left(oClient.IPAddress, 10) = "80.160.77.") Then Exit Sub
      If (Left(oClient.IPAddress, 10) = "192.168.0.") Then Exit Sub

      '
      ' Dynamic GreyListing
      '
      Dim strRegEx
      strRegEx = "^[a-z]+[0-9]{2}(-)[a-z]{2}[0-9](-obe\.outbound\.protection\.outlook\.com)$|"     &_
                 "^(a)[0-9]{1,2}(-)[0-9]{1,3}(\.smtp-out\.amazonses\.com)$|"                       &_
                 "^(mail-)[a-z]{2}[0-9](-f)[0-9]{1,3}(\.google\.com)$|"                            &_
                 "^(spring-chicken-)[a-z]{2}(\.twitter\.com)$|"                                    &_
                 "^(mail)[a-z](-)[a-z]{2}(\.linkedin\.com)$|"                                      &_
                 "^(mx)[0-9](\.)[a-z]{3}(\.paypal\.com)$|"                                         &_
                 "^(mx-out\.facebook\.com)$|"                                                      &_
                 "^(relay99\.mysmtp\.com)$|"                                                       &_
                 "(\.lifewavemembers\.com)$|"                                                      &_
                 "(\.companymobile\.dk)$|"                                                         &_
                 "(\.gratisdns\.dk)$|"                                                             &_
                 "(\.electric\.net)$|"                                                             &_
                 "(\.jobindex\.dk)$|"                                                              &_
                 "(\.anpdm\.com)$|"                                                                &_
                 "(\.exigo\.com)$|"                                                                &_
                 "(\.post\.dk)$"
      If Lookup(strRegEx, oClient.HELO) Then
         Call GreyWhiteList(oClient.IPAddress, oClient.HELO)
         Exit Sub
      End If

      '
      ' SnowShoe SPAM detection
      '
      If IsSnowShoe(oClient.IPAddress) Then
         Result.Value = 2
         Result.Message = "5.7.1 CODE01 Your access to this mail system has been rejected due to "  &_
                          "the sending MTA's poor reputation. If you believe that this failure is " &_
                          "in error, please contact the intended recipient via alternate means."
         Exit Sub
      End If

      '
      ' Deny servers with specific HELO/EHLO greetings
      '
      ' ^(\[87\.58\.176\.150\])$ and ^(lolle\.org)$ are my public IP and domain !!
      '
      strRegEx = "(localhost)$|(127(?:\.[0-9]{1,3}){3})|^(\[87\.58\.176\.150\])$|^(lolle\.org)$|"  &_
                 "(\.top)$|(\.xyz)$|(\.stream)$|(\.bid)$|(\.date)$|(\.win)$|(\.men)$|(\.vn)$|"     &_
                 "(userdb\.info)$|(\.host\.com)$|(api\.ru)$|(\.faith)$|(\.loan)$|(\.trade)$|"      &_
                 "(\.shop)$"
      If Lookup(strRegEx, oClient.HELO) Then
         Result.Value = 2
         Result.Message = "5.7.1 CODE02 Your access to this mail system has been rejected due to "  &_
                          "the sending MTA's poor reputation. If you believe that this failure is " &_
                          "in error, please contact the intended recipient via alternate means."
         Call AutoBan(oClient.IPAddress, oClient.HELO, 2, "d")
         Exit Sub
      End If

      '
      ' Validate HELO/EHLO greeting
      '
      Const strFQDN = "^(?=^.{1,254}$)(^(?:(?!\.|-)([a-z0-9\-\*]{1,63}|([a-z0-9\-]{1,62}[a-z0-9]))\.)+(?:[a-z]{2,})$)$"
      Const strIPv4 = "^\[(?:[0-9]{1,3}\.){3}[0-9]{1,3}\]$"
      Const strIPv6 = "^\[(IPv6)((?:[0-9A-Fa-f]{0,4}:){1,7}(?:(?:(>25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|[0-9A-Fa-f]{1,4}))\]$"
      strRegEx = strFQDN & "|" & strIPv4 & "|" & strIPv6
      If (Lookup(strRegEx, oClient.HELO) = False) Then
         Result.Value = 2
         Result.Message = "5.7.1 CODE03 Your access to this mail system has been rejected due to "  &_
                          "the sending MTA's poor reputation. If you believe that this failure is " &_
                          "in error, please contact the intended recipient via alternate means."
         Call AutoBan(oClient.IPAddress, oClient.HELO, 2, "d")
         Exit Sub
      End If
   End Sub

   Sub OnSMTPData(oClient, oMessage)

      '
      ' Exclude Backup-MX & local LAN from test
      '
      If (Left(oClient.IPAddress, 10) = "80.160.77.") Then Exit Sub
      If (Left(oClient.IPAddress, 10) = "192.168.0.") Then Exit Sub

      '
      ' Cleanup IDS registry
      '
      IDSDelete(oClient.IPAddress)
   End Sub

User avatar
SorenR
Senior user
Senior user
Posts: 6308
Joined: 2006-08-21 15:38
Location: Denmark

Re: Ban IP address on Hmail with Password proxy

Post by SorenR » 2017-10-28 19:10

insomniac2k2 wrote:Ok, thanks for clarification. I'll do some reading, but if you read this, feel free to beat me to the answer. I'm running 5.6.5-B2367. I'm guessing that OnHelo a burned-in unsupported feature in my version? I know i've seen an OnHelo thread, so i will go take a look as well.
You won't find OnHELO in the official code... I've been pushing to get in there - along with many others but so far no luck.

Yes, we have a OnHELO thread that has a life of it's own. RvdH has taken it upon himself to maintain an UN-official release.

Simply install the official (same version) release and replace the executeable and library from RvdH's code and you are set to go. If you go back in the OnHELO thread there are older versions if you prefer. My own version is a local mod of the original 5.4.2 and the OnHELO code originate from this mod. RvdH have added some of his own code and bugfixes - plus some experimental stuff too :mrgreen:

viewtopic.php?p=199083#p199083
SørenR.

Woke is Marxism advancing through Maoist cultural revolution.

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-28 19:13

I just started reading the thread. Your response saved me a ton of time!! Thank you. I'll give it a try soon.
SorenR wrote:
insomniac2k2 wrote:Ok, thanks for clarification. I'll do some reading, but if you read this, feel free to beat me to the answer. I'm running 5.6.5-B2367. I'm guessing that OnHelo a burned-in unsupported feature in my version? I know i've seen an OnHelo thread, so i will go take a look as well.
You won't find OnHELO in the official code... I've been pushing to get in there - along with many others but so far no luck.

Yes, we have a OnHELO thread that has a life of it's own. RvdH has taken it upon himself to maintain an UN-official release.

Simply install the official (same version) release and replace the executeable and library from RvdH's code and you are set to go. If you go back in the OnHELO thread there are older versions if you prefer. My own version is a local mod of the original 5.4.2 and the OnHELO code originate from this mod. RvdH have added some of his own code and bugfixes - plus some experimental stuff too :mrgreen:

viewtopic.php?p=199083#p199083

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-28 23:37

That was actually quite easy to add!

Attached is the latest version which now includes the ability to GreyWhitelist by domains via OnHELO.


I used your regex logic to test. Seems to work fine. I also separated the purge function. It now needs to be called independently for each list (presently greywhitelist or whitelist).

Example on how to purge each list based upon days would be:

Code: Select all

ProxyAuth.exe -secret secretpass -purge GreyWhitelist 180   -or-
ProxyAuth.exe -secret secretpass -purge Whitelist 180
Using your logic for OnHELO GreyWhitelist verification, to call ProxyAuth, it would look like this:

Code: Select all

   Sub OnHELO(oClient)
   '
   ' BEGIN
   '

   Dim strRegEx
   strRegEx = "^[a-z]+[0-9]{2}(-)[a-z]{2}[0-9](-obe\.outbound\.protection\.outlook\.com)$|"     &_
              "^(a)[0-9]{1,2}(-)[0-9]{1,3}(\.smtp-out\.amazonses\.com)$|"                       &_
              "^(mail-)[a-z]{2}[0-9](-f)[0-9]{1,3}(\.google\.com)$|"                            &_
              "^(spring-chicken-)[a-z]{2}(\.twitter\.com)$|"                                    &_
              "^(mail)[a-z](-)[a-z]{2}(\.linkedin\.com)$|"                                      &_
              "^(mx)[0-9](\.)[a-z]{3}(\.paypal\.com)$|"                                         &_
              "^(mx-out\.facebook\.com)$|"                                                      &_
              "^(relay99\.mysmtp\.com)$|"                                                       &_
              "(\.lifewavemembers\.com)$|"                                                      &_
              "(\.companymobile\.dk)$|"                                                         &_
              "(\.gratisdns\.dk)$|"                                                             &_
              "(\.electric\.net)$|"                                                             &_
              "(\.jobindex\.dk)$|"                                                              &_
              "(\.anpdm\.com)$|"                                                                &_
              "(\.exigo\.com)$|"                                                                &_
              "(\.post\.dk)$"
   If Lookup(strRegEx, oClient.HELO) Then
      Set oShell = CreateObject("WScript.Shell")
	oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyAuth.exe"" -secret mySecret -greywhitelist " & oClient.IPAddress & " " & oClient.HELO
      Exit Sub
   End If

   '
   ' END
   '
   End Sub
   
 Function Lookup(strRegEx, strMatch)
	With CreateObject("VBScript.RegExp")
		.Global = False
		.Pattern = strRegEx
		.IgnoreCase = True
		Lookup = .Test(strMatch)
	End With
End Function 
You wouldn't need any file locking or checking logic. As this is handled by the interop. If you feel like giving it a try, please feedback your results. Please note that I did not follow anyone's particular naming convention. My naming convention is as follows: "Auto Add IP Address - domain.com - todays date".

When An ip connects that is previously in the list, the description updates for that list item to reflect the days date. Nothing further is needed to be done. So as stated above, you can call ProxyAuth from batch or task to purge whatever record you want for how many days back you want to do it for. (ProxyAuth.exe -secret secretpass -purge GreyWhitelist 180)

PS: I realize that this may very well just be for me, but as this grows into something with a bit more versatility, it may suit a few others needs. I still like this much better than having passwords is plain text :)
Attachments
ProxyAuth.zip
(9.49 KiB) Downloaded 457 times

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-10-29 19:10

Up until this point, i have not been comfortable with including the source for this application, because the moment the source was available the "crypto" string which was static in the class, would be available for reverse engineering. (Ala, you have source, so you have everyone else's crypto key if they left it default). I didn't want anyone blaming me for this type of exposure.

This is now moot! From this point forward, the application will create its own random "hash" string and inject it into your ini file (or any other path of choice by changing the source.). What this means to you is several things:

You can use the application as it is (right out of the box). The application will set a unique hash that no one else will know.
You can now set your actual password (that gets encrypted) based on this unique hash
You can now set your "secret" right from command line.

Note this has absolutely no effect on your hmail install. Nor does it change your core password. It just allows you to never share it with anyone in plain text. If you run into an issue, then just wipe out the 3 settings in your ini file and start over. You will regenerate all new unique variables.

So here's how you get started:

Copy ProxyAuth to your bin folder
From command line:
ProxyAuth.exe -setpass <your real password to be encrypted>
ProxyAuth.exe -setsecret <your unique secret word that you will use to call ProxyAuth.exe in the future>

That's it. You are now using a unique and pretty damn secure way call your functions without sharing your passwords in plain text.

proxyAuth.exe (/?) presently supports the following commands:

C:\Program Files (x86)\hMailServer\Bin>ProxyAuth.exe /?
List of Parameters:
-setsecret -setsecret <secretphrasetobeset>
-setpass -setpass <passwordtobeencrypted>
-secret -secret <secretphrase>
-ban -ban <ip address>
-bandays -bandays <numberofdaystoban>
-whitelist -whitelist <emailaddr@domain.com>
-greywhitelist -greywhitelist <ipaddress> -or- -greywhitelist <ipaddress> <DomainName>


Usage Examples:

Ban IP address
ProxyAuth.exe -secret <your secret word> -ban <ip address>


GreyWhitelist known address
ProxyAuth.exe -secret <your secret word> --greywhitelist <ip address> <name>


Optional: Choose your own ban days
ProxyAuth.exe -secret <your secret word> -ban <ip address> -bandays <number of days>


Optional: Choose Whitelist or GreyWhitelist to purge
ProxyAuth.exe -secret <your secret word> -purge <Whitelist or GreyWhitelist> [optional to purge old records older t
e.g. ProxyAuth.exe -secret secretpass -purge GreyWhitelist 180
e.g. ProxyAuth.exe -secret secretpass -purge Whitelist 180


Change Password Syntax:
ProxyAuth.exe -secret <mySecret> -setPass <actual hmail administrator password>


Note: Your secret phrase muse be in your Hmailserver.ini as secretWord=mySecret for the above command line to work

Q: So what is there to gain by using this approach?
A: A few things:
i. As stated many times. No plain test passwords
ii. Reduction of scripting overhead on hmail threads. Once hmailserver hands off the task to ProxyAuth, the thread gets free'd to move on. It doesn't matter of ProxyAuth fails to complete a task. it will not affect the performance of the core application.
iii. You can confuse the hell out of everyone else trying to figure out what you are doing :)

Disclaimer: As it stands, everything is known to be bug free. I have some lazy catch code in there that can be improved on, but well, i'm lazy....
Attachments
ProxyPass_source.zip
(100.9 KiB) Downloaded 444 times
ProxyAuth.zip
(9.43 KiB) Downloaded 423 times

porcupine
Normal user
Normal user
Posts: 40
Joined: 2007-03-12 09:02

Re: Ban IP address on Hmail with Password proxy

Post by porcupine » 2017-11-06 05:52

My variation on the spamrats/ProxyAuth script but using dnsbl.dronebl.org and command-line based nslookup, many thanks to the other contributors on this:

Code: Select all

Sub OnClientConnect(oClient)
   If DroneBLAuthHacker(oClient.IPAddress) Then
      Set oShell = CreateObject("WScript.Shell")
      oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyAuth.exe"" -secret **yoursec** -ban " & oClient.IPAddress & " -bandays 30", 0, False
	  Result.Value = 1
      'Debug
      EventLog.Write("Message from: " & oClient.IPAddress & " Blocked as authentication hacker")
      Exit Sub
   End If   
End Sub

Function DroneBLAuthHacker(strIP)
   DroneBLAuthHacker = false
   Dim strLookupResult
   On Error Resume Next
   strLookupResult = NSLookup(strIP)
   On Error Goto 0
   'remove any that you don't want to match from http://dronebl.org/docs/howtouse
   Dim strRegEx : strRegEx = "127\.0\.0\.(3|5|6|7|8|9|10|11|12|13|14|15|16)"
   'Debug
   'EventLog.Write("DNS Result for: " & strIP & " is: " & strLookupResult)
   DroneBLAuthHacker = Lookup(strRegEx, strLookupResult)
End Function

Function NSLookup(strIP)
	Dim objshell, strCmd, objExec, strLine, strIPResult, strLookup
	Dim a : a = Split(strIP, ".")
	strLookup = a(3) & "." & a(2) & "." & a(1) & "." & a(0) & ".dnsbl.dronebl.org"
	'Debug
	'EventLog.Write("DNS Lookup for: " & strLookup)
	set objShell = CreateObject("Wscript.Shell")
	strCmd = "%comspec% /c nslookup " & strLookup
	Set objExec = objShell.Exec(strCmd)
	Do Until objExec.StdOut.AtEndOfStream
		strLine = objExec.StdOut.ReadLine()
		If (Left(strLine, 8) = "Address:") Then
			strIPResult = Trim(Mid(strLine, 9))
			NSLookup = strIPResult
		End If
	Loop
End Function

Function Lookup(strRegEx, strMatch)
   With CreateObject("VBScript.RegExp")
      .Global = False
      .Pattern = strRegEx
      .IgnoreCase = True
      Lookup = .Test(strMatch)
   End With
End Function

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-11-08 18:54

Glad you found use for it! Attached is updated source and compiled exe. I fixed a few small bugs and corrected some loops that were making redundant calls. I also added standardized logging for all tasks to write to the hmailserver_events.log file. If the file doesnt exist, it will create and use it.

I also removed the interop dll from the source, as it is redundant to include it. So if you use my code, make sure to move your interop dll over to the source root folder.
Attachments
ProxyPass.zip
(61.9 KiB) Downloaded 427 times
ProxyAuth.zip
(9.84 KiB) Downloaded 435 times

insomniac2k2
Normal user
Normal user
Posts: 87
Joined: 2016-08-09 19:47

Re: Ban IP address on Hmail with Password proxy

Post by insomniac2k2 » 2017-12-06 17:51

Porcupine added some great and necessary changes and was nice enough to share. Attached his his version oh Program.cs. Just overwrite the original program.cs file with this one. They are all great changes. Using the interop's event writer was much smarter than my hackery. :)

Copy Paste of changes:

"I've made some small tweaks just to program.cs to allow ProxyAuth to run on installations that are not in the default location. ProxyAuth.exe just need to be placed in the \Bin folder and it will automatically find the .ini file and extract the path of the log folder. For debugging, you can set the value of bDebug to True and it will take the hard coded values of the default installation folder, but don't forget to set it to False for release.

I have also changed the way that it logs to the Event Log so that it allows hMailServer to handle it. Everything else is unchanged. I've put comments around my changes to make it more visible."

Thanks Alex!

I have some other small tweaks that i'm testing. I will wrap in these changes with mine in a future release.
Attachments
Program.zip
(3.82 KiB) Downloaded 426 times

porcupine
Normal user
Normal user
Posts: 40
Joined: 2007-03-12 09:02

Re: Ban IP address on Hmail with Password proxy

Post by porcupine » 2017-12-07 04:52

I've modified one line of the OnClientConnect part of the script as the Shell.Run method seems to operate better when it waits for the process to complete before returning.

From https://msdn.microsoft.com/en-us/librar ... 84%29.aspx
object.Run(strCommand, [intWindowStyle], [bWaitOnReturn])

Set bWaitOnReturn to True instead of False:

Code: Select all

oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyAuth.exe"" -secret **yoursec** -ban " & oClient.IPAddress & " -bandays 30", 0, True
That makes the full script:

Code: Select all

Sub OnClientConnect(oClient)
   If DroneBLAuthHacker(oClient.IPAddress) Then
      Set oShell = CreateObject("WScript.Shell")
      oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyAuth.exe"" -secret **yoursec** -ban " & oClient.IPAddress & " -bandays 30", 0, True
     Result.Value = 1
      'Debug
      EventLog.Write("Message from: " & oClient.IPAddress & " Blocked as authentication hacker")
      Exit Sub
   End If   
End Sub

Function DroneBLAuthHacker(strIP)
   DroneBLAuthHacker = false
   Dim strLookupResult
   On Error Resume Next
   strLookupResult = NSLookup(strIP)
   On Error Goto 0
   'remove any that you don't want to match from http://dronebl.org/docs/howtouse
   Dim strRegEx : strRegEx = "127\.0\.0\.(3|5|6|7|8|9|10|11|12|13|14|15|16)"
   'Debug
   'EventLog.Write("DNS Result for: " & strIP & " is: " & strLookupResult)
   DroneBLAuthHacker = Lookup(strRegEx, strLookupResult)
End Function

Function NSLookup(strIP)
   Dim objshell, strCmd, objExec, strLine, strIPResult, strLookup
   Dim a : a = Split(strIP, ".")
   strLookup = a(3) & "." & a(2) & "." & a(1) & "." & a(0) & ".dnsbl.dronebl.org"
   'Debug
   'EventLog.Write("DNS Lookup for: " & strLookup)
   set objShell = CreateObject("Wscript.Shell")
   strCmd = "%comspec% /c nslookup " & strLookup
   Set objExec = objShell.Exec(strCmd)
   Do Until objExec.StdOut.AtEndOfStream
      strLine = objExec.StdOut.ReadLine()
      If (Left(strLine, 8) = "Address:") Then
         strIPResult = Trim(Mid(strLine, 9))
         NSLookup = strIPResult
      End If
   Loop
End Function

Function Lookup(strRegEx, strMatch)
   With CreateObject("VBScript.RegExp")
      .Global = False
      .Pattern = strRegEx
      .IgnoreCase = True
      Lookup = .Test(strMatch)
   End With
End Function

porcupine
Normal user
Normal user
Posts: 40
Joined: 2007-03-12 09:02

Re: Ban IP address on Hmail with Password proxy

Post by porcupine » 2017-12-20 12:36

I have changed the way that the nslookup is done, the Shell version produces some strange behavior on busier servers (possibly threading) and found that the WMI method works very well:

Code: Select all

Function NSLookup(strIP)
	Dim strLookup, oResponse
	Dim a : a = Split(strIP, ".")
	strLookup = a(3) & "." & a(2) & "." & a(1) & "." & a(0) & ".dnsbl.dronebl.org"
	Set oResponse = GetObject("winmgmts:").Get("Win32_PingStatus.Address='" & strLookup & "'")
	NSLookup = oResponse.ProtocolAddress
	Set oResponse = Nothing
End Function
this makes the full script:

Code: Select all

Sub OnClientConnect(oClient)
	If DroneBLAuthHacker(oClient.IPAddress) Then
		Set oShell = CreateObject("WScript.Shell")
		oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyAuth.exe"" -secret **yoursec** -ban " & oClient.IPAddress & " -bandays 30", 0, True
		Result.Value = 1
		'Debug
		EventLog.Write("Message from: " & oClient.IPAddress & " Blocked as authentication hacker")
		Exit Sub
	End If   
End Sub

Function DroneBLAuthHacker(strIP)
	DroneBLAuthHacker = false
	Dim strLookupResult
	On Error Resume Next
	strLookupResult = NSLookup(strIP)
	On Error Goto 0
	'remove any that you don't want to match from http://dronebl.org/docs/howtouse
	Dim strRegEx : strRegEx = "127\.0\.0\.(3|5|6|7|8|9|10|11|12|13|14|15|16)"
	'Debug
	'EventLog.Write("DNS Result for: " & strIP & " is: " & strLookupResult)
	DroneBLAuthHacker = Lookup(strRegEx, strLookupResult)
End Function

Function NSLookup(strIP)
	Dim strLookup, oResponse
	Dim a : a = Split(strIP, ".")
	strLookup = a(3) & "." & a(2) & "." & a(1) & "." & a(0) & ".dnsbl.dronebl.org"
	Set oResponse = GetObject("winmgmts:").Get("Win32_PingStatus.Address='" & strLookup & "'")
	NSLookup = oResponse.ProtocolAddress
	Set oResponse = Nothing
End Function

Function Lookup(strRegEx, strMatch)
	With CreateObject("VBScript.RegExp")
		.Global = False
		.Pattern = strRegEx
		.IgnoreCase = True
		Lookup = .Test(strMatch)
	End With
End Function

tunis
Senior user
Senior user
Posts: 351
Joined: 2015-01-05 20:22
Location: Sweden

Re: Ban IP address on Hmail with Password proxy

Post by tunis » 2017-12-20 13:01

porcupine wrote:I have changed the way that the nslookup is done, the Shell version produces some strange behavior on busier servers (possibly threading)
Your code do not handle multi addresses answer.

Here are my code:

Code: Select all

Function DNSResolver(strDNSLookup)
    Dim objshell, strCmd, objExec, strLine, strIP, boolNextLine
    boolNextLine = false
    set objShell = CreateObject("Wscript.Shell")
    strIP = strDNSLookup

    strCmd = "%comspec% /c nslookup " & strDNSLookup
    Set objExec = objShell.Exec(strCmd)
    Do Until objExec.StdOut.AtEndOfStream
        strLine = objExec.StdOut.ReadLine()
        If (Left(strLine, 8) = "Address:") Then
            strIP = Trim(Mid(strLine, 9))
        ElseIf (Left(strLine, 10) = "Addresses:") Then
            boolNextLine = true
        ElseIf (boolNextLine) Then 
            strIP = Trim(Mid(strLine, 2))
            boolNextLine = false
        End If
    Loop
    DNSResolver = strIP
End Function
HMS 5.6.8 B2534.28 on Windows Server 2019 Core VM.
HMS 5.6.9 B2641.67 on Windows Server 2016 Core VM.

porcupine
Normal user
Normal user
Posts: 40
Joined: 2007-03-12 09:02

Re: Ban IP address on Hmail with Password proxy

Post by porcupine » 2017-12-21 04:48

Using the code from ProxyAuth.exe, here is a way of adding to the ban list using native VBScript:
replace:

Code: Select all

Sub OnClientConnect(oClient)
	If DroneBLAuthHacker(oClient.IPAddress) Then
		Set oShell = CreateObject("WScript.Shell")
		oShell.Run """C:\Program Files (x86)\hMailServer\Bin\ProxyAuth.exe"" -secret **yoursec** -ban " & oClient.IPAddress & " -bandays 30", 0, True
		Result.Value = 1
		'Debug
		EventLog.Write("Message from: " & oClient.IPAddress & " Blocked as authentication hacker")
		Exit Sub
	End If   
End Sub
with

Code: Select all

Sub OnClientConnect(oClient)
	If DroneBLAuthHacker(oClient.IPAddress) Then
		Call AddToBanList (oClient.IPAddress, 30)
		Result.Value = 1
		'Debug
		EventLog.Write(oClient.IPAddress & "	Blocked as authentication hacker")
	End If   
End Sub
and add this Function to the EventHandlers.vbs

Code: Select all

Function AddToBanList(sIP, sDays)
	Dim hMailApp, myDomainAdd, sRuleName, bDebug, myDomainExists, bExists
	Set hMailApp = CreateObject("hMailServer.Application")
	Call hMailApp.Authenticate("Administrator", "password")
	sRuleName = "added from script - Auth Hacker BAN for " & sDays & " Day(s) - " & sIP
	Set myDomainExists = hMailApp.Settings.SecurityRanges
	bExists = False
	For i = 0 To myDomainExists.Count -1
		If myDomainExists.Item(i).Name = sRuleName Then
			bExists = True
			Set myDomainExists = Nothing
			Exit For
		End If
	Next
	If Not bExists Then
		Set myDomainAdd = hMailApp.Settings.SecurityRanges.Add()
		myDomainAdd.Name = sRuleName
		myDomainAdd.LowerIP = sIP
		myDomainAdd.UpperIP = sIP
		myDomainAdd.Priority = 20
		myDomainAdd.AllowSMTPConnections = False
		myDomainAdd.AllowIMAPConnections = False
		myDomainAdd.AllowPOP3Connections = False
		myDomainAdd.AllowDeliveryFromLocalToLocal = False
		myDomainAdd.AllowDeliveryFromLocalToRemote = False
		myDomainAdd.AllowDeliveryFromRemoteToLocal = False
		myDomainAdd.AllowDeliveryFromRemoteToRemote = False
		myDomainAdd.ExpiresTime = DateAdd("d",sDays,Now())
		myDomainAdd.Expires = True
		myDomainAdd.Save()
		Set myDomainAdd = Nothing
		Set hMailApp = Nothing
	End If
End Function

User avatar
SorenR
Senior user
Senior user
Posts: 6308
Joined: 2006-08-21 15:38
Location: Denmark

Re: Ban IP address on Hmail with Password proxy

Post by SorenR » 2017-12-21 17:40

viewtopic.php?f=2&t=30965&p=193666&hili ... an#p193666

This is the version I use now, first version without session locking was engineered in 2015 :wink:
SørenR.

Woke is Marxism advancing through Maoist cultural revolution.

Post Reply