PF on Mac OS X

Mac 系统从 10.7 (Lion) 开始就内置了两种防火墙, PF 和 应用防火墙,默认情况下他们都是禁用状态。

在 10.6之前是使用的 IPFW ,在10.10之后就被完全移出了,PF 的全称是 packet filter,在 OpenBSD 的系统上是用来过滤 TCP/IP 流量和路由转发的功能。

Application firewall 的缺点在于只能禁止软件监听端口,但不能阻止ta将信息发送出去。即所谓的出站规则。

假设我们要阻止 jetbrains 发送信息到ta的服务器上。

新建 anchor 文件

/etc/pf.anchors/[your file]

查找你的网卡名字
通常会是 lo0

$ cat /etc/pf.anchors/jetbrains
block drop log quick on en0 from any to 230.230.230.230

链接到默认配置文件

$ cat /etc/pf.conf
#
# Default PF configuration file.
...
# See pf.conf(5) for syntax.
#

#
# com.apple anchor point
#
scrub-anchor "com.apple/*"
nat-anchor "com.apple/*"
rdr-anchor "com.apple/*"
dummynet-anchor "com.apple/*"
anchor "com.apple/*"
load anchor "com.apple" from "/etc/pf.anchors/com.apple"

#
# jetbrains anchor point
#
anchor "jetbrains"
load anchor "jetbrains" from "/etc/pf.anchors/jetbrains"

上面的栗子是建立出站规则,下面建立一个转发规则。

首先在 /etc/pf.anchors/ 新建一个 com.pow 文件内容如下:

rdr pass on lo0 inet proto tcp from any to any port 80 -> 127.0.0.1 port 8080

添加到默认配置文件

scrub-anchor "com.apple/*"
nat-anchor "com.apple/*"
rdr-anchor "com.apple/*"
dummynet-anchor "com.apple/*"
anchor "com.apple/*"
load anchor "com.apple" from "/etc/pf.anchors/com.apple"

rdr-anchor "pow"
load anchor "pow" from "/etc/pf.anchors/com.pow"

检查配置是否正确

pfctl -nf /etc/pf.conf

导入配置

sudo pfctl -evf /etc/pf.anchors/com.pow

设置开机启动

sudo pfctl -e

关闭 PF

sudo pfctl -d

假设不要端口转发了,可以在默认的配置文件里注释掉你添加的配置,然后执行下面的命令。

pfctl -f /etc/pf.conf