awall-cli 2.05 KB
Newer Older
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
1 2 3 4 5 6 7 8
#!/usr/bin/lua

--[[
Alpine Wall
Copyright (C) 2012 Kaarle Ritvanen
Licensed under the terms of GPL2
]]--

9
require 'alt_getopt'
10
require 'lfs'
11
require 'signal'
12 13
require 'stringy'

14 15 16
short_opts = 'aFo:V'
long_opts = {activate='a',
	     ['output-dir']='o',
17
	     verify='V'}
18

19 20 21 22 23 24 25 26 27
if stringy.endswith(arg[0], '/awall-cli') then
   basedir = string.sub(arg[0], 1, -11)
   input = {basedir..'/json'}

   short_opts = short_opts..'i:'
   long_opts['input-dir'] = 'i'
end

for switch, value in pairs(alt_getopt.get_opts(arg, short_opts, long_opts)) do
28 29 30
   if switch == 'a' then activate = true
   elseif switch == 'F' then fallback = true
   elseif switch == 'i' then table.insert(input, value)
31 32 33
   elseif switch == 'o' then
      iptdir = value
      ipsfile = value..'/ipset'
34
   elseif switch == 'V' then verify = true
35
   else assert(false) end
36
end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
37

38

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
39
require 'awall'
40
require 'awall.iptables'
41
awall.loadmodules(basedir)
42

43
config = awall.Config.new(input)
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96


if activate then

   awall.iptables.backup()

   signal.signal('SIGCHLD',
		 function() if pid and lpc.wait(pid, 1) then os.exit(2) end end)
   for i, sig in ipairs({'INT', 'TERM'}) do
      signal.signal('SIG'..sig, function()
				   interrupted = true
				   io.stdin:close()
				end)
   end

   require 'lpc'
   pid, stdio, stdout = lpc.run(arg[0], '-F')
   stdio:close()
   stdout:close()
   
   config:activate()

   io.stderr:write('New firewall configuration activated\n')
   io.stderr:write('Press RETURN to commit changes permanently: ')
   io.read()

   signal.signal('SIGCHLD', 'default')
   signal.kill(pid, 'SIGTERM')
   lpc.wait(pid)

   if interrupted then
      io.stderr:write('\nActivation canceled, reverting to the old configuration\n')
      awall.iptables.revert()

   else config:dump() end


elseif fallback then

   for i, sig in ipairs({'HUP', 'PIPE'}) do
      signal.signal('SIG'..sig, function() end)
   end

   require 'lsleep'
   lsleep.sleep(10)

   io.stderr:write('\nTimeout, reverting to the old configuration\n')
   awall.iptables.revert()

else
   if verify then config:test() end
   config:dump(iptdir, ipsfile)
end