I have a daemon running on a CentOS (7) box that accepts raw TCP (not HTTP) connections, and I'd like to connect to the daemon from a remote machine via the internet. The problem is that the daemon will only accept connections that originate from localhost.
Also, I don't have any ability to change anything about how the daemon process handles communication, so any solution will have to "trick" it into thinking that external connections are originating locally on a specific port.
My current thinking is that I should be able to use iptables to proxy outside connections to the daemon, but I haven't yet found the right combination of firewall rules/directives to accomplish the task. I've also considered adding Nginx to the equation, but from what I understand, iptables alone should be enough.
I have intermediate Linux sysadmin experience, but am pretty new to iptables...
So, my question(s):
- What is the best/easiest way (iptables or not) to setup this configuration?
- If iptables is the best approach, what is the best way to test from the command line whether or not connections are working?
Thanks!
EDIT: I thought this might be helpful for any kind soul willing to help me out. I've tried various permutations of the below rules, but no luck:
Prerequisites
- echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward
- sudo sysctl -w net.ipv4.conf.eth0.route_localnet=1
Firewall rules
# Setup basic forwarding
sudo iptables --append FORWARD -i eth0 -p tcp --dport 9876 -j ACCEPT
# Route all incoming packets at external interface (eth0) on port 9876 to localhost 9876
# -- OR --
sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 9876 -j DNAT --to-destination 127.0.0.1:9876
# -- OR --
#sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 9876 -j REDIRECT --to-port 9876
# Make sure packets leaving the external interface have the external address of that interface
#sudo iptables -A POSTROUTING -t nat -o eth0 -p tcp --dport 9876 -d 127.0.0.1 -j SNAT --to-source 127.0.0.1
# -- OR --
sudo iptables -A POSTROUTING -t nat -s 127.0.0.1 -j SNAT –to-source XX.XX.XX.XX
# -- OR --
#iptables -A POSTROUTING -t nat -p tcp -d XX.XX.XX.XX --dport 9876 -j MASQUERADE