Proxy a TCP connection

Eugene Grosbein eugen at grosbein.net
Sat May 19 01:10:26 UTC 2018


19.05.2018 4:29, Andrea Venturoli wrote:

> Let's say I have a router connected to the Internet on one side and to a LAN with private IPs on the other.
> I want some clients from outside to be able to connect to a TCP service on a machine on the LAN: they should connect to port X on the firewall's public IP and reach port Y on the internal box.
> 
> I've used net/socket in the past, but stopped when, in some corner case, it would "ruin" the data; besides it has been removed from the port tree.
> 
> I happily switched to net/tcpproxy, but lately it's dying every few days and must be restarted; I could drop its rc.d script and use sysutils/daemontools' svscan instead, but if there's a simpler solution...
> 
> Does anyone have a good suggestion for a program similar to the above ones?
> I require nothing fancy, I just want it to be reliable.

You don't need any additional software at all.
Just instruct FreeBSD kernel to do what you need, it will do that just fine.

In /etc/rc.conf:

gateway_enable="YES"
firewall_enable="YES"
firewall_type="open"
firewall_nat_enable="YES"
firewall_nat_interface="em0" # your external interface with public IP
firewall_nat_flags="same_ports"
firewall_coscripts="/etc/rc.firewall.local"

And create executable script /etc/rc.firewall.local to configure port redirections:

#!/bin/sh

. /etc/rc.conf
fwcmd="/sbin/ipfw -q"
# redirect connections to external port 8000 to specified internal host and port 80
# redirect connections to external port 8443 to specified internal host and port 443
redirects="\
	redirect_port tcp 192.168.0.100:80 8000  \
	redirect_port tcp 192.168.0.200:443 8443 \
"

${fwcmd} nat 123 config if $firewall_nat_interface $firewall_nat_flags $redirects
# EOF

That's all. You can apply these changes without reboot using command like
service ipfw start >& /tmp/ipfw.log     # for tcsh or
service ipfw start > /tmp/ipfw.log 2>&1 # for sh/bash/zsh

No extra daemons needed. Additional advantage of this approach is that
internal hosts will see real public IP address of connecting external host
instead of your own.



More information about the freebsd-net mailing list