B4J Question b4j server localhost filter

billzhan

Active Member
Licensed User
Longtime User
Hi,

I want to make a b4j server can only be accessed by localhost, the current plan is to use a filter thread for all requests.

B4X:
    srvr.AddFilter("/*","localhostfilter",False)


'Return True to allow the request to proceed.
Public Sub Filter(req As ServletRequest, resp As ServletResponse) As Boolean
    Dim ip As String= req.RemoteAddress
    Log(ip)
    Dim ipmap As Map
    ipmap.Initialize
    '
    ipmap.Put("localhost","")
    ipmap.Put("LOCALHOST","")
    ipmap.Put("127.0.0.1","")
    ipmap.Put("0:0:0:0:0:0:0:1","")
    ipmap.Put("::1","")
    '... other permutations
 
    If ipmap.ContainsKey(ip) Then
        Return True
    Else
        Return False
    End If
 
End Sub



Is there any other method? List all permutations is not very good ( e.g. 127.0.0.* is not included).
 

Roycefer

Well-Known Member
Licensed User
Longtime User
Why are you putting the possible IPs in a Map? I suspect a List will be faster. Also, why are you reconstructing the Map every time a request comes in? It will most likely be faster to do it once in AppStart and then store it as a global variable. Also, have you checked that all those permutations are possibilities? I think I've only ever seen 127.0.0.1 and 0:0:0:0:0:0:0:1 reported by req.RemoteAddress (even when navigating to 127.0.0.5 or something).

Try something along these lines in AppStart:
B4X:
ipList.Add("127.0.0.")    'ipList was declared in Process_Globals
ipList.Add("localhost")
ipList.Add("0:0:0:0:0:0:0:1")
srvr.AddFilter("/*", "localhostfilter", False)
In Filter class:
B4X:
Public Sub Filter(req AsServletRequest, resp AsServletResponse) As Boolean
    Dim ip As String = req.RemoteAddress.ToLowerCase
    For Each ipCandidate As String in Main.ipList
        If ip.Contains(ipCandidate) Then Return False
    Next
    Return True
End Sub
 
Upvote 0

billzhan

Active Member
Licensed User
Longtime User
I tried already, and plan to use a whitelist (with permutations and Regex strings) set by user.
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
Or use this
B4X:
...
Dim jo As JavaObject = req
If jo.RunMethod("getLocalAddr",Null) <> req.RemoteAddress Then 
    Log("not from this machine") 
Else 
   Log("from local machine")
End If
...
 
Upvote 0

Roycefer

Well-Known Member
Licensed User
Longtime User
I don't think that will work. req.getLocalAddr() returns the IP address of the machine on the local network. "127.0.0.1" (or any of the other aliases) won't match with it.
 
Upvote 0
Top