Java - using a filter to verify a remote address

What would be the best approach to detect local access to a web application?
I am interested in checking this out in a filter ( javax.servlet.Filter ).
I could check ServletRequest#getRemoteAddr() if it is 127.0.0.1 , but if it is running on an IPv6 machine, the address will be 0:0:0:0:0:0:0:1 .
Are there any other errors that I should know about, or if I just check these 2 string patterns, would I understand everything?

thanks

+6
java java-ee web-applications tomcat servlet-filters
source share
3 answers

Theoretically, should be enough.

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

Strike>


Update according to the comments, request.getLocalAddr() seems to return 0.0.0.0 , which can actually happen when the server is behind the proxy server.

Instead, you can compare it with the addresses allowed 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, localAddresses contains the following:

 [192.168.1.101, 0:0:0:0:0:0:0:1, 127.0.0.1] 
+11
source share

You also need to check all the other IP addresses of your field as one of your Ethernet interfaces. Also consider aliases.

+1
source share

Even if the client is running locally, it may not use the loopback interface. The odds are good because your computer will have an assigned IP address, and depending on the configuration of / etc / hosts, the configuration of DNS, etc. The IP address you are connecting to may not be a feedback address.

Assuming you want to provide some kind of “enriched” interface that is “more secure” because it occurs on the same machine, be careful that even loopback interfaces can be tracked using tools like wireshark. If this interface is designed to display data suitable for a more trusted client, then the odds are good, you should make efforts to properly tunnel ssl through https.

+1
source share

All Articles