Problem with AutoBan

Use this forum if you have problems with a hMailServer script, such as hMailServer WebAdmin or code in an event handler.
Post Reply
adrianmihai83
New user
New user
Posts: 26
Joined: 2018-01-26 17:19

Problem with AutoBan

Post by adrianmihai83 » 2020-02-05 20:11

I am facing the following problem when trying to add to IpRanges some ip's. I have the latest RvdH build.

On short, the part for autoban is:

Code: Select all

Private Const ADMIN = "Administrator"
Private Const PASSWORD = "my-password"
Private Const TEMPDIR  = "C:\Program Files (x86)\hMailServer\Temp"

'	Function LockFile - https://www.hmailserver.com/forum/viewtopic.php?p=212052
Function LockFile(strPath)
   Const Append = 8
   Const Unicode = -1
   Dim i
   On Error Resume Next
   With CreateObject("Scripting.FileSystemObject")
      For i = 0 To 30
         Err.Clear
         Set LockFile = .OpenTextFile(strPath, Append, True, Unicode)
         If (Not Err.Number = 70) Then Exit For
         Wait(1)
      Next
   End With
   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
   On Error Goto 0
End Function

'	Function AutoBan - https://www.hmailserver.com/forum/viewtopic.php?p=212052
Function AutoBan(sIPAddress, sReason, iDuration, sType) : AutoBan = False
   '
   '   sType can be one of the following;
   '   "yyyy" Year, "m" Month, "d" Day, "h" Hour, "n" Minute, "s" Second
   '
   Dim oApp : Set oApp = CreateObject("hMailServer.Application")
   Call oApp.Authenticate(ADMIN, PASSWORD)
   With LockFile(TEMPDIR & "\autoban.lck")
      On Error Resume Next
      Dim oSecurityRange : Set oSecurityRange = oApp.Settings.SecurityRanges.ItemByName("(" & sReason & ") " & sIPAddress)
      If Err.Number = 9 Then
         With oApp.Settings.SecurityRanges.Add
            .Name = "(" & sReason & ") " & sIPAddress
            .LowerIP = sIPAddress
            .UpperIP = sIPAddress
            .Priority = 20
            .Expires = True
            .ExpiresTime = DateAdd(sType, iDuration, Now())
            .Save
         End With
         AutoBan = True
      End If
      On Error Goto 0
      .Close
   End With
   Set oApp = Nothing
End Function
And I call the function as follows:

Code: Select all

Call AutoBan(oClient.IPAddress, oGeoip("countryCode") & " - GeoIP - " & oClient.IpAddress, 30, "h")
oGeoip is working because I do print some messages in the hmailserver_events.log in the script, no messages from the AutoBan function though even though I know that it is called after some of the messages that I print from the script before calling the function.

No Ip is added in IpRanges. Checked the temp folder in hMailServer and no autolock.lck file was created automaticaly, created it myself. Checked the permission and the SYSTEM account, the one that hMailServer is running under, has read/write permission on Temp folder.

This is really odd. I used to do autoban with the following function, without LockFile and everything was working:

Code: Select all

Sub AutoBan(IPAddress, NumberOfDays, ReasonForBan)
   'custom event
   'uses functions: 
   'uses globals: g_sAdminPassword

   EventLog.Write("Autoban IP Address started for IP = " & IPAddress & " For " & NumberofDays & " days for reason " & Reasonforban)
   Dim oApp
   Set oApp = CreateObject("hMailServer.Application")

'       Give this script permission to access all
'       hMailServer settings.
   Call oApp.Authenticate("Administrator", g_sAdminPassword)

   Dim i
   For i = 0 To oApp.Settings.SecurityRanges.Count -1
      If IPAddress = oApp.Settings.SecurityRanges.Item(i).LowerIP Then Exit sub
   Next
   EventLog.Write("Autoban IP range being set for IP Address " & IPAddress)

   oApp.Settings.SecurityRanges.Refresh
   With oApp.Settings.SecurityRanges.Add()
      .lowerip = ipaddress
      .upperip = ipaddress
      .priority = 20
      .allowdeliveryfromlocaltolocal = False
      .allowdeliveryfromlocaltoremote = False
      .allowdeliveryfromremotetolocal = False
      .allowdeliveryfromremotetoremote = False
      .allowimapconnections = False
      .allowsmtpconnections = False
      .allowpop3connections = False
      .expires = True
      .ExpiresTime = DateAdd("d", NumberOfDays, Now())
      .name = ReasonForBan & " - banned for " & NumberOfDays & " days - " & ipaddress
      On Error Resume Next
      .save
      If (Err.Number = 0) Then
         EventLog.Write("Autoban IP range saved for IP Address " & IPAddress)
      ElseIf (Err.Number <> 0) Then
         EventLog.Write("ERROR: EventHandlers.vbs : Function LockFile")
         EventLog.Write("Error       : " & Err.Number)
         EventLog.Write("Source      : " & Err.Source)
         EventLog.Write("Description : " & Err.Description)
         Err.Clear
      End If
      On Error Goto 0
   End With
End Sub
At 4-5 hours hMailServer just stops working without any errors, I had only Application and SMTP logging enabled. When in this state, I cannot send/receive any emails. Also webmail (Afterlogic) does not work, when trying to login I get the error: "Can't connect to IMAP4 server, check IMAP4 server settings" and in the log of Afterlogic I get: "[INFO] Error: Socket connection has been refused by remote host. InnerException message follows: No connection could be made because the target machine actively refused it 127.0.0.1:993"

Now I have activated in hMailServer logging for IMAP, TCP/IP and Debug but as I said, it is crashing once every 4-5 hours, now it is working...

Do you have any opinion on this?

adrianmihai83
New user
New user
Posts: 26
Joined: 2018-01-26 17:19

Re: Problem with AutoBan

Post by adrianmihai83 » 2020-02-05 21:27

Some more insight, there is a problem with Disconnect function. I disabled the disconnect function and the script went to AutoBan and added the ip to IpRanges.

My Disconnect function is:

Code: Select all

'	Function Disconnect - http://hmailserver.com/forum/viewtopic.php?f=7&t=34058
'	Download disconnect.exe from: https://d-fault.nl/files/Disconnect.zip
Function Disconnect(sIPAddress)
	EventLog.Write("Disconnect.exe " & sIPAddress & "")
	With CreateObject("WScript.Shell")
		.Run """C:\Program Files (x86)\hMailServer\Events\Disconnect.exe"" " & sIPAddress & "", 0, True
		'REM EventLog.Write("Disconnect.exe " & sIPAddress & "")
	End With
End Function
Disconnect.exe is present in the Events folder

I belive that has something to do with WScript

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

Re: Problem with AutoBan

Post by SorenR » 2020-02-05 22:14

You are missing this...

Code: Select all

    Function Wait(sec)
        With CreateObject("WScript.Shell")
            .Run "powershell Start-Sleep -Milliseconds " & Int(sec * 1000), 0, True
        End With
    End Function
SørenR.

“Those who don't know history are doomed to repeat it.”
― Edmund Burke

palinka
Senior user
Senior user
Posts: 1968
Joined: 2017-09-12 17:57

Re: Problem with AutoBan

Post by palinka » 2020-02-05 22:18

adrianmihai83 wrote:
2020-02-05 21:27
Some more insight, there is a problem with Disconnect function. I disabled the disconnect function and the script went to AutoBan and added the ip to IpRanges.

My Disconnect function is:

Code: Select all

'	Function Disconnect - http://hmailserver.com/forum/viewtopic.php?f=7&t=34058
'	Download disconnect.exe from: https://d-fault.nl/files/Disconnect.zip
Function Disconnect(sIPAddress)
	EventLog.Write("Disconnect.exe " & sIPAddress & "")
	With CreateObject("WScript.Shell")
		.Run """C:\Program Files (x86)\hMailServer\Events\Disconnect.exe"" " & sIPAddress & "", 0, True
		'REM EventLog.Write("Disconnect.exe " & sIPAddress & "")
	End With
End Function
Disconnect.exe is present in the Events folder

I belive that has something to do with WScript
Very strange. My own code is identical and I don't have any problems. REM all calls to disconnect and wait a day or two. See if you have any other issues.

Also, try the windows cure-all: rebooting.

palinka
Senior user
Senior user
Posts: 1968
Joined: 2017-09-12 17:57

Re: Problem with AutoBan

Post by palinka » 2020-02-05 22:24

SorenR wrote:
2020-02-05 22:14
You are missing this...

Code: Select all

    Function Wait(sec)
        With CreateObject("WScript.Shell")
            .Run "powershell Start-Sleep -Milliseconds " & Int(sec * 1000), 0, True
        End With
    End Function
Eagle eye!

adrianmihai83
New user
New user
Posts: 26
Joined: 2018-01-26 17:19

Re: Problem with AutoBan

Post by adrianmihai83 » 2020-02-05 23:26

I do have the wait function inside my script, just did not put it in the first place:

Code: Select all

'	Function Wait - https://www.hmailserver.com/forum/viewtopic.php?p=212052
Function Wait(sec)
   With CreateObject("WScript.Shell")
     .Run "timeout /T " & Int(sec), 0, True                                     ' Windows 7/2003/2008 or later
'     .Run "sleep -m " & Int(sec * 1000), 0, True                                ' Windows 2003 Resource Kit
'     .Run "powershell Start-Sleep -Milliseconds " & Int(sec * 1000), 0, True    ' Windows 10 Powershell
   End With
End Function
Also have Include and Lookup and other functions but they are not relevant to my problem, everything is working except calling the disconnect function:

Code: Select all

Call Disconnect(oClient.IPAddress)
And in the disconnect function I have placed the two EventLog.Write, all I can see in the log is "Entering disconnect..." and that's it, no "Exit disconnect."

Code: Select all

Function Disconnect(sIPAddress)
	EventLog.Write("Entered disconnect...")
	With CreateObject("WScript.Shell")
		.Run """C:\Program Files (x86)\hMailServer\Events\Disconnect.exe"" " & sIPAddress & "", 0, True
		'REM EventLog.Write("Disconnect.exe " & sIPAddress & "")
	End With
	EventLog.Write("Exit disconnect")
End Function
My system is 2008 server R2, and yes, on another similar system, same script is running without a problem...

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

Re: Problem with AutoBan

Post by SorenR » 2020-02-05 23:54

Try this, it's using 8DOT3 directory name to avoid the spaces.

From a CMD prompt do "dir /X" to list 8DOT3 names.

Code: Select all

Function Disconnect(sIPAddress)
	EventLog.Write("Entered disconnect...")
	With CreateObject("WScript.Shell")
		.Run "C:\PROGRA~2\hMailServer\Events\Disconnect.exe " & sIPAddress, 0, True
		'REM EventLog.Write("Disconnect.exe " & sIPAddress & "")
	End With
	EventLog.Write("Exit disconnect")
End Function
SørenR.

“Those who don't know history are doomed to repeat it.”
― Edmund Burke

adrianmihai83
New user
New user
Posts: 26
Joined: 2018-01-26 17:19

Re: Problem with AutoBan

Post by adrianmihai83 » 2020-02-06 11:33

Not working... :(

Thanks SorenR for the suggestion.

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

Re: Problem with AutoBan

Post by mattg » 2020-02-06 12:25

Make your 'my computer IP range' (127.0.0.1) have a priority of 120

That will stop your webmail being blocked by Autoban
Just 'cause I link to a page and say little else doesn't mean I am not being nice.
https://www.hmailserver.com/documentation

adrianmihai83
New user
New user
Posts: 26
Joined: 2018-01-26 17:19

Re: Problem with AutoBan

Post by adrianmihai83 » 2020-02-06 12:54

Thanks mattg, but that was not the problem, localhost has priority 80. The problem is with the disconnect function from the script, after calling it a couple of times and failing, hMailServer freezes.

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

Re: Problem with AutoBan

Post by SorenR » 2020-02-06 15:00

adrianmihai83 wrote:
2020-02-06 11:33
Not working... :(

Thanks SorenR for the suggestion.
Maybe change "True" to "False" so that the script does not wait for the shell command to finish. You have a problem with the "disconnect.exe"...
SørenR.

“Those who don't know history are doomed to repeat it.”
― Edmund Burke

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

Re: Problem with AutoBan

Post by mattg » 2020-02-06 17:00

adrianmihai83 wrote:
2020-02-06 12:54
Thanks mattg, but that was not the problem, localhost has priority 80.
The reason that I said 120, is that the autoban entries are set to 100

80 is too low
Just 'cause I link to a page and say little else doesn't mean I am not being nice.
https://www.hmailserver.com/documentation

adrianmihai83
New user
New user
Posts: 26
Joined: 2018-01-26 17:19

Re: Problem with AutoBan

Post by adrianmihai83 » 2020-02-06 22:11

mattg, autoban entries are set at priority 20, my localhost is never banned

SorenR, I tried the following thing just to be sure that problem comes from disconnect.

1. telnet from another computer to the mail server
2. in cmd, ran Disconnect.exe to see all connections
3. tried Disconnect.exe Ip_Address without any other parameters and everything worked, connection was closed
4. tried anything after Ip_Address like ", 0, True" or " 0, True" or some variations and I get this error results:

Code: Select all

Unhandled Exception: System.Exception: Invalid IP address
   at ConnectionManager.Disconnecter.IPStringToInt(String IP)
   at ConnectionManager.Disconnecter.CloseRemoteIP(String IP)
   at ConnectionManager.Starter.Main(String[] args)
or

Code: Select all

Unhandled Exception: System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.Byte.Parse(String s, NumberStyles style, NumberFormatInfo info)
   at ConnectionManager.Disconnecter.IPStringToInt(String IP)
   at ConnectionManager.Disconnecter.CloseRemoteIP(String IP)
   at ConnectionManager.Starter.Main(String[] args)
Is there any list of parameters for this program?

Thanks

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

Re: Problem with AutoBan

Post by SorenR » 2020-02-06 22:28

Code: Select all

Function Disconnect(sIPAddress)
    Dim strCommand, intWindowStyle, bWaitOnReturn

    strCommand = "C:\PROGRA~2\hMailServer\Events\Disconnect.exe " & sIPAddress
    intWindowStyle = 0
    bWaitOnReturn = True

    With CreateObject("WScript.Shell")
        .Run strCommand, intWindowStyle, bWaitOnReturn
        EventLog.Write(strCommand)
    End With
    EventLog.Write("Exit disconnect")
End Function

'  Syntax 
'        objShell.Run (strCommand, [intWindowStyle], [bWaitOnReturn]) 
'
'  Key
'     objShell    :  A WScript.Shell object
'
'     strCommand  :  The Command to be executed
'
'     intWindowStyle
'     (Optional)  :  Int value indicating the appearance of 
'                    the program's window. 
'                    Not all programs make use of this. 
'
'   bWaitOnReturn :  Wait for the command to complete before
'                    continuing execution of the wsh script.

https://ss64.com/vb/run.html
SørenR.

“Those who don't know history are doomed to repeat it.”
― Edmund Burke

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

Re: Problem with AutoBan

Post by mattg » 2020-02-07 02:03

adrianmihai83 wrote:
2020-02-06 22:11
mattg, autoban entries are set at priority 20, my localhost is never banned
As long as you are sure for your setup, because this has changed in some builds

https://github.com/hmailserver/hmailserver/issues/306

This is what makes me think autoban
adrianmihai83 wrote:
2020-02-05 20:11
...and in the log of Afterlogic I get: "[INFO] Error: Socket connection has been refused by remote host. InnerException message follows: No connection could be made because the target machine actively refused it 127.0.0.1:993"
Just 'cause I link to a page and say little else doesn't mean I am not being nice.
https://www.hmailserver.com/documentation

adrianmihai83
New user
New user
Posts: 26
Joined: 2018-01-26 17:19

Re: Problem with AutoBan

Post by adrianmihai83 » 2020-02-07 23:01

@SorenR, still the same, copy pasted your function, thought that maybe there is something spelled wrong in my function, but the same function is working on another server... same Windows 2008 R2, same version of hMailServer... This is odd

@mattg, as I said, I am on the latest RvdH build - 5.6.8, the problem with priority is in 5.7, my autoban priority is 20 and also, since disabling disconnect everything is working great. I cannot disconnect localhost because in the script I exclude the posibility that localhost or local lan to be autobanned.

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

Re: Problem with AutoBan

Post by RvdH » 2020-02-08 12:29

SorenR wrote: You have a problem with the "disconnect.exe"...
Windows smartscreen filter? Tried to see if it's blocked?

the source of disconnect is pasted here, it doesn't take any other parameters as IP1 [IP2 [IP3 [IPn]]]
CIDR to RegEx: d-fault.nl/CIDRtoRegEx
DNS Lookup: d-fault.nl/DNSTools
DNSBL Lookup: d-fault.nl/DNSBLLookup
GEOIP Lookup: d-fault.nl/GeoipLookup

adrianmihai83
New user
New user
Posts: 26
Joined: 2018-01-26 17:19

Re: Problem with AutoBan

Post by adrianmihai83 » 2020-02-09 15:32

Thanks @RvdH for the suggestion, this was the solution:
F2934C38-20CF-4894-A48D-3531AC741A91.jpeg

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

Re: Problem with AutoBan

Post by RvdH » 2020-02-09 17:11

👍
CIDR to RegEx: d-fault.nl/CIDRtoRegEx
DNS Lookup: d-fault.nl/DNSTools
DNSBL Lookup: d-fault.nl/DNSBLLookup
GEOIP Lookup: d-fault.nl/GeoipLookup

Post Reply