配置

添加一个anchor。修改/etc/pf.conf如下:
    scrub-anchor "com.apple/*"
    nat-anchor "com.apple/*"
    nat-anchor "custom"
    rdr-anchor "com.apple/*"
    rdr-anchor "custom"
    dummynet-anchor "com.apple/*"
    anchor "com.apple/*"
    anchor "custom"
    load anchor "com.apple" from "/etc/pf.anchors/com.apple"
    load anchor "custom" from "/etc/pf.anchors/custom"
建立anchor规则文件/etc/pf.anchors/custom,内容为具体规则。
常用的规则:

    屏蔽IP入站TCP连接并记录:

    block in log proto tcp from 192.168.1.136 to any

    转发入站TCP连接到另一本地端口:

    rdr inet proto tcp from any to any port 8081 -> 127.0.0.1 port 80

经测试,rdr无法转发到另一台外部主机上(man page的示例,只可以转发到internal network),内核开启net.inet.ip.forwarding=1也无效。如需转发到另一个外网IP,需要配合mitmproxy的透明代理
    NAT,路由vlan12接口上(192.168.168.0/24)的出口包,经由非vlan12的接口转换到外部地址(204.92.77.111),并允许vlan12之间的互相访问:

    nat on ! vlan12 from 192.168.168.0/24 to any -> 204.92.77.111

使配置文件生效

`pfctl -evf /etc/pf.conf`

简化教程

修改/etc/pf.conf如下:

    scrub-anchor "com.apple/*"
    nat-anchor "com.apple/*"
    nat-anchor "custom"
    rdr-anchor "com.apple/*"
    rdr-anchor "custom"
    dummynet-anchor "com.apple/*"
    anchor "com.apple/*"
    anchor "custom"
    load anchor "com.apple" from "/etc/pf.anchors/com.apple"
    load anchor "custom" from "/etc/pf.anchors/custom"
    table <blockedips> persist file "/etc/pf.blocked.ip.conf"
    block in log proto tcp from <blockedips> to any
  1. 在/etc目录下生成文件/etc/pf.blocked.ip.conf,里面包含要block的ip地址。 比如:
218.240.39.102
#218.240.39.121
192.168.1.0/24
  1. 用一下命令载入新规则

pfctl -f /etc/pf.conf

  1. 实时加入拦截
# pfctl -t blockedips -T add 69.248.133.153
# pfctl -t blockedips -T add 91.196.232.0/22
  1. 实时删除拦截
pfctl -t blockedips -T delete 91.196.232.0/22
pfctl -t blockedips -T delete 69.248.133.153

清除所有已经建立的规则,并重新读取配置文件

pfctl -F all -f /etc/pf.conf