iptables是Linux下的防火墻,可以進(jìn)行數(shù)據(jù)包的過濾,在網(wǎng)絡(luò)層進(jìn)行數(shù)據(jù)的轉(zhuǎn)發(fā)、攔截或丟棄等,使用非常普遍,功能也非常強(qiáng)大。但是Mac下沒有iptables,為了實(shí)現(xiàn)流量轉(zhuǎn)發(fā)和過濾,要使用到Mac自帶的PFctl。PFctl即control the packet filter,是Unix LIKE系統(tǒng)上進(jìn)行TCP/IP流量過濾和網(wǎng)絡(luò)地址轉(zhuǎn)換的系統(tǒng),也能提供流量整形和控制等,詳情可以見PF防火墻。
數(shù)據(jù)轉(zhuǎn)發(fā)分兩種情況,流入數(shù)據(jù)的轉(zhuǎn)發(fā)和流出數(shù)據(jù)的轉(zhuǎn)發(fā),網(wǎng)絡(luò)上大部分的使用例子都是如何對流入數(shù)據(jù)進(jìn)行轉(zhuǎn)發(fā),搜索很久才發(fā)現(xiàn)如何通過pfctl進(jìn)行流出數(shù)據(jù)的轉(zhuǎn)發(fā),故此記錄一下,mac系統(tǒng)為10.11.2。
需要實(shí)現(xiàn)的功能如下:
1.將流入數(shù)據(jù)的端口從80轉(zhuǎn)發(fā)到8080
2.將本地發(fā)往192.168.1.8:80的數(shù)據(jù)丟棄
3.將本地發(fā)往192.168.1.6:80的數(shù)據(jù)轉(zhuǎn)發(fā)到192.168.1.7:8080
使用sudo或者進(jìn)入root模式(sudo -i)
1.本次開機(jī)生效:
sudo sysctl -w net.inet.ip.forwarding=1
sudo sysctl -w net.inet6.ip6.forwarding=1
開啟啟動(dòng)配置:
創(chuàng)建文件/etc/sysctl.conf, 內(nèi)容如下:
net.inet.ip.forwarding=1
net.inet6.ip6.forwarding=1
2.查看當(dāng)前端口轉(zhuǎn)發(fā)功能狀態(tài):
sysctl -a | grep forward
3.配置PF過濾功能:
創(chuàng)建配置文件/etc/pf.anchors/http,內(nèi)容為:
流入端口轉(zhuǎn)發(fā)
rdr pass on en0 inet proto tcp from any to any port 80 -> 127.0.0.1 port 8080
rdr pass on lo0 inet proto tcp from any to any port 80 -> 127.0.0.1 port 8080
流出數(shù)據(jù)丟棄
block drop out proto tcp from any to 192.168.1.8 port 80
流出數(shù)據(jù)轉(zhuǎn)發(fā)(1.將特定數(shù)據(jù)流從en0->lo0, 2.將lo0的數(shù)據(jù)進(jìn)行轉(zhuǎn)發(fā))
rdr pass log on lo0 proto tcp from any to 192.168.1.6 port 80 -> 192.168.1.7 port 8080
pass out on en0 route-to lo0 proto tcp from en0 to 192.168.1.6 port 80 keep state
4.校驗(yàn)/etc/pf.anchors/http配置是否正確
sudo pfctl -vnf /etc/pf.anchors/http
5.將配置添加到主配置文件
修改/etc/pf.conf,相同指令要放在一起
在 rdr-anchor "com.apple/*" 下添加
rdr-anchor "http-forwarding"
在 load anchor "com.apple" from "/etc/pf.anchors/com.apple" 下添加
load anchor "http-forwarding" from "/etc/pf.anchors/http"
6.開啟pf服務(wù)
sudo pfctl -ef /etc/pf.conf
或則
sudo pfctl -E
7.關(guān)閉pf服務(wù)
sudo pfctl -d
參考:
http://www.itdecent.cn/p/6052831a8e91
https://apple.stackexchange.com/questions/309286/macos-packet-filter-port-forwarding