java- using a filter to check remote address

后端 未结 3 1239
时光说笑
时光说笑 2020-12-17 01:56

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.Fi

相关标签:
3条回答
  • 2020-12-17 02:36

    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 讨论(0)
  • 2020-12-17 02:40

    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]
    
    0 讨论(0)
  • 2020-12-17 02:57

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

    0 讨论(0)
提交回复
热议问题