libs/sys: fix incomplete options table when parsing iptables rules
[project/luci.git] / libs / sys / luasrc / sys / iptparser.lua
1 --[[
2
3 Iptables parser and query library
4 (c) 2008-2009 Jo-Philipp Wich <xm@leipzig.freifunk.net>
5 (c) 2008-2009 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, table = tonumber, ipairs, table
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 -- @param       family  Number specifying the address family. 4 for IPv4, 6 for IPv6
32 -- @return      IptParser instance
33 IptParser = luci.util.class()
34
35 function IptParser.__init__( self, family )
36         self._family = (tonumber(family) == 6) and 6 or 4
37         self._rules  = { }
38         self._chains = { }
39
40         if self._family == 4 then
41                 self._nulladdr = "0.0.0.0/0"
42                 self._tables   = { "filter", "nat", "mangle", "raw" }
43                 self._command  = "iptables -t %s --line-numbers -nxvL"
44         else
45                 self._nulladdr = "::/0"
46                 self._tables   = { "filter", "mangle", "raw" }
47                 self._command  = "ip6tables -t %s --line-numbers -nxvL"
48         end
49
50         self:_parse_rules()
51 end
52
53 --- Find all firewall rules that match the given criteria. Expects a table with
54 -- search criteria as only argument. If args is nil or an empty table then all
55 -- rules will be returned.
56 --
57 -- The following keys in the args table are recognized:
58 -- <ul>
59 --  <li> table           - Match rules that are located within the given table
60 --  <li> chain           - Match rules that are located within the given chain
61 --  <li> target          - Match rules with the given target
62 --  <li> protocol        - Match rules that match the given protocol, rules with
63 --                                              protocol "all" are always matched
64 --  <li> source          - Match rules with the given source, rules with source
65 --                                              "0.0.0.0/0" (::/0) are always matched
66 --  <li> destination - Match rules with the given destination, rules with
67 --                                              destination "0.0.0.0/0" (::/0) are always matched
68 --  <li> inputif         - Match rules with the given input interface, rules
69 --                                              with input      interface "*" (=all) are always matched
70 --  <li> outputif        - Match rules with the given output interface, rules
71 --                                              with output     interface "*" (=all) are always matched
72 --  <li> flags           - Match rules that match the given flags, current
73 --                                              supported values are "-f" (--fragment)
74 --                                              and "!f" (! --fragment)
75 --  <li> options         - Match rules containing all given options
76 -- </ul>
77 -- The return value is a list of tables representing the matched rules.
78 -- Each rule table contains the following fields:
79 -- <ul>
80 --  <li> index           - The index number of the rule
81 --  <li> table           - The table where the rule is located, can be one
82 --                                              of "filter", "nat" or "mangle"
83 --  <li> chain           - The chain where the rule is located, e.g. "INPUT"
84 --                                              or "postrouting_wan"
85 --  <li> target          - The rule target, e.g. "REJECT" or "DROP"
86 --  <li> protocol               The matching protocols, e.g. "all" or "tcp"
87 --  <li> flags           - Special rule options ("--", "-f" or "!f")
88 --  <li> inputif         - Input interface of the rule, e.g. "eth0.0"
89 --                                              or "*" for all interfaces
90 --  <li> outputif        - Output interface of the rule,e.g. "eth0.0"
91 --                                              or "*" for all interfaces
92 --  <li> source          - The source ip range, e.g. "0.0.0.0/0" (::/0)
93 --  <li> destination - The destination ip range, e.g. "0.0.0.0/0" (::/0)
94 --  <li> options         - A list of specific options of the rule,
95 --                                              e.g. { "reject-with", "tcp-reset" }
96 --  <li> packets         - The number of packets matched by the rule
97 --  <li> bytes           - The number of total bytes matched by the rule
98 -- </ul>
99 -- Example:
100 -- <pre>
101 -- ip = luci.sys.iptparser.IptParser()
102 -- result = ip.find( {
103 --      target="REJECT",
104 --      protocol="tcp",
105 --      options={ "reject-with", "tcp-reset" }
106 -- } )
107 -- </pre>
108 -- This will match all rules with target "-j REJECT",
109 -- protocol "-p tcp" (or "-p all")
110 -- and the option "--reject-with tcp-reset".
111 -- @params args         Table containing the search arguments (optional)
112 -- @return                      Table of matching rule tables
113 function IptParser.find( self, args )
114
115         local args = args or { }
116         local rv   = { }
117
118         args.source      = args.source      and self:_parse_addr(args.source)
119         args.destination = args.destination and self:_parse_addr(args.destination)
120
121         for i, rule in ipairs(self._rules) do
122                 local match = true
123
124                 -- match table
125                 if not ( not args.table or args.table:lower() == rule.table ) then
126                         match = false
127                 end
128
129                 -- match chain
130                 if not ( match == true and (
131                         not args.chain or args.chain == rule.chain
132                 ) ) then
133                         match = false
134                 end
135
136                 -- match target
137                 if not ( match == true and (
138                         not args.target or args.target == rule.target
139                 ) ) then
140                         match = false
141                 end
142
143                 -- match protocol
144                 if not ( match == true and (
145                         not args.protocol or rule.protocol == "all" or
146                         args.protocol:lower() == rule.protocol
147                 ) ) then
148                         match = false
149                 end
150
151                 -- match source
152                 if not ( match == true and (
153                         not args.source or rule.source == self._nulladdr or
154                         self:_parse_addr(rule.source):contains(args.source)
155                 ) ) then
156                         match = false
157                 end
158
159                 -- match destination
160                 if not ( match == true and (
161                         not args.destination or rule.destination == self._nulladdr or
162                         self:_parse_addr(rule.destination):contains(args.destination)
163                 ) ) then
164                         match = false
165                 end
166
167                 -- match input interface
168                 if not ( match == true and (
169                         not args.inputif or rule.inputif == "*" or
170                         args.inputif == rule.inputif
171                 ) ) then
172                         match = false
173                 end
174
175                 -- match output interface
176                 if not ( match == true and (
177                         not args.outputif or rule.outputif == "*" or
178                         args.outputif == rule.outputif
179                 ) ) then
180                         match = false
181                 end
182
183                 -- match flags (the "opt" column)
184                 if not ( match == true and (
185                         not args.flags or rule.flags == args.flags
186                 ) ) then
187                         match = false
188                 end
189
190                 -- match specific options
191                 if not ( match == true and (
192                         not args.options or
193                         self:_match_options( rule.options, args.options )
194                 ) ) then
195                         match = false
196                 end
197
198                 -- insert match
199                 if match == true then
200                         rv[#rv+1] = rule
201                 end
202         end
203
204         return rv
205 end
206
207
208 --- Rebuild the internal lookup table, for example when rules have changed
209 -- through external commands.
210 -- @return      nothing
211 function IptParser.resync( self )
212         self._rules = { }
213         self._chain = nil
214         self:_parse_rules()
215 end
216
217
218 --- Find the names of all tables.
219 -- @return              Table of table names.
220 function IptParser.tables( self )
221         return self._tables
222 end
223
224
225 --- Find the names of all chains within the given table name.
226 -- @param table String containing the table name
227 -- @return              Table of chain names in the order they occur.
228 function IptParser.chains( self, table )
229         local lookup = { }
230         local chains = { }
231         for _, r in ipairs(self:find({table=table})) do
232                 if not lookup[r.chain] then
233                         lookup[r.chain]   = true
234                         chains[#chains+1] = r.chain
235                 end
236         end
237         return chains
238 end
239
240
241 --- Return the given firewall chain within the given table name.
242 -- @param table String containing the table name
243 -- @param chain String containing the chain name
244 -- @return              Table containing the fields "policy", "packets", "bytes"
245 --                              and "rules". The "rules" field is a table of rule tables.
246 function IptParser.chain( self, table, chain )
247         return self._chains[table:lower()] and self._chains[table:lower()][chain]
248 end
249
250
251 --- Test whether the given target points to a custom chain.
252 -- @param target        String containing the target action
253 -- @return                      Boolean indicating whether target is a custom chain.
254 function IptParser.is_custom_target( self, target )
255         for _, r in ipairs(self._rules) do
256                 if r.chain == target then
257                         return true
258                 end
259         end
260         return false
261 end
262
263
264 -- [internal] Parse address according to family.
265 function IptParser._parse_addr( self, addr )
266         if self._family == 4 then
267                 return luci.ip.IPv4(addr)
268         else
269                 return luci.ip.IPv6(addr)
270         end
271 end
272
273 -- [internal] Parse iptables output from all tables.
274 function IptParser._parse_rules( self )
275
276         for i, tbl in ipairs(self._tables) do
277
278                 self._chains[tbl] = { }
279
280                 for i, rule in ipairs(luci.util.execl(self._command % tbl)) do
281
282                         if rule:find( "^Chain " ) == 1 then
283
284                                 local crefs
285                                 local cname, cpol, cpkt, cbytes = rule:match(
286                                         "^Chain ([^%s]*) %(policy (%w+) " ..
287                                         "(%d+) packets, (%d+) bytes%)"
288                                 )
289
290                                 if not cname then
291                                         cname, crefs = rule:match(
292                                                 "^Chain ([^%s]*) %((%d+) references%)"
293                                         )
294                                 end
295
296                                 self._chain = cname
297                                 self._chains[tbl][cname] = {
298                                         policy     = cpol,
299                                         packets    = tonumber(cpkt or 0),
300                                         bytes      = tonumber(cbytes or 0),
301                                         references = tonumber(crefs or 0),
302                                         rules      = { }
303                                 }
304
305                         else
306                                 if rule:find("%d") == 1 then
307
308                                         local rule_parts   = luci.util.split( rule, "%s+", nil, true )
309                                         local rule_details = { }
310
311                                         -- cope with rules that have no target assigned
312                                         if rule:match("^%d+%s+%d+%s+%d+%s%s") then
313                                                 table.insert(rule_parts, 4, nil)
314                                         end
315
316                                         -- ip6tables opt column is usually zero-width
317                                         if self._family == 6 then
318                                                 table.insert(rule_parts, 6, "--")
319                                         end
320
321                                         rule_details["table"]       = tbl
322                                         rule_details["chain"]       = self._chain
323                                         rule_details["index"]       = tonumber(rule_parts[1])
324                                         rule_details["packets"]     = tonumber(rule_parts[2])
325                                         rule_details["bytes"]       = tonumber(rule_parts[3])
326                                         rule_details["target"]      = rule_parts[4]
327                                         rule_details["protocol"]    = rule_parts[5]
328                                         rule_details["flags"]       = rule_parts[6]
329                                         rule_details["inputif"]     = rule_parts[7]
330                                         rule_details["outputif"]    = rule_parts[8]
331                                         rule_details["source"]      = rule_parts[9]
332                                         rule_details["destination"] = rule_parts[10]
333                                         rule_details["options"]     = { }
334
335                                         for i = 11, #rule_parts  do
336                                                 if #rule_parts[i] > 0 then
337                                                         rule_details["options"][i-10] = rule_parts[i]
338                                                 end
339                                         end
340
341                                         self._rules[#self._rules+1] = rule_details
342
343                                         self._chains[tbl][self._chain].rules[
344                                                 #self._chains[tbl][self._chain].rules + 1
345                                         ] = rule_details
346                                 end
347                         end
348                 end
349         end
350
351         self._chain = nil
352 end
353
354
355 -- [internal] Return true if optlist1 contains all elements of optlist 2.
356 --            Return false in all other cases.
357 function IptParser._match_options( self, o1, o2 )
358
359         -- construct a hashtable of first options list to speed up lookups
360         local oh = { }
361         for i, opt in ipairs( o1 ) do oh[opt] = true end
362
363         -- iterate over second options list
364         -- each string in o2 must be also present in o1
365         -- if o2 contains a string which is not found in o1 then return false
366         for i, opt in ipairs( o2 ) do
367                 if not oh[opt] then
368                         return false
369                 end
370         end
371
372         return true
373 end