天天看點

使用iptables進行入站流量過濾

iptables是Linux内置的流量過濾工具,同時也是多種防火牆的底層實作(如fw3),在本次應用中,iptables通過丢棄不符合規則的資料包,使得未注冊裝置在DHCP擷取ip階段失敗,無法連接配接到專用内網,保證系統安全。

iptables使用責任鍊機制,

到本機某程序的封包:PREROUTING –> INPUT

由本機轉發的封包:PREROUTING –> FORWARD –> POSTROUTING

由本機的某程序發出封包(通常為響應封包):OUTPUT –> POSTROUTING

public Boolean blockNewDevice(){
        try{
            List<DeviceDO> devices = deviceDao.getDevices();
            StringBuffer stringBuffer = new StringBuffer();
            //測試用管理,上線時mac替換為超管裝置
            stringBuffer.append("iptables -I INPUT -m mac ! --mac-source 7C:76:35:E7:13:05 -j DROP&&");
            for(DeviceDO device : devices){
              stringBuffer.append("iptables -I INPUT -m mac --mac-source "
                        +device.getMac()+" -j ACCEPT&&");
            }
            String res= new RestTemplate().getForObject(host+"d.py?action=god&&cmd="+stringBuffer.toString(),String.class);
            System.out.println(res);

            return true;

         }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

   public Boolean allowDeviceConnect() {
        String res= new RestTemplate().getForObject(host+"d.py?action=allow",String.class);
        System.out.println(res);
        return true;
   }

           

通過代碼可以看到,通過向路由器的cgi腳本寫入iptables指令,即可實作裝置的過濾。使用allow可以讓cgi清除iptables内部的規則,實作裝置添加功能的需求。