model.lua 12.6 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 9 10 11
]]--


module(..., package.seeall)

require 'awall'
require 'awall.host'
12
require 'awall.iptables'
13
require 'awall.object'
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
14
require 'awall.optfrag'
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
15
require 'awall.uerror'
16
require 'awall.util'
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
17 18 19 20

local util = awall.util
local combinations = awall.optfrag.combinations

21
class = awall.object.class
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
22

23
require 'stringy'
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
24

25

26
ConfigObject = class()
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
27

28
function ConfigObject:init(context, location)
29 30
   if context then
      self.context = context
31
      self.root = context.objects
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
32
   end
33
   self.location = location
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
34 35
end

36
function ConfigObject:create(cls, params)
37 38
   if type(cls) == 'string' then
      local name = cls
39
      cls = awall.loadclass(cls)
40 41 42 43
      if not cls then
	 self:error('Support for '..name..' objects not installed')
      end
   end
44 45 46
   return cls.morph(params, self.context, self.location)
end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
47 48 49
function ConfigObject:error(msg)
   awall.uerror.raise(self.location..': '..msg)
end
50

51 52 53 54
function ConfigObject:warning(msg)
   io.stderr:write(self.location..': '..msg..'\n')
end

55
function ConfigObject:trules() return {} end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
56

57 58 59 60
function ConfigObject:info()
   local res = {}
   for i, trule in ipairs(self:trules()) do
      table.insert(res,
61 62
		   {'  '..awall.optfrag.location(trule),
		    (trule.opts and trule.opts..' ' or '')..'-j '..trule.target})
63 64 65 66
   end
   return res
end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
67

68
Zone = class(ConfigObject)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
69 70 71 72 73 74 75 76 77

function Zone:optfrags(dir)
   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
78 79 80 81
   local aopts = nil
   if self.addr then
      aopts = {}
      for i, hostdef in util.listpairs(self.addr) do
82
	 for i, addr in ipairs(awall.host.resolve(hostdef, self)) do
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
83 84 85 86 87
	    table.insert(aopts,
			 {family=addr[1],
			  [aprop]=addr[2],
			  opts='-'..aopt..' '..addr[2]})
	 end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
      end
   end

   return combinations(util.maplist(self.iface,
				    function(x)
				       return {[iprop]=x,
					       opts='-'..iopt..' '..x}
				    end),
		       aopts)
end


fwzone = Zone.new()


103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
IPSet = class(ConfigObject)

function IPSet:init(...)
   ConfigObject.init(self, unpack(arg))

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

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

   elseif stringy.startswith(self.type, 'hash:') then
      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


125 126
Rule = class(ConfigObject)

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
127

128 129
function Rule:init(...)
   ConfigObject.init(self, unpack(arg))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
130

131 132
   self.newchains = {}

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
133 134 135
   for i, prop in ipairs({'in', 'out'}) do
      self[prop] = self[prop] and util.maplist(self[prop],
					       function(z)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
136
						  if type(z) ~= 'string' then return z end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
137
						  return z == '_fw' and fwzone or
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
138
						     self.root.zone[z] or
139
						     self:error('Invalid zone: '..z)
140
					       end)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
141
   end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
142

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
143
   if self.service then
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
144
      if type(self.service) == 'string' then self.label = self.service end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
145 146
      self.service = util.maplist(self.service,
				  function(s)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
147
				     if type(s) ~= 'string' then return s end
148
				     return self.root.service[s] or self:error('Invalid service: '..s)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
149 150 151 152 153
				  end)
   end
end


154 155 156 157 158 159 160
function Rule:direction(dir)
   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


Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
161 162
function Rule:zoneoptfrags()

163
   local function zonepair(zin, zout)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
164

165
      local function zofs(zone, dir)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
166
	 if not zone then return zone end
167
	 return zone:optfrags(dir)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
168 169 170 171 172
      end

      local chain, ofrags

      if zin == fwzone or zout == fwzone then
173
	 if zin == zout then return {} end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
174 175 176 177 178
	 local dir, z = 'in', zin
	 if zin == fwzone then dir, z = 'out', zout end
	 chain = string.upper(dir)..'PUT'
	 ofrags = zofs(z, dir)

179 180 181 182 183 184 185 186 187 188 189
      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
190 191
      else
	 chain = 'FORWARD'
192 193
	 ofrags = combinations(zofs(zin, 'in'), zofs(zout, 'out'))

194
	 if ofrags and not zout['route-back'] then
195 196 197 198 199 200
	    ofrags = util.filter(ofrags,
				 function(of)
				    return not (of['in'] and of.out and
						of['in'] == of.out)
				 end)
	 end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
201 202
      end

203 204 205
      return combinations(ofrags,
			  chain and {{chain=chain}} or {{chain='PREROUTING'},
							{chain='OUTPUT'}})
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
206 207 208
   end

   local res = {}
209 210
   local izones = self[self:direction('in')] or {}
   local ozones = self[self:direction('out')] or {}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
211

212 213 214
   for i = 1,math.max(1, table.maxn(izones)) do
      for j = 1,math.max(1, table.maxn(ozones)) do
	 util.extend(res, zonepair(izones[i], ozones[j]))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
215 216 217 218 219 220 221 222 223 224 225
      end
   end

   return res
end


function Rule:servoptfrags()

   if not self.service then return end

226
   local fports = {inet={}, inet6={}}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
227 228 229 230
   local res = {}

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

	 if util.contains({6, 'tcp', 17, 'udp'}, sdef.proto) then
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
	    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
			util.extend(
			   ports[sdef.proto],
			   util.maplist(
			      sdef.port,
			      function(p) return string.gsub(p, '-', ':') end
			   )
			)
		     else ports[sdef.proto] = {} end
		  end
	       end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
252 253 254 255 256 257 258
	    end

	 else

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

259 260 261 262 263 264 265 266
	    -- TODO multiple ICMP types per rule
	    local oname
	    if util.contains({1, 'icmp'}, sdef.proto) then
	       family = 'inet'
	       oname = 'icmp-type'
	    elseif util.contains({58, 'ipv6-icmp', 'icmpv6'}, sdef.proto) then
	       family = 'inet6'
	       oname = 'icmpv6-type'
267
	    elseif sdef.type or sdef['reply-type'] then
268
	       self:error('Type specification not valid with '..sdef.proto)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
269 270
	    end

271 272 273 274 275 276 277 278 279
	    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

280 281
	    if sdef.type then
	       opts = opts..' --'..oname..' '..(
282
		  self.reverse and sdef['reply-type'] or sdef.type
283 284
	       )
	    end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
285 286 287 288 289
	    table.insert(res, {family=family, opts=opts})
	 end
      end
   end

290
   local popt = ' --'..(self.reverse and 's' or 'd')..'port'
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
   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]
		     
		     pc = pc + (string.find(port, ':') and 2 or 1)
		     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
328

329
      util.extend(res, combinations(ofrags, {{family=family}}))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
330 331 332 333 334
   end

   return res
end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
335
function Rule:destoptfrags()
336
   return self:create(Zone, {addr=self.dest}):optfrags(self:direction('out'))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
337 338
end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
339 340 341 342 343
function Rule:table() return 'filter' end

function Rule:position() return 'append' end

function Rule:target()
344
   if not self.action then self:error('Action not defined') end
345 346
   if self.action == 'accept' then return 'ACCEPT' end
   self:error('Invalid action: '..self.action)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
347 348 349 350 351
end


function Rule:trules()

352
   local function tag(ofrags, tag, value)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
353 354 355 356 357 358 359 360
      for i, ofrag in ipairs(ofrags) do
	 assert(not ofrag[tag])
	 ofrag[tag] = value
      end
   end

   local families

361
   local function setfamilies(ofrags)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
362 363 364 365 366 367 368 369 370 371 372 373
      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

374
   local function ffilter(ofrags)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
375
      if not ofrags or not ofrags[1] or not families then return ofrags end
376 377 378 379 380
      return util.filter(ofrags,
			 function(of)
			    return not of.family or util.contains(families,
								  of.family)
			 end)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
381 382 383 384
   end

   local res = self:zoneoptfrags()

385
   if self.ipset then
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
386 387
      local ipsetofrags = {}
      for i, ipset in util.listpairs(self.ipset) do
388
	 if not ipset.name then self:error('Set name not defined') end
389

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

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
393
	 if not ipset.args then
394
	    self:error('Set direction arguments not defined')
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
395
	 end
396

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
397
	 local setopts = '-m set --match-set '..ipset.name..' '
398 399
	 setopts = setopts..table.concat(util.map(util.list(ipset.args),
						  function(a)
400 401 402 403
						     if self:direction(a) == 'in' then
							return 'src'
						     end
						     return 'dst'
404 405
						  end),
					 ',')
406
	 table.insert(ipsetofrags, {family=setdef.family, opts=setopts})
407
      end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
408
      res = combinations(res, ipsetofrags)
409 410
   end

411
   if self.ipsec then
412 413
      res = combinations(res,
			 {{opts='-m policy --pol ipsec --dir '..self:direction(self.ipsec)}})
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
414 415 416 417 418 419
   end

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

   setfamilies(res)

420 421
   local addrofrags = combinations(self:create(Zone,
					       {addr=self.src}):optfrags(self:direction('in')),
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
422
				   self:destoptfrags())
423
   local combined = res
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
424 425 426 427 428 429

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

430 431 432 433 434 435 436 437 438
      combined = {}
      for i, ofrag in ipairs(res) do
	 local cc = combinations({ofrag}, addrofrags)
	 if #cc < #addrofrags then
	    combined = nil
	    break
	 end
	 util.extend(combined, cc)
      end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
439 440 441
   end

   local target
442
   if combined then
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
443
      target = self:target()
444 445 446
      res = combined
   else
      target = self:newchain('address')
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
447 448 449 450
   end

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

451
   res = combinations(res, {{target=target}})
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
452

453 454 455 456 457
   if not combined then
      util.extend(
	 res,
	 combinations(addrofrags, {{chain=target, target=self:target()}})
      )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
458 459
   end

460
   util.extend(res, self:extraoptfrags())
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
461

462 463 464 465 466 467 468 469 470 471 472
   local tbl = self:table()

   local function convertchains(ofrags)
      local res = {}

      for i, ofrag in ipairs(ofrags) do

	 if util.contains(awall.iptables.builtin[tbl], ofrag.chain) then
	    table.insert(res, ofrag)

	 else
473 474 475
	    local ofs, recursive
	    if ofrag.chain == 'PREROUTING' then
	       ofs = {{chain='FORWARD'}, {chain='INPUT'}}
476
	    elseif ofrag.chain == 'POSTROUTING' then
477 478 479 480 481 482 483 484
	       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'}
	       }
485 486
	    end

487
	    if ofs then
488
	       ofrag.chain = nil
489 490 491 492
	       ofs = combinations(ofs, {ofrag})
	       if recursive then ofs = convertchains(ofs) end
	       util.extend(res, ofs)

493 494 495 496 497 498 499
	    else table.insert(res, ofrag) end
	 end
      end

      return res
   end

500
   res = convertchains(ffilter(res))
501
   tag(res, 'table', tbl, false)
502 503 504 505 506 507 508 509 510 511 512

   local function checkzof(ofrag, dir, chains)
      if ofrag[dir] and util.contains(chains, ofrag.chain) then
	 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
513
   
514
   return combinations(res, ffilter({{family='inet'}, {family='inet6'}}))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
515 516 517 518
end

function Rule:extraoptfrags() return {} end

519 520 521
function Rule:newchain(key)
   if self.newchains[key] then return self.newchains[key] end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
522 523 524
   if not self.context.lastid then self.context.lastid = {} end
   local lastid = self.context.lastid

525 526 527 528 529 530 531 532
   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.newchains[key] = res
   return res
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
533 534
end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
535

536
export = {zone={class=Zone}, ipset={class=IPSet, before='%modules'}}