发布于 5年前

macOS 10.10 以上使用 PF 实现端口转发

macOS 默认是不开启1024以下端口的权限的,所以我们需要进行端口抓发。 macOS 10.10 以上已经无法使用ipfw进行端口转发了,只能使用PF进行端口转发。

以下是具体的配置方法,这里演示的是将80端口转发到8080端口。

sudo echo "rdr pass on lo0 inet proto tcp from any to any port 80 -> 127.0.0.1 port 8080" > /etc/pf.anchors/forwarding.pow #写入配置文件
sudo pfctl -vnf /etc/pf.anchors/forwarding.pow #检测配置文件

PF启动时会自动装载/etc/pf.conf文件,因此将anchor文件链接到/etc/pf.conf,转发规则就会自动建立了。

sudo vim /etc/pf.conf
 28 #
 27 # Default PF configuration file.
 26 #
 25 # This file contains the main ruleset, which gets automatically loaded
 24 # at startup.  PF will not be automatically enabled, however.  Instead,
 23 # each component which utilizes PF is responsible for enabling and disabling
 22 # PF via -E and -X as documented in pfctl(8).  That will ensure that PF
 21 # is disabled only when the last enable reference is released.
 20 #
 19 # Care must be taken to ensure that the main ruleset does not get flushed,
 18 # as the nested anchors rely on the anchor point defined here. In addition,
 17 # to the anchors loaded by this file, some system services would dynamically
 16 # insert anchors into the main ruleset. These anchors will be added only when
 15 # the system service is used and would removed on termination of the service.
 14 #
 13 # See pf.conf(5) for syntax.
 12 #
 11
 10 #
  9 # com.apple anchor point
  8 #
  7 scrub-anchor "com.apple/*"
  6 nat-anchor "com.apple/*"
  5 rdr-anchor "com.apple/*"
  4 rdr-anchor "pow"
  3 dummynet-anchor "com.apple/*"
  2 anchor "com.apple/*"
  1 load anchor "com.apple" from "/etc/pf.anchors/com.apple"
29  load anchor "pow" from "/etc/pf.anchors/forwarding.pow"
esc
:wq
sudo pfctl -f /etc/pf.anchors/forwarding.pow #重载
sudo pfctl -e #启动

rdr-anchor "com.apple/*"后一行增加rdr-anchor "pow"load anchor "com.apple" from "/etc/pf.anchors/com.apple"后一行增加load anchor "pow" from "/etc/pf.anchors/forwarding.pow" 具体操作如下所示:

sudo vim /System/Library/LaunchDaemons/com.apple.pfctl.plist 
 15 <?xml version="1.0" encoding="UTF-8"?>
 14 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
 13 <plist version="1.0">
 12 <dict>
 11     <key>Disabled</key>
 10     <false/>
  9     <key>Label</key>
  8     <string>com.apple.pfctl</string>
  7     <key>WorkingDirectory</key>
  6     <string>/var/run</string>
  5     <key>Program</key>
  4     <string>/sbin/pfctl</string>
  3     <key>ProgramArguments</key>
  2     <array>
  1         <string>pfctl</string>
16          <string>-e</string>
  1         <string>-f</string>
  2         <string>/etc/pf.conf</string>
  3     </array>
  4     <key>RunAtLoad</key>
  5     <true/>
  6 </dict>
  7 </plist>
esc
:wq

修改/System/Library/LaunchDaemons/com.apple.pfctl.plist之前需要先在安全模式执行csrutil disable

©2020 edoou.com   京ICP备16001874号-3