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