1

I am building a Java webserver in Karaf. I would like to know if the http call stems from the same machine ( = Is local) or not. Http headers like Referer and Host help me in this regard so far.

The strategy namely is to see if the appearing URL in the headers reads localhost or not.

What are the dangers of this approach? And is there a more secure way?

Makan
  • 2,508
  • 4
  • 24
  • 39
  • An interesting subquestion would be to decide if it is possible to spoof these headers and if there is a more secure way to get this information. – Beginner Oct 24 '19 at 15:20
  • 2
    You *cannot* rely on HTTP headers because the client can send whatever headers it wants, including forged headers. The Host header only names the domain name of the server, and does not provide any info about the client. Similarly, the Referer is an optional field indicating the previously visited page, and provides no info about the client. Instead, you need to look at the remote address from the underlying TCP connection. With a JavaEE ServletRequest, try the `getRemoteAddr()` method. It should match any IP address of the server, likely the loopback address 127.0.01 (IPv4) or ::1 (IPv6). – amon Oct 25 '19 at 18:57

1 Answers1

1

As amon pointed out in his comment, the reliable method would be to use the javax.servlet.http.HttpServletRequest.

import javax.ws.rs.core.Context;
import javax.servlet.http.HttpServletRequest; 

inject the HttpServletRequest into your code using Context annotation:

@Context private HttpServletRequest req;

Then use the object to get the address from one of the two:

LOG.info("{}", req.getRemoteHost());
LOG.info("{}", req.getRemoteAddr());

This answer helped me with the details.

Makan
  • 2,508
  • 4
  • 24
  • 39