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


module(..., package.seeall)

require 'awall.model'
require 'awall.util'

local model = awall.model


local NATRule = model.class(model.Rule)

18 19
function NATRule:init(...)
   model.Rule.init(self, unpack(arg))
20
   for i, dir in ipairs({'in', 'out'}) do
21
      if awall.util.contains(self[dir], model.fwzone) then
22
	 self:error('NAT rules not allowed for firewall zone')
23
      end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
24 25 26 27 28 29 30
   end
end

function NATRule:defaultzones() return {nil} end

function NATRule:checkzoneoptfrag(ofrag)
   if ofrag[self.params.forbidif] then
31
      self:error('Cannot specify '..self.params.forbidif..'bound interface for '..self.params.target..' rule')
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
32 33 34 35 36 37
   end
end

function NATRule:trules()
   local res = {}
   for i, ofrags in ipairs(model.Rule.trules(self)) do
38
      if ofrags.family == 'inet' then table.insert(res, ofrags) end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
39 40 41 42 43 44 45 46 47
   end
   return res
end

function NATRule:table() return 'nat' end

function NATRule:chain() return self.params.chain end

function NATRule:target()
48
   if self.action then return model.Rule.target(self) end
49 50 51 52 53 54

   local target
   if self['ip-range'] then
      target = self.params.target..' --to-'..self.params.subject..' '..self['ip-range']
   else target = self.params.deftarget end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
55 56 57 58 59 60 61
   if self['port-range'] then target = target..':'..self['port-range'] end
   return target
end


local DNATRule = model.class(NATRule)

62 63
function DNATRule:init(...)
   NATRule.init(self, unpack(arg))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
64
   self.params = {forbidif='out', subject='destination',
65
		  chain='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
		  chain='POSTROUTING', target='SNAT', deftarget='MASQUERADE'}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
75 76 77
end


78 79
classes = {{'dnat', DNATRule},
	   {'snat', SNATRule}}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
80

81
defrules = {}