1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96 |
"""
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 <http://www.gnu.org/licenses/>.
"""
#
# 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] |