Search code examples
restiptablesnetfilter

How to use iptables to route an HTTP request to a private network


First of all I want to clarify that I am a complete noob in computer networks, so I apologize in advance if I am using incorrect terms or saying nonesense. Having said that, I'll try to explain my question as clear as possible. Let's say I have two Linux servers (ubuntu), Server A and Server B connected as shown in the figure:

enter image description here

Both servers have 3 network interfaces each with the IP addresses listed in the image, both servers have two networks that are common to each other:

172.16.0.0/24
10.20.0.0/24

Server B has an application with an endpoint in the following network

192.168.0.1/24 

which Server B can reach but server A cannot. The application has the following endpoint

http://192.168.0.1:35357

Is there a way to reach the application endpoint from Server A so I can do a curl with a POST to the endpoint from Server A and gets to the application in Server B? Maybe through iptables or something like that? I also want to be able to get the response from the application in Server A.


Solution

  • I was finally able to make it work, and in the end it was pretty simple, just two steps. I will update the answer in case it helps someone. What I did was the following:

    Step 1: in server A, I added a route to the 192.168.0.0/24 network over the vboxnet1 interface:

    ip route add 192.168.0.0/24 dev vboxnet1
    

    After running the command above you should be able to see your new route by using the ip route show command which should show your route:

    $ sudo ip route show
    ...
    192.168.0.0/24 dev vboxnet1  scope link
    ...
    

    You can also run the ip route get <IP> command with the IP address you are trying to reach to see the route on which the system will send the packets to get to that IP address. In my case I wanted to get to 192.168.0.1:

    $ ip route get 192.168.0.1
    192.168.0.1 dev vboxnet1  src 172.16.0.1
    

    Step 2: since what I am trying to access is really a service that lives in Server B, and is not another machine, I need to also change the destination of my packets so they are sent to Server B using its IP address within the 192.168.0.0/24 network. The IP address of server B in that network is 192.168.0.2:

    $ iptables -t nat -A OUTPUT -p tcp -d 192.168.0.1 -j DNAT --to-destination 192.168.0.2
    

    That's it! After doing that I am able to run my HTTP request via cURL and it successfully reaches my endpoint.

    curl -v -k -X 'POST' http://192.168.0.1:35357/my_REST_resource -H 'Content-Type:application/json' -H 'Accept:application/json'