model.lua 20.1 KB
Newer Older
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
1 2
--[[
Base data model for Alpine Wall
3
Copyright (C) 2012-2017 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
local util = require('awall.util')
local contains = util.contains
23
local copy = util.copy
24 25
local extend = util.extend
local filter = util.filter
26
local join = util.join
27
local listpairs = util.listpairs
28
local map = util.map
29
local maplist = util.maplist
30
local setdefault = util.setdefault
31
local sortedkeys = util.sortedkeys
32

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
33

34 35 36 37 38 39
local startswith = require('stringy').startswith


M.ConfigObject = M.class()

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

   self.extraobjs = {}
47
   self.uniqueids = {}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
48 49
end

50 51 52 53 54 55 56 57
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

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

66
   if type(params) ~= 'table' then params = {params} end
67
   params.label = join(self.label, '-', label)
68

69 70 71
   local obj = cls.morph(params, self.context, self.location)
   if key then self.extraobjs[key] = obj end
   return obj
72 73
end

74
function M.ConfigObject:uniqueid(key)
75
   if not key then key = '' end
76 77
   if self.uniqueids[key] then return self.uniqueids[key] end

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

   self.uniqueids[key] = res
   return res
end

87
function M.ConfigObject:error(msg) raise(self.location..': '..msg) end
88

89
function M.ConfigObject:warning(msg)
90
   util.printmsg(self.location..': '..msg)
91 92
end

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

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

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
103

104
M.Zone = M.class(M.ConfigObject)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
105

106
function M.Zone:optfrags(dir)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
107 108 109 110 111 112 113
   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
114 115 116
   local aopts = nil
   if self.addr then
      aopts = {}
117 118
      for i, hostdef in listpairs(self.addr) do
	 for i, addr in ipairs(resolve(hostdef, self)) do
119 120 121 122
	    table.insert(
	       aopts,
	       {family=addr[1], [aprop]=addr[2], match='-'..aopt..' '..addr[2]}
	    )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
123
	 end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
124 125 126
      end
   end

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

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


148
M.fwzone = M.Zone()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
149 150


151
local IPSet = M.class(M.ConfigObject)
152 153

function IPSet:init(...)
154
   IPSet.super(self):init(...)
155 156 157

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

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

163
   elseif startswith(self.type, 'hash:') then
164 165 166 167 168 169 170 171 172
      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


173
M.Rule = M.class(M.ConfigObject)
174

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
175

176 177
function M.Rule:init(...)
   M.Rule.super(self):init(...)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
178 179

   for i, prop in ipairs({'in', 'out'}) do
180 181 182 183 184 185 186 187 188
      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
189
   end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
190

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
   -- 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
211
   if self.service then
212 213 214 215
      if not self.label and type(self.service) == 'string' then
	 self.label = self.service
      end

216 217 218 219 220 221
      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)
222
	 end
223 224 225 226 227 228 229
	 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
230 231 232 233
   end
end


234
function M.Rule:direction(dir)
235 236 237 238 239 240
   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


241
function M.Rule:zoneoptfrags()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
242

243
   local function zonepair(zin, zout)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
244

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

      local chain, ofrags

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

259 260 261 262 263 264 265 266 267 268 269
      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
270 271
      else
	 chain = 'FORWARD'
272 273
	 ofrags = combinations(zofs(zin, 'in'), zofs(zout, 'out'))

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

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

   local res = {}
290 291
   local izones = self[self:direction('in')] or {}
   local ozones = self[self:direction('out')] or {}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
292

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
293 294
   for i = 1,math.max(1, #izones) do
      for j = 1,math.max(1, #ozones) do
295
	 extend(res, zonepair(izones[i], ozones[j]))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
296 297 298 299 300 301 302
      end
   end

   return res
end


303
function M.Rule:servoptfrags()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
304 305 306

   if not self.service then return end

307
   local fports = {inet={}, inet6={}}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
308 309 310
   local res = {}

   for i, serv in ipairs(self.service) do
311
      for i, sdef in listpairs(serv) do
312
	 if contains({'tcp', 'udp'}, sdef.proto) then
313 314 315 316 317 318 319 320
	    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
321
			extend(
322
			   ports[sdef.proto],
323
			   maplist(
324
			      sdef.port,
325
			      function(p) return tostring(p):gsub('-', ':') end
326 327 328 329 330
			   )
			)
		     else ports[sdef.proto] = {} end
		  end
	       end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
331 332 333 334 335 336 337
	    end

	 else

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

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

350 351 352 353 354 355 356 357 358
	    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

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

369
   local popt = ' --'..(self.reverse and 's' or 'd')..'port'
370
   for _, family in sortedkeys(fports) do
371
      local ofrags = {}
372
      local pports = fports[family]
373

374
      for _, proto in sortedkeys(pports) do
375
	 local propt = '-p '..proto
376
	 local ports = pports[proto]
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393

	 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]
		     
394
		     pc = pc + (port:find(':') and 2 or 1)
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

404
	       table.insert(ofrags, {match=opts})
405 406
	    until len == 0

407
	 else table.insert(ofrags, {match=propt}) end
408
      end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
409

410
      extend(res, combinations(ofrags, {{family=family}}))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
411 412 413 414 415
   end

   return res
end

416 417
function M.Rule:destoptfrags()
   return self:create(M.Zone, {addr=self.dest}):optfrags(self:direction('out'))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
418 419
end

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

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

424
function M.Rule:target()
425 426 427 428 429 430 431 432 433 434
   -- 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
435 436 437
end


438 439 440 441 442 443
function M.Rule:combine(ofs1, ofs2, key, unique)

   local function connect()
      local chain = self:uniqueid(key)
      local function setvar(name)
	 return function(of)
444 445 446
	    local res = copy(of)
	    setdefault(res, name, chain)
	    return res
447 448 449 450 451 452 453
	 end
      end

      return extend(map(ofs1, setvar('target')), map(ofs2, setvar('chain')))
   end

   local chainless = filter(ofs2, function(of) return not of.chain end)
454
   local created
455 456 457 458 459 460 461 462
   local res = {}

   for _, of in ipairs(ofs1) do
      if of.target == nil then

	 local ofs = combinations(chainless, {{family=of.family}})
	 assert(#ofs > 0)

463 464
	 local comb = combinations({of}, ofs)
	 if #comb < #ofs then return connect() end
465

466
	 if unique then
467 468
	    if #self:convertchains{of} > 1 then return connect() end

469 470 471 472 473 474 475 476 477 478 479 480
	    for _, c in ipairs(comb) do
	       if c.family then
	          if not created then created = {}
		  elseif created == true or created[c.family] then
		     return connect()
		  end
		  created[c.family] = true
	       else
	          if created then return connect() end
		  created = true
	       end
	    end
481 482 483 484 485 486 487
	 end

	 extend(res, comb)

      else table.insert(res, of) end
   end

488
   return extend(res, filter(ofs2, function(of) return of.chain end))
489 490 491
end


492
function M.Rule:trules()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
493

494
   local function tag(ofrags, tag, value)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
495 496 497 498 499 500 501 502
      for i, ofrag in ipairs(ofrags) do
	 assert(not ofrag[tag])
	 ofrag[tag] = value
      end
   end

   local families

503
   local function setfamilies(ofrags)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
504 505 506 507 508 509 510 511 512 513 514 515
      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

516
   local function ffilter(ofrags)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
517
      if not ofrags or not ofrags[1] or not families then return ofrags end
518 519 520 521 522 523
      return filter(
	 ofrags,
	 function(of)
	    return not of.family or contains(families, of.family)
	 end
      )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
524 525
   end

526
   local ofrags = self:zoneoptfrags()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
527

528
   if self.ipset then
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
529
      local ipsetofrags = {}
530
      for i, ipset in listpairs(self.ipset) do
531
	 if not ipset.name then self:error('Set name not defined') end
532

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

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
536
	 if not ipset.args then
537
	    self:error('Set direction arguments not defined')
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
538
	 end
539

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
540
	 local setopts = '-m set --match-set '..ipset.name..' '
541 542
	 setopts = setopts..table.concat(util.map(util.list(ipset.args),
						  function(a)
543 544 545 546
						     if self:direction(a) == 'in' then
							return 'src'
						     end
						     return 'dst'
547 548
						  end),
					 ',')
549
	 table.insert(ipsetofrags, {family=setdef.family, match=setopts})
550
      end
551
      ofrags = combinations(ofrags, ipsetofrags)
552 553
   end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
554 555 556 557 558 559 560
   if self.string then
      if type(self.string) == 'string' then
	 self.string = {match=self.string}
      end
      if not self.string.match then self:error('String match not defined') end
      setdefault(self.string, 'algo', 'bm')

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
561
      local opts = '-m string --string '..util.quote(self.string.match)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
562 563 564 565 566 567 568 569 570 571

      for _, attr in ipairs{'algo', 'from', 'to'} do
	 if self.string[attr] then
	    opts = opts..' --'..attr..' '..self.string[attr]
	 end
      end

      ofrags = combinations(ofrags, {{match=opts}})
   end

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

574
   ofrags = combinations(ofrags, self:servoptfrags())
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
575

576 577
   tag(ofrags, 'position', self:position())

578
   setfamilies(ofrags)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
579

580 581 582 583
   local addrofrags = combinations(
      self:create(M.Zone, {addr=self.src}):optfrags(self:direction('in')),
      self:destoptfrags()
   )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
584 585 586
   if addrofrags then
      addrofrags = ffilter(addrofrags)
      setfamilies(addrofrags)
587
      ofrags = self:combine(ffilter(ofrags), addrofrags, 'address')
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
588 589
   end

590
   ofrags = self:mangleoptfrags(ofrags)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
591

592 593
   local custom = self:customtarget()
   for _, ofrag in ipairs(ofrags) do
594
      setdefault(ofrag, 'target', custom or self:target())
595
   end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
596

597 598
   ofrags = self:convertchains(ffilter(ofrags))
   tag(ofrags, 'table', self:table(), false)
599 600

   local function checkzof(ofrag, dir, chains)
601
      if ofrag[dir] and contains(chains, ofrag.chain) then
602 603 604 605
	 self:error('Cannot specify '..dir..'bound interface ('..ofrag[dir]..')')
      end
   end

606
   for i, ofrag in ipairs(ofrags) do
607 608 609
      checkzof(ofrag, 'in', {'OUTPUT', 'POSTROUTING'})
      checkzof(ofrag, 'out', {'INPUT', 'PREROUTING'})
   end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
610
   
611 612 613 614
   ofrags = filter(
      combinations(ofrags, ffilter({{family='inet'}, {family='inet6'}})),
      function(r) return self:trulefilter(r) end
   )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
615

616
   local extra = self:extratrules(ofrags)
617
   if custom and extra[1] then self:error('Custom action not allowed here') end
618
   return extend(ofrags, extra)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
619 620 621 622 623
end

function M.Rule:customtarget()
   if self.action then
      local as = self.action:sub(1, 1)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
624 625 626
      if as == as:upper() or startswith(self.action, 'custom:') then
	 return self.action
      end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
627
   end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
628 629
end

630
function M.Rule:mangleoptfrags(ofrags) return ofrags end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
631

632 633 634 635
function M.Rule:trulefilter(rule) return true end

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

636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
function M.Rule:convertchains(ofrags)
   local res = {}

   for _, ofrag in ipairs(ofrags) do

      if contains(builtin[self:table()], ofrag.chain) then
	 table.insert(res, ofrag)

      else
	 local ofs, recursive
	 if ofrag.chain == 'PREROUTING' then
	    ofs = {{chain='FORWARD'}, {chain='INPUT'}}
	 elseif ofrag.chain == 'POSTROUTING' then
	    ofs = {{chain='FORWARD'}, {chain='OUTPUT'}}
	    recursive = true
	 elseif ofrag.chain == 'INPUT' then
	    ofs = {{match='-m addrtype --dst-type LOCAL', chain='PREROUTING'}}
	 elseif ofrag.chain == 'FORWARD' then
	    ofs = {{match='-m addrtype ! --dst-type LOCAL', chain='PREROUTING'}}
	 end

	 if ofs then
658 659 660
	    local of = copy(ofrag)
	    of.chain = nil
	    ofs = combinations(ofs, {of})
661 662 663 664 665 666 667 668 669 670
	    if recursive then ofs = self:convertchains(ofs) end
	    extend(res, ofs)

	 else table.insert(res, ofrag) end
      end
   end

   return res
end

671 672 673 674
function M.Rule:extrarules(label, cls, options)
   local params = {}

   for _, attr in ipairs(
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
675
      extend(
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
676
         {'in', 'out', 'src', 'dest', 'ipset', 'string', 'match', 'service'},
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
677 678
	 options.attrs
      )
679 680 681 682 683 684 685 686 687 688
   ) 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
689

690
M.Maskable = M.class(M.ConfigObject)
691

692 693
function M.Maskable:init(...)
   M.Maskable.super(self):init(...)
694

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
695 696 697 698 699 700 701 702 703
   -- alpine v3.5 compatibility
   if self.mask then
      self:warning(
	 "'mask' attribute is deprecated, please use 'src-mask' and 'dest-mask'"
      )
      self['src-mask'] = {}
      self['dest-mask'] = {}
      if type(self.mask) == 'number' then self.mask = {src=self.mask} end
      for _, family in ipairs{'inet', 'inet6'} do
704
	 setdefault(self.mask, family, copy(self.mask))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
705 706 707 708 709
	 for _, attr in ipairs{'src', 'dest'} do
	    self[attr..'-mask'][family] = self.mask[family][attr] or
	       ({src=({inet=32, inet6=128})[family], dest=0})[attr]
	 end
      end
710
   end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
711

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
712 713 714
   self:initmask()
end

715
function M.Maskable:initmask()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
716 717 718 719 720 721 722 723 724 725 726 727 728 729
   setdefault(self, 'src-mask', not self['dest-mask'])
   setdefault(self, 'dest-mask', false)

   for _, addr in ipairs{'src', 'dest'} do
      local mask = addr..'-mask'
      if type(self[mask]) ~= 'table' then
	 self[mask] = {inet=self[mask], inet6=self[mask]}
      end
      for _, family in ipairs{'inet', 'inet6'} do
	 local value = self[mask][family]
	 if not value then self[mask][family] = 0
	 elseif value == true then
	    self[mask][family] = ({inet=32, inet6=128})[family]
	 end
730 731
      end
   end
732 733
end

734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
function M.Maskable:recentmask(name)
   local res = {}

   for _, family in ipairs{'inet', 'inet6'} do
      local addr, len
      for _, a in ipairs{'src', 'dest'} do
	 local mask = self[a..'-mask'][family]
	 if mask > 0 then
	    if addr then return end
	    addr = a
	    len = mask
	 end
      end
      if not addr then return end

      local mask = ''

      if family == 'inet' then
	 local octet
	 for i = 0, 3 do
	    if len <= i * 8 then octet = 0
	    elseif len > i * 8 + 7 then octet = 255
	    else octet = 256 - 2^(8 - len % 8) end
	    mask = util.join(mask, '.', octet)
	 end

      elseif family == 'inet6' then
	 while len > 0 do
	    if #mask % 5 == 4 then mask = mask..':' end
	    mask = mask..('%x'):format(16 - 2^math.max(0, 4 - len))
	    len = len - 4
	 end
	 while #mask % 5 < 4 do mask = mask..'0' end
	 if #mask < 39 then mask = mask..'::' end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
768
      end
769 770 771 772 773 774 775 776 777 778

      table.insert(
	 res,
	 {
	    family=family,
	    match='-m recent --name '..
	       (self.name and 'user:'..self.name or name)..' --r'..
	       ({src='source', dest='dest'})[addr]..' --mask '..mask
	 }
      )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
779
   end
780 781

   return res
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
782 783
end

784 785 786 787

M.Limit = M.class(M.Maskable)

function M.Limit:init(...)
788
   setdefault(self, 'count', self[1] or 1)
789
   setdefault(self, 'interval', 1)
790 791

   M.Limit.super(self):init(...)
792 793
end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
794 795 796
function M.Limit:rate() return self.count / self.interval end

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

798
function M.Limit:limitofrags(name)
799
   local rate = self:rate()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
800 801 802 803 804 805 806 807 808 809
   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

810 811 812 813 814
   local ofrags = {}

   for _, family in ipairs{'inet', 'inet6'} do
      local keys = {}
      local maskopts = ''
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
815 816
      for _, addr in ipairs{'src', 'dest'} do
	 local mask = self[addr..'-mask'][family]
817
	 if mask > 0 then
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
818
	    local opt = ({src='src', dest='dst'})[addr]
819 820 821 822 823 824 825 826 827
	    table.insert(keys, opt..'ip')
	    maskopts = maskopts..' --hashlimit-'..opt..'mask '..mask
	 end
      end

      table.insert(
	 ofrags,
	 {
	    family=family,
828
	    match=keys[1] and
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
829 830 831 832
	       '-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
833 834 835 836 837
	 }
      )
   end

   return ofrags
838 839 840
end


Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
841 842 843 844 845
M.export = {
   custom={class=M.ConfigObject},
   ipset={class=IPSet, before='%modules'},
   zone={class=M.Zone}
}
846 847

return M