0

I want to write a ContainerRequestFilter for a Jersey webapp that will filter out all remote calls.
So only requests from same machine (where webapp is running) are allowed.

I get a context object of type ContainerRequestContext where I get the host name via ctx.getUriInfo().getRequestUri().getHost().

How can I check if this host name (in form of IPv4, IPv6 or domain name) is an address of the local machine?

thersch
  • 1,316
  • 12
  • 19

1 Answers1

5

I'd go with something like this, once you stripped the host name from the request. It should work with inputs like localhost and such as well.

public boolean isLocalAddress(String domain) {
    try {
        InetAddress address = InetAddress.getByName(domain);
        return address.isAnyLocalAddress()
                || address.isLoopbackAddress()
                || NetworkInterface.getByInetAddress(address) != null;
    } catch (UnknownHostException | SocketException e) {
        // ignore
    }
    return false;
}

But please keep in mind, as it's not straightforward to determine if a request is originated from a local client, and there is also performance implications, I'd suggest to bind the container's listen address only to a locally accessible interface (127.0.0.1, ::1), or implement some sort of authentication. This approach - where you trying to determine this info from the request is also insecure.

Z4-
  • 1,851
  • 14
  • 17
  • We have different Root Resource classes in one webapp. So we cannot limit the whole Tomcat or the webapp to 127.0.0.1 and ::1. But we implement the local clients (not running in Tomcat). Is it secure to let local clients send only to 127.0.0.1 and let ContainerRequestFilter for the RootResourceClass filter out all addresses but 127.0.0.1? – thersch May 27 '14 at 10:56
  • 1
    Unfortunately not so secure in that way either. Request headers could be easily forged. It would be much more secure, if you could get a hold on the remote socket address, and filter based on that, but AFAIK that's not possible without implementation specific hacks. In your case I would still recommend binding Tomcat only to loopback interfaces, and put a forwarder (Nginx, Apache with mod_proxy) in front of it, which listens to the publicly accessible interfaces, and forwards anything except for the "protected" services to Tomcat. – Z4- May 27 '14 at 12:31