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