B4J Code Snippet [ABM Material] GeoIp ip block

Running a home automation server i noticed that a large number of attacks has been done to get access into it.
I dont like the sniffing so based on the idea of geoip block SSH port 22 i wrote some lines to get the same for ABMaterial
you need a database with all ip ranges. maxmind has a freedownload
the ip range is represented as integer, which makes life a lot easier, all in csv format, see description on their site.

so far it works, next step is to redirect the sniffer to a page with some funny text....

The code can be called from ABMApplication
B4X:
Private Sub WebSocket_Connected (WebSocket1 As WebSocket)
   Log("Connected")
   ws = WebSocket1
 
   ABMPageId = ABM.GetPageID(AppPage, ABMShared.AppName,ws)
   '----------------------START MODIFICATION 4.00-------------------------------
   If AppPage.WebsocketReconnected Then
       ABMShared.NavigateToPage(ws, "", "./")
       Return
   End If
 
   Dim session As HttpSession = ABM.GetSession(ws, ABMShared.SessionMaxInactiveIntervalSeconds) 'ignore
    If geoip(ws.UpgradeRequest.RemoteAddress)=false Then DoWhatYouLikeToDoWithTheHacker

   If session.IsNew Then
       session.Invalidate
       ABMShared.NavigateToPage(ws, "", "./")
       Return
   End If

and the code you need is here. You can use it freely, modify if you like, and maybe make it better!

B4X:
Sub DecodeGeoIp(line As String,ipnumber As Int) As Int
   Dim sf As JStringFunctions
   sf.Initialize

   Dim numbers() As String=Regex.Split("[,.\s""]",line)
   Dim allow() As String=Array As String("FR","DE") 'only let the countrys in, which may have access and keep others out.
 

   If ipnumber>=sf.Val(numbers(13)) And ipnumber<=sf.Val(numbers(16)) Then
'   
           For i=0 To allow.length-1
           If allow(i)=numbers(19) Then Return 1
           Next
'           Log(numbers(13)&"-" &numbers(16))
           Return 0
   Else
       Return -1
   End If
End Sub

Sub geoip(ipnumber As String) As Boolean
   Dim Reader As TextReader
   Dim line As String
   Dim sf As JStringFunctions
   sf.Initialize
   Dim ip() As String=Regex.Split("[,.\s""]",ipnumber)
   Dim ipnummer=((sf.Val(ip(0))*256+sf.Val(ip(1)))*256+sf.Val(ip(2)))*256+sf.Val(ip(3)) As Int
 
   Reader.Initialize(File.OpenInput(File.DirApp & "/" & filedir, "GeoIPCountryWhois.csv"))
   line=Reader.ReadLine
   Select DecodeGeoIp(line,ipnummer)
   Case 1
           Return True
   Case 0
           Return False
       End Select
   Do While line <> Null

       Select DecodeGeoIp(line,ipnummer)
           Case 1
               Return True
           Case 0
               Return False
           End Select
       line = Reader.ReadLine
   Loop
   Reader.Close
   Return True
End Sub
 
Last edited:
Top