5.7 + IPv6 Autoban

Use this forum if you want to discuss a problem or ask a question related to a hMailServer beta release.
Post Reply
User avatar
mattg
Moderator
Moderator
Posts: 21025
Joined: 2007-06-14 05:12
Location: 'The Outback' Australia

5.7 + IPv6 Autoban

Post by mattg » 2020-08-01 02:22

I use this to manually autoban. It's called from many places

Code: Select all

Sub AutobanIP(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
	On Error Resume next
	For i = 0 To oApp.Settings.SecurityRanges.Count -1
		If IPAddress = oApp.Settings.SecurityRanges.Item(i).LowerIP Then Exit sub
	Next
	If (Err.Number <> 0) Then
			EventLog.Write("ERROR: EventHandlers.vbs : Function AutoBanIP")
			EventLog.Write("Error       : " & Err.Number)
			EventLog.Write("Source      : " & Err.Source)
			EventLog.Write("Description : " & Err.Description)
			Err.Clear
	End If
	On Error Goto 0
	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 = 100
		.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 AutoBanIP - Saving")
			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
I added an IPv6 mx record to my DNS this week

IPv6 entries get autobanned, and the bans seem to work, but they don't get displayed in the admin GUI which makes management of them problematic

IPv6 attempts that trigger the builtin hmailserver autoban DO SHOW in the admin GUI

I've also gotten some MySQL errors about 'unable to lock' that may or may not be related

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

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

Re: 5.7 + IPv6 Autoban

Post by SorenR » 2020-08-01 03:21

What's wrong with the "old" Autoban() function with record locking?
SørenR.

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

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

Re: 5.7 + IPv6 Autoban

Post by mattg » 2020-08-02 12:42

You mean this one that you wrote??

Is there that much difference except that I explicitly set no connections, and log?


Code: Select all

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
   '
   On Error Resume Next
   If (oApp.Settings.SecurityRanges.ItemByName("(" & sReason & ") " & sIPAddress) Is Nothing) 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
   oApp.Settings.SecurityRanges.Refresh
   On Error Goto 0
End Function
Just 'cause I link to a page and say little else doesn't mean I am not being nice.
https://www.hmailserver.com/documentation

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

Re: 5.7 + IPv6 Autoban

Post by SorenR » 2020-08-02 16:31

mattg wrote:
2020-08-02 12:42
You mean this one that you wrote??

Is there that much difference except that I explicitly set no connections, and log?


Code: Select all

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
   '
   On Error Resume Next
   If (oApp.Settings.SecurityRanges.ItemByName("(" & sReason & ") " & sIPAddress) Is Nothing) 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
   oApp.Settings.SecurityRanges.Refresh
   On Error Goto 0
End Function
It's faster (I see you took out the record locking - that could be related to your MySQL errors), it only deals with the minimum required data and there is no search loop - why search for a banned IP if it is banned and thus have no access ... No?

The only reason for searching for the IP address is if the email came in via a Backup-MX.
And by the way I have a function to extract the IP address from a relayed (Backup-MX) email by searching the "Received:" headers as I used one for 10+ years.
SørenR.

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

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

Re: 5.7 + IPv6 Autoban

Post by SorenR » 2020-08-02 16:37

My current version... It seems someone took out the check for err.number 9 ...

Code: Select all

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

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 (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(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, PASSWD)
    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
SørenR.

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

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

Re: 5.7 + IPv6 Autoban

Post by SorenR » 2020-08-02 16:54

Banned IP via BackupMX...

Code: Select all

'
'   COM authentication
'
Private Const ADMIN  = "Administrator"
Private Const PASSWD = "Super Secret Chainnumber"
'
'   Misc. settings
'
Private Const BACKUPMX   = "backup-mx.domain.tld"

Function setEnvelope(oClient, oMessage)
    Dim i, a, strTo, strOriginalTo, strIP, strRegEx, oMatch, oMatchCollection
    If Lookup("from " & BACKUPMX, oMessage.HeaderValue("Received")) Then
        For i = 0 To oMessage.Headers.Count-1
            If (oMessage.Headers(i).Name = "Received") Then
                If Lookup("by " & BACKUPMX & " with", oMessage.Headers(i).Value) Then
                    a = Split( oMessage.Headers(i).Value, " " )
                    oMessage.HeaderValue("X-Envelope-HELO") = Trim(a(1))
                    strRegEx = "(?:\[)((?:[0-9]{1,3}\.){3}[0-9]{1,3})(?:\])"
                    Set oMatchCollection = oLookup(strRegEx, oMessage.Headers(i).Value, False)
                    For Each oMatch In oMatchCollection
                        If oMatch.SubMatches.Count > 0 Then
                            oMessage.HeaderValue("X-Envelope-IP") = oMatch.SubMatches(0)
                        Else
                            oMessage.HeaderValue("X-Envelope-IP") = ""
                        End If
                    Next
                    Exit For
                End If
            End If
        Next
    Else
        oMessage.HeaderValue("X-Envelope-HELO") = Trim(oClient.HELO)
        oMessage.HeaderValue("X-Envelope-IP") = Trim(oClient.IPAddress)
    End If
    For i = 0 To oMessage.Recipients.Count-1
        If (i = 0) Then
            strTo = oMessage.Recipients(i).Address
            strOriginalTo = oMessage.Recipients(i).OriginalAddress
        Else
            strTo = strTo & ", " & oMessage.Recipients(i).Address
            strOriginalTo = strOriginalTo & ", " & oMessage.Recipients(i).OriginalAddress
        End If
    Next
    oMessage.HeaderValue("X-Envelope-To") = strTo
    oMessage.HeaderValue("X-Envelope-OriginalTo") = strOriginalTo
    oMessage.HeaderValue("X-Envelope-From") = oMessage.FromAddress
    oMessage.Save
    Rem Set oMatch = Nothing
    Rem Set oMatchCollection = Nothing
End Function

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

Function oLookup(strRegEx, strMatch, bGlobal)
    If strRegEx = "" Then strRegEx = StrReverse(strMatch)
    With CreateObject("VBScript.RegExp")
        .Pattern = strRegEx
        .Global = bGlobal
        .MultiLine = True
        .IgnoreCase = True
        Set oLookup = .Execute(strMatch)
    End With
End Function

Function INET_NTOA(strIP)
    '
    '   The inet_ntoa() function converts the specified Internet host address
    '   to a string in the Internet standard dot notation.
    '
    Dim a, i, N : N = 0
    a = Split(strIP, ".")
    For i = 0 To UBound(a)
        N = N + CLng( a(i) ) * ( 256 ^ (3 - i) )
    Next
    INET_NTOA = N
End Function

Function isBanned(oMessage) : isBanned = False
    Dim oApp : Set oApp = CreateObject("hMailServer.Application")
    Call oApp.Authenticate(ADMIN, PASSWD)
    strIP = INET_NTOA(oMessage.HeaderValue("X-Envelope-IP"))
    For a = 0 To oApp.Settings.SecurityRanges.Count-1
        If (oApp.Settings.SecurityRanges.Item(a).Priority = 20) Then
            strLowerIP = INET_NTOA(oApp.Settings.SecurityRanges.Item(a).LowerIP)
            strUpperIP = INET_NTOA(oApp.Settings.SecurityRanges.Item(a).UpperIP)
            If (strUpperIP >= strIP) And (strIP >= strLowerIP) Then
                isBanned = True
                Set oApp = Nothing
                Set oMatch = Nothing
                Set oMatchCollection = Nothing
                Exit Function
            End If
        End If
    Next
    Set oApp = Nothing
    Set oMatch = Nothing
    Set oMatchCollection = Nothing
End Function

Sub OnAcceptMessage(oClient, oMessage)

    Call setEnvelope(oClient, oMessage)
    If IsBanned(oMessage) Then
        ' May fire and brimstone rain down on you ;-)
        Result.Value = 1
	    Exit Sub
    End If

End Sub
SørenR.

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

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

Re: 5.7 + IPv6 Autoban

Post by SorenR » 2020-08-02 17:09

Hmm... Just remembered that my INET_NTOA function is IPV4 only .. :roll:
SørenR.

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

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

Re: 5.7 + IPv6 Autoban

Post by mattg » 2020-08-03 03:33

SorenR wrote:
2020-08-02 16:31
mattg wrote:
2020-08-02 12:42
You mean this one that you wrote??

Is there that much difference except that I explicitly set no connections, and log?
It's faster (I see you took out the record locking - that could be related to your MySQL errors), it only deals with the minimum required data and there is no search loop - why search for a banned IP if it is banned and thus have no access ... No?

The only reason for searching for the IP address is if the email came in via a Backup-MX.
And by the way I have a function to extract the IP address from a relayed (Backup-MX) email by searching the "Received:" headers as I used one for 10+ years.
I probably had mine before you wrote yours, and I may have changed mine to add some of the things that you have in yours, but I didn't get yours and then remove stuff from it.

Reason I search for existing bans is that otherwise a eror is generated.

I like your iprange is nothing idea though. I will use that.

I'm just trying to work out why IPv6 addresses don't show in my admin GUI - even though the bans seems to work
Just 'cause I link to a page and say little else doesn't mean I am not being nice.
https://www.hmailserver.com/documentation

Post Reply