hMailserver is a free Windows based email server. One of the nice features is that certain email events are available through a COM interface. In this article we use hMailserver events to check if a connection comes from a country that is blacklisted.
This is how it works:
1. Look up country from IP address
2. Check if that country is in your Blacklist
3. If yes, stop processing of that email and log the blacklist event
The people from Geobytes provide a free service to determine the ISO3166 country code based on an IP address. This is the link that returns Geobytes information:
http://getcitydetails.geobytes.com/GetCityDetails?fqcn=1.2.3.4
One return variable, "geobytescode", provides the ISO3166 2 character country code, e.g. with this IP address (1.2.3.4):"TW" (Taiwan). We filter this variable with a Regular Expression.
Now we can check if this code is in our Blacklist and if it is, stop all further processing of that email.
This is the code (add this to hMailserver's EventHandlers.vbs)
Sub OnClientConnect(oClient)
'--- ISO3166 2 character list of blocked countries...
Const BlackList="AR VN CN"
Dim IP, Port, locationRaw, locationArray, s, regExp, CountryCode
Const chr34="\"""
Const Accept=0
Const Deny=1
'--- Get IP:port...
IP = oClient.IPAddress
Port = oClient.Port
'--- Exclude local IP addressess...
if not (InStr(IP,"127.")=1 or InStr(IP,"192.168.")=1) then
'--- Prepare regular expression...
Set regEx = New RegExp
'--- Search for first `"geobytesinternet":"AA"` occurence...
regEx.Pattern=chr34 & "geobytesinternet" & chr34 & "\:" & chr34 & "[A-Z]{2}" & chr34
'--- Match case...
regEx.IgnoreCase = False
'--- First match only...
regEx.Global = False
'--- Get GeoIP information...
Set locationRaw = CreateObject("MSXML2.XMLHTTP")
locationRaw.open "GET", "http://getcitydetails.geobytes.com/GetCityDetails?fqcn=" & trim(oClient.IPaddress), False
locationRaw.send
'--- Search for CountryCode...
Set Matches = regEx.Execute(locationRaw.responseText)
'--- If found then set CountryCode...
if Matches.Count=1 then CountryCode=mid(Matches(0).value,21,2) else CountryCode="??"
'--- Check for blacklisted country and abort session if so...
If InStr(Blacklist,CountryCode)<>0 then
EventLog.Write("Blacklisted: " & IP & ", " & CountryCode)
Result.Value=Deny
End if
End If
End Sub
Check the new EventHandlers.vbs in the hMailserver console (hMailserver>Settings>Advanced>Scripts>[Check Syntax]) and reload the hMailserver script (hMailserver>Settings>Advanced>Scripts>[Reload scripts]).
Ranting about an R1200RT, motorcycle trips, information security and other day by day annoyances...
Very nice job. It is working perfectly.
ReplyDelete