nat.lua 1.99 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(context)
   model.Rule.init(self, context)
20
   for i, dir in ipairs({'in', 'out'}) do
21
      if awall.util.contains(self[dir], model.fwzone) then
22 23
	 error('NAT rules not allowed for firewall zone')
      end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37
   end
end

function NATRule:defaultzones() return {nil} end

function NATRule:checkzoneoptfrag(ofrag)
   if ofrag[self.params.forbidif] then
      error('Cannot specify '..self.params.forbidif..'bound interface for '..target..' rule')
   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
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
49 50 51 52 53 54 55 56 57
   if not self['ip-range'] then error('IP range not defined for NAT rule') end
   local target = self.params.target..' --to-'..self.params.subject..' '..self['ip-range']
   if self['port-range'] then target = target..':'..self['port-range'] end
   return target
end


local DNATRule = model.class(NATRule)

58 59
function DNATRule:init(context)
   NATRule.init(self, context)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
60 61 62 63 64 65 66
   self.params = {forbidif='out', subject='destination',
		  chain='PREROUTING', target='DNAT'}
end


local SNATRule = model.class(NATRule)

67 68
function SNATRule:init(context)
   NATRule.init(self, context)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
69 70 71 72 73
   self.params = {forbidif='in', subject='source',
		  chain='POSTROUTING', target='SNAT'}
end

function SNATRule:target()
74
   if self.action or self['ip-range'] then return NATRule.target(self) end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
75 76 77 78
   return 'MASQUERADE'..(self['port-range'] and ' --to-ports '..self['port-range'] or '')
end


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

82
defrules = {}