nat.lua 1.88 KB
Newer Older
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
1 2 3 4 5 6 7 8 9 10
--[[
NAT module for Alpine Wall
Copyright (C) 2012 Kaarle Ritvanen
Licensed under the terms of GPL2
]]--


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
   if self.action then return model.Rule.target(self) end
45

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

52 53
   if self['to-port'] then
      target = target..(addr and ':' or ' --to-ports ')..self['to-port']
54
   end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
55 56 57 58 59 60
   return target
end


local DNATRule = model.class(NATRule)

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


local SNATRule = model.class(NATRule)

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


79 80
classes = {{'dnat', DNATRule},
	   {'snat', SNATRule}}