第一种思路是策略型的,需要自己定义默认策略(链表chain默认DROP),而我们复用的fw_OUTPUT、fw_INPUT的规则是非策略型的,如下
int FirewallController::enableFirewall(void) {int res =0;// flush any existing rules disableFirewall();// create default rule to drop all traffic res |= execIptables(V4V6,"-A", LOCAL_INPUT,"-j","DROP",NULL); res |= execIptables(V4V6,"-A", LOCAL_OUTPUT,"-j","REJECT",NULL); res |= execIptables(V4V6,"-A", LOCAL_FORWARD,"-j","REJECT",NULL);return res; }
如果用这种思路就要修改这条链,或者自己再建一条链,比较麻烦,反而不如将“关闭所有网络”独立出来更方便。为了更灵活,我们选第二种思路。
关闭网络
在应用层调用NetworkManagementService的setFirewallEnabled(true)就好。打开DNS端口
仿照setFirewallEnabled方法,在它实现的类FirewallController.cpp添加int FirewallController::enableDNSPort(int protocol,int port) { char protocolStr[16];sprintf(protocolStr,"%d", protocol); char portStr[16];sprintf(portStr,"%d", port);int res =0; res |= execIptables(V4,"-I", LOCAL_INPUT,"-p", protocolStr,"--sport", portStr,"-j","ACCEPT", NULL); res |= execIptables(V4,"-I", LOCAL_OUTPUT,"-p", protocolStr,"--dport", portStr,"-j","ACCEP