model.lua 14.7 KB
Newer Older
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
1 2
--[[
Base data model for Alpine Wall
3
Copyright (C) 2012-2014 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 88 89
   io.stderr:write(self.location..': '..msg..'\n')
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
   return combinations(
      maplist(
	 self.iface,
	 function(x) return {[iprop]=x, opts='-'..iopt..' '..x} end
      ),
      aopts
   )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
131 132 133
end


134
M.fwzone = M.Zone()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
135 136


137
local IPSet = M.class(M.ConfigObject)
138 139

function IPSet:init(...)
140
   IPSet.super(self):init(...)
141 142 143

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

144
   if startswith(self.type, 'bitmap:') then
145 146 147 148
      if not self.range then self:error('Range not defined') end
      self.options = {self.type, 'range', self.range}
      self.family = 'inet'

149
   elseif startswith(self.type, 'hash:') then
150 151 152 153 154 155 156 157 158
      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


159
M.Rule = M.class(M.ConfigObject)
160

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
161

162 163
function M.Rule:init(...)
   M.Rule.super(self):init(...)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
164 165

   for i, prop in ipairs({'in', 'out'}) do
166 167 168 169 170 171 172 173 174
      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
175
   end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
176

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
177
   if self.service then
178 179 180 181
      if not self.label and type(self.service) == 'string' then
	 self.label = self.service
      end

182 183 184 185 186 187 188
      self.service = maplist(
	 self.service,
	 function(s)
	    if type(s) ~= 'string' then return s end
	    return self.root.service[s] or self:error('Invalid service: '..s)
	 end
      )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
189 190 191 192
   end
end


193
function M.Rule:direction(dir)
194 195 196 197 198 199
   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


200
function M.Rule:zoneoptfrags()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
201

202
   local function zonepair(zin, zout)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
203

204
      local function zofs(zone, dir)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
205
	 if not zone then return zone end
206
	 return zone:optfrags(dir)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
207 208 209 210
      end

      local chain, ofrags

211
      if zin == M.fwzone or zout == M.fwzone then
212
	 if zin == zout then return {} end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
213
	 local dir, z = 'in', zin
214
	 if zin == M.fwzone then dir, z = 'out', zout end
215
	 chain = dir:upper()..'PUT'
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
216 217
	 ofrags = zofs(z, dir)

218 219 220 221 222 223 224 225 226 227 228
      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
229 230
      else
	 chain = 'FORWARD'
231 232
	 ofrags = combinations(zofs(zin, 'in'), zofs(zout, 'out'))

233
	 if ofrags and not zout['route-back'] then
234 235 236 237 238 239
	    ofrags = filter(
	       ofrags,
	       function(of)
		  return not (of['in'] and of.out and of['in'] == of.out)
	       end
	    )
240
	 end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
241 242
      end

243 244 245
      return combinations(ofrags,
			  chain and {{chain=chain}} or {{chain='PREROUTING'},
							{chain='OUTPUT'}})
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
246 247 248
   end

   local res = {}
249 250
   local izones = self[self:direction('in')] or {}
   local ozones = self[self:direction('out')] or {}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
251

252 253
   for i = 1,math.max(1, table.maxn(izones)) do
      for j = 1,math.max(1, table.maxn(ozones)) do
254
	 extend(res, zonepair(izones[i], ozones[j]))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
255 256 257 258 259 260 261
      end
   end

   return res
end


262
function M.Rule:servoptfrags()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
263 264 265

   if not self.service then return end

266
   local fports = {inet={}, inet6={}}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
267 268 269
   local res = {}

   for i, serv in ipairs(self.service) do
270
      for i, sdef in listpairs(serv) do
271
	 if not sdef.proto then self:error('Protocol not defined') end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
272

273
	 if contains({6, 'tcp', 17, 'udp'}, sdef.proto) then
274 275 276 277 278 279 280 281
	    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
282
			extend(
283
			   ports[sdef.proto],
284
			   maplist(
285
			      sdef.port,
286
			      function(p) return tostring(p):gsub('-', ':') end
287 288 289 290 291
			   )
			)
		     else ports[sdef.proto] = {} end
		  end
	       end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
292 293 294 295 296 297 298
	    end

	 else

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

299 300
	    -- TODO multiple ICMP types per rule
	    local oname
301
	    if contains({1, 'icmp'}, sdef.proto) then
302 303
	       family = 'inet'
	       oname = 'icmp-type'
304
	    elseif contains({58, 'ipv6-icmp', 'icmpv6'}, sdef.proto) then
305 306
	       family = 'inet6'
	       oname = 'icmpv6-type'
307
	    elseif sdef.type or sdef['reply-type'] then
308
	       self:error('Type specification not valid with '..sdef.proto)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
309 310
	    end

311 312 313 314 315 316 317 318 319
	    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

320 321
	    if sdef.type then
	       opts = opts..' --'..oname..' '..(
322
		  self.reverse and sdef['reply-type'] or sdef.type
323 324
	       )
	    end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
325 326 327 328 329
	    table.insert(res, {family=family, opts=opts})
	 end
      end
   end

330
   local popt = ' --'..(self.reverse and 's' or 'd')..'port'
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
   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]
		     
353
		     pc = pc + (port:find(':') and 2 or 1)
354 355 356 357 358 359 360 361 362 363 364 365 366 367
		     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
368

369
      extend(res, combinations(ofrags, {{family=family}}))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
370 371 372 373 374
   end

   return res
end

375 376
function M.Rule:destoptfrags()
   return self:create(M.Zone, {addr=self.dest}):optfrags(self:direction('out'))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
377 378
end

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

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

383
function M.Rule:target()
384 385 386 387 388 389 390 391 392 393
   -- 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
394 395 396
end


397
function M.Rule:trules()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
398

399
   local function tag(ofrags, tag, value)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
400 401 402 403 404 405 406 407
      for i, ofrag in ipairs(ofrags) do
	 assert(not ofrag[tag])
	 ofrag[tag] = value
      end
   end

   local families

408
   local function setfamilies(ofrags)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
409 410 411 412 413 414 415 416 417 418 419 420
      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

421
   local function ffilter(ofrags)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
422
      if not ofrags or not ofrags[1] or not families then return ofrags end
423 424 425 426 427 428
      return filter(
	 ofrags,
	 function(of)
	    return not of.family or contains(families, of.family)
	 end
      )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
429 430 431 432
   end

   local res = self:zoneoptfrags()

433
   if self.ipset then
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
434
      local ipsetofrags = {}
435
      for i, ipset in listpairs(self.ipset) do
436
	 if not ipset.name then self:error('Set name not defined') end
437

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

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
441
	 if not ipset.args then
442
	    self:error('Set direction arguments not defined')
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
443
	 end
444

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
445
	 local setopts = '-m set --match-set '..ipset.name..' '
446 447
	 setopts = setopts..table.concat(util.map(util.list(ipset.args),
						  function(a)
448 449 450 451
						     if self:direction(a) == 'in' then
							return 'src'
						     end
						     return 'dst'
452 453
						  end),
					 ',')
454
	 table.insert(ipsetofrags, {family=setdef.family, opts=setopts})
455
      end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
456
      res = combinations(res, ipsetofrags)
457 458
   end

459
   if self.ipsec then
460 461
      res = combinations(res,
			 {{opts='-m policy --pol ipsec --dir '..self:direction(self.ipsec)}})
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
462 463 464 465 466 467
   end

   res = combinations(res, self:servoptfrags())

   setfamilies(res)

468 469 470 471
   local addrofrags = combinations(
      self:create(M.Zone, {addr=self.src}):optfrags(self:direction('in')),
      self:destoptfrags()
   )
472
   local combined = res
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
473 474 475 476 477 478

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

479 480
      combined = {}
      for i, ofrag in ipairs(res) do
481 482 483
	 local aofs = combinations(addrofrags, {{family=ofrag.family}})
	 local cc = combinations({ofrag}, aofs)
	 if #cc < #aofs then
484 485 486
	    combined = nil
	    break
	 end
487
	 extend(combined, cc)
488
      end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
489 490 491
   end

   local target
492
   if combined then
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
493
      target = self:target()
494
      res = combined
495
   else target = self:uniqueid('address') end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
496 497 498

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

499
   res = combinations(res, {{target=target}})
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
500

501
   if not combined then
502
      extend(
503 504 505
	 res,
	 combinations(addrofrags, {{chain=target, target=self:target()}})
      )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
506 507
   end

508
   extend(res, self:extraoptfrags())
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
509

510 511 512 513 514 515 516
   local tbl = self:table()

   local function convertchains(ofrags)
      local res = {}

      for i, ofrag in ipairs(ofrags) do

517
	 if contains(builtin[tbl], ofrag.chain) then table.insert(res, ofrag)
518
	 else
519 520 521
	    local ofs, recursive
	    if ofrag.chain == 'PREROUTING' then
	       ofs = {{chain='FORWARD'}, {chain='INPUT'}}
522
	    elseif ofrag.chain == 'POSTROUTING' then
523 524 525 526 527 528 529 530
	       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'}
	       }
531 532
	    end

533
	    if ofs then
534
	       ofrag.chain = nil
535 536
	       ofs = combinations(ofs, {ofrag})
	       if recursive then ofs = convertchains(ofs) end
537
	       extend(res, ofs)
538

539 540 541 542 543 544 545
	    else table.insert(res, ofrag) end
	 end
      end

      return res
   end

546
   res = convertchains(ffilter(res))
547
   tag(res, 'table', tbl, false)
548 549

   local function checkzof(ofrag, dir, chains)
550
      if ofrag[dir] and contains(chains, ofrag.chain) then
551 552 553 554 555 556 557 558
	 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
559
   
560
   return combinations(res, ffilter({{family='inet'}, {family='inet6'}}))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
561 562
end

563
function M.Rule:extraoptfrags() return {} end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
564 565


566 567 568 569 570 571 572 573 574 575 576 577
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

578
   setdefault(self, 'interval', 1)
579 580 581 582 583 584 585 586 587 588 589 590 591 592

   if type(setdefault(self, 'mask', {})) == 'number' then
      self.mask = {src=self.mask}
   end
   for family, len in pairs{inet=32, inet6=128} do
      setdefault(self.mask, family, util.copy(self.mask))
      for attr, default in pairs{src=len, dest=0} do
	 local mask = setdefault(self.mask[family], attr, default)
	 if mask > 0 then
	    self.mask[family].mode =
	       self.mask[family].mode and true or {attr, mask}
	 end
      end
   end
593 594 595 596
end

function M.Limit:rate() return math.ceil(self.count / self.interval) end

597
function M.Limit:limitofrags(name)
598
   local rate = self:rate()
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
   local ofrags = {}

   for _, family in ipairs{'inet', 'inet6'} do
      local keys = {}
      local maskopts = ''
      for attr, opt in pairs{src='src', dest='dst'} do
	 local mask = self.mask[family][attr]
	 if mask > 0 then
	    table.insert(keys, opt..'ip')
	    maskopts = maskopts..' --hashlimit-'..opt..'mask '..mask
	 end
      end

      table.insert(
	 ofrags,
	 {
	    family=family,
	    opts=keys[1] and
	       '-m hashlimit --hashlimit-upto '..rate..
	       '/second --hashlimit-burst '..rate..' --hashlimit-mode '..
	       table.concat(keys, ',')..maskopts..' --hashlimit-name '..
	       (name or self:uniqueid()) or
	       '-m limit --limit '..rate..'/second'
	 }
      )
   end

   return ofrags
627 628 629
end


630 631 632
M.export = {zone={class=M.Zone}, ipset={class=IPSet, before='%modules'}}

return M