Search code examples
linuxsocketsiptablesportforwarding

Allow incoming connection on Port 502 with bidirectional port forwarding


Working on an embedded Linux system (with some limited resources), my current application demands that external device talk to this board via Ethernet TCP/IP, on port 502. By default, ports under 1024 are blocked under *nix environments.

So, lets suppose that external device opens a port on 502, and embedded device listens on 8502. How can I transparently allow a bidirectional communication in between those devices?

Good news is that ROOT access is granted to implement this Port Forwarding solution, which will reside inside the embedded Linux device on continuous run, but haven't found what is the correct command for such.

I have tried using iptables, with different combinations of the following commands:

iptables -A INPUT -p tcp --dport 502 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 502 -j ACCEPT
iptables -A INPUT -p tcp --dport 8502 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 8502 -j ACCEPT
iptables -t nat -A PREROUTING -p tcp --dport 502 -j DNAT --to 0.0.0.0:8502
iptables -A INPUT -p tcp --dport 502 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp --sport 502 -m state --state ESTABLISHED -j ACCEPT
iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 502 -j DNAT --to 127.0.0.1:8502
iptables -t nat -I OUTPUT -p tcp -o eth0 --dport 8502 -j REDIRECT --to-ports 502

Lastly, performing iptables-save so rules can be implemented.

Some limitations:

  • since it's a constrained device, cannot install new packages (far from having an apt-get inside it...);
  • cannot predict the external device's IP address, since it can be from different devices each established connection.

Any idea on how to proceed on this task? Thanks in advance.

EDIT: Neither socat nor netcap are available...


Solution

  • In case someone else stumbles on this very issue: unfortunately, my iptables version hasn't support for REDIRECT, which was crucial to make it work. So the solution was to compile another application for my hardware. And in this case socat.

    The command to make my application work was:

    socat TCP-LISTEN:502,fork TCP-CONNECT:127.0.0.1:8502

    Hope it can be helpful for future needs.