nat.lua 1.89 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
local model = require('awall.model')
local class = model.class
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
10

11
local contains = require('awall.util').contains
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
12 13


14
local NATRule = class(model.Rule)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
15

16 17
-- alpine v2.4 compatibility
function NATRule:init(...)
18
   NATRule.super(self):init(...)
19 20 21 22 23 24 25 26 27
   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
28 29
function NATRule:trules()
   local res = {}
30
   for i, ofrags in ipairs(NATRule.super(self):trules()) do
31
      if not contains(self.params.chains, ofrags.chain) then
32 33
	 self:error('Inappropriate zone definitions for a '..self.params.target..' rule')
      end
34
      if ofrags.family == 'inet' then table.insert(res, ofrags) end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
35 36 37 38 39 40 41
   end
   return res
end

function NATRule:table() return 'nat' end

function NATRule:target()
42
   local target = NATRule.super(self):target()
43

44 45 46 47 48
   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
49

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

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
55 56 57 58
   return target
end


59
local DNATRule = class(NATRule)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
60

61
function DNATRule:init(...)
62
   DNATRule.super(self):init(...)
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
end


69
local SNATRule = class(NATRule)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
70

71
function SNATRule:init(...)
72
   SNATRule.super(self):init(...)
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
return {export={dnat={class=DNATRule}, snat={class=SNATRule}}}