OSX上pf的简单配置笔记
水果的OSX上没有iptables,在10.10以后以pf取代ipfw。相比于iptables,pf一般使用配置文件保存防火墙规则,语法规范上更严谨,但是配置也更复杂、规则冗长。本文记录pf的简单配置方法。
cat /etc/pf.conf
,可看到以下已有内容:(忽略注释部分)
|
|
anchor
可理解为一组规则的集合。默认情况下,这里的几行anchor都是苹果留的place holder,实际上没有active的规则。
/etc/pf.conf
在以后的OSX更新中可能会被覆盖,最好可以另外建立一个自定义的pf.conf
。
配置文件必须按照Macros
, Tables
, Options
, Traffic Normalization
, Queueing
, Translation
, Packet Filtering
的顺序。
更详细的说明参考pf.conf man page
-
添加一个
anchor
。修改/etc/pf.conf
如下:12345678910scrub-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连接并记录:
1block in log proto tcp from 192.168.1.136 to any -
转发入站TCP连接到另一本地端口:
1rdr 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之间的互相访问:
1nat on ! vlan12 from 192.168.168.0/24 to any -> 204.92.77.111
-
-
使配置文件生效
1pfctl -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
2. 在/etc目录下生成文件/etc/pf.blocked.ip.conf,里面包含要block的ip地址。
比如:
218.240.39.102
#218.240.39.121
192.168.1.0/24
3. 用一下命令载入新规则
pfctl -f /etc/pf.conf
4. 实时加入拦截
# pfctl -t blockedips -T add 69.248.133.153
# pfctl -t blockedips -T add 91.196.232.0/22
5. 实时删除拦截
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
以上可以实现 随时屏蔽要屏蔽的ip
参考内容
https://cn2.chionlab.moe/2016/02/01/use-pf-on-osx/
http://tieba.baidu.com/p/1299818333