Home > Blockchain >  Allow access to local host from specific URL only on Linux
Allow access to local host from specific URL only on Linux

Time:01-21

I have a REST API listening on the localhost:8000 and I want it to accept requests from localhost:5000 only. Is there a way to achieve this on Linux without modifying the API code?

CodePudding user response:

you can use iptables,

but I think it will be easier to use socat like this:

socat TCP4:localhost:8000 TCP4:localhost:5000

for more information, you can look at this https://unix.stackexchange.com/questions/10428/simple-way-to-create-a-tunnel-from-one-local-port-to-another

CodePudding user response:

Your REST API probably have it's own mechanism of preventing cross-origin requests and that is the reason why you struggle with connecting those two locations. This problem can't be solved on the Linux level.

First of all, let's explain a few things. Request's origin is defined by the following features:

  • scheme, which is simply a protocol that you API uses (HTTP or HTTPS)
  • hostname, which is domain or IP address (in your case it is localhost)
  • port, which is self-explanatory.

So, you want to perform a cross-origin request. In case of the simple HTTP request (GET, HEAD or POST request), you have to set Access-Control-Allow-Origin on the side of your REST API (localhost:8000). For that, check how to set up that header in your specific technology.

Cross-origin requests in your case will be possible if you set this header for the following value:

Access-Control-Allow-Origin: *

You want your localhost to be accessible for the specific URL only - in case of localhost, it is only accessible by the locally running applications. If you deploy your application somewhere in the web, and you want only specific URLs to be able to connect with the REST API, you have to use the following setting of Access-Control-Allow-Origin header:

Access-Control-Allow-Origin: https://foo.example

In your case on localhost, that would be:

Access-Control-Allow-Origin: http://localhost:5000

(I assumed that you use http protocol)...

In my opinion, it doesn't make much sense to restrict localhost connections this way - '*' is good. The only reason I can think of is protection against SSRF attacks, is that the case? (It is only justified if your server is exposed to the web.)

Further resources:

  •  Tags:  
  • Related