iptables.lua 1.35 KB
Newer Older
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
1 2 3 4 5 6 7 8 9
--[[
Iptables file dumper for Alpine Wall
Copyright (C) 2012 Kaarle Ritvanen
Licensed under the terms of GPL2
]]--


module(..., package.seeall)

10 11 12 13 14 15 16 17 18 19
require 'lpc'

require 'awall.util'
contains = awall.util.contains

local families = {ip4={cmd='iptables-restore', file='rules-save'},
		  ip6={cmd='ip6tables-restore', file='rules6-save'}}

local builtin = {'INPUT', 'FORWARD', 'OUTPUT',
		 'PREROUTING', 'POSTROUTING'}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
20 21 22 23 24 25 26 27 28

config = {}
setmetatable(config,
	     {__index=function(t, k)
			 t[k] = {}
			 setmetatable(t[k], getmetatable(t))
			 return t[k]
		      end})

29 30 31 32 33 34 35 36 37 38 39
local function dumpfile(family, iptfile)
   iptfile:write('# '..families[family].file..' generated by awall\n')
   for tbl, chains in pairs(config[family]) do
      iptfile:write('*'..tbl..'\n')
      for chain, rules in pairs(chains) do
	 iptfile:write(':'..chain..' '..(contains(builtin, chain) and
				      'DROP' or '-')..' [0:0]\n')
      end
      for chain, rules in pairs(chains) do
	 for i, rule in ipairs(rules) do
	    iptfile:write('-A '..chain..' '..rule..'\n')
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
40 41
	 end
      end
42 43 44 45 46 47 48 49 50 51 52 53
      iptfile:write('COMMIT\n')
   end
end

function dump(dir)
   for family, tbls in pairs(config) do
      local pid, stdin = lpc.run(families[family].cmd, '-t')
      dumpfile(family, stdin)
      stdin:close()
      assert(lpc.wait(pid) == 0)

      dumpfile(family, io.output(dir..'/'..families[family].file))
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
54 55
   end
end