MacOS 配置pf(Pocket Filter)防火墙
Mac自带的防火墙粒度太粗,可以使用pf来做精细的控制。
1. 修改pf配置文件
可以新建一个,或者备份原本的配置文件然后修改/etc/pf.conf。
#把原来的内容都注释掉
#自定义规则
#定义允许访问的IP
allowed_ips = "{192.168.x.x, 192.168.x.x}"
#定义允许访问的端口
allowed_ports = "{22, 5900, 3306 }"
#block 22 ips
blocked_22_ips = "{192.168.x.x}
#跳过本地回环接口 set skip on lo0
#阻止特定的ip访问特定端口
block in quick proto tcp from $blocked_22_ips to any port 22
#允许特定ip访问特定端口
pass in quick proto tcp from $allowed_ips to any port $allowed_ports
#允许路由器的流量,否则会导致连不上路由器
pass in quick from 192.168.x.x to any
#阻止所有其他入站流量 block in all #允许所有出站流量 pass out all
#对于pf的规则优先级,网上和AI众说纷纭。尝试后发现,如果没有quick关键字,后面的规则会覆盖前面的规则。如果有quick关键字,则该规则立刻生效。
#所以可以尽量使用quick来确保符合期望
2. 启动pf
sudo pfctl -e
sudo pfctl -f /etc/pf.conf
3. 记得关闭自带的防火墙
4. pocket filter 默认不会开机自启动,我们加上配置。
macOS 使用 launchd 管理系统服务。我们需要创建一个 launchd 配置文件来确保 pf 在启动时自动启用。
创建配置文件:/Library/LaunchDaemons/com.wargon.pfctl.plist
内容:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.wargon.pfctl</string>
<key>ProgramArguments</key>
<array>
<string>/sbin/pfctl</string>
<string>-e</string>
<string>-f</string>
<string>/etc/pf.conf</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<false/>
</dict>
</plist>
修改文件owner和权限:
sudo chown root:wheel /Library/LaunchDaemons/com.wargon.pfctl.plist
sudo chmod 644 /Library/LaunchDaemons/com.wargon.pfctl.plist
加载launchd配置:
sudo launchctl load -w /Library/LaunchDaemons/com.wargon.pfctl.plist
注意,由于macos已经配置了pfctl的launchd,在 /System/Library/LaunchDaemons下面,所以我们这里使用的命名为 com.wargon.pfctl.plist,防止冲突。
如果配置launchd的时候报错,可以检查日志:
log show --predicate 'process == "launchd"' --info --last 5m
浙公网安备 33010602011771号