2012年2月14日 星期二

Using iptables to Implement URL Filter

Link form:http://ohohsblog.blogspot.com/2011/01/url-filter-by-iptables.html

URL filter是router很常見的功能; 在PC上, 或許可以透過squid來達成, 若是在flash很小的embedded system上, 還不知道有什麼軟體可以實現該功能(squid-lite?!). 因此, 只好先透過iptables來做URL filter

有幾個match可能可以拿來實現URL filter:  destination, string, webstr, weburl

destination
1
iptables -D FORWARD -d www.google.com.tw -j DROP
在某個版本以後的iptables會幫忙做DNS反查,若該Domain Name對應到多個IP時, iptables會幫你加上所有的rule
1
2
3
4
5
6
7
8
9
$iptables -L FORWARD -v -n
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source          destination        
    0     0 DROP       all  --  *      *       0.0.0.0/0       72.14.203.106      
    0     0 DROP       all  --  *      *       0.0.0.0/0       72.14.203.147      
    0     0 DROP       all  --  *      *       0.0.0.0/0       72.14.203.99      
    0     0 DROP       all  --  *      *       0.0.0.0/0       72.14.203.103      
    0     0 DROP       all  --  *      *       0.0.0.0/0       72.14.203.104      
    0     0 DROP       all  --  *      *       0.0.0.0/0       72.14.203.105
但是如果你再試一次的話
1
2
3
4
5
6
7
8
9
10
11
$iptables -F FORWARD
$iptables -A FORWARD -d www.google.com.tw -j DROP
$iptables -L FORWARD -v -n
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source          destination        
    0     0 DROP       all  --  *      *       0.0.0.0/0       64.233.183.104    
    0     0 DROP       all  --  *      *       0.0.0.0/0       64.233.183.105    
    0     0 DROP       all  --  *      *       0.0.0.0/0       64.233.183.106    
    0     0 DROP       all  --  *      *       0.0.0.0/0       64.233.183.147    
    0     0 DROP       all  --  *      *       0.0.0.0/0       64.233.183.99      
    0     0 DROP       all  --  *      *       0.0.0.0/0       64.233.183.103
IP變了...囧...但用來鎖一般的網站應該還OK...

string
1
iptables -A FORWARD -m string --string "www.google.com" –algo bm -j DROP
這樣做應該可以成功阻擋連到google的封包, 但是你也會發現, 若是有些網頁的內容含有字串"www.google.com", 那麼那個網頁應該也不能開了, 一個可能的解法, 就是利用string match裡面的--from/--to去限制字串比對的範圍

webstr
1
iptables -A FORWARD -m webstr --url "www.google.com" -j DROP
xt_webstr.c, 可以大概知道, 他是去抓HTTP Get/Post/Head封包裡帶的URL來作比對
webstr解決string match比對範圍的問題, 多了些HTTP相關條件, 減少誤判的可能性

weburl
URL Filter有時候可能會用regex或某個關鍵字而非完整的URL; 如輸入"yahoo", 是要擋"www.yahoo.com"與"tw.yahoo.com", 這時候就可利用weburl
1
iptables -A FORWARD -m weburl --contains "yahoo" -j DROP
原始碼可參考Gargoyle


參考資料:
[1] OpenWrt
[2] iptables webstr not blocking https

How to use simple speedtest in RaspberryPi CLI

  pi@ChunchaiRPI2:/tmp $  wget -O speedtest-cli https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py --2023-06-26 10:4...