nat.lua 1.83 KB
Newer Older
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
1 2
--[[
NAT module for Alpine Wall
3
Copyright (C) 2012-2016 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

28 29 30 31 32
function NATRule:trulefilter(rule)
   if not contains(self.params.chains, rule.chain) then
      self:error(
         'Inappropriate zone definitions for a '..self.params.target..' rule'
      )
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
33
   end
34
   return rule.family == 'inet'
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
35 36 37 38 39
end

function NATRule:table() return 'nat' end

function NATRule:target()
40
   local target = NATRule.super(self):target()
41

42 43 44 45 46
   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
47

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

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
53 54 55 56
   return target
end


57
local DNATRule = class(NATRule)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
58

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


71
local SNATRule = class(NATRule)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
72

73
function SNATRule:init(...)
74
   SNATRule.super(self):init(...)
75 76 77 78 79 80 81
   self.params = {
      forbidif='in',
      subject='source',
      chains={'INPUT', 'POSTROUTING'},
      target='SNAT',
      deftarget='MASQUERADE'
   }
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
82 83 84
end


85
return {export={dnat={class=DNATRule}, snat={class=SNATRule}}}