model.lua 17 KB
Newer Older
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
1 2
--[[
Base data model for Alpine Wall
3
Copyright (C) 2012-2016 Kaarle Ritvanen
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
4
See LICENSE file for license details
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
5 6 7
]]--


8
local M = {}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
9 10


11 12 13 14
local loadclass = require('awall').loadclass
M.class = require('awall.class')
local resolve = require('awall.host')
local builtin = require('awall.iptables').builtin
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
15

16 17
local optfrag = require('awall.optfrag')
local combinations = optfrag.combinations
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
18

19
local raise = require('awall.uerror').raise
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
20

21 22 23 24
local util = require('awall.util')
local contains = util.contains
local extend = util.extend
local filter = util.filter
25
local join = util.join
26 27
local listpairs = util.listpairs
local maplist = util.maplist
28
local setdefault = util.setdefault
29

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
30

31 32 33 34 35 36
local startswith = require('stringy').startswith


M.ConfigObject = M.class()

function M.ConfigObject:init(context, location)
37 38
   if context then
      self.context = context
39
      self.root = context.objects
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
40
   end
41
   self.location = location
42 43

   self.extraobjs = {}
44
   self.uniqueids = {}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
45 46
end

47 48 49 50 51 52 53 54
function M.ConfigObject:create(cls, params, label, index)
   local key
   if label then
      key = label..(index or '')
      local obj = self.extraobjs[key]
      if obj then return obj end
   end

55 56
   if type(cls) == 'string' then
      local name = cls
57
      cls = loadclass(cls)
58 59 60 61
      if not cls then
	 self:error('Support for '..name..' objects not installed')
      end
   end
62

63
   if type(params) ~= 'table' then params = {params} end
64
   params.label = join(self.label, '-', label)
65

66 67 68
   local obj = cls.morph(params, self.context, self.location)
   if key then self.extraobjs[key] = obj end
   return obj
69 70
end

71
function M.ConfigObject:uniqueid(key)
72
   if not key then key = '' end
73 74
   if self.uniqueids[key] then return self.uniqueids[key] end

75
   local lastid = setdefault(self.context, 'lastid', {})
76
   local res = join(key, '-', self.label)
77
   lastid[res] = setdefault(lastid, res, -1) + 1
78 79 80 81 82 83
   res = res..'-'..lastid[res]

   self.uniqueids[key] = res
   return res
end

84
function M.ConfigObject:error(msg) raise(self.location..': '..msg) end
85

86
function M.ConfigObject:warning(msg)
87
   util.printmsg(self.location..': '..msg)
88 89
end

90
function M.ConfigObject:trules() return {} end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
91

92
function M.ConfigObject:info()
93 94
   local res = {}
   for i, trule in ipairs(self:trules()) do
95
      table.insert(res, {'  '..optfrag.location(trule), optfrag.command(trule)})
96 97 98 99
   end
   return res
end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
100

101
M.Zone = M.class(M.ConfigObject)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
102

103
function M.Zone:optfrags(dir)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
104 105 106 107 108 109 110
   local iopt, aopt, iprop, aprop
   if dir == 'in' then
      iopt, aopt, iprop, aprop = 'i', 's', 'in', 'src'
   elseif dir == 'out' then
      iopt, aopt, iprop, aprop = 'o', 'd', 'out', 'dest'
   else assert(false) end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
111 112 113
   local aopts = nil
   if self.addr then
      aopts = {}
114 115
      for i, hostdef in listpairs(self.addr) do
	 for i, addr in ipairs(resolve(hostdef, self)) do
116 117 118 119
	    table.insert(
	       aopts,
	       {family=addr[1], [aprop]=addr[2], match='-'..aopt..' '..addr[2]}
	    )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
120
	 end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
121 122 123
      end
   end

124 125 126 127
   local popt
   if self.ipsec ~= nil then
      popt = {
	 {
128
	    match='-m policy --dir '..dir..' --pol '..
129 130 131 132 133
	       (self.ipsec and 'ipsec' or 'none')
	 }
      }
   end

134 135 136
   return combinations(
      maplist(
	 self.iface,
137
	 function(x) return {[iprop]=x, match='-'..iopt..' '..x} end
138
      ),
139 140
      aopts,
      popt
141
   )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
142 143 144
end


145
M.fwzone = M.Zone()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
146 147


148
local IPSet = M.class(M.ConfigObject)
149 150

function IPSet:init(...)
151
   IPSet.super(self):init(...)
152 153 154

   if not self.type then self:error('Type not defined') end

155
   if startswith(self.type, 'bitmap:') then
156 157 158 159
      if not self.range then self:error('Range not defined') end
      self.options = {self.type, 'range', self.range}
      self.family = 'inet'

160
   elseif startswith(self.type, 'hash:') then
161 162 163 164 165 166 167 168 169
      if not self.family then self:error('Family not defined') end
      self.options = {self.type, 'family', self.family}

   elseif self.type == 'list:set' then self.options = {self.type}

   else self:error('Invalid type: '..self.type) end
end


170
M.Rule = M.class(M.ConfigObject)
171

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
172

173 174
function M.Rule:init(...)
   M.Rule.super(self):init(...)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
175 176

   for i, prop in ipairs({'in', 'out'}) do
177 178 179 180 181 182 183 184 185
      self[prop] = self[prop] and maplist(
	 self[prop],
	 function(z)
	    if type(z) ~= 'string' then return z end
	    return z == '_fw' and M.fwzone or
	       self.root.zone[z] or
	       self:error('Invalid zone: '..z)
	 end
      )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
186
   end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
187

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
   -- alpine v3.4 compatibility
   if self.ipsec then
      if not contains({'in', 'out'}, self.ipsec) then
	 self:error('Invalid ipsec policy direction')
      end
      self:warning('ipsec deprecated in rules, define in zones instead')
      local zones = self[self.ipsec]
      if zones then
	 self[self.ipsec] = maplist(
	    zones,
	    function(z)
	       return self:create(
		  M.Zone, {iface=z.iface, addr=z.addr, ipsec=true}
	       )
	    end
	 )
      else self[self.ipsec] = {self:create(M.Zone, {ipsec=true})} end
      self.ipsec = nil
   end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
208
   if self.service then
209 210 211 212
      if not self.label and type(self.service) == 'string' then
	 self.label = self.service
      end

213 214 215 216 217 218
      self.service = util.list(self.service)

      for i, serv in ipairs(self.service) do
	 if type(serv) == 'string' then
	    self.service[i] = self.root.service[serv] or
	       self:error('Invalid service: '..serv)
219
	 end
220 221 222 223 224 225 226
	 for i, sdef in listpairs(self.service[i]) do
	    if not sdef.proto then self:error('Protocol not defined') end
	    sdef.proto = (
	       {[1]='icmp', [6]='tcp', [17]='udp', [58]='ipv6-icmp'}
            )[sdef.proto] or sdef.proto
	 end
      end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
227 228 229 230
   end
end


231
function M.Rule:direction(dir)
232 233 234 235 236 237
   if dir == 'in' then return self.reverse and 'out' or 'in' end
   if dir == 'out' then return self.reverse and 'in' or 'out' end
   self:error('Invalid direction: '..dir)
end


238
function M.Rule:zoneoptfrags()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
239

240
   local function zonepair(zin, zout)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
241

242
      local function zofs(zone, dir)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
243
	 if not zone then return zone end
244
	 return zone:optfrags(dir)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
245 246 247 248
      end

      local chain, ofrags

249
      if zin == M.fwzone or zout == M.fwzone then
250
	 if zin == zout then return {} end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
251
	 local dir, z = 'in', zin
252
	 if zin == M.fwzone then dir, z = 'out', zout end
253
	 chain = dir:upper()..'PUT'
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
254 255
	 ofrags = zofs(z, dir)

256 257 258 259 260 261 262 263 264 265 266
      elseif not zin or not zout then

	 if zin then
	    chain = 'PREROUTING'
	    ofrags = zofs(zin, 'in')

	 elseif zout then
	    chain = 'POSTROUTING'
	    ofrags = zofs(zout, 'out')
	 end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
267 268
      else
	 chain = 'FORWARD'
269 270
	 ofrags = combinations(zofs(zin, 'in'), zofs(zout, 'out'))

271
	 if ofrags and not zout['route-back'] then
272 273 274 275 276 277
	    ofrags = filter(
	       ofrags,
	       function(of)
		  return not (of['in'] and of.out and of['in'] == of.out)
	       end
	    )
278
	 end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
279 280
      end

281 282 283
      return combinations(ofrags,
			  chain and {{chain=chain}} or {{chain='PREROUTING'},
							{chain='OUTPUT'}})
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
284 285 286
   end

   local res = {}
287 288
   local izones = self[self:direction('in')] or {}
   local ozones = self[self:direction('out')] or {}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
289

290 291
   for i = 1,math.max(1, table.maxn(izones)) do
      for j = 1,math.max(1, table.maxn(ozones)) do
292
	 extend(res, zonepair(izones[i], ozones[j]))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
293 294 295 296 297 298 299
      end
   end

   return res
end


300
function M.Rule:servoptfrags()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
301 302 303

   if not self.service then return end

304
   local fports = {inet={}, inet6={}}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
305 306 307
   local res = {}

   for i, serv in ipairs(self.service) do
308
      for i, sdef in listpairs(serv) do
309
	 if contains({'tcp', 'udp'}, sdef.proto) then
310 311 312 313 314 315 316 317
	    for family, ports in pairs(fports) do
	       if not sdef.family or family == sdef.family then

		  local new = not ports[sdef.proto]
		  if new then ports[sdef.proto] = {} end

		  if new or ports[sdef.proto][1] then
		     if sdef.port then
318
			extend(
319
			   ports[sdef.proto],
320
			   maplist(
321
			      sdef.port,
322
			      function(p) return tostring(p):gsub('-', ':') end
323 324 325 326 327
			   )
			)
		     else ports[sdef.proto] = {} end
		  end
	       end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
328 329 330 331 332 333 334
	    end

	 else

	    local opts = '-p '..sdef.proto
	    local family = nil

335 336
	    -- TODO multiple ICMP types per rule
	    local oname
337
	    if sdef.proto == 'icmp' then
338 339
	       family = 'inet'
	       oname = 'icmp-type'
340
	    elseif contains({'ipv6-icmp', 'icmpv6'}, sdef.proto) then
341 342
	       family = 'inet6'
	       oname = 'icmpv6-type'
343
	    elseif sdef.type or sdef['reply-type'] then
344
	       self:error('Type specification not valid with '..sdef.proto)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
345 346
	    end

347 348 349 350 351 352 353 354 355
	    if sdef.family then
	       if not family then family = sdef.family
	       elseif family ~= sdef.family then
		  self:error(
		     'Protocol '..sdef.proto..' is incompatible with '..sdef.family
		  )
	       end
	    end

356 357
	    if sdef.type then
	       opts = opts..' --'..oname..' '..(
358
		  self.reverse and sdef['reply-type'] or sdef.type
359 360
	       )
	    end
361
	    table.insert(res, {family=family, match=opts})
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
362 363 364 365
	 end
      end
   end

366
   local popt = ' --'..(self.reverse and 's' or 'd')..'port'
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
   for family, pports in pairs(fports) do
      local ofrags = {}

      for proto, ports in pairs(pports) do
	 local propt = '-p '..proto

	 if ports[1] then
	    local len = #ports
	    repeat
	       local opts

	       if len == 1 then
		  opts = propt..popt..' '..ports[1]
		  len = 0

	       else
		  opts = propt..' -m multiport'..popt..'s '
		  local pc = 0
		  repeat
		     local sep = pc == 0 and '' or ','
		     local port = ports[1]
		     
389
		     pc = pc + (port:find(':') and 2 or 1)
390 391 392 393 394 395 396 397 398
		     if pc > 15 then break end
		     
		     opts = opts..sep..port
		     
		     table.remove(ports, 1)
		     len = len - 1
		  until len == 0
	       end

399
	       table.insert(ofrags, {match=opts})
400 401
	    until len == 0

402
	 else table.insert(ofrags, {match=propt}) end
403
      end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
404

405
      extend(res, combinations(ofrags, {{family=family}}))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
406 407 408 409 410
   end

   return res
end

411 412
function M.Rule:destoptfrags()
   return self:create(M.Zone, {addr=self.dest}):optfrags(self:direction('out'))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
413 414
end

415
function M.Rule:table() return 'filter' end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
416

417
function M.Rule:position() return 'append' end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
418

419
function M.Rule:target()
420 421 422 423 424 425 426 427 428 429
   -- alpine v2.7 compatibility
   if self.action == 'accept' then
      self:warning("'accept' action deprecated in favor of 'exclude'")
      self.action = 'exclude'
   end

   if self.action == 'exclude' then return 'ACCEPT' end
   if self.action and self.action ~= 'include' then
      self:error('Invalid action: '..self.action)
   end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
430 431 432
end


433
function M.Rule:trules()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
434

435
   local function tag(ofrags, tag, value)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
436 437 438 439 440 441 442 443
      for i, ofrag in ipairs(ofrags) do
	 assert(not ofrag[tag])
	 ofrag[tag] = value
      end
   end

   local families

444
   local function setfamilies(ofrags)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
445 446 447 448 449 450 451 452 453 454 455 456
      if ofrags then
	 families = {}
	 for i, ofrag in ipairs(ofrags) do
	    if not ofrag.family then
	       families = nil
	       return
	    end
	    table.insert(families, ofrag.family)
	 end
      else families = nil end
   end

457
   local function ffilter(ofrags)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
458
      if not ofrags or not ofrags[1] or not families then return ofrags end
459 460 461 462 463 464
      return filter(
	 ofrags,
	 function(of)
	    return not of.family or contains(families, of.family)
	 end
      )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
465 466
   end

467
   local ofrags = self:zoneoptfrags()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
468

469
   if self.ipset then
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
470
      local ipsetofrags = {}
471
      for i, ipset in listpairs(self.ipset) do
472
	 if not ipset.name then self:error('Set name not defined') end
473

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
474
	 local setdef = self.root.ipset and self.root.ipset[ipset.name]
475
	 if not setdef then self:error('Invalid set name') end
476

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
477
	 if not ipset.args then
478
	    self:error('Set direction arguments not defined')
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
479
	 end
480

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
481
	 local setopts = '-m set --match-set '..ipset.name..' '
482 483
	 setopts = setopts..table.concat(util.map(util.list(ipset.args),
						  function(a)
484 485 486 487
						     if self:direction(a) == 'in' then
							return 'src'
						     end
						     return 'dst'
488 489
						  end),
					 ',')
490
	 table.insert(ipsetofrags, {family=setdef.family, match=setopts})
491
      end
492
      ofrags = combinations(ofrags, ipsetofrags)
493 494
   end

495
   if self.match then ofrags = combinations(ofrags, {{match=self.match}}) end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
496

497
   ofrags = combinations(ofrags, self:servoptfrags())
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
498

499
   setfamilies(ofrags)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
500

501 502 503 504
   local addrofrags = combinations(
      self:create(M.Zone, {addr=self.src}):optfrags(self:direction('in')),
      self:destoptfrags()
   )
505
   local combined = ofrags
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
506 507 508 509

   if addrofrags then
      addrofrags = ffilter(addrofrags)
      setfamilies(addrofrags)
510
      ofrags = ffilter(ofrags)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
511

512
      combined = {}
513
      for i, ofrag in ipairs(ofrags) do
514 515 516
	 local aofs = combinations(addrofrags, {{family=ofrag.family}})
	 local cc = combinations({ofrag}, aofs)
	 if #cc < #aofs then
517 518 519
	    combined = nil
	    break
	 end
520
	 extend(combined, cc)
521
      end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
522 523
   end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
524 525 526 527
   local custom = self:customtarget()
   local final = custom or self:target()

   local nxt
528
   if combined then
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
529
      nxt = final
530
      ofrags = combined
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
531
   else nxt = self:uniqueid('address') end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
532

533
   tag(ofrags, 'position', self:position())
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
534

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
535
   ofrags = combinations(ofrags, {{target=nxt}})
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
536

537
   if not combined then
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
538 539 540 541 542 543
      extend(ofrags, combinations(addrofrags, {{chain=nxt, target=final}}))
   end

   local function extofrags(new)
      if not custom then extend(ofrags, new)
      elseif new[1] then self:error('Custom action not allowed here') end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
544 545
   end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
546
   extofrags(self:extraoptfrags())
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
547

548 549 550 551 552 553 554
   local tbl = self:table()

   local function convertchains(ofrags)
      local res = {}

      for i, ofrag in ipairs(ofrags) do

555
	 if contains(builtin[tbl], ofrag.chain) then table.insert(res, ofrag)
556
	 else
557 558 559
	    local ofs, recursive
	    if ofrag.chain == 'PREROUTING' then
	       ofs = {{chain='FORWARD'}, {chain='INPUT'}}
560
	    elseif ofrag.chain == 'POSTROUTING' then
561 562 563
	       ofs = {{chain='FORWARD'}, {chain='OUTPUT'}}
	       recursive = true
	    elseif ofrag.chain == 'INPUT' then
564 565 566
	       ofs = {
	          {match='-m addrtype --dst-type LOCAL', chain='PREROUTING'}
	       }
567 568
	    elseif ofrag.chain == 'FORWARD' then
	       ofs = {
569
		  {match='-m addrtype ! --dst-type LOCAL', chain='PREROUTING'}
570
	       }
571 572
	    end

573
	    if ofs then
574
	       ofrag.chain = nil
575 576
	       ofs = combinations(ofs, {ofrag})
	       if recursive then ofs = convertchains(ofs) end
577
	       extend(res, ofs)
578

579 580 581 582 583 584 585
	    else table.insert(res, ofrag) end
	 end
      end

      return res
   end

586 587
   ofrags = convertchains(ffilter(ofrags))
   tag(ofrags, 'table', tbl, false)
588 589

   local function checkzof(ofrag, dir, chains)
590
      if ofrag[dir] and contains(chains, ofrag.chain) then
591 592 593 594
	 self:error('Cannot specify '..dir..'bound interface ('..ofrag[dir]..')')
      end
   end

595
   for i, ofrag in ipairs(ofrags) do
596 597 598
      checkzof(ofrag, 'in', {'OUTPUT', 'POSTROUTING'})
      checkzof(ofrag, 'out', {'INPUT', 'PREROUTING'})
   end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
599
   
600 601 602 603
   ofrags = filter(
      combinations(ofrags, ffilter({{family='inet'}, {family='inet6'}})),
      function(r) return self:trulefilter(r) end
   )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
604 605 606 607 608 609 610 611 612 613
   extofrags(self:extratrules(ofrags))

   return ofrags
end

function M.Rule:customtarget()
   if self.action then
      local as = self.action:sub(1, 1)
      if as == as:upper() then return self.action end
   end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
614 615
end

616
function M.Rule:extraoptfrags() return {} end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
617

618 619 620 621
function M.Rule:trulefilter(rule) return true end

function M.Rule:extratrules(rules) return {} end

622 623 624 625
function M.Rule:extrarules(label, cls, options)
   local params = {}

   for _, attr in ipairs(
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
626 627 628 629
      extend(
         {'in', 'out', 'src', 'dest', 'ipset', 'match', 'service'},
	 options.attrs
      )
630 631 632 633 634 635 636 637 638 639
   ) do
      params[attr] = (options.src or self)[attr]
   end

   util.update(params, options.update)
   if options.discard then params[options.discard] = nil end

   return self:create(cls, params, label, options.index):trules()
end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
640

641 642 643 644 645 646 647 648 649 650 651 652
M.Limit = M.class(M.ConfigObject)

function M.Limit:init(...)
   M.Limit.super(self):init(...)

   if not self.count then
      if not self[1] then
	 self:error('Packet count not defined for limit')
      end
      self.count = self[1]
   end

653
   setdefault(self, 'interval', 1)
654 655 656 657

   if type(setdefault(self, 'mask', {})) == 'number' then
      self.mask = {src=self.mask}
   end
658
   for _, family in ipairs{'inet', 'inet6'} do
659
      setdefault(self.mask, family, util.copy(self.mask))
660 661 662 663 664 665
      for _, attr in ipairs{'src', 'dest'} do
	 local mask = setdefault(
	    self.mask[family],
	    attr,
	    ({src=({inet=32, inet6=128})[family], dest=0})[attr]
	 )
666 667 668 669 670 671
	 if mask > 0 then
	    self.mask[family].mode =
	       self.mask[family].mode and true or {attr, mask}
	 end
      end
   end
672 673
end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
674 675 676
function M.Limit:rate() return self.count / self.interval end

function M.Limit:intrate() return math.ceil(self:rate()) end
677

678
function M.Limit:limitofrags(name)
679
   local rate = self:rate()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
680 681 682 683 684 685 686 687 688 689
   local unit
   for _, quantum in ipairs{
      {1, 'second'}, {60, 'minute'}, {60, 'hour'}, {24, 'day'}
   } do
      rate = rate * quantum[1]
      unit = quantum[2]
      if rate >= 1 then break end
   end
   rate = math.ceil(rate)..'/'..unit

690 691 692 693 694
   local ofrags = {}

   for _, family in ipairs{'inet', 'inet6'} do
      local keys = {}
      local maskopts = ''
695
      for _, attr in ipairs{'src', 'dest'} do
696 697
	 local mask = self.mask[family][attr]
	 if mask > 0 then
698
	    local opt = ({src='src', dest='dst'})[attr]
699 700 701 702 703 704 705 706 707
	    table.insert(keys, opt..'ip')
	    maskopts = maskopts..' --hashlimit-'..opt..'mask '..mask
	 end
      end

      table.insert(
	 ofrags,
	 {
	    family=family,
708
	    match=keys[1] and
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
709 710 711 712
	       '-m hashlimit --hashlimit-upto '..rate..' --hashlimit-burst '..
	       self:intrate()..' --hashlimit-mode '..table.concat(keys, ',')..
	       maskopts..' --hashlimit-name '..(name or self:uniqueid()) or
	       '-m limit --limit '..rate
713 714 715 716 717
	 }
      )
   end

   return ofrags
718 719 720
end


721 722 723
M.export = {zone={class=M.Zone}, ipset={class=IPSet, before='%modules'}}

return M