nat.lua 2.2 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 48 49 50 51 52 53 54 55 56
   end
   return res
end

function NATRule:table() return 'nat' end

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

function NATRule:target()
   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)

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


local SNATRule = model.class(NATRule)

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

function SNATRule:target()
   if self['ip-range'] then return NATRule.target(self) end
   return 'MASQUERADE'..(self['port-range'] and ' --to-ports '..self['port-range'] or '')
end


classmap = {dnat=DNATRule, snat=SNATRule}

80
-- TODO configuration of the ipset via JSON config
81
defrules = {{family='inet', table='nat', chain='POSTROUTING',
82
	     opts='-m set --match-set awall-masquerade src -j awall-masquerade'},
83
	    {family='inet', table='nat', chain='awall-masquerade',
84
	     opts='-m set ! --match-set awall-masquerade dst -j MASQUERADE'}}