model.lua 14.4 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 25 26
local util = require('awall.util')
local contains = util.contains
local extend = util.extend
local filter = util.filter
local listpairs = util.listpairs
local maplist = util.maplist
27
local setdefault = util.setdefault
28

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
29

30 31 32
local startswith = require('stringy').startswith


33 34 35
local RECENT_MAX_COUNT = 20


36 37 38 39 40 41 42 43 44
local function join(a, b)
   local comps = {}
   local function add(s) if s and s > '' then table.insert(comps, s) end end
   add(a)
   add(b)
   if comps[1] then return table.concat(comps, '-') end
end


45 46 47
M.ConfigObject = M.class()

function M.ConfigObject:init(context, location)
48 49
   if context then
      self.context = context
50
      self.root = context.objects
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
51
   end
52
   self.location = location
53 54

   self.extraobjs = {}
55
   self.uniqueids = {}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
56 57
end

58 59 60 61 62 63 64 65
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

66 67
   if type(cls) == 'string' then
      local name = cls
68
      cls = loadclass(cls)
69 70 71 72
      if not cls then
	 self:error('Support for '..name..' objects not installed')
      end
   end
73

74
   if type(params) ~= 'table' then params = {params} end
75
   params.label = join(self.label, label)
76

77 78 79
   local obj = cls.morph(params, self.context, self.location)
   if key then self.extraobjs[key] = obj end
   return obj
80 81
end

82
function M.ConfigObject:uniqueid(key)
83
   if not key then key = '' end
84 85
   if self.uniqueids[key] then return self.uniqueids[key] end

86
   local lastid = setdefault(self.context, 'lastid', {})
87
   local res = join(key, self.label)
88
   lastid[res] = setdefault(lastid, res, -1) + 1
89 90 91 92 93 94
   res = res..'-'..lastid[res]

   self.uniqueids[key] = res
   return res
end

95
function M.ConfigObject:error(msg) raise(self.location..': '..msg) end
96

97
function M.ConfigObject:warning(msg)
98 99 100
   io.stderr:write(self.location..': '..msg..'\n')
end

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

103
function M.ConfigObject:info()
104 105
   local res = {}
   for i, trule in ipairs(self:trules()) do
106
      table.insert(res, {'  '..optfrag.location(trule), optfrag.command(trule)})
107 108 109 110
   end
   return res
end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
111

112
M.Zone = M.class(M.ConfigObject)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
113

114
function M.Zone:optfrags(dir)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
115 116 117 118 119 120 121
   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
122 123 124
   local aopts = nil
   if self.addr then
      aopts = {}
125 126
      for i, hostdef in listpairs(self.addr) do
	 for i, addr in ipairs(resolve(hostdef, self)) do
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
127 128 129 130 131
	    table.insert(aopts,
			 {family=addr[1],
			  [aprop]=addr[2],
			  opts='-'..aopt..' '..addr[2]})
	 end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
132 133 134
      end
   end

135 136 137 138 139 140 141
   return combinations(
      maplist(
	 self.iface,
	 function(x) return {[iprop]=x, opts='-'..iopt..' '..x} end
      ),
      aopts
   )
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

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
188
   if self.service then
189 190 191 192
      if not self.label and type(self.service) == 'string' then
	 self.label = self.service
      end

193 194 195 196 197 198 199
      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
200 201 202 203
   end
end


204
function M.Rule:direction(dir)
205 206 207 208 209 210
   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


211
function M.Rule:zoneoptfrags()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
212

213
   local function zonepair(zin, zout)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
214

215
      local function zofs(zone, dir)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
216
	 if not zone then return zone end
217
	 return zone:optfrags(dir)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
218 219 220 221
      end

      local chain, ofrags

222
      if zin == M.fwzone or zout == M.fwzone then
223
	 if zin == zout then return {} end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
224
	 local dir, z = 'in', zin
225
	 if zin == M.fwzone then dir, z = 'out', zout end
226
	 chain = dir:upper()..'PUT'
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
227 228
	 ofrags = zofs(z, dir)

229 230 231 232 233 234 235 236 237 238 239
      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
240 241
      else
	 chain = 'FORWARD'
242 243
	 ofrags = combinations(zofs(zin, 'in'), zofs(zout, 'out'))

244
	 if ofrags and not zout['route-back'] then
245 246 247 248 249 250
	    ofrags = filter(
	       ofrags,
	       function(of)
		  return not (of['in'] and of.out and of['in'] == of.out)
	       end
	    )
251
	 end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
252 253
      end

254 255 256
      return combinations(ofrags,
			  chain and {{chain=chain}} or {{chain='PREROUTING'},
							{chain='OUTPUT'}})
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
257 258 259
   end

   local res = {}
260 261
   local izones = self[self:direction('in')] or {}
   local ozones = self[self:direction('out')] or {}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
262

263 264
   for i = 1,math.max(1, table.maxn(izones)) do
      for j = 1,math.max(1, table.maxn(ozones)) do
265
	 extend(res, zonepair(izones[i], ozones[j]))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
266 267 268 269 270 271 272
      end
   end

   return res
end


273
function M.Rule:servoptfrags()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
274 275 276

   if not self.service then return end

277
   local fports = {inet={}, inet6={}}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
278 279 280
   local res = {}

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

284
	 if contains({6, 'tcp', 17, 'udp'}, sdef.proto) then
285 286 287 288 289 290 291 292
	    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
293
			extend(
294
			   ports[sdef.proto],
295
			   maplist(
296
			      sdef.port,
297
			      function(p) return tostring(p):gsub('-', ':') end
298 299 300 301 302
			   )
			)
		     else ports[sdef.proto] = {} end
		  end
	       end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
303 304 305 306 307 308 309
	    end

	 else

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

310 311
	    -- TODO multiple ICMP types per rule
	    local oname
312
	    if contains({1, 'icmp'}, sdef.proto) then
313 314
	       family = 'inet'
	       oname = 'icmp-type'
315
	    elseif contains({58, 'ipv6-icmp', 'icmpv6'}, sdef.proto) then
316 317
	       family = 'inet6'
	       oname = 'icmpv6-type'
318
	    elseif sdef.type or sdef['reply-type'] then
319
	       self:error('Type specification not valid with '..sdef.proto)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
320 321
	    end

322 323 324 325 326 327 328 329 330
	    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

331 332
	    if sdef.type then
	       opts = opts..' --'..oname..' '..(
333
		  self.reverse and sdef['reply-type'] or sdef.type
334 335
	       )
	    end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
336 337 338 339 340
	    table.insert(res, {family=family, opts=opts})
	 end
      end
   end

341
   local popt = ' --'..(self.reverse and 's' or 'd')..'port'
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
   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]
		     
364
		     pc = pc + (port:find(':') and 2 or 1)
365 366 367 368 369 370 371 372 373 374 375 376 377 378
		     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
379

380
      extend(res, combinations(ofrags, {{family=family}}))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
381 382 383 384 385
   end

   return res
end

386 387
function M.Rule:destoptfrags()
   return self:create(M.Zone, {addr=self.dest}):optfrags(self:direction('out'))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
388 389
end

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

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

394
function M.Rule:target()
395 396 397 398 399 400 401 402 403 404
   -- 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
405 406 407
end


408
function M.Rule:trules()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
409

410
   local function tag(ofrags, tag, value)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
411 412 413 414 415 416 417 418
      for i, ofrag in ipairs(ofrags) do
	 assert(not ofrag[tag])
	 ofrag[tag] = value
      end
   end

   local families

419
   local function setfamilies(ofrags)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
420 421 422 423 424 425 426 427 428 429 430 431
      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

432
   local function ffilter(ofrags)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
433
      if not ofrags or not ofrags[1] or not families then return ofrags end
434 435 436 437 438 439
      return filter(
	 ofrags,
	 function(of)
	    return not of.family or contains(families, of.family)
	 end
      )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
440 441 442 443
   end

   local res = self:zoneoptfrags()

444
   if self.ipset then
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
445
      local ipsetofrags = {}
446
      for i, ipset in listpairs(self.ipset) do
447
	 if not ipset.name then self:error('Set name not defined') end
448

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

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
452
	 if not ipset.args then
453
	    self:error('Set direction arguments not defined')
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
454
	 end
455

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
456
	 local setopts = '-m set --match-set '..ipset.name..' '
457 458
	 setopts = setopts..table.concat(util.map(util.list(ipset.args),
						  function(a)
459 460 461 462
						     if self:direction(a) == 'in' then
							return 'src'
						     end
						     return 'dst'
463 464
						  end),
					 ',')
465
	 table.insert(ipsetofrags, {family=setdef.family, opts=setopts})
466
      end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
467
      res = combinations(res, ipsetofrags)
468 469
   end

470
   if self.ipsec then
471 472
      res = combinations(res,
			 {{opts='-m policy --pol ipsec --dir '..self:direction(self.ipsec)}})
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
473 474 475 476 477 478
   end

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

   setfamilies(res)

479 480 481 482
   local addrofrags = combinations(
      self:create(M.Zone, {addr=self.src}):optfrags(self:direction('in')),
      self:destoptfrags()
   )
483
   local combined = res
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
484 485 486 487 488 489

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

490 491
      combined = {}
      for i, ofrag in ipairs(res) do
492 493 494
	 local aofs = combinations(addrofrags, {{family=ofrag.family}})
	 local cc = combinations({ofrag}, aofs)
	 if #cc < #aofs then
495 496 497
	    combined = nil
	    break
	 end
498
	 extend(combined, cc)
499
      end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
500 501 502
   end

   local target
503
   if combined then
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
504
      target = self:target()
505
      res = combined
506
   else target = self:uniqueid('address') end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
507 508 509

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

510
   res = combinations(res, {{target=target}})
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
511

512
   if not combined then
513
      extend(
514 515 516
	 res,
	 combinations(addrofrags, {{chain=target, target=self:target()}})
      )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
517 518
   end

519
   extend(res, self:extraoptfrags())
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
520

521 522 523 524 525 526 527
   local tbl = self:table()

   local function convertchains(ofrags)
      local res = {}

      for i, ofrag in ipairs(ofrags) do

528
	 if contains(builtin[tbl], ofrag.chain) then table.insert(res, ofrag)
529
	 else
530 531 532
	    local ofs, recursive
	    if ofrag.chain == 'PREROUTING' then
	       ofs = {{chain='FORWARD'}, {chain='INPUT'}}
533
	    elseif ofrag.chain == 'POSTROUTING' then
534 535 536 537 538 539 540 541
	       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'}
	       }
542 543
	    end

544
	    if ofs then
545
	       ofrag.chain = nil
546 547
	       ofs = combinations(ofs, {ofrag})
	       if recursive then ofs = convertchains(ofs) end
548
	       extend(res, ofs)
549

550 551 552 553 554 555 556
	    else table.insert(res, ofrag) end
	 end
      end

      return res
   end

557
   res = convertchains(ffilter(res))
558
   tag(res, 'table', tbl, false)
559 560

   local function checkzof(ofrag, dir, chains)
561
      if ofrag[dir] and contains(chains, ofrag.chain) then
562 563 564 565 566 567 568 569
	 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
570
   
571
   return combinations(res, ffilter({{family='inet'}, {family='inet6'}}))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
572 573
end

574
function M.Rule:extraoptfrags() return {} end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
575 576


577 578 579 580 581 582 583 584 585 586 587 588
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

589
   setdefault(self, 'interval', 1)
590 591 592 593
end

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

594
function M.Limit:recentofrags(name)
595 596 597 598 599 600 601 602
   local count = self.count
   local interval = self.interval

   if count > RECENT_MAX_COUNT then
      count = self:rate()
      interval = 1
   end

603 604 605
   if count > RECENT_MAX_COUNT then return end

   local rec = '-m recent --name '..name
606 607 608
   return {
      {opts=rec..' --update --hitcount '..count..' --seconds '..interval}
   }, {{opts=rec..' --set'}}
609 610
end

611
function M.Limit:limitofrags(name)
612
   local rate = self:rate()
613 614 615 616 617 618 619 620
   return {
      {
	 opts='-m hashlimit --hashlimit-upto '..rate..
	    '/second --hashlimit-burst '..rate..
	    ' --hashlimit-mode srcip --hashlimit-name '..
	    (name or self:uniqueid())
      }
   }
621 622 623
end


624 625 626
M.export = {zone={class=M.Zone}, ipset={class=IPSet, before='%modules'}}

return M