nat.lua 1.9 KB
Newer Older
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
1 2
--[[
NAT module 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
]]--


module(..., package.seeall)

require 'awall.model'
11
require 'awall.util'
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
12 13 14 15

local model = awall.model


16
local NATRule = model.class(model.Rule)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
17

18 19 20 21 22 23 24 25 26 27 28 29
-- alpine v2.4 compatibility
function NATRule:init(...)
   model.Rule.init(self, unpack(arg))
   local attrs = {['ip-range']='to-addr', ['port-range']='to-port'}
   for old, new in pairs(attrs) do
      if not self[new] and self[old] then
	 self:warning(old..' deprecated in favor of '..new)
	 self[new] = self[old]
      end
   end
end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
30 31
function NATRule:trules()
   local res = {}
32 33 34 35
   for i, ofrags in ipairs(model.Rule.trules(self)) do
      if not awall.util.contains(self.params.chains, ofrags.chain) then
	 self:error('Inappropriate zone definitions for a '..self.params.target..' rule')
      end
36
      if ofrags.family == 'inet' then table.insert(res, ofrags) end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
37 38 39 40 41 42 43
   end
   return res
end

function NATRule:table() return 'nat' end

function NATRule:target()
44
   local target = model.Rule.target(self)
45

46 47 48 49 50
   if not target then
      local addr = self['to-addr']
      if addr then
	 target = self.params.target..' --to-'..self.params.subject..' '..addr
      else target = self.params.deftarget end
51

52 53 54
      if self['to-port'] then
	 target = target..(addr and ':' or ' --to-ports ')..self['to-port']
      end
55
   end
56

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
57 58 59 60 61 62
   return target
end


local DNATRule = model.class(NATRule)

63 64
function DNATRule:init(...)
   NATRule.init(self, unpack(arg))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
65
   self.params = {forbidif='out', subject='destination',
66 67
		  chains={'INPUT', 'PREROUTING'},
		  target='DNAT', deftarget='REDIRECT'}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
68 69 70 71 72
end


local SNATRule = model.class(NATRule)

73 74
function SNATRule:init(...)
   NATRule.init(self, unpack(arg))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
75
   self.params = {forbidif='in', subject='source',
76 77
		  chains={'OUTPUT', 'POSTROUTING'},
		  target='SNAT', deftarget='MASQUERADE'}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
78 79 80
end


81 82 83 84
export = {
   dnat={class=DNATRule},
   snat={class=SNATRule}
}