338fb7dad8aea81b081512f8f013cf56f5b9d1e0
[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 = 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._chains = { }
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:lower() == 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 --- Find the names of all chains within the given table name.
206 -- @param table String containing the table name
207 -- @return              Table of chain names in the order they occur.
208 function IptParser.chains( self, table )
209         local lookup = { }
210         local chains = { }
211         for _, r in ipairs(self:find({table=table})) do
212                 if not lookup[r.chain] then
213                         lookup[r.chain]   = true
214                         chains[#chains+1] = r.chain
215                 end
216         end
217         return chains
218 end
219
220
221 --- Return the given firewall chain within the given table name.
222 -- @param table String containing the table name
223 -- @param chain String containing the chain name
224 -- @return              Table containing the fields "policy", "packets", "bytes"
225 --                              and "rules". The "rules" field is a table of rule tables.
226 function IptParser.chain( self, table, chain )
227         return self._chains[table:lower()] and self._chains[table:lower()][chain]
228 end
229
230
231 --- Test whether the given target points to a custom chain.
232 -- @param target        String containing the target action
233 -- @return                      Boolean indicating whether target is a custom chain.
234 function IptParser.is_custom_target( self, target )
235         for _, r in ipairs(self._rules) do
236                 if r.chain == target then
237                         return true
238                 end
239         end
240         return false
241 end
242
243
244 -- [internal] Parse iptables output from all tables.
245 function IptParser._parse_rules( self )
246
247         for i, tbl in ipairs({ "filter", "nat", "mangle" }) do
248
249                 self._chains[tbl] = { }
250
251                 for i, rule in ipairs(luci.util.execl("iptables -t " .. tbl .. " --line-numbers -nxvL")) do
252
253                         if rule:find( "Chain " ) == 1 then
254
255                                 local crefs
256                                 local cname, cpol, cpkt, cbytes = rule:match(
257                                         "Chain ([^%s]*) %(policy (%w+) " ..
258                                         "(%d+) packets, (%d+) bytes%)"
259                                 )
260
261                                 if not cname then
262                                         cname, crefs = rule:match(
263                                                 "Chain ([^%s]*) %((%d+) references%)"
264                                         )
265                                 end
266
267                                 self._chain = cname
268                                 self._chains[tbl][cname] = {
269                                         policy     = cpol,
270                                         packets    = tonumber(cpkt or 0),
271                                         bytes      = tonumber(cbytes or 0),
272                                         references = tonumber(crefs or 0),
273                                         rules      = { }
274                                 }
275
276                         else
277                                 if rule:find("%d") == 1 then
278
279                                         local rule_parts   = luci.util.split( rule, "%s+", nil, true )
280                                         local rule_details = { }
281
282                                         rule_details["table"]       = tbl
283                                         rule_details["chain"]       = self._chain
284                                         rule_details["index"]       = tonumber(rule_parts[1])
285                                         rule_details["packets"]     = tonumber(rule_parts[2])
286                                         rule_details["bytes"]       = tonumber(rule_parts[3])
287                                         rule_details["target"]      = rule_parts[4]
288                                         rule_details["protocol"]    = rule_parts[5]
289                                         rule_details["flags"]       = rule_parts[6]
290                                         rule_details["inputif"]     = rule_parts[7]
291                                         rule_details["outputif"]    = rule_parts[8]
292                                         rule_details["source"]      = rule_parts[9]
293                                         rule_details["destination"] = rule_parts[10]
294                                         rule_details["options"]     = { }
295
296                                         for i = 11, #rule_parts - 1 do
297                                                 rule_details["options"][i-10] = rule_parts[i]
298                                         end
299
300                                         self._rules[#self._rules+1] = rule_details
301
302                                         self._chains[tbl][self._chain].rules[
303                                                 #self._chains[tbl][self._chain].rules + 1
304                                         ] = rule_details
305                                 end
306                         end
307                 end
308         end
309
310         self._chain = nil
311 end
312
313
314 -- [internal] Return true if optlist1 contains all elements of optlist 2.
315 --            Return false in all other cases.
316 function IptParser._match_options( self, o1, o2 )
317
318         -- construct a hashtable of first options list to speed up lookups
319         local oh = { }
320         for i, opt in ipairs( o1 ) do oh[opt] = true end
321
322         -- iterate over second options list
323         -- each string in o2 must be also present in o1
324         -- if o2 contains a string which is not found in o1 then return false
325         for i, opt in ipairs( o2 ) do
326                 if not oh[opt] then
327                         return false
328                 end
329         end
330
331         return true
332 end