pf (Mac OS X) rule to redirect all traffic to a specific ip/port

I'm trying to recreate this iptables setup (from https://github.com/darkk/redsocks) with pf:

iptables -t nat -A REDSOCKS -p tcp -d 10.0.0.0/8 -j REDIRECT --to-ports 12345
iptables -t nat -A OUTPUT -p tcp -j REDSOCKS

I want to redirect all connections going to 10.0.0.0/8 (no matter what port) to the local port 12345. In linux this works great with the above specified rules. Now I'm trying to recreate it on Mac OS X. Currently nothing I have tried works e.g.

rdr inet proto tcp from any to 10.0.0.0/8 port 0:65535 -> 127.0.0.1 port 12345

I have set sysctl net.inet.ip.forwarding=1

I'm not sure if even the rdr rule is equivalent to the iptables nat redirect. Redsocks requires the connection to keep the destination ip/port for correct forwarding through the proxy. So I guess the destination in the packages should not be changed/rewritten to 127.0.0.1:12345.


Solution 1:

So, I am likely misunderstanding but I think you may be confusing the iptables TPROXY and REDIRECT targets - but I don't think that's important. Ignoring that, you may still be able to realize your goal.

Your frustration with the rdr pf rule is because only applies to incoming packets. According to a 2005 FreeBSD-pf mailinglist post, you may be able to circumvent that limitation with a route-to rule. I've never used pf, but if I understand the syntax and the linked email, the following rule with your rdr rule may be correct?

rdr inet proto tcp from any to 10.0.0.0/8 -> 127.0.0.1 port 12345
pass out route-to (lo0 127.0.0.1) from any to 10.0.0.0/8

I realize I'm hardly qualified as any manner of expert to comment here; but, I hope my comments may help you find a solution.


Regarding your comment at the end of your question where you wrote:

I'm not sure if even the rdr rule is equivalent to the iptables nat redirect. Redsocks requires the connection to keep the destination ip/port for correct forwarding through the proxy. So I guess the destination in the packages should not be changed/rewritten to 127.0.0.1:12345.

According to iptables-extensions(8), the REDIRECT target:

"It redirects the packet to the machine itself by changing the destination IP to the primary address of the incoming interface..."

and, TPROXY preserves the original destination address:

"It redirects the packet to a local socket without changing the packet header in any way."

I don't know if pf supports the linux-specific style TPROXY operation.