Script to block or allow country connections

This section contains scripts that hMailServer has contributed with. hMailServer 5 is needed to use these.
Post Reply
User avatar
SorenR
Senior user
Senior user
Posts: 3154
Joined: 2006-08-21 15:38
Location: Denmark

Script to block or allow country connections

Post by SorenR » 2014-06-27 09:09

I've been scavenging the interweb for snippets and have come up with this, using an alternate GeoIP service. Unfortunately the output from the website is in JSON format, so it may be a bit heavy on busy servers... Credits for the VbsJson class is in the vbsjson.vbs file - not mine - way beyond my skills :oops:

Code: Select all

	Sub Include(sInstFile)
		Dim f, s, oFSO
		Set oFSO = CreateObject("Scripting.FileSystemObject")
		On Error Resume Next
		If oFSO.FileExists(sInstFile) Then
			Set f = oFSO.OpenTextFile(sInstFile)
			s = f.ReadAll
			f.Close
			ExecuteGlobal s
		End If
		On Error Goto 0
		Set f = Nothing
		Set oFSO = Nothing
	End Sub

	Include("C:\hMailServer\Events\VbsJson.vbs")

	Sub OnClientConnect(oClient)

'		ip			(Visitor IP address, or IP address specified as parameter)
'		country_code	(Two-letter ISO 3166-1 alpha-2 country code)
'		country_code3	(Three-letter ISO 3166-1 alpha-3 country code)
'		country		(Name of the country)
'		region_code	(Two-letter ISO-3166-2 state / region code)
'		region		(Name of the region)
'		city			(Name of the city)
'		postal_code	(Postal code / Zip code)
'		continent_code	(Two-letter continent code)
'		latitude		(Latitude)
'		longitude		(Longitude)
'		dma_code		(DMA Code)
'		area_code		(Area Code)
'		asn			(Autonomous System Number)
'		isp			(Internet service provider)
'		timezone		(Time Zone)

		' Skip if client is local LAN
		If InStr(oClient.IPAddress,"192.168.0") Then
			Result.Value = 0
		Else			
			Dim oXML, json, oGeoip
			Set json = New VbsJson
			Set oXML = CreateObject ("Msxml2.XMLHTTP.3.0")
			oXML.Open "GET","http://www.telize.com/geoip/"+oClient.IPAddress,False
			oXML.Send
			If (oXML.status = 200 ) Then
				Set oGeoip = json.Decode(oXML.responseText)

				Select Case oGeoip("country_code")
					Case "CN"
						Result.Value = 1
					Case "RO"
						Result.Value = 1
					Case "RU"
						Result.Value = 1
					Case "US"
						If     (oGeoip("isp") = "Google Inc.") Then
							Result.Value = 0
						ElseIf (oGeoip("isp") = "Microsoft Corp") Then
							Result.Value = 0
						Else
							Result.Value = 1
						End If
					Case "VN"
						Result.Value = 1
					Case else
						Result.Value = 0
				End Select

				If Result.Value = 1 Then
					EventLog.Write("OnClientConnect Denied :"+Chr(34)+vbTab+oClient.IPAddress+vbTab+Chr(34)+oGeoip("country_code")+" - "+oGeoip("country")+" - "+oGeoip("isp"))
				Else
					EventLog.Write("OnClientConnect        :"+Chr(34)+vbTab+oClient.IPAddress+vbTab+Chr(34)+oGeoip("country_code")+" - "+oGeoip("country")+" - "+oGeoip("isp"))
				End If
			Else
				Result.Value = 0
				EventLog.Write("www.telize.com/geoip error ->"+Chr(34)+vbTab+oXML.status+vbTab+Chr(34)+oClient.IPAddress)
			End If
		End If
	End Sub
This is what my hmailserver_event.log looks like...

Code: Select all

3780	"2014-06-27 08:45:04.824"	"OnClientConnect Denied :"	216.*.*.222	"US - United States - ViaWest"
3780	"2014-06-27 08:45:06.543"	"OnClientConnect        :"	80.*.*.115	"DK - Denmark - TDC Data Networks"
3780	"2014-06-27 08:45:12.089"	"OnClientConnect        :"	209.*.*.66	"US - United States - Google Inc."
3780	"2014-06-27 08:51:56.030"	"OnClientConnect        :"	95.*.*.103	"NL - Netherlands - LeaseWeb B.V."
3780	"2014-06-27 08:51:57.686"	"OnClientConnect        :"	80.*.*.115	"DK - Denmark - TDC Data Networks"
3780	"2014-06-27 08:55:47.015"	"OnClientConnect        :"	94.*.*.151	"PT - Portugal - NFSi Telecom, Lda."
Disclaimer: It runs on my Windows Server 2003 R2 Standard Edition with hMailServer 5.4.2-B1964... So far...
Attachments
msxml_check.zip
(356 Bytes) Downloaded 245 times
VbsJson.zip
(2.21 KiB) Downloaded 268 times
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: Script to block or allow country connections

Post by SorenR » 2014-07-04 16:00

Updated script...

I've been looking at the difference between using nested IF - THEN - ELSE and CASE and it seems that CASE is faster (and smaller code) when compiled.

Output is a bit different as I wanted to keep an eye on how connections are made, so the script will now state IMAP/SMTP/SUBM as per the last CASE statement. You will need to modify code to suit your set-up.

Interrestingly I have not had ONE SINGLE unauthorised attempt on port 587 since I started this logging...

Code: Select all

	Sub Include(sInstFile)
		Dim f, s, oFSO
		Set oFSO = CreateObject("Scripting.FileSystemObject")
		On Error Resume Next
		If oFSO.FileExists(sInstFile) Then
			Set f = oFSO.OpenTextFile(sInstFile)
			s = f.ReadAll
			f.Close
			ExecuteGlobal s
		End If
		On Error Goto 0
		Set f = Nothing
		Set oFSO = Nothing
	End Sub

	Include("C:\hMailServer\Events\VbsJson.vbs")

	Sub OnClientConnect(oClient)
	
'		ip			(Visitor IP address, or IP address specified as parameter)
'		country_code	(Two-letter ISO 3166-1 alpha-2 country code)
'		country_code3	(Three-letter ISO 3166-1 alpha-3 country code)
'		country		(Name of the country)
'		region_code	(Two-letter ISO-3166-2 state / region code)
'		region		(Name of the region)
'		city			(Name of the city)
'		postal_code	(Postal code / Zip code)
'		continent_code	(Two-letter continent code)
'		latitude		(Latitude)
'		longitude		(Longitude)
'		dma_code		(DMA Code)
'		area_code		(Area Code)
'		asn			(Autonomous System Number)
'		isp			(Internet service provider)
'		timezone		(Time Zone)

		' Skip if client is local LAN
		If InStr(oClient.IPAddress,"192.168.0") Then
			Result.Value = 0
		Else
			Dim oXML, json, oGeoip, strPort
			Set json = New VbsJson
			Set oXML = CreateObject ("Msxml2.XMLHTTP.3.0")
			oXML.Open "GET","http://www.telize.com/geoip/"+oClient.IPAddress,False
			oXML.Send
			If (oXML.status = 200 ) Then
				Set oGeoip = json.Decode(oXML.responseText)

				Select Case oGeoip("continent_code")
					Case "AS"					' Asia
						Result.Value = 1
					Case "AF"					' Africa
						Result.Value = 1
					Case "AN"					' Antarctica
						Result.Value = 1
					Case "OC"					' Oceania
						Result.Value = 1
					Case "SA"					' South America
						Result.Value = 1
					Case Else					' Europe & North America
						Select Case oGeoip("country_code")
							Case "BY"				' Belarus
								Result.Value = 1
							Case "CO"				' Colombia
								Result.Value = 1
							Case "CR"				' Costa Rica
								Result.Value = 1
							Case "CW"				' Curacao
								Result.Value = 1
							Case "DO"				' Dominican Republic
								Result.Value = 1
							Case "LT"				' Lithuania
								Result.Value = 1
							Case "MD"				' Moldova
								Result.Value = 1
							Case "MX"				' Mexico
								Result.Value = 1
							Case "PA"				' Panama
								Result.Value = 1
							Case "RO"				' Romania
								Result.Value = 1
							Case "RS"				' Serbia
								Result.Value = 1
							Case "RU"				' Russia
								Result.Value = 1
							Case "SV"				' El Salvador
								Result.Value = 1
							Case "UA"				' Ukraine
								Result.Value = 1
							Case Else
								Result.Value = 0
						End Select
				End Select

				Select Case oClient.Port
					Case "25"
						strPort = "SMTP"
					Case "143"
						strPort = "IMAP"
					Case "587"
						strPort = "SUBM"
					Case Else
						strPort = "N/A "
				End Select

				If Result.Value = 1 Then
					EventLog.Write(strPort+" Connection REJECTED"+Chr(34)+vbTab+oClient.IPAddress+vbTab+Chr(34)+oGeoip("country_code")+Chr(34)+vbTab+Chr(34)+oGeoip("country")+Chr(34)+vbTab+Chr(34)+oGeoip("isp")+Chr(34)+vbTab+Chr(34)+oGeoip("continent_code"))
				Else
					EventLog.Write(strPort+" Connection accepted"+Chr(34)+vbTab+oClient.IPAddress+vbTab+Chr(34)+oGeoip("country_code")+Chr(34)+vbTab+Chr(34)+oGeoip("country")+Chr(34)+vbTab+Chr(34)+oGeoip("isp")+Chr(34)+vbTab+Chr(34)+oGeoip("continent_code"))
				End If
			Else
				Result.Value = 0
				EventLog.Write("<OnClientConnect.error> www.telize.com/geoip lookup failed, error code: "+oXML.status+" on IP address "+oClient.IPAddress)
			End If
		End If
	End Sub
Output:

Code: Select all

1708 "2014-07-04 14:41:59.253" "SMTP Connection REJECTED" ***.***.***.*** "VN" "Vietnam" "" "AS"
1724 "2014-07-04 14:45:52.049" "IMAP Connection accepted" ***.***.***.*** "DK" "Denmark" "TDC Data Networks" "EU"
1708 "2014-07-04 14:46:14.814" "SMTP Connection REJECTED" ***.***.***.*** "TW" "Taiwan" "Data Communication Business Group" "AS"
1708 "2014-07-04 14:57:21.435" "SMTP Connection accepted" ***.***.***.*** "US" "United States" "LinkedIn Corporation" "NA"
1724 "2014-07-04 14:58:19.857" "IMAP Connection accepted" ***.***.***.*** "DK" "Denmark" "TDC Data Networks" "EU"
1724 "2014-07-04 14:58:26.028" "IMAP Connection accepted" ***.***.***.*** "DK" "Denmark" "TDC Data Networks" "EU"
1724 "2014-07-04 14:58:32.216" "IMAP Connection accepted" ***.***.***.*** "DK" "Denmark" "TDC Data Networks" "EU"
1724 "2014-07-04 14:58:34.856" "IMAP Connection accepted" ***.***.***.*** "DK" "Denmark" "TDC Data Networks" "EU"
1708 "2014-07-04 15:14:13.274" "SMTP Connection REJECTED" ***.***.***.*** "ZA" "South Africa" "DPBOL" "AF"
1708 "2014-07-04 15:18:49.540" "SMTP Connection accepted" ***.***.***.*** "DE" "Germany" "IP Exchange GmbH" "EU"
1708 "2014-07-04 15:24:55.118" "SMTP Connection REJECTED" ***.***.***.*** "RS" "Serbia" "Serbia BroadBand-Srpske Kablovske mreze d.o.o." "EU"
1708 "2014-07-04 15:33:33.833" "SMTP Connection REJECTED" ***.***.***.*** "ZA" "South Africa" "Vodacom-VB" "AF"
1708 "2014-07-04 15:35:29.176" "SMTP Connection accepted" ***.***.***.*** "US" "United States" "Road Runner HoldCo LLC" "NA"
1708 "2014-07-04 15:35:49.692" "SMTP Connection accepted" ***.***.***.*** "DE" "Germany" "Deutsche Telekom AG" "EU"
1708 "2014-07-04 15:36:23.176" "SMTP Connection accepted" ***.***.***.*** "US" "United States" "Yahoo" "NA"
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.

1ucasPitts
New user
New user
Posts: 3
Joined: 2014-08-27 17:06

Re: Script to block or allow country connections

Post by 1ucasPitts » 2014-08-27 17:17

I installed your script and it is working fine. Very useful.

I did however make the following change to it.

Added a scripting dictionary

Code: Select all

		dim objDict   ' Create a variable.
		set objDict = CreateObject("Scripting.Dictionary")
Added the Continents and Countries

Code: Select all

			'Continents
			objDict.Add "AS", "Asia"
			objDict.Add "AF", "Africa"
			objDict.Add "AN", "Antarctica"
			objDict.Add "OC", "Oceania"
			objDict.Add "SA", "South America"
			
			'Countries
			objDict.Add "BE", "Belgium"
			objDict.Add "BG", "Bulgaria"
			objDict.Add "BY", "Belarus"
			objDict.Add "CO", "Colombia"
			objDict.Add "CR", "Costa Rica"
			objDict.Add "CW", "Curacao"
			objDict.Add "DE", "Germany"
			objDict.Add "DO", "Dominican Republic"
			objDict.Add "ES", "Spain"
			objDict.Add "FR", "France"
			objDict.Add "LT", "Lithuania"
			objDict.Add "MD", "Moldova"
			objDict.Add "MX", "Mexico"
			objDict.Add "PA", "Panama"
			objDict.Add "PL", "Poland"
			objDict.Add "RO", "Romania"
			objDict.Add "RS", "Serbia"
			objDict.Add "RU", "Russia"
			objDict.Add "SV", "El Salvador"
			objDict.Add "UA", "Ukraine"
And then checked if a match was found

Code: Select all

			'Check if match is found
			if objDict.Exists(oGeoip("country_code")) then
			  Result.Value = 1
			 else
			   Result.Value = 0
			 end if
Working great with no problems.

Also, your original works fine on Server 2008 R2.

Thanks again.

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

Re: Script to block or allow country connections

Post by SorenR » 2014-08-27 18:10

1ucasPitts wrote:I installed your script and it is working fine. Very useful.

I did however make the following change to it.

Added a scripting dictionary
Cool ! Glad to hear that it makes a difference :mrgreen:

My primary use for the script was to block port probes coming in from all over. Tons of login attempts.

I have since downloaded the 5.4.2-B1964 code and modified it to NOT allow AUTH LOGON on port 25.

After a couple of hours of running the modified code, all the port probes stopped. :shock:
Now I only get the occational relay probe trying to send mail to mike24@outlook.it (yes, I posted the email address - now all the address scavenger bots can harvest it :mrgreen: )

So... I'm not using the script any longer... :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.

1ucasPitts
New user
New user
Posts: 3
Joined: 2014-08-27 17:06

Re: Script to block or allow country connections

Post by 1ucasPitts » 2014-08-27 21:54

I did find an error in my logic after all. Here is the corrected match lookup.

Code: Select all

			'Check if match is found
			if ( objDict.Exists(oGeoip("country_code")) ) or ( objDict.Exists(oGeoip("continent_code")) ) then
			  Result.Value = 1
			 else
			   Result.Value = 0
			 end if

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

Re: Script to block or allow country connections

Post by jimimaseye » 2014-12-29 12:29

Alternatively, I use

zz.countries.nerd.dk

as a DNS Blacklist (to use within HMS DNSBlacklist (antispam). Just enter the relevant result code for the countries you want to block (as found here: http://countries.nerd.dk/isolist.txt)

eg,
127.0.0.158|127.0.2.131|127.0.2.198
will score (to block/reject) mails from .TW .RU and .ZA
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
SorenR
Senior user
Senior user
Posts: 3154
Joined: 2006-08-21 15:38
Location: Denmark

Re: Script to block or allow country connections

Post by SorenR » 2016-10-27 15:10

Major overhaul... Still using the vbsjson.vbs linked to in the first post but the geoip lookup host is changed and so are some of the parameters...

PLEASE... PLEASE do have a look at the code BEFORE putting it into production! You may wish to block other continents and/or countries than I do and if you do not have a Backup-MX you WILL loose emails.

Code: Select all

   Include("C:\hMailServer\Events\VbsJson.vbs")

   Function Include(sInstFile)
      Dim f, s, oFSO
      Set oFSO = CreateObject("Scripting.FileSystemObject")
      On Error Resume Next
      If oFSO.FileExists(sInstFile) Then
         Set f = oFSO.OpenTextFile(sInstFile)
         s = f.ReadAll
         f.Close
         ExecuteGlobal s
      End If
      On Error Goto 0
      Set f = Nothing
      Set oFSO = Nothing
   End Function
   
   Function Lookup(strBase, strMatch)
      With CreateObject("VBScript.RegExp")
         .IgnoreCase = True
         .Global = False
         .Pattern = strBase
         If .Test(strMatch) Then
            Lookup = True
         Else
            Lookup = False
         End If
      End With
   End Function

   Sub OnClientConnect(oClient)
      If (Left(oClient.IPAddress, 10) = "192.168.0.") Then Exit Sub
      If (oClient.Port = 25) Then Wait(20)
      Dim ReturnCode, Json, oGeoip, oXML, strPort, strBase
      strPort = Mid("SMTP IMAP SMTPSSUBM IMAPS", InStr("25   143  465  587  993  ", oClient.Port), 5)
      Set Json = New VbsJson
      On Error Resume Next
      Set oXML = CreateObject ("Msxml2.XMLHTTP.3.0")
      oXML.Open "GET", "http://www.geoplugin.net/json.gp?ip=" & oClient.IPAddress, False
      oXML.Send
      Set oGeoip = Json.Decode(oXML.responseText)
      ReturnCode = oXML.Status
      On Error Goto 0
      If (ReturnCode <> 200 ) Then
         EventLog.Write("<OnClientConnect.error> www.geoplugin.net lookup failed, error code: " & ReturnCode & " on IP address " & oClient.IPAddress)
         Exit Sub
      End If
      strBase = "^(AS)$|^(AF)$|^(AN)$|^(OC)$|^(SA)$"
      If Lookup(strBase, oGeoip("geoplugin_continentCode")) Then
         Result.Value = 1
         EventLog.Write(strPort & " Connection REJECTED" & Chr(34) & vbTab & oClient.IPAddress & vbTab & Chr(34) & oGeoip("geoplugin_countryCode") & Chr(34) & vbTab & Chr(34) & oGeoip("geoplugin_countryName") & Chr(34) & vbTab & Chr(34) & oGeoip("geoplugin_continentCode"))
         Exit Sub
      End If
      strBase = "^(BY)$|^(CR)$|^(CZ)$|^(DO)$|^(GP)$|^(LT)$|^(LV)$|^(MD)$|^(MX)$|^(PA)$|^(PL)$|^(RO)$|^(RS)$|^(RU)$|^(SV)$|^(UA)$"
      If Lookup(strBase, oGeoip("geoplugin_countryCode")) Then
         Result.Value = 1
         EventLog.Write(strPort & " Connection REJECTED" & Chr(34) & vbTab & oClient.IPAddress & vbTab & Chr(34) & oGeoip("geoplugin_countryCode") & Chr(34) & vbTab & Chr(34) & oGeoip("geoplugin_countryName") & Chr(34) & vbTab & Chr(34) & oGeoip("geoplugin_continentCode"))
         Exit Sub
      End If
      EventLog.Write(strPort & " Connection accepted" & Chr(34) & vbTab & oClient.IPAddress & vbTab & Chr(34) & oGeoip("geoplugin_countryCode") & Chr(34) & vbTab & Chr(34) & oGeoip("geoplugin_countryName") & Chr(34) & vbTab & Chr(34) & oGeoip("geoplugin_continentCode"))
   End Sub
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: 8011
Joined: 2011-09-08 17:48

Re: Script to block or allow country connections

Post by jimimaseye » 2018-07-06 09:03

Heads up SorenR and others.

According to https://github.com/eklam/VbsJson/pull/1 (the original source for the jsonvbs.vbs script) there is a minor error. The contributor has posted a change to the script to fix it. It might be worth you updating the script with the 2 changes:

(Add the GREEN LINES to your existing script)
Capture.JPG
(Over recent months since installing I occasionally had errors (IOCP problems) that always seemed to happen related to this script. They're infrequent and random and without obvious cause. I have just found this github entry and maybe this fix is the solution. Time will tell.)
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
SorenR
Senior user
Senior user
Posts: 3154
Joined: 2006-08-21 15:38
Location: Denmark

Re: Script to block or allow country connections

Post by SorenR » 2018-07-06 11:24

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.

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

Re: Script to block or allow country connections

Post by palinka » 2018-08-24 16:40

SorenR wrote:
2018-07-06 11:24
File with changes ...

https://github.com/wqweto/VbsJson/blob/ ... bsJson.vbs
I'm on a roll with your scripts lately. That is to say, install, error, beg for help. Its a roll, right? :mrgreen:

It seems to be at least partially working. The event log has lots of "accepted" and "rejected" events. One thing I noticed is that there are very few SMTP entries which is surprising since for the past week I've been bombarded with spam and I expected to see a lot more of those.

I'm getting errors. The most common one is this: "ERROR" 3324 "2018-08-24 09:49:35.385" "Script Error: Source: Microsoft VBScript runtime error - Error: 800A000D - Description: Type mismatch: 'Test' - Line: 57 Column: 6 - Code: (null)" which is part of the Lookup function: If .Test(strMatch) Then Lookup = True

I'm not using the lookup function posted above - I'm using the one supplied in the auto-unsubscribe thread. They appear to be pretty much the same (except for .multiline = True), but I tried both and got the same results.

There are also a few mismatch errors for "wait": If (oClient.Port = 25) Then Wait(20)

There are also a few "invalid procedure call or argument" errors for "mid": strPort = Mid("SMTP IMAP SMTPS SUBM IMAPS", InStr("25 143 465 587 993 ", oClient.Port), 5)

But for the "mid" one I found what I think is a typo (as copied from the above post): Mid("SMTP IMAP SMTPSSUBM IMAPS" (no space between SMTP & SUBM). Hopefully that's resolved. I'm not sure if it means anything, but there are a different number of spaces between port numbers, plus there are spaces between 993 & ".

I looked up vbs mismatch and found they can only be mismatches in the type of data returned. I'm not sure what to look for. :?: :?:

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

Re: Script to block or allow country connections

Post by palinka » 2018-08-24 23:20

OK, I looked through the log and found that ALL the "Type mismatch: 'Test'" errors occurred when a connection was made from 127.0.0.1. The vast majority of my connections are from 127.0.0.1 because I connect through horde activesync, so lots and lots of IMAP connections on 127.0.0.1. And it means that my error log is full of thousands of these:

Code: Select all

"TCPIP"	10392	"2018-08-23 20:57:43.012"	"TCP - 127.0.0.1 connected to 127.0.0.1:143."
"DEBUG"	10392	"2018-08-23 20:57:43.012"	"Executing event OnClientConnect"
"ERROR"	10392	"2018-08-23 20:57:44.809"	"Script Error: Source: Microsoft VBScript runtime error - Error: 800A000D - Description: Type mismatch: 'Test' - Line: 219 Column: 2 - Code: (null)"
I changed:

Code: Select all

If (Left(oClient.IPAddress, 10) = "192.168.1.") Then Exit Sub
to:

Code: Select all

If (Left(oClient.IPAddress, 10) = "127.0.0.1") Then Exit Sub
but it didn't get rid of the errors.

edit - I went back to

Code: Select all

If (Left(oClient.IPAddress, 10) = "127.0.0.1") Then Exit Sub
then I played around with horde/imp backend and broke something, went back to my original settings but still broken, restarted apache and now the "type mismatch: test" errors are gone.

I still have Type mismatch: 'Wait' errors. I'll have to wait a while to see if the "invalid procedure: mid" errors are still present - there were very few of those.
Last edited by palinka on 2018-08-24 23:49, edited 1 time in total.

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

Re: Script to block or allow country connections

Post by jimimaseye » 2018-08-24 23:35

If (Left(oClient.IPAddress, 10) = "127.0.0.1")
Hint:

127.0.0.1 only has 9 characters (not 10).

[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
SorenR
Senior user
Senior user
Posts: 3154
Joined: 2006-08-21 15:38
Location: Denmark

Re: Script to block or allow country connections

Post by SorenR » 2018-08-24 23:45

palinka wrote:
2018-08-24 16:40
There are also a few "invalid procedure call or argument" errors for "mid": strPort = Mid("SMTP IMAP SMTPS SUBM IMAPS", InStr("25 143 465 587 993 ", oClient.Port), 5)

But for the "mid" one I found what I think is a typo (as copied from the above post): Mid("SMTP IMAP SMTPSSUBM IMAPS" (no space between SMTP & SUBM). Hopefully that's resolved. I'm not sure if it means anything, but there are a different number of spaces between port numbers, plus there are spaces between 993 & ".
Not quite sure what you have done to "my" code but it works, I still use it...

Dim strPort : strPort = Trim(Mid("SMTP IMAP SMTPSSUBM IMAPS", InStr("25 143 465 587 993 ", oClient.Port), 5))

InStr("25 143 465 587 993 ", oClient.Port) will return the position of the port in the string. Eg. oClient.Port = 587 will return 16.

Mid("SMTP IMAP SMTPSSUBM IMAPS", 16, 5) will return SUBM.

Why don't you post your complete eventhandlers.vbs in a PM to me and I'll have a look at it ?

You are probably missing a few of my custom functions ...
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.

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

Re: Script to block or allow country connections

Post by palinka » 2018-08-24 23:54

jimimaseye wrote:
2018-08-24 23:35
If (Left(oClient.IPAddress, 10) = "127.0.0.1")
Hint:

127.0.0.1 only has 9 characters (not 10).

[Entered by mobile. Excuse my spelling.]
Thanks! I updated that to 9. But... I edited my post and we cross posted. Maybe you haven't seen it yet. I only updated to 9 after I saw your post.

Any idea what the wait errors could be?

Code: Select all

If (oClient.Port = 25) Then Wait(20)

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

Re: Script to block or allow country connections

Post by jimimaseye » 2018-08-24 23:59

Missing function called 'wait'.

Send your eventhandlers to soren for full review.
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

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

Re: Script to block or allow country connections

Post by palinka » 2018-08-25 00:01

jimimaseye wrote:
2018-08-24 23:59
Missing function called 'wait'.

Send your eventhandlers to soren for full review.
Ah. OK just did and thanks in advance, Soren!

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

Re: Script to block or allow country connections

Post by palinka » 2018-08-25 02:11

SorenR wrote:
2018-08-24 23:45
Dim strPort : strPort = Trim(Mid("SMTP IMAP SMTPSSUBM IMAPS", InStr("25 143 465 587 993 ", oClient.Port), 5))

InStr("25 143 465 587 993 ", oClient.Port) will return the position of the port in the string. Eg. oClient.Port = 587 will return 16.

Mid("SMTP IMAP SMTPSSUBM IMAPS", 16, 5) will return SUBM.
This ^^^ resolved the "mid" error. After looking in the log, I figured out that the error only occurred with pop logins. So using your lesson above, I added POP and POPS 110 & 995. I don't get many pop logins, so it might take a couple hours to make sure I did it right. :D

Edit - Just got a pop login and it worked - no "mid" error. Event log:

Code: Select all

5408	"2018-08-24 20:10:04.567"	"POPS Connection accepted"	209.85.161.7	"US"	"United States"	"NA"
Great success! :mrgreen:

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

Re: Script to block or allow country connections

Post by palinka » 2018-08-25 11:20

SorenR wrote:
2018-08-24 23:45
Why don't you post your complete eventhandlers.vbs in a PM to me and I'll have a look at it ?

You are probably missing a few of my custom functions ...
Thank you so much for the help! Everything is running smooth as silk now. I looked at my logs and found the number of spam reduced to almost nothing and 0 virus messages. I've been getting slammed this past week by some bot spam including many with viruses. Now my logs are super clean. The wait thing is really ingenious.

Thanks a million!

Goodsie
New user
New user
Posts: 5
Joined: 2018-12-12 21:13

Re: Script to block or allow country connections

Post by Goodsie » 2018-12-12 21:14

I too require the missing 'wait' function.

Soren?

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

Re: Script to block or allow country connections

Post by mattg » 2018-12-12 23:22

A search of 'wait' by author SorenR turned up 64 responses
Here's one >> http://www.hmailserver.com/forum/viewto ... it#p208249
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: Script to block or allow country connections

Post by SorenR » 2018-12-13 01:50

Due to popular demand... :mrgreen:

Un-comment the line that works for you. They are all Windows, only different versions :roll:

Code: Select all

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

Goodsie
New user
New user
Posts: 5
Joined: 2018-12-12 21:13

Re: Script to block or allow country connections

Post by Goodsie » 2018-12-13 15:14

Thanks so much :)

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

Re: Script to block or allow country connections

Post by palinka » 2019-04-29 00:44

I'm getting a lot of these errors lately. LOTS.

Code: Select all

"ERROR"	10208	"2019-04-28 17:58:17.289"	"Script Error: Source: Microsoft VBScript runtime error - Error: 800A000D - Description: Type mismatch: 'Test' - Line: 46 Column: 6 - Code: (null)"
This relates to OnClientConnect. I looked in the log and picked one "test mismatch", put the IP into the url and got a 404 error with lots of null results.

Code: Select all

http://www.geoplugin.net/json.gp?ip=141.98.80.33

{
  "geoplugin_request":"141.98.80.33",
  "geoplugin_status":404,
  "geoplugin_delay":"1ms",
  "geoplugin_credit":"Some of the returned data includes GeoLite data created by MaxMind, available from <a href='http:\/\/www.maxmind.com'>http:\/\/www.maxmind.com<\/a>.",
  "geoplugin_city":null,
  "geoplugin_region":null,
  "geoplugin_regionCode":null,
  "geoplugin_regionName":null,
  "geoplugin_areaCode":null,
  "geoplugin_dmaCode":null,
  "geoplugin_countryCode":null,
  "geoplugin_countryName":null,
  "geoplugin_inEU":0,
  "geoplugin_euVATrate":false,
  "geoplugin_continentCode":null,
  "geoplugin_continentName":null,
  "geoplugin_latitude":null,
  "geoplugin_longitude":null,
  "geoplugin_locationAccuracyRadius":null,
  "geoplugin_timezone":null,
  "geoplugin_currencyCode":null,
  "geoplugin_currencySymbol":null,
  "geoplugin_currencySymbol_UTF8":"",
  "geoplugin_currencyConverter":0
}


Looks like geoplugin.net is having some issues. I googled for another geo ip finder, picked the first one on the list, put the same IP and got a proper result.

Code: Select all

http://ip-api.com/json/141.98.80.33

{
	"as":"AS43350 NForce Entertainment B.V."
	"city":"Amsterdam"
	"country":"Netherlands"
	"countryCode":"NL"
	"isp":"NForce Entertainment B.V."
	"lat":52.3702
	"lon":4.89517
	"org":"Cloud CDN"
	"query":"141.98.80.33"
	"region":"NH"
	"regionName":"North Holland"
	"status":"success"
	"timezone":"Europe/Amsterdam"
	"zip":"1012"
}
Looks like its time for a new api. The one I used doesn't give continent info, but I could probably find one.

By the way, the IP in the example is NL in some locators and Panama in others. Weird.

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

Re: Script to block or allow country connections

Post by palinka » 2019-04-29 00:51

Found one that allows 30,000 lookups per month and returns continent code as well as country code.

Code: Select all

https://ipapi.co/141.98.80.33/json
{
    "ip": "141.98.80.33",
    "city": "Amsterdam",
    "region": "North Holland",
    "region_code": "NH",
    "country": "NL",
    "country_name": "Netherlands",
    "continent_code": "EU",
    "in_eu": true,
    "postal": "1019",
    "latitude": 52.3734,
    "longitude": 4.9388,
    "timezone": "Europe/Amsterdam",
    "utc_offset": "+0200",
    "country_calling_code": "+31",
    "currency": "EUR",
    "languages": "nl-NL,fy-NL",
    "asn": "AS43350",
    "org": "NForce Entertainment B.V."
}

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

Re: Script to block or allow country connections

Post by palinka » 2019-04-29 04:13

I didn't think about the rate limit before I posted. After I looked at my logs, I think 30k/month is a little too low for me and probably very low for most. I couldn't find one with a reasonable limit that offered continent codes - which would have been a drop in replacement in the script. So I went with one that offers country codes. However, I had to flip the script (heh..) because banning most of the world would make the list of countries unbearably long. So I changed it to the list being countries accepted.

From ip-api.com's website:
How many requests can I do?

The limit is 150 requests per minute from an IP address. If you go over this limit your IP address will be blackholed. You can unban here.
If you need unlimited queries, please see our pro service.

Do I need an API key for the free endpoint?

Nope! We will never require an API key, and our API schema will not change.
Looks like a good alternative. So far its working without throwing errors for the past hour or so.

Code: Select all

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

  
   ' Filter out "impatient" servers. Alternative to GreyListing.
   '
   If (oClient.Port = 25) Then Wait(20)

   Dim ReturnCode, Json, oGeoip, oXML, strPort, strBase
   strPort = Trim(Mid("SMTP POP  IMAP SMTPSSUBM IMAPSPOPS ", InStr("25   110  143  465  587  993  995  ", oClient.Port), 5))
   Set Json = New VbsJson

   On Error Resume Next
   Set oXML = CreateObject ("Msxml2.XMLHTTP.3.0")
   oXML.Open "GET", "https://ip-api.com/json/" & oClient.IPAddress, False
   oXML.Send
   Set oGeoip = Json.Decode(oXML.responseText)
   ReturnCode = oXML.Status
   On Error Goto 0

   If (ReturnCode <> 200 ) Then
      EventLog.Write("<OnClientConnect.error> ipapi.com lookup failed, error code: " & ReturnCode & " on IP address " & oClient.IPAddress)
      Exit Sub
   End If

   ' Only countries we want connecting to our server ... Check Alpha-2 Code here -> https://en.wikipedia.org/wiki/ISO_3166-1
   '
   strBase = "^(US)$|^(CA)$|^(GB)$|^(BE)$|^(DK)$|^(FR)$|^(GR)$|^(GL)$|^(IS)$|^(IE)$|^(IT)$|^(LI)$|^(NO)$|^(PL)$|^(PT)$|^(RO)$|^(SK)$|^(SI)$|^(ES)$|^(SE)$"
   If Lookup(strBase, oGeoip("countryCode")) Then
      Result.Value = 0
	  EventLog.Write(strPort & " Connection accepted" & Chr(34) & vbTab & oClient.IPAddress & vbTab & Chr(34) & oGeoip("countryCode") & Chr(34) & vbTab & Chr(34) & oGeoip("country") & Chr(34))
      Exit Sub
   Else
      Result.Value = 1
      EventLog.Write(strPort & " Connection REJECTED" & Chr(34) & vbTab & oClient.IPAddress & vbTab & Chr(34) & oGeoip("countryCode") & Chr(34) & vbTab & Chr(34) & oGeoip("country") & Chr(34))
   End If

End Sub

Pompz88
New user
New user
Posts: 9
Joined: 2018-07-03 03:04

Re: Script to block or allow country connections

Post by Pompz88 » 2019-06-20 05:06

Hi, I'm trying to get this script working but keep getting the following error:

Code: Select all

"ERROR"	2808	"2019-06-20 05:03:38.122"	"Script Error: Source: Microsoft VBScript runtime error - Error: 800A01FA - Description: Class not defined: 'VbsJson' - Line: 54 Column: 3 - Code: (null)"
"ERROR"	2788	"2019-06-20 05:03:38.123"	"Script Error: Source: Microsoft VBScript runtime error - Error: 800A01FA - Description: Class not defined: 'VbsJson' - Line: 54 Column: 3 - Code: (null)"
"ERROR"	2780	"2019-06-20 05:03:38.124"	"Script Error: Source: Microsoft VBScript runtime error - Error: 800A01FA - Description: Class not defined: 'VbsJson' - Line: 54 Column: 3 - Code: (null)"
"ERROR"	2784	"2019-06-20 05:04:56.113"	"Script Error: Source: Microsoft VBScript runtime error - Error: 800A01FA - Description: Class not defined: 'VbsJson' - Line: 54 Column: 3 - Code: (null)"
Linne 54 of my code is:

Code: Select all

Set Json = New VbsJson
I was originally using SorenR updated code, but ran into the same error. So switch to code palinka posted which only allows specified countries instead of blocking specified countries as it was the same method I had already been running. Any help would be greatly appreciated.

Full code is:

Code: Select all

   Include("C:\hMailServer\Events\VbsJson.vbs")
   
   Function Wait(sec)
   With CreateObject("WScript.Shell")
      .Run "timeout /T " & Int(sec), 0, True
'     .Run "sleep -m " & Int(sec * 1000), 0, True
'     .Run "powershell Start-Sleep -Milliseconds " & Int(sec * 1000), 0, True
   End With
End Function

   Function Include(sInstFile)
      Dim f, s, oFSO
      Set oFSO = CreateObject("Scripting.FileSystemObject")
      On Error Resume Next
      If oFSO.FileExists(sInstFile) Then
         Set f = oFSO.OpenTextFile(sInstFile)
         s = f.ReadAll
         f.Close
         ExecuteGlobal s
      End If
      On Error Goto 0
      Set f = Nothing
      Set oFSO = Nothing
   End Function
   
   Function Lookup(strBase, strMatch)
      With CreateObject("VBScript.RegExp")
         .IgnoreCase = True
         .Global = False
         .Pattern = strBase
         If .Test(strMatch) Then
            Lookup = True
         Else
            Lookup = False
         End If
      End With
   End Function

   Sub OnClientConnect(oClient)
      If (Left(oClient.IPAddress, 10) = "192.168.0.") Then Exit Sub
      If (oClient.Port = 25) Then Wait(20)
      Dim ReturnCode, Json, oGeoip, oXML, strPort, strBase
      strPort = Mid("SMTP IMAP SMTPSSUBM IMAPS", InStr("25   143  465  587  993  ", oClient.Port), 5)
      Set Json = New VbsJson
      On Error Resume Next
      Set oXML = CreateObject ("Msxml2.XMLHTTP.3.0")
      oXML.Open "GET", "http://www.geoplugin.net/json.gp?ip=" & oClient.IPAddress, False
      oXML.Send
      Set oGeoip = Json.Decode(oXML.responseText)
      ReturnCode = oXML.Status
      On Error Goto 0
      If (ReturnCode <> 200 ) Then
         EventLog.Write("<OnClientConnect.error> www.geoplugin.net lookup failed, error code: " & ReturnCode & " on IP address " & oClient.IPAddress)
         Exit Sub
      End If
      strBase = "^(AS)$|^(AF)$|^(AN)$|^(OC)$|^(SA)$"
      If Lookup(strBase, oGeoip("geoplugin_continentCode")) Then
         Result.Value = 1
         EventLog.Write(strPort & " Connection REJECTED" & Chr(34) & vbTab & oClient.IPAddress & vbTab & Chr(34) & oGeoip("geoplugin_countryCode") & Chr(34) & vbTab & Chr(34) & oGeoip("geoplugin_countryName") & Chr(34) & vbTab & Chr(34) & oGeoip("geoplugin_continentCode"))
         Exit Sub
      End If
      strBase = "^(BY)$|^(CR)$|^(CZ)$|^(DO)$|^(GP)$|^(LT)$|^(LV)$|^(MD)$|^(MX)$|^(PA)$|^(PL)$|^(RO)$|^(RS)$|^(RU)$|^(SV)$|^(UA)$"
      If Lookup(strBase, oGeoip("geoplugin_countryCode")) Then
         Result.Value = 1
         EventLog.Write(strPort & " Connection REJECTED" & Chr(34) & vbTab & oClient.IPAddress & vbTab & Chr(34) & oGeoip("geoplugin_countryCode") & Chr(34) & vbTab & Chr(34) & oGeoip("geoplugin_countryName") & Chr(34) & vbTab & Chr(34) & oGeoip("geoplugin_continentCode"))
         Exit Sub
      End If
      EventLog.Write(strPort & " Connection accepted" & Chr(34) & vbTab & oClient.IPAddress & vbTab & Chr(34) & oGeoip("geoplugin_countryCode") & Chr(34) & vbTab & Chr(34) & oGeoip("geoplugin_countryName") & Chr(34) & vbTab & Chr(34) & oGeoip("geoplugin_continentCode"))
   End Sub

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

Re: Script to block or allow country connections

Post by palinka » 2019-06-20 10:52

Are you using the latest vbsjson.vbs?

https://github.com/wqweto/VbsJson/blob/ ... bsJson.vbs

Is this a valid path? It's not the default events folder location.
"C:\hMailServer\Events\VbsJson.vbs"

Try moving this line:
Include("C:\hMailServer\Events\VbsJson.vbs")
Inside the sub

Code: Select all

Sub OnClientConnect(oClient)
      Include("C:\hMailServer\Events\VbsJson.vbs") '<<< make sure it's a valid path
      If (Left(oClient.IPAddress, 10) = "192.168.0.") Then Exit Sub
      If (oClient.Port = 25) Then Wait(20)
      Dim ReturnCode, Json, oGeoip
      Etc...

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

Re: Script to block or allow country connections

Post by jimimaseye » 2019-06-20 12:07

FYI, mine is set like this:

Code: Select all

Sub OnClientConnect(oClient)
   If Lookup("127\.0\.0\.1|192\.168\." , oClient.ipaddress) = False then
      If (oClient.Port = 25) Then call wait(20)  ' Create a 20 second pause on connection to disuade spam connections
      Call GeoAutoban(oClient)       ' <<--- separate function for only when its needed
   End if
End Sub

Function GeoAutoban(oClient)
   If (oClient.Port <> 25) then
      Dim strRegEx
      Dim obApp : Set obApp = CreateObject("hMailServer.Application")
      Call obApp.Authenticate("Administrator", "secret")
      Include(obApp.Settings.Directories.EventDirectory & "\VbsJson.vbs")     <<---- it lives in the events directory whereever the environment points to it, and is only called when required
      .
      .
      .
   End If
End Function
      
ITs all included within functions within the subs therefore only called when needed.
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

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

Re: Script to block or allow country connections

Post by palinka » 2019-06-20 12:29

jimimaseye wrote:
2019-06-20 12:07
FYI, mine is set like this:

Code: Select all

Sub OnClientConnect(oClient)
   If Lookup("127\.0\.0\.1|192\.168\." , oClient.ipaddress) = False then
      If (oClient.Port = 25) Then call wait(20)  ' Create a 20 second pause on connection to disuade spam connections
      Call GeoAutoban(oClient)       ' <<--- separate function for only when its needed
   End if
End Sub

Function GeoAutoban(oClient)
   If (oClient.Port <> 25) then
      Dim strRegEx
      Dim obApp : Set obApp = CreateObject("hMailServer.Application")
      Call obApp.Authenticate("Administrator", "secret")
      Include(obApp.Settings.Directories.EventDirectory & "\VbsJson.vbs")     <<---- it lives in the events directory whereever the environment points to it, and is only called when required
      .
      .
      .
   End If
End Function
      
.
FIREWALL BAN those suckers!

Call FWBan(oClient.IPAddress, "GeoIP")

:mrgreen:

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

Re: Script to block or allow country connections

Post by jimimaseye » 2019-06-20 12:47

palinka wrote:
2019-06-20 12:29
FIREWALL BAN those suckers!

Call FWBan(oClient.IPAddress, "GeoIP")

:mrgreen:
Dont need to. Banning at delivery request is sufficient for the amount I get. And I dont want to just fill the Firewall block list with non-expiring ip addresses.



Code: Select all

5012	"2019-06-14 00:00:04.219"	"status:200--sm587	162.243.144.193	US	United States"
1568	"2019-06-14 06:56:41.173"	"status:200--IMAP	162.243.149.170	US	United States"
1864	"2019-06-14 16:21:59.080"	"status:200--IMAP	77.123.33.154	UA	Ukraine"
1776	"2019-06-14 22:07:36.040"	"status:200--sm587	185.137.111.129	IR	Iran"
1776	"2019-06-14 23:22:12.983"	"status:200--sm587	208.100.26.235	US	United States"
1776	"2019-06-15 00:01:09.602"	"status:200--sm587	162.243.144.216	US	United States"
3568	"2019-06-15 05:36:07.819"	"status:200--IMAP	196.52.43.53	US	United States"
3568	"2019-06-15 07:12:39.329"	"status:200--IMAP	111.206.52.81	CN	China"
3568	"2019-06-15 07:12:39.782"	"status:200--IMAP	111.206.52.101	CN	China"
1776	"2019-06-16 00:04:19.551"	"status:200--sm587	107.170.202.91	US	United States"
1776	"2019-06-16 03:24:51.368"	"status:200--sm587	108.178.61.58	US	United States"
3892	"2019-06-16 13:50:59.276"	"status:200--IMAP	198.108.66.96	US	United States"
1776	"2019-06-16 20:30:04.585"	"status:200--sm587	103.89.90.197	VN	Vietnam"
1776	"2019-06-16 21:18:46.970"	"status:200--sm587	185.100.87.248	RO	Romania"
3296	"2019-06-16 21:54:21.974"	"status:200--IMAP	107.170.195.35	US	United States"
1776	"2019-06-17 00:05:18.600"	"status:200--sm587	192.241.226.16	US	United States"
1776	"2019-06-17 18:43:44.941"	"status:200--sm587	187.1.20.37		BR	Brazil"
4900	"2019-06-18 00:09:35.707"	"status:200--sm587	162.243.149.151	US	United States"
548	"2019-06-18 05:08:38.858"	"status:200--IMAP	89.248.174.161	SC	Seychelles"
1096	"2019-06-18 12:29:42.948"	"status:200--IMAP	80.82.77.33		SC	Seychelles"
4900	"2019-06-18 16:54:33.728"	"status:200--sm587	71.6.232.4		US	United States"
4900	"2019-06-18 16:59:53.201"	"status:200--sm587	178.73.215.171	SE	Sweden"
4900	"2019-06-18 18:56:13.730"	"status:200--IMAP	34.76.114.54	US	United States"
2804	"2019-06-19 00:09:13.558"	"status:200--sm587	162.243.144.152	US	United States"
2804	"2019-06-19 01:19:34.520"	"status:200--sm587	104.152.52.37	US	United States"
2804	"2019-06-19 05:58:42.959"	"status:200--sm587	141.98.80.54				"
3464	"2019-06-19 07:23:42.795"	"status:200--IMAP	162.243.148.46	US	United States"
2804	"2019-06-19 12:25:08.172"	"status:200--sm587	37.113.61.232	RU	Russia"
4688	"2019-06-19 13:25:03.962"	"status:200--IMAP	196.52.43.122	US	United States"
4188	"2019-06-19 18:50:42.139"	"status:200--IMAP	107.170.196.87	US	United States"
4488	"2019-06-19 19:11:15.945"	"status:200--sm587	192.241.204.70	US	United States"
2840	"2019-06-20 00:12:12.025"	"status:200--sm587	107.170.238.143	US	United States"
2840	"2019-06-20 07:23:22.954"	"status:200--sm587	125.64.94.220	CN	China"
Not many over 5 days.
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

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

Re: Script to block or allow country connections

Post by palinka » 2019-06-20 13:08

jimimaseye wrote:
2019-06-20 12:47

Dont need to. Banning at delivery request is sufficient for the amount I get. And I dont want to just fill the Firewall block list with non-expiring ip addresses.



Code: Select all

5012	"2019-06-14 00:00:04.219"	"status:200--sm587	162.243.144.193	US	United States"
1568	"2019-06-14 06:56:41.173"	"status:200--IMAP	162.243.149.170	US	United States"
1864	"2019-06-14 16:21:59.080"	"status:200--IMAP	77.123.33.154	UA	Ukraine"
1776	"2019-06-14 22:07:36.040"	"status:200--sm587	185.137.111.129	IR	Iran"
1776	"2019-06-14 23:22:12.983"	"status:200--sm587	208.100.26.235	US	United States"
1776	"2019-06-15 00:01:09.602"	"status:200--sm587	162.243.144.216	US	United States"
3568	"2019-06-15 05:36:07.819"	"status:200--IMAP	196.52.43.53	US	United States"
3568	"2019-06-15 07:12:39.329"	"status:200--IMAP	111.206.52.81	CN	China"
3568	"2019-06-15 07:12:39.782"	"status:200--IMAP	111.206.52.101	CN	China"
1776	"2019-06-16 00:04:19.551"	"status:200--sm587	107.170.202.91	US	United States"
1776	"2019-06-16 03:24:51.368"	"status:200--sm587	108.178.61.58	US	United States"
3892	"2019-06-16 13:50:59.276"	"status:200--IMAP	198.108.66.96	US	United States"
1776	"2019-06-16 20:30:04.585"	"status:200--sm587	103.89.90.197	VN	Vietnam"
1776	"2019-06-16 21:18:46.970"	"status:200--sm587	185.100.87.248	RO	Romania"
3296	"2019-06-16 21:54:21.974"	"status:200--IMAP	107.170.195.35	US	United States"
1776	"2019-06-17 00:05:18.600"	"status:200--sm587	192.241.226.16	US	United States"
1776	"2019-06-17 18:43:44.941"	"status:200--sm587	187.1.20.37		BR	Brazil"
4900	"2019-06-18 00:09:35.707"	"status:200--sm587	162.243.149.151	US	United States"
548	"2019-06-18 05:08:38.858"	"status:200--IMAP	89.248.174.161	SC	Seychelles"
1096	"2019-06-18 12:29:42.948"	"status:200--IMAP	80.82.77.33		SC	Seychelles"
4900	"2019-06-18 16:54:33.728"	"status:200--sm587	71.6.232.4		US	United States"
4900	"2019-06-18 16:59:53.201"	"status:200--sm587	178.73.215.171	SE	Sweden"
4900	"2019-06-18 18:56:13.730"	"status:200--IMAP	34.76.114.54	US	United States"
2804	"2019-06-19 00:09:13.558"	"status:200--sm587	162.243.144.152	US	United States"
2804	"2019-06-19 01:19:34.520"	"status:200--sm587	104.152.52.37	US	United States"
2804	"2019-06-19 05:58:42.959"	"status:200--sm587	141.98.80.54				"
3464	"2019-06-19 07:23:42.795"	"status:200--IMAP	162.243.148.46	US	United States"
2804	"2019-06-19 12:25:08.172"	"status:200--sm587	37.113.61.232	RU	Russia"
4688	"2019-06-19 13:25:03.962"	"status:200--IMAP	196.52.43.122	US	United States"
4188	"2019-06-19 18:50:42.139"	"status:200--IMAP	107.170.196.87	US	United States"
4488	"2019-06-19 19:11:15.945"	"status:200--sm587	192.241.204.70	US	United States"
2840	"2019-06-20 00:12:12.025"	"status:200--sm587	107.170.238.143	US	United States"
2840	"2019-06-20 07:23:22.954"	"status:200--sm587	125.64.94.220	CN	China"
Not many over 5 days.
They can expire if you set them to. I currently have mine set to not expire (for geoip only), but i think I'll probably change that after i get ONE MILLION BANS! :mrgreen: LOL, but seriously, if it ever starts causing performance issues then I'll start releasing them. At this point i don't know where that number might be. But yes, they can be programmatically expired in my script.

And you have a VERY short list. You must have some other extensive filtering before it reaches your geoip filter. I ban hundreds a day. Im sure that's partly due to the geoip being my first filter in sequence.

When i autobanned geoip (7 days expire), i had an autoban list that held steady around 2,000 entries. The only performance issue i had was opening ip ranges to look, or opening the ip ranges on the phpwebadmin since it loaded all of them in a single page. Otherwise i didn't really notice any other performance hits.

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

Re: Script to block or allow country connections

Post by jimimaseye » 2019-06-20 13:36

palinka wrote:
2019-06-20 13:08
They can expire if you set them to. I currently have mine set to not expire (for geoip only), but i think I'll probably change that after i get ONE MILLION BANS! :mrgreen: LOL, but seriously, if it ever starts causing performance issues then I'll start releasing them. At this point i don't know where that number might be. But yes, they can be programmatically expired in my script.

And you have a VERY short list. You must have some other extensive filtering before it reaches your geoip filter. I ban hundreds a day. Im sure that's partly due to the geoip being my first filter in sequence.

When i autobanned geoip (7 days expire), i had an autoban list that held steady around 2,000 entries. The only performance issue i had was opening ip ranges to look, or opening the ip ranges on the phpwebadmin since it loaded all of them in a single page. Otherwise i didn't really notice any other performance hits.
I dont AUTOBAN them from Geoip lookup - I simply reject them. Looking through the list there are very few repeat offenders which would mean that adding the address to Autoban list would be a waste of time and resources. And, after all, if they do come back again they will get dumped again!

Shortlist: the main (probable) difference between my server and yours is that I dont have public facing MX records pointing to it in DNS. Therefore I am not an obvious Mailserver open to t'internet and as such I dont get so many spambots targetting me. I have proven that if I make an MX record to point to it then I do get targetted like everyone else.
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

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

Re: Script to block or allow country connections

Post by palinka » 2019-06-20 14:10

jimimaseye wrote:
2019-06-20 13:36
Shortlist: the main (probable) difference between my server and yours is that I dont have public facing MX records pointing to it in DNS. Therefore I am not an obvious Mailserver open to t'internet and as such I dont get so many spambots targetting me. I have proven that if I make an MX record to point to it then I do get targetted like everyone else.
How do you receive mail? Through a relay? POP3 from another mta?

I'm a spam target for sure. But lately I've been receiving almost 0 spam. I've had several days recently where I've received 0 spam messages. So thank you for that! And also thanks especially to Soren and Matt too for helping me achieve a spam free lifestyle. :mrgreen:

As to why ban IPs to the firewall? Why did Hilary climb Everest? Why did Columbus sail the ocean blue? Maybe it's proof of concept. Maybe it's just fun to ban spammers as harshly as I'm able. :mrgreen:

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

Re: Script to block or allow country connections

Post by jimimaseye » 2019-06-20 14:42

palinka wrote:
2019-06-20 14:10
How do you receive mail? Through a relay? POP3 from another mta?
Via POP3 every 1 minute.

Front end mail server (with Spamsassin) provided by web host receives the mail.

I then POP it and run it through my own spamassassin with my own tighter rules and scoring (mail held on host server for 30 days retention)

Benefit:
1, Mail host gets the spambot sniffing (due to being MX)

2, double spam checking (majority of the REALLY shit obvious stuff gets dumped by them)
2b, if my spamassassin is down then I still have some spamassassin scoring headers in the email for my rules to work with

3a, if my server goes down then the mail is still being received by host (contingency and disaster recovery) awaiting me to collect it when my server is back up
3b, email clients can be redirected to host server in the event of disaster whilst hmailserver is repaired if needed

4, I can use or target my mailserver directly by address behind the A record of a different company address if I want. ie, user@company.ddnshost.net (instead of company.co.uk which is the official domain) where company.ddnshost.net is an alias of company.co.uk in my setup. (this is good so I dont have to wait up to 1 minute for deliveries when Im sending in test emails).
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
SorenR
Senior user
Senior user
Posts: 3154
Joined: 2006-08-21 15:38
Location: Denmark

Re: Script to block or allow country connections

Post by SorenR » 2019-06-20 15:07

jimimaseye wrote:
2019-06-20 14:42
palinka wrote:
2019-06-20 14:10
How do you receive mail? Through a relay? POP3 from another mta?
Via POP3 every 1 minute.

Front end mail server (with Spamsassin) provided by web host receives the mail.

I then POP it and run it through my own spamassassin with my own tighter rules and scoring (mail held on host server for 30 days retention)

Benefit:
1, Mail host gets the spambot sniffing (due to being MX)

2, double spam checking (majority of the REALLY shit obvious stuff gets dumped by them)
2b, if my spamassassin is down then I still have some spamassassin scoring headers in the email for my rules to work with

3a, if my server goes down then the mail is still being received by host (contingency and disaster recovery) awaiting me to collect it when my server is back up
3b, email clients can be redirected to host server in the event of disaster whilst hmailserver is repaired if needed


4, I can use or target my mailserver directly by address behind the A record of a different company address if I want. ie, user@company.ddnshost.net (instead of company.co.uk which is the official domain) where company.ddnshost.net is an alias of company.co.uk in my setup. (this is good so I dont have to wait up to 1 minute for deliveries when Im sending in test emails).
That's the reason I have my Backup-MX ... Just had a 2 day blackout due to lightning and some technician messing up the wires in the local cable box. No mails lost and if I really wanted my emails I could have taken my server to a friend using the same ISP - a simple DNS update is all it takes.

Yesterday I tried for the first time (on my new development laptop) to reinstall hMailServer and restore the latest backup ... 27 minutes to restore the backup. :wink:
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.

Pompz88
New user
New user
Posts: 9
Joined: 2018-07-03 03:04

Re: Script to block or allow country connections

Post by Pompz88 » 2019-06-20 18:30

palinka wrote:
2019-06-20 10:52
Is this a valid path? It's not the default events folder location.
"C:\hMailServer\Events\VbsJson.vbs"
[/code]
Thanks palinka! It was late & I had overlooked the fact that my installation was in program files :roll:
Now the next issue :lol:

I am getting failed lookups on all IPs using ap-api. I am able to manually browse to the urls & see the data, so I know the links are correct (hidden IPs as it was me testing from my own servers)

Code: Select all

2784	"2019-06-20 18:15:21.465"	"<OnClientConnect.error> ip-api.com lookup failed, error code: 12029 on IP address ***.***.***.***"
2776	"2019-06-20 18:15:24.131"	"<OnClientConnect.error> ip-api.com lookup failed, error code: 12029 on IP address ***.***.***.***"
2784	"2019-06-20 18:18:50.140"	"<OnClientConnect.error> ip-api.com lookup failed, error code: 12029 on IP address ***.***.***.***"
2800	"2019-06-20 18:18:51.175"	"<OnClientConnect.error> ip-api.com lookup failed, error code: 12029 on IP address ***.***.***.***"
2776	"2019-06-20 18:18:52.482"	"<OnClientConnect.error> ip-api.com lookup failed, error code: 12029 on IP address ***.***.***.***"
Code is as follows:

Code: Select all

Set oXML = CreateObject ("Msxml2.XMLHTTP.3.0")
   oXML.Open "GET", "http://ip-api.com/json/" & oClient.IPAddress, False
   oXML.Send
   Set oGeoip = Json.Decode(oXML.responseText)
   ReturnCode = oXML.Status

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

Re: Script to block or allow country connections

Post by palinka » 2019-06-20 19:07

Try this.

Code: Select all

Sub OnClientConnect(oClient)
   
   ' Exclude Backup-MX & local LAN from test
   If (Left(oClient.IPAddress, 12) = "184.105.182.") Then Exit Sub
   If (Left(oClient.IPAddress, 10) = "192.168.1.") Then Exit Sub
   If oClient.IPAddress = "127.0.0.1" Then Exit Sub

   ' Filter out "impatient" servers. Alternative to GreyListing.
   'If (oClient.Port = 25) Then Wait(20)

	'	GEOIP Lookup
   Dim ReturnCode, Json, oGeoip, oXML, strPort, strBase, sMSG, sMSNumber
   Include("C:\Program Files (x86)\hMailServer\Events\VbsJson.vbs")
   strPort = Trim(Mid("SMTP POP  IMAP SMTPSSUBM IMAPSPOPS ", InStr("25   110  143  465  587  993  995  ", oClient.Port), 5))
   Set Json = New VbsJson

   On Error Resume Next
   Set oXML = CreateObject ("Msxml2.XMLHTTP.3.0")
   oXML.Open "GET", "http://ip-api.com/json/" & oClient.IPAddress, False
   oXML.Send
   Set oGeoip = Json.Decode(oXML.responseText)
   ReturnCode = oXML.Status
   On Error Goto 0

   If (ReturnCode <> 200 ) Then
      EventLog.Write("<OnClientConnect.error> ip-api.com lookup failed, error code: " & ReturnCode & " on IP address " & oClient.IPAddress)
      Exit Sub
   End If

   ' ALLOWED COUNTRIES - Port 25 only... Check Alpha-2 Code here -> https://en.wikipedia.org/wiki/ISO_3166-1
   If (oClient.Port = 25) Then
	   strBase = "^(US|CA|AT|BE|CH|CZ|DE|DK|ES|FI|FR|GB|GL|GR|HR|HU|IE|IS|IT|LI|MC|NL|NO|PL|PT|RO|RS|SE|SI|SK|SM|AU|NZ)$"
	   If Lookup(strBase, oGeoip("countryCode")) Then
	   EventLog.Write(strPort & " " & oClient.Port & " OnClientConnect Accepted GeoIP-Lookup " & oClient.IPAddress & " " & oGeoip("countryCode") & " " & oGeoip("country"))
	      Exit Sub
	   End If
   ' Disconnect all others connecting to port 25.
	   Call idsAddIP(oClient.IPAddress, oClient.Port)
	   Result.Value = 1
       Call Disconnect(oClient.IPAddress)
       Call FWBan(oClient.IPAddress, "GeoIP")
       ' Call AutoBan(oClient.IPAddress, "GeoIP - " & oClient.IpAddress, 7, "d")
	   EventLog.Write(strPort & " " & oClient.Port & " OnClientConnect REJECTED GeoIP-Lookup " & oClient.IPAddress & " " & oGeoip("countryCode") & " " & oGeoip("country"))
	   Exit Sub
   Else
   ' ALLOWED COUNTRIES - All ports except 25... Check Alpha-2 Code here -> https://en.wikipedia.org/wiki/ISO_3166-1
	   strBase = "^(US)$"
	   If Lookup(strBase, oGeoip("countryCode")) Then
		  EventLog.Write(strPort & " Port " & oClient.Port & vbTab & " Connection accepted by GeoIP Lookup" & vbTab & vbTab & Chr(34) & oClient.IPAddress & Chr(34) & vbTab & Chr(34) & oGeoip("countryCode") & Chr(34) & vbTab & Chr(34) & oGeoip("country"))
		  Exit Sub
	   End If
   ' Disconnect all others connecting to any port except 25.
	   Call idsAddIP(oClient.IPAddress, oClient.Port)
	   Result.Value = 1
       Call Disconnect(oClient.IPAddress)
       Call FWBan(oClient.IPAddress, "GeoIP")
       ' Call AutoBan(oClient.IPAddress, "GeoIP - " & oClient.IpAddress, 7, "d")
	   EventLog.Write(strPort & " Port " & oClient.Port & vbTab & " Connection REJECTED by GeoIP Lookup" & vbTab & vbTab & Chr(34) & oClient.IPAddress & Chr(34) & vbTab & Chr(34) & oGeoip("countryCode") & Chr(34) & vbTab & Chr(34) & oGeoip("country"))
	   Exit Sub
   End If
End Sub

plus you need this.

Code: Select all

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

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

Re: Script to block or allow country connections

Post by jimimaseye » 2019-06-20 19:18

Pompz88 wrote:
2019-06-20 18:30
palinka wrote:
2019-06-20 10:52
Is this a valid path? It's not the default events folder location.
"C:\hMailServer\Events\VbsJson.vbs"
[/code]
Thanks palinka! It was late & I had overlooked the fact that my installation was in program files :roll:
As i said above:
jimimaseye wrote:
2019-06-20 12:07
FYI, mine is set like this:

Code: Select all

      Include(obApp.Settings.Directories.EventDirectory & "\VbsJson.vbs")     <<---- it lives in the events directory whereever the environment points to it
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

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

Re: Script to block or allow country connections

Post by palinka » 2019-06-21 11:20

Pompz88 wrote:
2019-06-20 18:30
I am getting failed lookups on all IPs using ap-api. I am able to manually browse to the urls & see the data, so I know the links are correct (hidden IPs as it was me testing from my own servers)

Code: Select all

2784	"2019-06-20 18:15:21.465"	"<OnClientConnect.error> ip-api.com lookup failed, error code: 12029 on IP address ***.***.***.***"
2776	"2019-06-20 18:15:24.131"	"<OnClientConnect.error> ip-api.com lookup failed, error code: 12029 on IP address ***.***.***.***"
2784	"2019-06-20 18:18:50.140"	"<OnClientConnect.error> ip-api.com lookup failed, error code: 12029 on IP address ***.***.***.***"
2800	"2019-06-20 18:18:51.175"	"<OnClientConnect.error> ip-api.com lookup failed, error code: 12029 on IP address ***.***.***.***"
2776	"2019-06-20 18:18:52.482"	"<OnClientConnect.error> ip-api.com lookup failed, error code: 12029 on IP address ***.***.***.***"
Starting at 22:13 Zulu last night I started getting the same thing.

Code: Select all

13440	"2019-06-20 22:13:25.633"	"<OnClientConnect.error> ip-api.com lookup failed, error code: 12002 on IP address 94.23.196.177"
8596	"2019-06-20 22:13:25.633"	"<OnClientConnect.error> ip-api.com lookup failed, error code: 12029 on IP address 94.23.196.177"
8596	"2019-06-20 22:20:01.102"	"<OnClientConnect.error> ip-api.com lookup failed, error code: 12029 on IP address 117.4.101.26"
8596	"2019-06-20 22:46:41.727"	"<OnClientConnect.error> ip-api.com lookup failed, error code: 12029 on IP address 209.119.0.170"
3716	"2019-06-20 22:48:11.258"	"<OnClientConnect.error> ip-api.com lookup failed, error code: 12029 on IP address 45.227.253.210"

Right before that I got hammered with a ton of connections from 94.23.196.177 in France. It worked up to about 75 requests in a row then the errors came and since then it has not worked at all.

ip-api.com has a rate limit of 150/minute so I figured that was it. ( http://ip-api.com/docs/unban ) Nope. I tried to unban my IP and got "Error: IP XXX.MY.IP.XXX is not banned".

I searched the interwebs for the error codes and found this page: https://support.microsoft.com/en-us/hel ... ough-12156

Code: Select all

   Code        Error Message and Description
   -----       -----------------------------
   12002       ERROR_INTERNET_TIMEOUT
               The request has timed out.

   12029       ERROR_INTERNET_CANNOT_CONNECT
               The attempt to connect to the server failed.
Of the errors, all but the very first one are 12029. There are lots more in the log through right now. They're all the same and no point to post them all.

I'm stumped. I don't know where to look to figure this out.

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

Re: Script to block or allow country connections

Post by palinka » 2019-06-21 11:57

Pompz88 wrote:
2019-06-20 18:30
I am getting failed lookups on all IPs using ap-api.
Update - Its working now. I guess I was banned from ip-api.com after all. Even though I got an error saying I was not banned, miraculously(!) it started working again after I attempted to unban myself. I'm going to keep an eye on it, but it appears that was my problem.

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

Re: Script to block or allow country connections

Post by jimimaseye » 2019-06-21 15:06

I dont know why you changed the Geo-lookup service to your new one (ip-api).

I sill use the original (geoplugin):

Code: Select all

      With CreateObject("Msxml2.ServerXMLHTTP.6.0")
         .Open "GET", "http://www.geoplugin.net/json.gp?ip=" & oClient.IPAddress, False
         .Send
         Set oGeoip = Json.Decode(.responseText)
         If (.Status = 200 ) Then
and still get results.
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

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

Re: Script to block or allow country connections

Post by palinka » 2019-06-21 19:04

jimimaseye wrote:
2019-06-21 15:06
I dont know why you changed the Geo-lookup service to your new one (ip-api).

I sill use the original (geoplugin):

Code: Select all

      With CreateObject("Msxml2.ServerXMLHTTP.6.0")
         .Open "GET", "http://www.geoplugin.net/json.gp?ip=" & oClient.IPAddress, False
         .Send
         Set oGeoip = Json.Decode(.responseText)
         If (.Status = 200 ) Then
and still get results.
I was getting a lot of "type: mismatch" errors for null responses. I finally figured out the null responses were not connection errors but actually a json response with no information. I confirmed that by manually trying out a few IPs that returned null results. Apparently they don't update their database often enough.

You might not even notice with the very low volume of geoip requests you handle. But with hundreds a day, I was getting a lot of errors - like 50 or more per day after a while. That's why I switched. And I haven't had a single null response from ip-api.com. I haven't had any issues at all until last night when some joker in France bombarded me with over 75 requests in under a minute. Each instance of connection from this jerk called geoip twice: once at onclientconnect and once when my firewall ban was called due to his IP being listed on spamhaus. 75x2=150 requests in less than a minute = RATE LIMITED. That's a very particular and rare occurance. I have never seen DOS style attack like that before. He's firewall blocked now anyway.

Pompz88
New user
New user
Posts: 9
Joined: 2018-07-03 03:04

Re: Script to block or allow country connections

Post by Pompz88 » 2019-06-21 19:18

palinka wrote:
2019-06-21 11:57
Pompz88 wrote:
2019-06-20 18:30
I am getting failed lookups on all IPs using ap-api.
Update - Its working now. I guess I was banned from ip-api.com after all. Even though I got an error saying I was not banned, miraculously(!) it started working again after I attempted to unban myself. I'm going to keep an eye on it, but it appears that was my problem.
Mine was the same problem. But I was impatient and found a different one to use. extreme-ip-lookup.com is doing the job for me right now. Its limited to 50 requests a minute that that's enough for me.

The previous method I used only logged rejected connections. Now that I'm logging all connections, I'm seeing a lot of spam requests from countries on my safe list. Its an insight for sure. Also noticed Microsoft uses some servers in locations I don't allow. So I've been slowly adding to the script to allow certain ISPs like Microsoft/Google etc and then block others. Fara Negar Pardaz Noor Khuzestan Co.JSP is a real bad one currently. It looks like an Iranian provider using IPs that resolve to US/NL (they're on my good list). So its nice to block those requests that I previously wasn't aware of.

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

Re: Script to block or allow country connections

Post by palinka » 2019-06-21 20:05

Pompz88 wrote:
2019-06-21 19:18
Also noticed Microsoft uses some servers in locations I don't allow. So I've been slowly adding to the script to allow certain ISPs like Microsoft/Google etc and then block others. Fara Negar Pardaz Noor Khuzestan Co.JSP is a real bad one currently. It looks like an Iranian provider using IPs that resolve to US/NL (they're on my good list). So its nice to block those requests that I previously wasn't aware of.
Please share! :mrgreen:

Pompz88
New user
New user
Posts: 9
Joined: 2018-07-03 03:04

Re: Script to block or allow country connections

Post by Pompz88 » 2019-06-21 20:20

Code: Select all

	If (oGeoip("org") = "Fara Negar Pardaz Noor Khuzestan Co.JSP") Then
      Result.Value = 1
	  EventLog.Write(strPort & " Connection REJECTED - Bad ISP" & Chr(34) & vbTab & oClient.IPAddress & vbTab & Chr(34) & oGeoip("countryCode") & Chr(34) & vbTab & Chr(34) & oGeoip("country") & Chr(34) & vbTab & Chr(34) & oGeoip("org") & Chr(34))
	  Exit Sub
	ElseIf (Left(oClient.IPAddress, 12) = "185.137.111.") Then
	  Result.Value = 1
	  EventLog.Write(strPort & " Connection REJECTED - Bad IP Range" & Chr(34) & vbTab & oClient.IPAddress & vbTab & Chr(34) & oGeoip("countryCode") & Chr(34) & vbTab & Chr(34) & oGeoip("country") & Chr(34) & vbTab & Chr(34) & oGeoip("org") & Chr(34))
      Exit Sub
	End If
	  
	strBase = "^(DE)$|^(US)$|^(CA)$|^(GB)$|^(LH)$|^(LN)$|^(IE)$|^(AU)$|^(CH)$|^(LI)$"  
   If lookup(strBase, oGeoip("countryCode")) Then
      Result.Value = 0
      EventLog.Write(strPort & " Connection accepted" & Chr(34) & vbTab & oClient.IPAddress & vbTab & Chr(34) & oGeoip("countryCode") & Chr(34) & vbTab & Chr(34) & oGeoip("country") & Chr(34) & vbTab & Chr(34) & oGeoip("org") & Chr(34))
      Exit Sub

   ElseIf (oGeoip("org") = "Microsoft Corporation") Then
	  Result.Value = 0
	  EventLog.Write(strPort & " Connection accepted" & Chr(34) & vbTab & oClient.IPAddress & vbTab & Chr(34) & oGeoip("countryCode") & Chr(34) & vbTab & Chr(34) & oGeoip("country") & Chr(34) & vbTab & Chr(34) & oGeoip("org") & Chr(34))
	  Exit Sub

   ElseIf (oGeoip("org") = "Google LLC") Then
	  Result.Value = 0
	  EventLog.Write(strPort & " Connection accepted" & Chr(34) & vbTab & oClient.IPAddress & vbTab & Chr(34) & oGeoip("countryCode") & Chr(34) & vbTab & Chr(34) & oGeoip("country") & Chr(34) & vbTab & Chr(34) & oGeoip("org") & Chr(34))
	Exit Sub
 
   Else
      Result.Value = 1
      EventLog.Write(strPort & " Connection REJECTED" & Chr(34) & vbTab & oClient.IPAddress & vbTab & Chr(34) & oGeoip("countryCode") & Chr(34) & vbTab & Chr(34) & oGeoip("country") & Chr(34) & Chr(34) & oGeoip("org") & Chr(34))
   End If

End Sub
Its blocking the ISP first (Fara Negar Pardaz Noor Khuzestan Co.JSP). Then blocking anything coming from 185.137.111.x.
Then I'm allowing my list of 'safe' countries.
Then allowing anything where Microsoft or Google are the ISP (Microsoft often originates from different EU countries like Finland & Netherlands where I wouldnt be expecting connections so arent on my safe list)

That results in something like this:

Code: Select all

2760	"2019-06-21 20:17:07.520"	"SUBM Connection REJECTED - Bad ISP"	185.137.111.125	"US"	"United States"	"Fara Negar Pardaz Noor Khuzestan Co.JSP""
2760	"2019-06-21 20:17:13.337"	"SUBM Connection REJECTED - Bad ISP"	185.137.111.136	"US"	"United States"	"Fara Negar Pardaz Noor Khuzestan Co.JSP""
2760	"2019-06-21 20:17:13.539"	"SUBM Connection REJECTED - Bad ISP"	185.137.111.96	"US"	"United States"	"Fara Negar Pardaz Noor Khuzestan Co.JSP""
2760	"2019-06-21 20:17:21.918"	"SUBM Connection REJECTED - Bad ISP"	185.137.111.129	"US"	"United States"	"Fara Negar Pardaz Noor Khuzestan Co.JSP""
2808	"2019-06-21 20:17:23.228"	"SMTP Connection accepted"	40.92.70.16	"NL"	"Netherlands"	"Microsoft Corporation""
2760	"2019-06-21 20:17:25.351"	"SUBM Connection REJECTED - Bad ISP"	103.231.139.130	"NL"	"Netherlands"	"Fara Negar Pardaz Noor Khuzestan Co.JSP""
2760	"2019-06-21 20:17:28.193"	"SUBM Connection REJECTED - Bad ISP"	185.137.111.125	"US"	"United States"	"Fara Negar Pardaz Noor Khuzestan Co.JSP""
2760	"2019-06-21 20:17:33.670"	"SUBM Connection REJECTED - Bad ISP"	185.137.111.136	"US"	"United States"	"Fara Negar Pardaz Noor Khuzestan Co.JSP""
2760	"2019-06-21 20:17:35.837"	"SUBM Connection REJECTED - Bad ISP"	185.137.111.96	"US"	"United States"	"Fara Negar Pardaz Noor Khuzestan Co.JSP""
Most of the Fara ISP requests come from US which is on my safe list. And the Microsoft connection comes from the Netherlands which isnt on my safe list.

Disclaimer.. I'm no expert, just always used different coding languages and often able to pick through code to figure out what's what and adapt it to my liking. But there is probably better ways of doing this.

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

Re: Script to block or allow country connections

Post by palinka » 2019-06-21 21:34

Cool. Just so you know... https://www.spamhaus.org/query/ip/185.137.111.125

There are a few scripts around here for querying spamhaus.

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

Re: Script to block or allow country connections

Post by mattg » 2019-06-22 01:52

I just use zz.countries.nerd.dk as a DNS BL

That works for me
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