""" This file is part of Mokonnect. Mokonnect is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License Version 3 as published by the Free Software Foundation. Mokonnect is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Mokonnect. If not, see . """ # # pyptables # a module to handle iptables configuration using process running # import subprocess IPTABLES_PATH = "/usr/sbin/iptables" FORWARD_PATH = "/proc/sys/net/ipv4/ip_forward" class IPTables(): def __init__(self): self.tables = ["filter","nat"] self.rules = {} def ForwardGet(self): fh = file(FORWARD_PATH,"rt") res = fh.read() fh.close() num = int(res.strip()) if num == 0: return False if num == 1: return True return None def ForwardSet(self,value): fh = file(FORWARD_PATH,"wt") strvalue = "0\n" if value: strvalue = "1\n" fh.write(strvalue) fh.close() def AddRule(self,table,rule): tid = table if not tid in self.rules: self.rules[tid] = [] # check if rule already exists for rid in range(len(self.rules[tid])): if self.rules[tid][rid] == rule: return (tid,rid) # add new rule self._iptables("-t %s %s" % (table,rule)) self.rules[tid].append(rule) # find rule id for rid in range(len(self.rules[tid])): if self.rules[tid][rid] == rule: return (tid,rid) return None def DelRuleRaw(self,table,rule_text): tid = table if not tid in self.rules: return True self._iptables("-t %s %s" % (tid,rule_text.replace("-A","-D"))) for rid in range(len(self.rules[tid])): if self.rules[tid][rid] == rule_text: del self.rules[tid][rid] break return True def DelRule(self,rid): tid = rid[0] rid = rid[1] rule_text = None # check if rule exists if tid in self.rules: if rid < len(self.rules[tid]): rule_text = self.rules[tid][rid] if not rule_text: return True # remove it return self.DelRuleRaw(tid,rule_text) def _iptables(self,params): params = params.split(" ") iptp = subprocess.Popen([IPTABLES_PATH] + params,stdout=subprocess.PIPE,stderr=subprocess.PIPE) res = iptp.communicate() return res[0]