Can i do an autban script based on this?

Use this forum if you have problems with a hMailServer script, such as hMailServer WebAdmin or code in an event handler.
Post Reply
mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Can i do an autban script based on this?

Post by mats » 2018-12-18 20:39

I see two repeating patterns on my mailserver of spammers trying to use on of my domains.
They try to send a Mail and when they get a PW request they quit the connection.

"SMTPD" 2316 1668 "2018-12-18 18:34:56.751" "190.236.239.220" "SENT: 530 SMTP authentication is required."
"DEBUG" 2316 "2018-12-18 18:34:56.751" "AWStats::LogDeliveryFailure"
"DEBUG" 2240 "2018-12-18 18:35:04.249" "The read operation failed. Bytes transferred: 0 Remote IP: 190.236.239.220, Session: 1668, Code: 10054, Message: An existing connection was forcibly closed by the remote host"

"SMTPD" 2316 1669 "2018-12-18 18:40:16.798" "185.171.235.253" "SENT: 530 SMTP authentication is required."
"DEBUG" 2316 "2018-12-18 18:40:16.798" "AWStats::LogDeliveryFailure"
"SMTPD" 2240 1669 "2018-12-18 18:40:20.232" "185.171.235.253" "RECEIVED: QUIT"

Since they never ever sends an incorrect password autoban won't block them.
Therefore I would like to know if there is a way to use a script to generate autoban rules for these patterns.
they are annoying me :D

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

Re: Can i do an autban script based on this?

Post by mattg » 2018-12-18 23:50

I call this every 10 minutes with a scheduled task

It does rely on me blocking port25 AUTH in the hmailserver.ini, and logging SMTP
You can change the log line checked to match what you need

Code: Select all

Option Explicit
Private const g_sAdminPassword = "TopSecretPassword"

Dim oApp
Set oApp = CreateObject("hMailServer.Application")

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

Dim sYear, iMonth, iDay, sMonth, sDay
Dim s, FSO, OBJfile, OBJfile1, OBJoutfile 
Dim FileIn, FileOut, Filebase
Dim a, b(5), c, d, i, j, e, f, g(5), t
Dim LastLogLine(15), NoIndexIssueFound, DateToUse

NoIndexIssueFound = true
'DateToUse = DateAdd("d",-1,Now())
DateToUse = Now()


sYear = Year(DateToUse)
iMonth = Month(DateToUse)
iDay = Day(DateToUse)

if  iMonth < 10 then
	sMonth = "0" + cstr(iMonth)
Else 'iMonth >= 10
	sMonth = cstr(iMonth)
End if

If iDay < 10 then
	sDay = "0" + cstr(iDay)
Else 'sDay >= 10
	sDay = cstr(iDay)
End if

Filebase = oapp.Settings.Directories.LogDirectory
FileOut = Filebase + "\504 Rejections" & "_" & sYear & "-" & sMonth & ".log"

Call CreateFiles(FileOut)
Set OBJoutfile = FSO.opentextfile(FileOut,8)

FileIn = filebase & "\hMailserver_" & cstr(sYear) & "-" & sMonth & "-" & sDay & ".log"
If fso.FileExists(Filein) Then
	set OBJfile = FSO.opentextfile(filein,1,0)
	While Not OBJfile.atendofstream
		s = OBJfile.ReadLine
		For i = 15 To 2 Step -1
			LastLogLine(i) = LastLogLine(i-1)
		Next
		LastLogLine(1) = s
		If InStr(s,"SENT: 504 Authentication not enabled.") > 0 Then
'			OBJoutfile.writeline s
				
			a = Split(s,Chr(9))
			i = 0

			For Each c In a
				b(i) = c
				i = i + 1
			Next 'c		
			set OBJfile1 = FSO.opentextfile(filein,1,0)
			While Not OBJfile1.atendofstream
				t = OBJfile1.ReadLine
				If InStr(t,b(2)) > 0 And InStr(t,"SMTPD") > 0 Then
					If InStr(t,"RECEIVED: HELO") > 0 Or InStr(t,"RECEIVED: EHLO") > 0 Then
						e = Split(t,Chr(9))
						j = 0
						For Each f In e
							g(j) = f
							j = j + 1
						Next 'f
'						OBJoutfile.WriteLine b(3) & Chr(9) & g(4) & Chr(9) & g(5) & Chr(9) & b(5)
						Call AutobanIP(Replace(g(4),Chr(34),""),7,"Port 25 AUTH - " & Replace(g(5),"RECEIVED: ",""))
						t = OBJfile1.ReadAll
					End If ' get HELO/EHLO	
				End If 'same messageID	
			Wend	
		End If
	Wend
	OBJfile.close
	set Objfile = Nothing
End If

Sub CreateFiles(Name)
	Set FSO = CreateObject("Scripting.FileSystemObject")
	If Not FSO.FileExists(Name) Then
		Dim txtFile
		Set txtFile = FSO.CreateTextFile(Name,true)
		txtFile.close
	End If
End Sub

Sub AutobanIP(IPAddress, NumberOfDays, ReasonForBan)
	'custom event
	'uses functions: 
	'uses globals: 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

	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
			OBJoutfile.WriteLine "Autoban IP range saved for IP Address " & IPAddress & " with Reason-" & reasonforban
		ElseIf (Err.Number <> 0) Then
			OBJoutfile.WriteLine"ERROR: EventHandlers.vbs : Function LockFile"
			OBJoutfile.WriteLine"Error       : " & Err.Number
			OBJoutfile.WriteLine"Source      : " & Err.Source
			OBJoutfile.WriteLine"Description : " & Err.Description
			Err.Clear
		End If
		On Error Goto 0
	End With
End 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

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

Re: Can i do an autban script based on this?

Post by SorenR » 2018-12-19 00:58

mats wrote:
2018-12-18 20:39
I see two repeating patterns on my mailserver of spammers trying to use on of my domains.
They try to send a Mail and when they get a PW request they quit the connection.

"SMTPD" 2316 1668 "2018-12-18 18:34:56.751" "190.236.239.220" "SENT: 530 SMTP authentication is required."
"DEBUG" 2316 "2018-12-18 18:34:56.751" "AWStats::LogDeliveryFailure"
"DEBUG" 2240 "2018-12-18 18:35:04.249" "The read operation failed. Bytes transferred: 0 Remote IP: 190.236.239.220, Session: 1668, Code: 10054, Message: An existing connection was forcibly closed by the remote host"

"SMTPD" 2316 1669 "2018-12-18 18:40:16.798" "185.171.235.253" "SENT: 530 SMTP authentication is required."
"DEBUG" 2316 "2018-12-18 18:40:16.798" "AWStats::LogDeliveryFailure"
"SMTPD" 2240 1669 "2018-12-18 18:40:20.232" "185.171.235.253" "RECEIVED: QUIT"

Since they never ever sends an incorrect password autoban won't block them.
Therefore I would like to know if there is a way to use a script to generate autoban rules for these patterns.
they are annoying me :D
Are the requests recurring from the same IP or are they "from all over"? How frequent are they if recurring?
SørenR.

The quantum rule of insecurity which states that the act of observing how vulnerable a host or service is changes the insecurity level of the service.

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

Re: Can i do an autban script based on this?

Post by SorenR » 2018-12-19 01:14

I just remembered that RvdH's custom build contain an experimental trigger OnClientLogon(oClient)...

Scenario:

Code: Select all

OnClientConnect:
- register IP Address in database
- if IP Address exists, increment counter (may skip if 12 hours old)
- if counter > 3 = AutoBan

OnClientLogon:
- If logon OK then delete IP Address from database (or set counter = 0)

OnAcceptMessage:
- delete IP Address from database (or set counter = 0)
My own IDS system is only doing 2/3 of the above... Maybe it's time to upgrade :oops:
SørenR.

The quantum rule of insecurity which states that the act of observing how vulnerable a host or service is changes the insecurity level of the service.

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

Re: Can i do an autban script based on this?

Post by jimimaseye » 2018-12-19 01:31

SorenR wrote:
2018-12-19 01:14

My own IDS system is only doing 2/3 of the above... Maybe it's time to upgrade :oops:
Go on, soren, you can do it. We'll be here for you, to hold your hand. It's time to let go.

Trust your feelings. Use the force....
HMS 5.6.6 B2383 on Win Server 2008 R2 Foundation, + 5.6.7-B2415 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

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2018-12-19 20:53

SorenR wrote:
2018-12-19 00:58
mats wrote:
2018-12-18 20:39
I see two repeating patterns on my mailserver of spammers trying to use on of my domains.
They try to send a Mail and when they get a PW request they quit the connection.

"SMTPD" 2316 1668 "2018-12-18 18:34:56.751" "190.236.239.220" "SENT: 530 SMTP authentication is required."
"DEBUG" 2316 "2018-12-18 18:34:56.751" "AWStats::LogDeliveryFailure"
"DEBUG" 2240 "2018-12-18 18:35:04.249" "The read operation failed. Bytes transferred: 0 Remote IP: 190.236.239.220, Session: 1668, Code: 10054, Message: An existing connection was forcibly closed by the remote host"

"SMTPD" 2316 1669 "2018-12-18 18:40:16.798" "185.171.235.253" "SENT: 530 SMTP authentication is required."
"DEBUG" 2316 "2018-12-18 18:40:16.798" "AWStats::LogDeliveryFailure"
"SMTPD" 2240 1669 "2018-12-18 18:40:20.232" "185.171.235.253" "RECEIVED: QUIT"

Since they never ever sends an incorrect password autoban won't block them.
Therefore I would like to know if there is a way to use a script to generate autoban rules for these patterns.
they are annoying me :D
Are the requests recurring from the same IP or are they "from all over"? How frequent are they if recurring?
They are from all over so a simple block of one or a few IP:s won't help.
the freq. varies too from one attempt and never try again to two-three attempts with 10 sec between.
Another pattern is one attempt every 12 hour.

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

Re: Can i do an autban script based on this?

Post by SorenR » 2018-12-19 22:40

mats wrote:
2018-12-19 20:53
SorenR wrote:
2018-12-19 00:58
mats wrote:
2018-12-18 20:39
I see two repeating patterns on my mailserver of spammers trying to use on of my domains.
They try to send a Mail and when they get a PW request they quit the connection.

"SMTPD" 2316 1668 "2018-12-18 18:34:56.751" "190.236.239.220" "SENT: 530 SMTP authentication is required."
"DEBUG" 2316 "2018-12-18 18:34:56.751" "AWStats::LogDeliveryFailure"
"DEBUG" 2240 "2018-12-18 18:35:04.249" "The read operation failed. Bytes transferred: 0 Remote IP: 190.236.239.220, Session: 1668, Code: 10054, Message: An existing connection was forcibly closed by the remote host"

"SMTPD" 2316 1669 "2018-12-18 18:40:16.798" "185.171.235.253" "SENT: 530 SMTP authentication is required."
"DEBUG" 2316 "2018-12-18 18:40:16.798" "AWStats::LogDeliveryFailure"
"SMTPD" 2240 1669 "2018-12-18 18:40:20.232" "185.171.235.253" "RECEIVED: QUIT"

Since they never ever sends an incorrect password autoban won't block them.
Therefore I would like to know if there is a way to use a script to generate autoban rules for these patterns.
they are annoying me :D
Are the requests recurring from the same IP or are they "from all over"? How frequent are they if recurring?
They are from all over so a simple block of one or a few IP:s won't help.
the freq. varies too from one attempt and never try again to two-three attempts with 10 sec between.
Another pattern is one attempt every 12 hour.
Only port 25 or other SMTP ports too?

My server have login disabled for port 25 and clients connect on port 465 (SSL).

hMailServer.ini

Code: Select all

[settings]

DisableAUTHList=25
; Setting DisableAUTHList allows you to specify a comma-separated list of SMTP ports which authentication should not be enabled for.
; This is useful when working with legacy systems with malfunctioning SMTP support.
SørenR.

The quantum rule of insecurity which states that the act of observing how vulnerable a host or service is changes the insecurity level of the service.

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2018-12-20 21:48

Seems to be 25 only.

I have 5.6.6 installed.
Does DisableAUTHList work with that?
Found an older thread that indicated that a special build was required

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

Re: Can i do an autban script based on this?

Post by SorenR » 2018-12-20 21:51

mats wrote:
2018-12-20 21:48
Seems to be 25 only.

I have 5.6.6 installed.
Does DisableAUTHList work with that?
Found an older thread that indicated that a special build was required
Was introduced in Version 5.6.3 - Build 2249 (2015-04-03)

https://www.hmailserver.com/changelog
SørenR.

The quantum rule of insecurity which states that the act of observing how vulnerable a host or service is changes the insecurity level of the service.

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2018-12-22 17:00

Thanks.
I have activated that and made my own variant of the AbuseIPDB script to blacklist all that i can.

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2018-12-22 21:02

My variant, added support for whitelisting IP ranges

Code: Select all

Sub OnClientConnect(oClient)
'Variables
	ClientIp				= oClient.IpAddress			'Connecting remote IP address
	WhiteList				= "127.0.0.1,172.16.1.1-172.16.255.255,1.2.3.4"		'Variable array for whitelisted IP addresses to exclude, localhost, maybe your servers IP address, your WebClient IP address whatever. Now supports ranges
	
	PercentageReject		= "5"
	PercentageWarn			= "2"
	PercentageInform	    = "0"
	AutobanDays				= "2"
	g_sAdminPassword		= "Password"
	
	
'Check if connecting client is whitelisted
	If CheckWhitelisted(WhiteList,ClientIp) Then
	  EventLog.Write "Whitelisted IP: " & ClientIp
	else
	  Percentage 				= "0"					'Default value
	  Percentage			= CheckAbuseIPDBConfidence(ClientIP)

'Process reported percentage		
		If Percentage >= PercentageReject then
			Result.Value 		= 1
			EventLog.Write ("AbuseIPDB: IP Address " & ClientIp & " rejected: Confidence of Abuse: " & Percentage & "%.")
			AutobanIP ClientIp,AutobanDays,"AbuseIPDB: IP Address " & ClientIp & " rejected: Confidence of Abuse: " & Percentage & "%."
		ElseIf Percentage >= PercentageWarn then
			Result.Value 		= 0
			EventLog.Write ("AbuseIPDB: IP Address " & ClientIp & " warning: Confidence of Abuse: " & Percentage & "%.")
		ElseIf Percentage >= PercentageInform Then 'changed logic so that Percentage 0 gets logged
			Result.Value 		= 0
			EventLog.Write ("AbuseIPDB: IP Address " & ClientIp & " notification: Confidence of Abuse: " & Percentage & "%.")
		End If
	End If
End Sub




  
function CheckWhitelisted(List,ClientIp)
  
  CheckWhitelisted=false
  arrIpranges=Split(list,",")
  For Each Iprange In arrIpranges
    If InStr(Iprange,"-") Then
      If ClientIp>=Left(Iprange,InStr(Iprange,"-")) And ClientIP<=mid(Iprange,InStr(Iprange,"-")+1) then
		CheckWhitelisted=true
	  End if	  
    Else
      If ClientIp=Iprange Then
        CheckWhitelisted=true
	  End if
	End if
  next
End Function

Public Function CheckAbuseIPDBConfidence(IPAddress)
	CheckAbuseIPDBConfidence		= "0"
	Set objXMLHTTP				= CreateObject("msxml2.xmlhttp.6.0")
		objXMLHTTP.Open "GET", "https://www.abuseipdb.com/check/" & IPAddress, False
		objXMLHTTP.Send ""
		ResponseText			= objXMLHTTP.responseText
		ResponseArray			= Split(ResponseText, VbLf)
		For Each ResponseLine in ResponseArray
			If Left(ResponseLine, 6) = "<span>" And Right(ResponseLine, 8) = "%</span>" Then
				CheckAbuseIPDBConfidence 	= Mid(ResponseLine,7, Len(ResponseLine)-14)
				Exit For
			End If
		Next	
	Set objXMLHTTP 				= Nothing
End Function	

Sub AutobanIP(IPAddress, NumberOfDays, ReasonForBan)
	'custom event
	'uses functions: 
	'uses globals: g_sAdminPassword
	Dim oApp
	Set oApp = CreateObject("hMailServer.Application")
	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

	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 & " with Reason-" & reasonforban
		ElseIf (Err.Number <> 0) Then
			
			EventLog.Write"Error       : " & Err.Number
			EventLog.Write"ERROR: EventHandlers.vbs : Function LockFile""Source      : " & Err.Source
			EventLog.Write"ERROR: EventHandlers.vbs : Function LockFile""Description : " & Err.Description
			Err.Clear
		End If
		On Error Goto 0
	End With
End Sub

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2018-12-22 22:32

updated. Missed one parameter

Code: Select all

Sub OnClientConnect(oClient)
'Variables
	ClientIp				= oClient.IpAddress			'Connecting remote IP address
	WhiteList				= "127.0.0.1,172.16.1.1-172.16.255.255,1.2.3.4"		'Variable array for whitelisted IP addresses to exclude, localhost, maybe your servers IP address, your WebClient IP address whatever. Now supports ranges
	
	PercentageReject		= "5"
	PercentageWarn			= "2"
	PercentageInform	    = "0"
	AutobanDays				= "2"
	AdminPassword			= "Password"
	
	
'Check if connecting client is whitelisted
	If CheckWhitelisted(WhiteList,ClientIp) Then
	  EventLog.Write "Whitelisted IP: " & ClientIp
	else
	  Percentage 				= "0"					'Default value
	  Percentage			= CheckAbuseIPDBConfidence(ClientIP)

'Process reported percentage		
		If Percentage >= PercentageReject then
			Result.Value 		= 1
			EventLog.Write ("AbuseIPDB: IP Address " & ClientIp & " rejected: Confidence of Abuse: " & Percentage & "%.")
			AutobanIP ClientIp,AutobanDays,"AbuseIPDB: IP Address " & ClientIp & " rejected: Confidence of Abuse: " & Percentage & "%.",AdminPassword
		ElseIf Percentage >= PercentageWarn then
			Result.Value 		= 0
			EventLog.Write ("AbuseIPDB: IP Address " & ClientIp & " warning: Confidence of Abuse: " & Percentage & "%.")
		ElseIf Percentage >= PercentageInform Then 'changed logic so that Percentage 0 gets logged
			Result.Value 		= 0
			EventLog.Write ("AbuseIPDB: IP Address " & ClientIp & " notification: Confidence of Abuse: " & Percentage & "%.")
		End If
	End If
End Sub




  
function CheckWhitelisted(List,ClientIp)
  
  CheckWhitelisted=false
  arrIpranges=Split(list,",")
  For Each Iprange In arrIpranges
    If InStr(Iprange,"-") Then
      If ClientIp>=Left(Iprange,InStr(Iprange,"-")) And ClientIP<=mid(Iprange,InStr(Iprange,"-")+1) then
		CheckWhitelisted=true
	  End if	  
    Else
      If ClientIp=Iprange Then
        CheckWhitelisted=true
	  End if
	End if
  next
End Function

Public Function CheckAbuseIPDBConfidence(IPAddress)
	CheckAbuseIPDBConfidence		= "0"
	Set objXMLHTTP				= CreateObject("msxml2.xmlhttp.6.0")
		objXMLHTTP.Open "GET", "https://www.abuseipdb.com/check/" & IPAddress, False
		objXMLHTTP.Send ""
		ResponseText			= objXMLHTTP.responseText
		ResponseArray			= Split(ResponseText, VbLf)
		For Each ResponseLine in ResponseArray
			If Left(ResponseLine, 6) = "<span>" And Right(ResponseLine, 8) = "%</span>" Then
				CheckAbuseIPDBConfidence 	= Mid(ResponseLine,7, Len(ResponseLine)-14)
				Exit For
			End If
		Next	
	Set objXMLHTTP 				= Nothing
End Function	

Sub AutobanIP(IPAddress, NumberOfDays, ReasonForBan,AdminPassword)
	
	Dim oApp
	Set oApp = CreateObject("hMailServer.Application")
	Call oApp.Authenticate("Administrator",AdminPassword)

	Dim i
	For i = 0 To oApp.Settings.SecurityRanges.Count -1
		If IPAddress = oApp.Settings.SecurityRanges.Item(i).LowerIP Then Exit sub
	Next

	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 & " with Reason-" & reasonforban
		ElseIf (Err.Number <> 0) Then
			
			EventLog.Write"Error       : " & Err.Number
			EventLog.Write"ERROR: EventHandlers.vbs : Function LockFile""Source      : " & Err.Source
			EventLog.Write"ERROR: EventHandlers.vbs : Function LockFile""Description : " & Err.Description
			Err.Clear
		End If
		On Error Goto 0
	End With
End Sub

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

Re: Can i do an autban script based on this?

Post by SorenR » 2018-12-23 01:21

Learned something new today...

I would never have believed one could compare IP addresses that way so had to try it :mrgreen:
I do somewhat the same in my EventHandler and I convert IPAddresses to LongInteger before comparing ...

Oh well... Had a play with the code...

Code: Select all

' ClientIP = "127.0.0.1"
ClientIP = "172.16.128.128"
' ClientIP = "1.2.3.4"
List     = "127.0.0.1,172.16.1.1-172.16.255.255,1.2.3.4"

IPRanges=Split(list,",")
For Each IPRange In IPRanges
   If InStr(IPRange,"-") Then
      p_strIP = Split(IPRange, "-")
      If ClientIP >= p_strIP(0) And ClientIP <= p_strIP(1) Then _
                               WScript.Echo "Yes - range"
   Else
      If ClientIP=IPRange Then WScript.Echo "Yes - single"
   End If
Next
SørenR.

The quantum rule of insecurity which states that the act of observing how vulnerable a host or service is changes the insecurity level of the service.

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

Re: Can i do an autban script based on this?

Post by insomniac2k2 » 2018-12-24 02:12

Just a heads up. I check AbuseIPDB as well, and it has either temp banned my IP address for hammering or has been down for reasonably long periods of time. In either case, it you have a busy server like I do, the byproduct is that mail will slow to a trickle and get backed up. You basically end up with a bunch of locked threads waiting to time out.

No biggy, just something for you to keep an eye on to see if it will affect you.
mats wrote:
2018-12-22 22:32
updated. Missed one parameter

Code: Select all

Sub OnClientConnect(oClient)
'Variables
	ClientIp				= oClient.IpAddress			'Connecting remote IP address
	WhiteList				= "127.0.0.1,172.16.1.1-172.16.255.255,1.2.3.4"		'Variable array for whitelisted IP addresses to exclude, localhost, maybe your servers IP address, your WebClient IP address whatever. Now supports ranges
	
	PercentageReject		= "5"
	PercentageWarn			= "2"
	PercentageInform	    = "0"
	AutobanDays				= "2"
	AdminPassword			= "Password"
	
	
'Check if connecting client is whitelisted
	If CheckWhitelisted(WhiteList,ClientIp) Then
	  EventLog.Write "Whitelisted IP: " & ClientIp
	else
	  Percentage 				= "0"					'Default value
	  Percentage			= CheckAbuseIPDBConfidence(ClientIP)

'Process reported percentage		
		If Percentage >= PercentageReject then
			Result.Value 		= 1
			EventLog.Write ("AbuseIPDB: IP Address " & ClientIp & " rejected: Confidence of Abuse: " & Percentage & "%.")
			AutobanIP ClientIp,AutobanDays,"AbuseIPDB: IP Address " & ClientIp & " rejected: Confidence of Abuse: " & Percentage & "%.",AdminPassword
		ElseIf Percentage >= PercentageWarn then
			Result.Value 		= 0
			EventLog.Write ("AbuseIPDB: IP Address " & ClientIp & " warning: Confidence of Abuse: " & Percentage & "%.")
		ElseIf Percentage >= PercentageInform Then 'changed logic so that Percentage 0 gets logged
			Result.Value 		= 0
			EventLog.Write ("AbuseIPDB: IP Address " & ClientIp & " notification: Confidence of Abuse: " & Percentage & "%.")
		End If
	End If
End Sub




  
function CheckWhitelisted(List,ClientIp)
  
  CheckWhitelisted=false
  arrIpranges=Split(list,",")
  For Each Iprange In arrIpranges
    If InStr(Iprange,"-") Then
      If ClientIp>=Left(Iprange,InStr(Iprange,"-")) And ClientIP<=mid(Iprange,InStr(Iprange,"-")+1) then
		CheckWhitelisted=true
	  End if	  
    Else
      If ClientIp=Iprange Then
        CheckWhitelisted=true
	  End if
	End if
  next
End Function

Public Function CheckAbuseIPDBConfidence(IPAddress)
	CheckAbuseIPDBConfidence		= "0"
	Set objXMLHTTP				= CreateObject("msxml2.xmlhttp.6.0")
		objXMLHTTP.Open "GET", "https://www.abuseipdb.com/check/" & IPAddress, False
		objXMLHTTP.Send ""
		ResponseText			= objXMLHTTP.responseText
		ResponseArray			= Split(ResponseText, VbLf)
		For Each ResponseLine in ResponseArray
			If Left(ResponseLine, 6) = "<span>" And Right(ResponseLine, 8) = "%</span>" Then
				CheckAbuseIPDBConfidence 	= Mid(ResponseLine,7, Len(ResponseLine)-14)
				Exit For
			End If
		Next	
	Set objXMLHTTP 				= Nothing
End Function	

Sub AutobanIP(IPAddress, NumberOfDays, ReasonForBan,AdminPassword)
	
	Dim oApp
	Set oApp = CreateObject("hMailServer.Application")
	Call oApp.Authenticate("Administrator",AdminPassword)

	Dim i
	For i = 0 To oApp.Settings.SecurityRanges.Count -1
		If IPAddress = oApp.Settings.SecurityRanges.Item(i).LowerIP Then Exit sub
	Next

	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 & " with Reason-" & reasonforban
		ElseIf (Err.Number <> 0) Then
			
			EventLog.Write"Error       : " & Err.Number
			EventLog.Write"ERROR: EventHandlers.vbs : Function LockFile""Source      : " & Err.Source
			EventLog.Write"ERROR: EventHandlers.vbs : Function LockFile""Description : " & Err.Description
			Err.Clear
		End If
		On Error Goto 0
	End With
End Sub

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2018-12-25 16:19

My server is rather low loaded so it should be rather safe i hope :)

However I found a "feature" aka BUG

the current code seems to be comparing the percentage values as strings meaning that 20 is smaller than 5.
quick fix

PercentageReject = cint("5")
PercentageWarn = cint("2")
PercentageInform = cint("0")

and
Percentage = cint(CheckAbuseIPDBConfidence(ClientIP))

The next thing is to see what can be done about that ugly unsafe password handeling

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2018-12-26 14:46

One way of solving the password problem is to store the PW in an external file.
That file should then be encrypted with EFS (you must be logged on as the account that is running the Hmailserver service to do this).

Cons:
An external file reference.
You need a windows version with EFS

Pro:s
Crypto key stored in the user profile for that user. IE you have to have access to that account to get the PW.
By using a dedicated PW file you can still change the script with your regular admin user.

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

Re: Can i do an autban script based on this?

Post by SorenR » 2018-12-26 16:04

May I suggest something?

1: Buy a good FIREWALL.
2: LOCK the DOOR to the computer room.
SørenR.

The quantum rule of insecurity which states that the act of observing how vulnerable a host or service is changes the insecurity level of the service.

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2018-12-26 18:37

Done since long.
Next step moving Hmailserver away from running as system

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

Re: Can i do an autban script based on this?

Post by SorenR » 2018-12-26 19:18

Running a virtual hMailServer on a cloud based intrusion detection system that, if compromised, will spawn a new server on a new IP address, update DNS et al. and start a "cat after mouse" chase across the Internet :mrgreen:

That could be really cool 8)

Problem is though, safe systems are not user friendly ... :roll:
SørenR.

The quantum rule of insecurity which states that the act of observing how vulnerable a host or service is changes the insecurity level of the service.

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2018-12-26 20:29

The trick is to find a reasonably safe and user friendly solution :)

I have now changed the service account for Hmailserver from System to a dedicated account (network service would work too).
It has read on the Hmailserver folder structure and modify on the data substructure as described in viewtopic.php?t=23311#p141389.

Also changed the Mysql account from root to a dedicated account.
I did find an issue during that reconfig .
The database reconfigure wizzard seems to take it for granted that the Hmailserver service has write permissions on Hmailserver.ini.
It doesn't report back failed write attempts (in my case it failed to write the new DB user and PW).


The quick fix is to run Hmailserver-service as system during the change.
The proper fix is to change the permissions of the INI so that the serviceaccount has modify on it.

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

Re: Can i do an autban script based on this?

Post by insomniac2k2 » 2018-12-27 02:41

You mean like this:
viewtopic.php?f=20&t=31874

I started using this as a banning solution and ended up adapting it to use it as an auth function for multiple things interop based. The source is there, so you can adapt it to whatever you need.
mats wrote:
2018-12-26 14:46
One way of solving the password problem is to store the PW in an external file.
That file should then be encrypted with EFS (you must be logged on as the account that is running the Hmailserver service to do this).

Cons:
An external file reference.
You need a windows version with EFS

Pro:s
Crypto key stored in the user profile for that user. IE you have to have access to that account to get the PW.
By using a dedicated PW file you can still change the script with your regular admin user.

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2018-12-27 12:31

insomniac2k2 wrote:
2018-12-27 02:41
You mean like this:
viewtopic.php?f=20&t=31874

I started using this as a banning solution and ended up adapting it to use it as an auth function for multiple things interop based. The source is there, so you can adapt it to whatever you need.
mats wrote:
2018-12-26 14:46
One way of solving the password problem is to store the PW in an external file.
That file should then be encrypted with EFS (you must be logged on as the account that is running the Hmailserver service to do this).

Cons:
An external file reference.
You need a windows version with EFS

Pro:s
Crypto key stored in the user profile for that user. IE you have to have access to that account to get the PW.
By using a dedicated PW file you can still change the script with your regular admin user.
Well, sort of ;)
there are two major differences
1. I do want to limit the access to a user and that user only.
2. I want the solution to be available for all uses.

But your code actually gave me an idea how it might be done.

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

Re: Can i do an autban script based on this?

Post by insomniac2k2 » 2018-12-27 15:46

Oh ok. I misunderstood what you were trying to accomplish. Glad it was of some help though.
mats wrote:
2018-12-27 12:31
insomniac2k2 wrote:
2018-12-27 02:41
You mean like this:
viewtopic.php?f=20&t=31874

I started using this as a banning solution and ended up adapting it to use it as an auth function for multiple things interop based. The source is there, so you can adapt it to whatever you need.
mats wrote:
2018-12-26 14:46
One way of solving the password problem is to store the PW in an external file.
That file should then be encrypted with EFS (you must be logged on as the account that is running the Hmailserver service to do this).

Cons:
An external file reference.
You need a windows version with EFS

Pro:s
Crypto key stored in the user profile for that user. IE you have to have access to that account to get the PW.
By using a dedicated PW file you can still change the script with your regular admin user.
Well, sort of ;)
there are two major differences
1. I do want to limit the access to a user and that user only.
2. I want the solution to be available for all uses.

But your code actually gave me an idea how it might be done.

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2018-12-28 21:18

It was indeed.

After thinking things through a few times I probably will have to do more in compiled code than I really would like to.
Simply to prevent someone from doing msgbox "here is the secret password" and that's the part where I'm going to bluntly steal some code ;)

The other part about storing the password in a protected way - I have found the DPAPI. It looks very promising. The user that encrypted the data can read it but noone else.
If someone tampers the whole thing by resetting the password? Nope. If you reset the password - you destroy the key

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2018-12-29 17:19

Did a little democode in VB.net to test the API.
Found out that I don't even have to call the API. There is a Dotnet class for it - Protecteddata.
That made it really simple, just three lines of code to encrypt the data and store it to file

Code: Select all

Sub encode(indata As String)

        Dim clearTextbytes() As Byte = System.Text.Encoding.Unicode.GetBytes(indata)
        Dim Protectedbytes As Byte() = ProtectedData.Protect(clearTextbytes, Nothing, DataProtectionScope.CurrentUser)
        System.IO.File.WriteAllBytes("c:\temp\test.txt", Protectedbytes)

    End Sub
It is as easy to decode too

Code: Select all

    Sub decode(ByRef outdata As String)
        Dim Protectedbytes As Byte()
        Protectedbytes = System.IO.File.ReadAllBytes("c:\temp\test.txt")
        Dim clearTextbytes As Byte() = ProtectedData.Unprotect(Protectedbytes, Nothing, DataProtectionScope.CurrentUser)
        outdata = System.Text.Encoding.Unicode.GetString(clearTextbytes)
    End Sub

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2018-12-30 22:23

Making more progress.

Been playing around with com objects and passing and returning an object as a parameter to a com object.
The nice thing is that we can call objects byref IE we can modify the object externally and continue to use it after that.
That makes it possible to do an external auth function and we can return the authenticated object to the script

in my DLL i have

Code: Select all

Public Sub secureauth(ByRef HmailserverObject As Object, strusername As String)
        Dim strpassword = ""
        decode(strpassword)
        HmailserverObject.authenticate(strusername, strpassword)
    End Sub

Private Sub decode(ByRef outdata As String)
        Dim Protectedbytes As Byte()
        Protectedbytes = System.IO.File.ReadAllBytes(Environment.GetEnvironmentVariable("appdata") & "\Hmailextender.txt")
        Dim clearTextbytes As Byte() = ProtectedData.Unprotect(Protectedbytes, Nothing, DataProtectionScope.CurrentUser)
        outdata = System.Text.Encoding.Unicode.GetString(clearTextbytes)
    End Sub
In my script i got

Code: Select all

Set objApp = CreateObject("hMailServer.Application")
   set MySecurity = CreateObject("HmailExtender.security")
   MySecurity.secureauth objApp, "Username"
   
The result is an objapp object that is authenticated :)

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

Re: Can i do an autban script based on this?

Post by insomniac2k2 » 2019-01-03 18:18

Quite cool. I'm watching this with much curiosity :)
mats wrote:
2018-12-30 22:23
Making more progress.

Been playing around with com objects and passing and returning an object as a parameter to a com object.
The nice thing is that we can call objects byref IE we can modify the object externally and continue to use it after that.
That makes it possible to do an external auth function and we can return the authenticated object to the script

in my DLL i have

Code: Select all

Public Sub secureauth(ByRef HmailserverObject As Object, strusername As String)
        Dim strpassword = ""
        decode(strpassword)
        HmailserverObject.authenticate(strusername, strpassword)
    End Sub

Private Sub decode(ByRef outdata As String)
        Dim Protectedbytes As Byte()
        Protectedbytes = System.IO.File.ReadAllBytes(Environment.GetEnvironmentVariable("appdata") & "\Hmailextender.txt")
        Dim clearTextbytes As Byte() = ProtectedData.Unprotect(Protectedbytes, Nothing, DataProtectionScope.CurrentUser)
        outdata = System.Text.Encoding.Unicode.GetString(clearTextbytes)
    End Sub
In my script i got

Code: Select all

Set objApp = CreateObject("hMailServer.Application")
   set MySecurity = CreateObject("HmailExtender.security")
   MySecurity.secureauth objApp, "Username"
   
The result is an objapp object that is authenticated :)

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

Re: Can i do an autban script based on this?

Post by RvdH » 2019-01-04 12:33

mats wrote:
2018-12-28 21:18
Simply to prevent someone from doing msgbox "here is the secret password" and that's the part where I'm going to bluntly steal some code ;)
And how exactly does your solution prevent the msgbox "here is the secret password" example you referred to yourself earlier? (Not saying MsgBox "here is the secret password" is possible in the first place!)

Fake security, with only extra overhead as result if you ask me
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

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2019-01-04 22:22

RvdH wrote:
2019-01-04 12:33
mats wrote:
2018-12-28 21:18
Simply to prevent someone from doing msgbox "here is the secret password" and that's the part where I'm going to bluntly steal some code ;)
And how exactly does your solution prevent the msgbox "here is the secret password" example you referred to yourself earlier? (Not saying MsgBox "here is the secret password" is possible in the first place!)
it's simple to do a msgbox of the password when it is stored in cleartext in the script, I don't believe we have to discuss that further

To prevent it takes a few steps.
first we need a secure way to store the password.
My way of doing that is to run Hmailserver with a serviceaccount instead of system. That gives access to the built in data protection API.
With that API the "secret" in reality becomes the password for the serviceaccount. Hence no public secret and only processes running under that user can access the data encrypted by the DPAPI.
But since I'm an admin - I can just reset the password for that account? Nope - doing that destroys the "secret" and you can't decrypt the data anyway.

The next step is to prevent even other processes running under the same user account access to the data.
For that I have three different methods of salting the password. One based on the userprofile, Another one is a fixed value (would love to have it generated at compile time) and the last one is a custom string (not secure if used from a script - can be ok from compiled code).

The last step is the one that really counts.
Doing the Hmailserapplication.authenticate step inside the DLL instead of doing it in the script.
Hence there is no way (I hope) to get the DLL to export the password.

Therefore there should be nothing you can pass to that msgbox.


RvdH wrote:
2019-01-04 12:33
Fake security, with only extra overhead as result if you ask me
Well, I dont ;)
Did you not ask for this kind of function yourself earlier (viewtopic.php?f=20&t=31874#p199560)?
With my solution you can do that

The downside so far is that you can run all methods once you are authenticated.
There is only two ways of preventing that. The first one is to add the functions you need to the DLL and plug them to the auth method.
The second method is the true fix - recoding the permission system of Hmailserver so that it can do ACL:s on each and every method of the API - I do not have the skills for that

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2019-01-04 23:06

There are currently three public functions
GenerateSalt (string)
It will accept an empty string EQ use no salt
The string User will make it use a Salt based on the user sid
The string Static will make it use a static salt encoded in the DLL
Any other string will be used as the salt

encode(password, filename,dataprotectionscope)
The function will encode the password using the DPAPI (must be running as a user, system or network service will not work)
Filename is optional. If none is given it will use %appdata%\HmailExtender.Ini
dataprotectionscope is optional. if none is given it will encrypt for currentuser

SecureAuth (HmailServerObject, StrUserName, FileName, dataprotectionscope)
The function will do the Hmailserver.authentication API call
HmailserverObject is the mailserverobject that should be authenticated
Strusername is the username for the adminuser you want to authenticate
Filename is optional. If none is given it will use %appdata%\HmailExtender.Ini
dataprotectionscope is optional. if none is given it will encrypt for currentuser

There is no DLL in the attached code.
You will have to compile it yourself.
Thereafter you must place it in a good location and register it with regasm.exe /codebase. Regasm can be found under %Windows%\Microsoft.NET\Framework or framework64 depending on your server

You will need to generate the password and store it first.

Code: Select all

strpassword=inputbox("enter password")
set HmailEX=CreateObject("HmailExtender.security"
GenerateSalt ("User")
HmailEX.encode strpassword


With that done you should be able to do

Code: Select all

set HmailEX=CreateObject("HmailExtender.security"
GenerateSalt ("User")
HmailEX.secureauth obApp, "username"
Attachments
Hmailextender.zip
(10.36 KiB) Downloaded 29 times

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

Re: Can i do an autban script based on this?

Post by SorenR » 2019-01-04 23:21

Why not use vbsedit to convert vbs to an exe file and call it from the script in a CMD prompt with parameters ??

I've just converted the "Handler.vbs" that does all my banning of IDS, PORTBLOCK and stuff externally of hMailServer. The script and my handler share the MySQL database for information exchange.

If I change it back to SQLite I can use the database without a password... There is NO password data in the dataexchange...
SørenR.

The quantum rule of insecurity which states that the act of observing how vulnerable a host or service is changes the insecurity level of the service.

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

Re: Can i do an autban script based on this?

Post by mattg » 2019-01-05 00:07

SorenR wrote:
2019-01-04 23:21
Why not use vbsedit to convert vbs to an exe file ...
Now that is an interesting thought
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
RvdH
Senior user
Senior user
Posts: 772
Joined: 2008-06-27 14:42
Location: Netherlands

Re: Can i do an autban script based on this?

Post by RvdH » 2019-01-05 03:49

mats wrote:
2018-12-28 21:18
it's simple to do a msgbox of the password when it is stored in cleartext in the script, I don't believe we have to discuss that further
Please show me how, i could not do it....and i doubt you can do it either,
Sure, if you stored the password in a CONST you could, but then again simply do not do that!

The point in general is, if an unauthorized person has physical access to the server it is probably a (skilled) hacker, who has no problems defeating your additional protection as well, any debugger will have discovered your encrypted password just as easy by putting a breakpoint on the Application object Authenticate(string Username, string Password) which is still submitted through to your COM object and then is passed to to original object in plain text. I know, i earlier have said i liked the idea insomniac2k2 suggested, but in reality i have never used it


But hey, i like to be surprised....please prove me otherwise
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

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2019-01-05 13:51

RvdH wrote:
2019-01-05 03:49
mats wrote:
2018-12-28 21:18
it's simple to do a msgbox of the password when it is stored in cleartext in the script, I don't believe we have to discuss that further
Please show me how, i could not do it....and i doubt you can do it either,
Sure, if you stored the password in a CONST you could, but then again simply do not do that!

The point in general is, if an unauthorized person has physical access to the server it is probably a (skilled) hacker, who has no problems defeating your additional protection as well, any debugger will have discovered your encrypted password just as easy by putting a breakpoint on the Application object Authenticate(string Username, string Password) which is still submitted through to your COM object and then is passed to to original object in plain text. I know, i earlier have said i liked the idea insomniac2k2 suggested, but in reality i have never used it


But hey, i like to be surprised....please prove me otherwise

Code: Select all

Const sAdminPassword = "<ADMINISTRATORPASSWORD>"

Dim oApp
Set oApp = CreateObject("hMailServer.Application")

' Authenticate the client.
Call oApp.Authenticate ("Administrator", sAdminPassword)

Call oApp.BackupManager.StartBackup()
The included backup script in Hmailserver.
Just add a msgbox sAdminPassword and you are done,. That is the current security level.

But since you say that we shouldn't do that please show a script that does authenticate and doesn't have the password in cleartext then.

with physical access to a server without an encrypted harddrive, then you are always f-cked. I usually need 3-5 mins to have system privs on that kind of box using 100% signed Microsoft code.
One guy thought that they where safe using applocker - Well they wasn't. The way to handle that is with drive encryption, locked doors and if possible armed guards.

My main concerns are not the superhacker. I'm a lot more worried about script kiddies and automated attacks targeting software issues like buffer and stack overflows because they are remotely exploitable.
That's why my first step was to switch from system to a ordinary user account (an account that can't log on interactively or over network either)
If the service is compromised it will not have more than user privs, therefore you can't do a net user /add or attach a debugger.

The next thing I'm worried about is usernames and passwords in cleartext since people tends to reuse them regardless of how many times you tell them not to.
With the password in script all the attacker needs is notepad or cmd .......

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

Re: Can i do an autban script based on this?

Post by mattg » 2019-01-05 15:47

mats wrote:
2019-01-05 13:51
With the password in script all the attacker needs is notepad or cmd .......
Don't they also need access to your file system?
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: 3154
Joined: 2006-08-21 15:38
Location: Denmark

Re: Can i do an autban script based on this?

Post by SorenR » 2019-01-05 15:55

mattg wrote:
2019-01-05 00:07
SorenR wrote:
2019-01-04 23:21
Why not use vbsedit to convert vbs to an exe file ...
Now that is an interesting thought
From HELP file...
Convert Into Executable

VbsEdit lets you convert your scripts into standalone applications. Unlike the older versions of VbsEdit, the script will now be executed directly within the executable. The original script will no longer be extracted into a temporary folder.

Once converted, the source of your script will be nearly impossible to be viewed by other users.

Built-in WScript object

The application uses a built-in WScript object.
  • Create a new script with only one line: WScript.Echo WScript.ScriptFullname
  • Convert the script into an executable and run it. The ScriptFullname property is now the application's path!
UAC Execution Level

VbsEdit adds an application manifest to the program that tells the operating system what the application needs. The possible requested execution level values are:
  • asInvoker: The application will run with the same permissions as the process that started it. The application can be elevated to a higher permission level by selecting Run as Administrator.
  • highestAvailable: The application will run with the highest permission level that it can. If the user who starts the application is a member of the Administrators group, this option is the same as requireAdministrator. If the highest available permission level is higher than the level of the opening process, the system will prompt for credentials.
  • requireAdministrator: The application will run with administrator permissions. The user who starts the application must be a member of the Administrators group. If the opening process is not running with administrative permissions, the system will prompt for credentials.
How does VbsEdit pre-populate fields and options?

Vbsedit now stores parameters into an xml file. To get the path of this xml file, just add "2exe" to the path of the script file. If the path of your script is c:\myfolder\myscript.vbs, then the xml file is c:\myfolder\myscript.vbs2exe.

Command-line option

To automate the creation of the executable, start Vbsedit with the /convert2exe option.
Examples:
Vbsedit.exe /convert2exe c:\myfolder\myscript.vbs
Vbsedit.exe /convert2exe:c:\myxmlfile.vbs2exe c:\myfolder\myscript.vbs


Digital signature

Code signing is the process of digitally signing executables to confirm the software author and guarantee that the code has not been altered or corrupted since it was signed.

If you want to buy a code signing certificate, visit K Software [http://codesigning.ksoftware.net/] (we are not affiliated with them in any way, but they have reasonable prices).

Alternate User Account and Password

It allows a user to run the executable under a different username to the one that was used to logon to a computer interactively. It is similar to the runas command.
For example, it could allow a user to run a task as admin even if he does not have administrator permissions himself.
SørenR.

The quantum rule of insecurity which states that the act of observing how vulnerable a host or service is changes the insecurity level of the service.

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2019-01-05 17:42

mattg wrote:
2019-01-05 15:47
mats wrote:
2019-01-05 13:51
With the password in script all the attacker needs is notepad or cmd .......
Don't they also need access to your file system?
Yes, but a compromised serviceaccount will have that.
If running as system you own the file system.
If you are running as user it's a little better but still, the serviceaccount must be able to read it and hence anything that compromises the service also can.

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2019-01-05 17:44

SorenR wrote:
2019-01-05 15:55
mattg wrote:
2019-01-05 00:07
SorenR wrote:
2019-01-04 23:21
Why not use vbsedit to convert vbs to an exe file ...
Now that is an interesting thought
From HELP file...
Convert Into Executable

VbsEdit lets you convert your scripts into standalone applications. Unlike the older versions of VbsEdit, the script will now be executed directly within the executable. The original script will no longer be extracted into a temporary folder.

Once converted, the source of your script will be nearly impossible to be viewed by other users.

Built-in WScript object

The application uses a built-in WScript object.
  • Create a new script with only one line: WScript.Echo WScript.ScriptFullname
  • Convert the script into an executable and run it. The ScriptFullname property is now the application's path!
UAC Execution Level

VbsEdit adds an application manifest to the program that tells the operating system what the application needs. The possible requested execution level values are:
  • asInvoker: The application will run with the same permissions as the process that started it. The application can be elevated to a higher permission level by selecting Run as Administrator.
  • highestAvailable: The application will run with the highest permission level that it can. If the user who starts the application is a member of the Administrators group, this option is the same as requireAdministrator. If the highest available permission level is higher than the level of the opening process, the system will prompt for credentials.
  • requireAdministrator: The application will run with administrator permissions. The user who starts the application must be a member of the Administrators group. If the opening process is not running with administrative permissions, the system will prompt for credentials.
How does VbsEdit pre-populate fields and options?

Vbsedit now stores parameters into an xml file. To get the path of this xml file, just add "2exe" to the path of the script file. If the path of your script is c:\myfolder\myscript.vbs, then the xml file is c:\myfolder\myscript.vbs2exe.

Command-line option

To automate the creation of the executable, start Vbsedit with the /convert2exe option.
Examples:
Vbsedit.exe /convert2exe c:\myfolder\myscript.vbs
Vbsedit.exe /convert2exe:c:\myxmlfile.vbs2exe c:\myfolder\myscript.vbs


Digital signature

Code signing is the process of digitally signing executables to confirm the software author and guarantee that the code has not been altered or corrupted since it was signed.

If you want to buy a code signing certificate, visit K Software [http://codesigning.ksoftware.net/] (we are not affiliated with them in any way, but they have reasonable prices).

Alternate User Account and Password

It allows a user to run the executable under a different username to the one that was used to logon to a computer interactively. It is similar to the runas command.
For example, it could allow a user to run a task as admin even if he does not have administrator permissions himself.
Looks interesting. It's worth taking a look at

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

Re: Can i do an autban script based on this?

Post by SorenR » 2019-01-05 18:55

My IDS Handler, CheckState and RunBackup scripts are now "compiled" and running. Next is my SA-Learn script.

Reworking my EventHandler will require some thoughts on optimizing if I am to move all password dependant functions out. It should be doable though. Not sure about performance but time will tell.
SørenR.

The quantum rule of insecurity which states that the act of observing how vulnerable a host or service is changes the insecurity level of the service.

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

Re: Can i do an autban script based on this?

Post by insomniac2k2 » 2019-01-05 19:51

I just want you to know that you are not alone mats. I completely share your mentality on this topic. Hence why i started down that path. Albeit my solution was not quite as good as yours, from what it seems :)
mats wrote:
2019-01-05 13:51
RvdH wrote:
2019-01-05 03:49
mats wrote:
2018-12-28 21:18
it's simple to do a msgbox of the password when it is stored in cleartext in the script, I don't believe we have to discuss that further
Please show me how, i could not do it....and i doubt you can do it either,
Sure, if you stored the password in a CONST you could, but then again simply do not do that!

The point in general is, if an unauthorized person has physical access to the server it is probably a (skilled) hacker, who has no problems defeating your additional protection as well, any debugger will have discovered your encrypted password just as easy by putting a breakpoint on the Application object Authenticate(string Username, string Password) which is still submitted through to your COM object and then is passed to to original object in plain text. I know, i earlier have said i liked the idea insomniac2k2 suggested, but in reality i have never used it


But hey, i like to be surprised....please prove me otherwise

Code: Select all

Const sAdminPassword = "<ADMINISTRATORPASSWORD>"

Dim oApp
Set oApp = CreateObject("hMailServer.Application")

' Authenticate the client.
Call oApp.Authenticate ("Administrator", sAdminPassword)

Call oApp.BackupManager.StartBackup()
The included backup script in Hmailserver.
Just add a msgbox sAdminPassword and you are done,. That is the current security level.

But since you say that we shouldn't do that please show a script that does authenticate and doesn't have the password in cleartext then.

with physical access to a server without an encrypted harddrive, then you are always f-cked. I usually need 3-5 mins to have system privs on that kind of box using 100% signed Microsoft code.
One guy thought that they where safe using applocker - Well they wasn't. The way to handle that is with drive encryption, locked doors and if possible armed guards.

My main concerns are not the superhacker. I'm a lot more worried about script kiddies and automated attacks targeting software issues like buffer and stack overflows because they are remotely exploitable.
That's why my first step was to switch from system to a ordinary user account (an account that can't log on interactively or over network either)
If the service is compromised it will not have more than user privs, therefore you can't do a net user /add or attach a debugger.

The next thing I'm worried about is usernames and passwords in cleartext since people tends to reuse them regardless of how many times you tell them not to.
With the password in script all the attacker needs is notepad or cmd .......

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

Re: Can i do an autban script based on this?

Post by RvdH » 2019-01-11 00:46

mats wrote:
2019-01-05 13:51

Code: Select all

Const sAdminPassword = "<ADMINISTRATORPASSWORD>"
The included backup script in Hmailserver.
Just add a msgbox sAdminPassword and you are done,. That is the current security level.
That is exactly why i said with password stored in a CONST you could, but then again simply do not do that!
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

mats
New user
New user
Posts: 24
Joined: 2018-05-06 20:58

Re: Can i do an autban script based on this?

Post by mats » 2019-01-12 16:25

RvdH wrote:
2019-01-11 00:46
mats wrote:
2019-01-05 13:51

Code: Select all

Const sAdminPassword = "<ADMINISTRATORPASSWORD>"
The included backup script in Hmailserver.
Just add a msgbox sAdminPassword and you are done,. That is the current security level.
That is exactly why i said with password stored in a CONST you could, but then again simply do not do that!
So why don't you provide an Answer to how we should do then?
How do we have a password for the script in a safe manner according to you?

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

Re: Can i do an autban script based on this?

Post by jimimaseye » 2019-01-12 20:46

How about strict security to stop unauthorised persons looking at random script files on your server in the first place?

I'm pretty sure that if anyone had gained access to your system and shouldn't be there, the last thing they will be looking at is some unknown script file in a 3rd party software on your system (to read a password it uses). Worse case scenario is they then go and lookup on the internet what hmailserver is and how it works, write a script to suit it and work out a way of uploading it back to your events directory, restart the service, and try to then use it to send out some spam. (... eventually).

Or maybe they rub their hands together, ignore the little known hmailserver software and embark on exploiting known global windows exploits that they already know and start to spread viruses.

Just a thought.

[Entered by mobile. Excuse my spelling.]
HMS 5.6.6 B2383 on Win Server 2008 R2 Foundation, + 5.6.7-B2415 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

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

Re: Can i do an autban script based on this?

Post by RvdH » 2019-01-13 11:32

jimimaseye wrote:
2019-01-12 20:46
How about strict security to stop unauthorised persons looking at random script files on your server in the first place?

I'm pretty sure that if anyone had gained access to your system and shouldn't be there, the last thing they will be looking at is some unknown script file in a 3rd party software on your system (to read a password it uses). Worse case scenario is they then go and lookup on the internet what hmailserver is and how it works, write a script to suit it and work out a way of uploading it back to your events directory, restart the service, and try to then use it to send out some spam. (... eventually).

Or maybe they rub their hands together, ignore the little known hmailserver software and embark on exploiting known global windows exploits that they already know and start to spread viruses.

Just a thought.

[Entered by mobile. Excuse my spelling.]
ditto
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