Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java- using a filter to check remote address

What would be the best approach to detect if a web application is accessed locally?
I am interested in checking this in a filter (javax.servlet.Filter).
I could check the ServletRequest#getRemoteAddr() if it is 127.0.0.1 but if it is running in a IPv6 machine, the address would be 0:0:0:0:0:0:0:1.
Are there any other pitfalls I should be aware of, or if I just check for these 2 string patterns, I would be ok?

Thanks

like image 653
Cratylus Avatar asked Feb 15 '11 20:02

Cratylus


3 Answers

In theory, the following ought to be sufficient.

if (request.getRemoteAddr().equals(request.getLocalAddr())) {
    // Locally accessed.
} else {
    // Remotely accessed.
}


Update as per the comments, request.getLocalAddr() seems to return 0.0.0.0 which can indeed happen when the server is behind a proxy.

You may instead want to compare it against the addresses as resolved by InetAddress.

private Set<String> localAddresses = new HashSet<String>(); 

@Override
public void init(FilterConfig config) throws ServletException {
    try {
        localAddresses.add(InetAddress.getLocalHost().getHostAddress());
        for (InetAddress inetAddress : InetAddress.getAllByName("localhost")) {
            localAddresses.add(inetAddress.getHostAddress());
        }
    } catch (IOException e) {
        throw new ServletException("Unable to lookup local addresses");
    }
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
    if (localAddresses.contains(request.getRemoteAddr())) {
        // Locally accessed.
    } else {
        // Remotely accessed.
    }
}

In my case, the localAddresses contains the following:

[192.168.1.101, 0:0:0:0:0:0:0:1, 127.0.0.1]
like image 134
BalusC Avatar answered Nov 15 '22 01:11

BalusC


You also need to check all other IP-addresses of your box like the one of your ethernet interfaces. Also consider aliases.

like image 34
Heiko Rupp Avatar answered Nov 14 '22 23:11

Heiko Rupp


Even if the client is running locally, it might not be using the loopback interface. Odds are good that your machine will have an assigned IP address, and depending on /etc/hosts configuration, DNS configuration, etc. the IP address you connect to might not be the loopback address.

Assuming that you want to provide some sort of "enahanced" interface that is "more secure" because it originates on the same machine, beware that even loopback interfaces can be snooped upon by using tools like wireshark. If this interface is meant to display data suitable for a more-trusted client, then odds are good you should take the efforts to do proper ssl tunneling via https.

like image 34
Edwin Buck Avatar answered Nov 15 '22 00:11

Edwin Buck