File: //lib/python2.7/site-packages/lap/check_firewall.py
import subprocess
import yaml
import os
import re
def get_lines(file, lines=0):
if os.path.isfile(file):
lines = sum(1 for line in open(file) if re.match(r"^(-A|-I)", line))
return(lines)
def get_loaded(table=False):
command = "iptables -nL" if not table else "iptables -nL -t {0}".format(table)
iptables = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = iptables.communicate()
loaded = sum(1 for line in output.split("\n") if not re.match(r"^(Chain|target)|^$", line))
return(loaded)
def __run__(params):
rulescount = 0
files = params.get("rulesfiles", False)
tables = params.get("tables", False)
try:
loadedrules = get_loaded()
if files:
for file in files.split(","):
lines = get_lines(file)
rulescount += lines
else:
return([1, "Files to check rules not found in yaml file"])
if tables:
for table in tables.split(","):
rules = get_loaded(table)
loadedrules += rules
if rulescount != loadedrules:
return([2, "Firewall: the firewall configuration does not match the loaded rules."])
else:
return([0, "Firewall: rules loaded."])
except Exception, err:
return([2, "PluginError: {0}".format(err)])