model.lua 13.2 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

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
28

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


M.ConfigObject = M.class()

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

   self.extraobjs = {}
42
   self.uniqueids = {}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
43 44
end

45 46 47 48 49 50 51 52
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

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

61 62 63
   local lbl = {self.label}
   table.insert(lbl, label)
   if lbl[1] then params.label = table.concat(lbl, '-') end
64

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

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
function M.ConfigObject:uniqueid(key)
   if self.uniqueids[key] then return self.uniqueids[key] end

   if not self.context.lastid then self.context.lastid = {} end
   local lastid = self.context.lastid

   local res = key
   if self.label then res = res..'-'..self.label end
   if not lastid[res] then lastid[res] = -1 end
   lastid[res] = lastid[res] + 1
   res = res..'-'..lastid[res]

   self.uniqueids[key] = res
   return res
end

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

88
function M.ConfigObject:warning(msg)
89 90 91
   io.stderr:write(self.location..': '..msg..'\n')
end

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

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

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
102

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

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

126 127 128 129 130 131 132
   return combinations(
      maplist(
	 self.iface,
	 function(x) return {[iprop]=x, opts='-'..iopt..' '..x} end
      ),
      aopts
   )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
133 134 135
end


136
M.fwzone = M.Zone()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
137 138


139
local IPSet = M.class(M.ConfigObject)
140 141

function IPSet:init(...)
142
   IPSet.super(self):init(...)
143 144 145

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

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

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


161
M.Rule = M.class(M.ConfigObject)
162

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
163

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

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

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

184 185 186 187 188 189 190
      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
191 192 193 194
   end
end


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


202
function M.Rule:zoneoptfrags()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
203

204
   local function zonepair(zin, zout)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
205

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

      local chain, ofrags

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

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

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

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

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

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

   return res
end


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

   if not self.service then return end

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

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

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

	 else

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

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

313 314 315 316 317 318 319 320 321
	    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

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

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

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

   return res
end

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

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

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

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


399
function M.Rule:trules()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
400

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

   local families

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

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

   local res = self:zoneoptfrags()

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

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

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

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

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

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

   setfamilies(res)

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

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

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

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

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

501
   res = combinations(res, {{target=target}})
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
502

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

510
   extend(res, self:extraoptfrags())
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
511

512 513 514 515 516 517 518
   local tbl = self:table()

   local function convertchains(ofrags)
      local res = {}

      for i, ofrag in ipairs(ofrags) do

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

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

541 542 543 544 545 546 547
	    else table.insert(res, ofrag) end
	 end
      end

      return res
   end

548
   res = convertchains(ffilter(res))
549
   tag(res, 'table', tbl, false)
550 551

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

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


568 569 570
M.export = {zone={class=M.Zone}, ipset={class=IPSet, before='%modules'}}

return M