开发者

java- using a filter to check remote address

开发者 https://www.devze.com 2023-02-11 04:39 出处:网络
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).

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


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]


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消