model.lua 16.3 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
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
116 117 118 119 120
	    table.insert(aopts,
			 {family=addr[1],
			  [aprop]=addr[2],
			  opts='-'..aopt..' '..addr[2]})
	 end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
121 122 123
      end
   end

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

134 135 136 137 138
   return combinations(
      maplist(
	 self.iface,
	 function(x) return {[iprop]=x, opts='-'..iopt..' '..x} end
      ),
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
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
361 362 363 364 365
	    table.insert(res, {family=family, opts=opts})
	 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 399 400 401 402 403
		     if pc > 15 then break end
		     
		     opts = opts..sep..port
		     
		     table.remove(ports, 1)
		     len = len - 1
		  until len == 0
	       end

	       table.insert(ofrags, {opts=opts})
	    until len == 0

	 else table.insert(ofrags, {opts=propt}) end
      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 467 468
   end

   local res = self:zoneoptfrags()

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, opts=setopts})
491
      end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
492
      res = combinations(res, ipsetofrags)
493 494
   end

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

   setfamilies(res)

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

   if addrofrags then
      addrofrags = ffilter(addrofrags)
      setfamilies(addrofrags)
      res = ffilter(res)

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

   local target
523
   if combined then
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
524
      target = self:target()
525
      res = combined
526
   else target = self:uniqueid('address') end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
527 528 529

   tag(res, 'position', self:position())

530
   res = combinations(res, {{target=target}})
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
531

532
   if not combined then
533
      extend(
534 535 536
	 res,
	 combinations(addrofrags, {{chain=target, target=self:target()}})
      )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
537 538
   end

539
   extend(res, self:extraoptfrags())
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
540

541 542 543 544 545 546 547
   local tbl = self:table()

   local function convertchains(ofrags)
      local res = {}

      for i, ofrag in ipairs(ofrags) do

548
	 if contains(builtin[tbl], ofrag.chain) then table.insert(res, ofrag)
549
	 else
550 551 552
	    local ofs, recursive
	    if ofrag.chain == 'PREROUTING' then
	       ofs = {{chain='FORWARD'}, {chain='INPUT'}}
553
	    elseif ofrag.chain == 'POSTROUTING' then
554 555 556 557 558 559 560 561
	       ofs = {{chain='FORWARD'}, {chain='OUTPUT'}}
	       recursive = true
	    elseif ofrag.chain == 'INPUT' then
	       ofs = {{opts='-m addrtype --dst-type LOCAL', chain='PREROUTING'}}
	    elseif ofrag.chain == 'FORWARD' then
	       ofs = {
		  {opts='-m addrtype ! --dst-type LOCAL', chain='PREROUTING'}
	       }
562 563
	    end

564
	    if ofs then
565
	       ofrag.chain = nil
566 567
	       ofs = combinations(ofs, {ofrag})
	       if recursive then ofs = convertchains(ofs) end
568
	       extend(res, ofs)
569

570 571 572 573 574 575 576
	    else table.insert(res, ofrag) end
	 end
      end

      return res
   end

577
   res = convertchains(ffilter(res))
578
   tag(res, 'table', tbl, false)
579 580

   local function checkzof(ofrag, dir, chains)
581
      if ofrag[dir] and contains(chains, ofrag.chain) then
582 583 584 585 586 587 588 589
	 self:error('Cannot specify '..dir..'bound interface ('..ofrag[dir]..')')
      end
   end

   for i, ofrag in ipairs(res) do
      checkzof(ofrag, 'in', {'OUTPUT', 'POSTROUTING'})
      checkzof(ofrag, 'out', {'INPUT', 'PREROUTING'})
   end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
590
   
591
   return combinations(res, ffilter({{family='inet'}, {family='inet6'}}))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
592 593
end

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

596 597 598 599
function M.Rule:extrarules(label, cls, options)
   local params = {}

   for _, attr in ipairs(
600
      extend({'in', 'out', 'src', 'dest', 'ipset', 'service'}, options.attrs)
601 602 603 604 605 606 607 608 609 610
   ) 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
611

612 613 614 615 616 617 618 619 620 621 622 623
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

624
   setdefault(self, 'interval', 1)
625 626 627 628

   if type(setdefault(self, 'mask', {})) == 'number' then
      self.mask = {src=self.mask}
   end
629
   for _, family in ipairs{'inet', 'inet6'} do
630
      setdefault(self.mask, family, util.copy(self.mask))
631 632 633 634 635 636
      for _, attr in ipairs{'src', 'dest'} do
	 local mask = setdefault(
	    self.mask[family],
	    attr,
	    ({src=({inet=32, inet6=128})[family], dest=0})[attr]
	 )
637 638 639 640 641 642
	 if mask > 0 then
	    self.mask[family].mode =
	       self.mask[family].mode and true or {attr, mask}
	 end
      end
   end
643 644
end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
645 646 647
function M.Limit:rate() return self.count / self.interval end

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

649
function M.Limit:limitofrags(name)
650
   local rate = self:rate()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
651 652 653 654 655 656 657 658 659 660
   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

661 662 663 664 665
   local ofrags = {}

   for _, family in ipairs{'inet', 'inet6'} do
      local keys = {}
      local maskopts = ''
666
      for _, attr in ipairs{'src', 'dest'} do
667 668
	 local mask = self.mask[family][attr]
	 if mask > 0 then
669
	    local opt = ({src='src', dest='dst'})[attr]
670 671 672 673 674 675 676 677 678 679
	    table.insert(keys, opt..'ip')
	    maskopts = maskopts..' --hashlimit-'..opt..'mask '..mask
	 end
      end

      table.insert(
	 ofrags,
	 {
	    family=family,
	    opts=keys[1] and
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
680 681 682 683
	       '-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
684 685 686 687 688
	 }
      )
   end

   return ofrags
689 690 691
end


692 693 694
M.export = {zone={class=M.Zone}, ipset={class=IPSet, before='%modules'}}

return M