libs/sys/iptparser: import required functions
[project/luci.git] / libs / sys / luasrc / sys / iptparser.lua
1 --[[
2
3 Iptables parser and query library
4 (c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
5 (c) 2008 Steven Barth <steven@midlink.org>
6
7 Licensed under the Apache License, Version 2.0 (the "License");
8 you may not use this file except in compliance with the License.
9 You may obtain a copy of the License at
10
11         http://www.apache.org/licenses/LICENSE-2.0
12
13 $Id$
14
15 ]]--
16
17 local luci  = {}
18 luci.util   = require "luci.util"
19 luci.sys    = require "luci.sys"
20 luci.ip     = require "luci.ip"
21
22 local tonumber, ipairs = tonumber, ipairs
23
24 --- LuCI iptables parser and query library
25 -- @cstyle      instance
26 module("luci.sys.iptparser")
27
28 --- Create a new iptables parser object.
29 -- @class       function
30 -- @name        IptParser
31 -- @return      IptParser instance
32 IptParser = luci.util.class()
33
34 function IptParser.__init__( self, ... )
35         self._rules = { }
36         self._chain = nil
37         self:_parse_rules()
38 end
39
40 --- Find all firewall rules that match the given criteria. Expects a table with
41 -- search criteria as only argument. If args is nil or an empty table then all
42 -- rules will be returned.
43 --
44 -- The following keys in the args table are recognized:
45 -- <ul>
46 --  <li> table           - Match rules that are located within the given table
47 --  <li> chain           - Match rules that are located within the given chain
48 --  <li> target          - Match rules with the given target
49 --  <li> protocol        - Match rules that match the given protocol, rules with
50 --                                              protocol "all" are always matched
51 --  <li> source          - Match rules with the given source, rules with source
52 --                                              "0.0.0.0/0" are always matched
53 --  <li> destination - Match rules with the given destination, rules with
54 --                                              destination "0.0.0.0/0" are always matched
55 --  <li> inputif         - Match rules with the given input interface, rules
56 --                                              with input      interface "*" (=all) are always matched
57 --  <li> outputif        - Match rules with the given output interface, rules
58 --                                              with output     interface "*" (=all) are always matched
59 --  <li> flags           - Match rules that match the given flags, current
60 --                                              supported values are "-f" (--fragment)
61 --                                              and "!f" (! --fragment)
62 --  <li> options         - Match rules containing all given options
63 -- </ul>
64 -- The return value is a list of tables representing the matched rules.
65 -- Each rule table contains the following fields:
66 -- <ul>
67 --  <li> index           - The index number of the rule
68 --  <li> table           - The table where the rule is located, can be one
69 --                                              of "filter", "nat" or "mangle"
70 --  <li> chain           - The chain where the rule is located, e.g. "INPUT"
71 --                                              or "postrouting_wan"
72 --  <li> target          - The rule target, e.g. "REJECT" or "DROP"
73 --  <li> protocol               The matching protocols, e.g. "all" or "tcp"
74 --  <li> flags           - Special rule options ("--", "-f" or "!f")
75 --  <li> inputif         - Input interface of the rule, e.g. "eth0.0"
76 --                                              or "*" for all interfaces
77 --  <li> outputif        - Output interface of the rule,e.g. "eth0.0"
78 --                                              or "*" for all interfaces
79 --  <li> source          - The source ip range, e.g. "0.0.0.0/0"
80 --  <li> destination - The destination ip range, e.g. "0.0.0.0/0"
81 --  <li> options         - A list of specific options of the rule,
82 --                                              e.g. { "reject-with", "tcp-reset" }
83 --  <li> packets         - The number of packets matched by the rule
84 --  <li> bytes           - The number of total bytes matched by the rule
85 -- </ul>
86 -- Example:
87 -- <pre>
88 -- ip = luci.sys.iptparser.IptParser()
89 -- result = ip.find( {
90 --      target="REJECT",
91 --      protocol="tcp",
92 --      options={ "reject-with", "tcp-reset" }
93 -- } )
94 -- </pre>
95 -- This will match all rules with target "-j REJECT",
96 -- protocol "-p tcp" (or "-p all")
97 -- and the option "--reject-with tcp-reset".
98 -- @params args         Table containing the search arguments (optional)
99 -- @return                      Table of matching rule tables
100 function IptParser.find( self, args )
101
102         local args = args or { }
103         local rv   = { }
104
105         args.source      = args.source      and luci.ip.IPv4(args.source)
106         args.destination = args.destination and luci.ip.IPv4(args.destination)
107
108         for i, rule in ipairs(self._rules) do
109                 local match = true
110
111                 -- match table
112                 if not ( not args.table or args.table == rule.table ) then
113                         match = false
114                 end
115
116                 -- match chain
117                 if not ( match == true and (
118                         not args.chain or args.chain == rule.chain
119                 ) ) then
120                         match = false
121                 end
122
123                 -- match target
124                 if not ( match == true and (
125                         not args.target or args.target:upper() == rule.target
126                 ) ) then
127                         match = false
128                 end
129
130                 -- match protocol
131                 if not ( match == true and (
132                         not args.protocol or rule.protocol == "all" or
133                         args.protocol:lower() == rule.protocol
134                 ) ) then
135                         match = false
136                 end
137
138                 -- match source
139                 if not ( match == true and (
140                         not args.source or rule.source == "0.0.0.0/0" or
141                         luci.ip.IPv4(rule.source):contains(args.source)
142                 ) ) then
143                         match = false
144                 end
145
146                 -- match destination
147                 if not ( match == true and (
148                         not args.destination or rule.destination == "0.0.0.0/0" or
149                         luci.ip.IPv4(rule.destination):contains(args.destination)
150                 ) ) then
151                         match = false
152                 end
153
154                 -- match input interface
155                 if not ( match == true and (
156                         not args.inputif or rule.inputif == "*" or
157                         args.inputif == rule.inputif
158                 ) ) then
159                         match = false
160                 end
161
162                 -- match output interface
163                 if not ( match == true and (
164                         not args.outputif or rule.outputif == "*" or
165                         args.outputif == rule.outputif
166                 ) ) then
167                         match = false
168                 end
169
170                 -- match flags (the "opt" column)
171                 if not ( match == true and (
172                         not args.flags or rule.flags == args.flags
173                 ) ) then
174                         match = false
175                 end
176
177                 -- match specific options
178                 if not ( match == true and (
179                         not args.options or
180                         self:_match_options( rule.options, args.options )
181                 ) ) then
182                         match = false
183                 end
184
185                 -- insert match
186                 if match == true then
187                         rv[#rv+1] = rule
188                 end
189         end
190
191         return rv
192 end
193
194
195 --- Rebuild the internal lookup table, for example when rules have changed
196 -- through external commands.
197 -- @return      nothing
198 function IptParser.resync( self )
199         self._rules = { }
200         self._chain = nil
201         self:_parse_rules()
202 end
203
204
205 -- [internal] Parse iptables output from all tables.
206 function IptParser._parse_rules( self )
207
208         for i, tbl in ipairs({ "filter", "nat", "mangle" }) do
209
210                 for i, rule in ipairs(luci.util.execl("iptables -t " .. tbl .. " --line-numbers -nxvL")) do
211
212                         if rule:find( "Chain " ) == 1 then
213
214                                 self._chain = rule:gsub("Chain ([^%s]*) .*", "%1")
215
216                         else
217                                 if rule:find("%d") == 1 then
218
219                                         local rule_partmays   = luci.util.split( rule, "%s+", nil, true )
220                                         local rule_details = { }
221
222                                         rule_details["table"]       = tbl
223                                         rule_details["chain"]       = self._chain
224                                         rule_details["index"]       = tonumber(rule_parts[1])
225                                         rule_details["packets"]     = tonumber(rule_parts[2])
226                                         rule_details["bytes"]       = tonumber(rule_parts[3])
227                                         rule_details["target"]      = rule_parts[4]
228                                         rule_details["protocol"]    = rule_parts[5]
229                                         rule_details["flags"]       = rule_parts[6]
230                                         rule_details["inputif"]     = rule_parts[7]
231                                         rule_details["outputif"]    = rule_parts[8]
232                                         rule_details["source"]      = rule_parts[9]
233                                         rule_details["destination"] = rule_parts[10]
234                                         rule_details["options"]     = { }
235
236                                         for i = 11, #rule_parts - 1 do
237                                                 rule_details["options"][i-10] = rule_parts[i]
238                                         end
239
240                                         self._rules[#self._rules+1] = rule_details
241                                 end
242                         end
243                 end
244         end
245
246         self._chain = nil
247 end
248
249
250 -- [internal] Return true if optlist1 contains all elements of optlist 2.
251 --            Return false in all other cases.
252 function IptParser._match_options( self, o1, o2 )
253
254         -- construct a hashtable of first options list to speed up lookups
255         local oh = { }
256         for i, opt in ipairs( o1 ) do oh[opt] = true end
257
258         -- iterate over second options list
259         -- each string in o2 must be also present in o1
260         -- if o2 contains a string which is not found in o1 then return false
261         for i, opt in ipairs( o2 ) do
262                 if not oh[opt] then
263                         return false
264                 end
265         end
266
267         return true
268 end