示例#1
0
    def flagCheck(self,flagvalue,flagname, indexNumber, iptflags_config):
        self.methodname="flagCheck(self,"+str(flagvalue)+","+str(flagname)+","+str(indexNumber)+","+str(iptflags_config)+")"
        self.flagvalue = flagvalue
        self.flagname = flagname
        valueSupport = ""

        log = logger("xml_parser")

        if self.verbose:
           log.debug("launched "+self.methodname+" of "+self.classname+".")

        # check if this flag supports values

        # this xpath expression selects the value arguemnt of the given cli_switch argument under the given index number
        valueSupport = iptflags_config.xpath('/flags/flag[@index="'+str(indexNumber)+'"]//*[@cli_switch="'+flagname+'"]/@value')
        valueSupport = valueSupport[0]

        if valueSupport == "no":
            self.flagstr = self.flagname+' '
        else:

            if not self.flagvalue:
                self.flagstr = ''
            else:
                self.flagstr = self.flagname+' '+self.flagvalue+' '

        return self.flagstr
示例#2
0
    def __init__(self, fwconfigpath, interface, rulesfile, ipt_xmlconfig, excludedInterfaces, verbose):
        self.classname = "abyleparse"
        self.verbose=verbose
        self.fwconfigpath = fwconfigpath
        self.pinterface = interface
        self.rulesfile = rulesfile
        self.iptflagsfile = ipt_xmlconfig
        self.rulesarray = []
        self.iptflags_dict = {}
        self.excludedInterfaces = excludedInterfaces
        self.allowping = ""
        log = logger("xml_parser")

        if self.verbose:
           log.debug(self.classname+" object created")

        try:
            #old            self.iptflags_config = xml.dom.minidom.parse(self.fwconfigpath+self.iptflagsfile).documentElement
            self.iptflags_config = etree.parse(self.fwconfigpath+self.iptflagsfile)
            if self.excludedInterfaces.count(self.pinterface) > 0:
               #old self.rules_config = xml.dom.minidom.parse(self.fwconfigpath+self.rulesfile)
               self.rules_config = etree.parse(self.fwconfigpath+self.rulesfile)

            elif self.pinterface == "default":
                #old self.rules_config = xml.dom.minidom.parse(self.fwconfigpath+self.rulesfile)
                self.rules_config = etree.parse(self.fwconfigpath+self.rulesfile)
            else:
                # old self.rules_config = xml.dom.minidom.parse(self.fwconfigpath+'interfaces/'+self.pinterface+'/'+self.rulesfile)
                self.rules_config = etree.parse(self.fwconfigpath+'interfaces/'+self.pinterface+'/'+self.rulesfile)
        except (IOError):
            log.error(sys.exc_info()[1])
    def __init__(self, fwconfigpath, interface, xmlconfig, verbose):
        self.classname = "abyle_config_parse"
        self.verbose=verbose
        self.fwconfigpath = fwconfigpath
        self.pinterface = interface
        self.xmlconfig = xmlconfig
        self.configarr = []
        self.configvar = ''

        log = logger("xml_config_parser")

        if self.verbose:
           log.debug(self.classname+" object created.")

        try:
            if self.pinterface == "default":
                self.abyle_config = etree.parse(self.fwconfigpath+self.xmlconfig)
                if self.verbose:
                      log.debug("trying to parse "+self.fwconfigpath+self.xmlconfig)
            else:
                self.abyle_config = etree.parse(self.fwconfigpath+'interfaces/'+self.pinterface+'/'+self.xmlconfig)
                if self.verbose:
                      log.debug("trying to parse "+self.fwconfigpath+'interfaces/'+self.pinterface+'/'+self.xmlconfig)
        except (IOError):
            log.error(str(sys.exc_info()[1]))
    def flagCheck(self, flagvalue, flagname, indexNumber, iptflags_config):
        self.methodname = "flagCheck(self," + str(flagvalue) + "," + str(
            flagname) + "," + str(indexNumber) + "," + str(
                iptflags_config) + ")"
        self.flagvalue = flagvalue
        self.flagname = flagname
        valueSupport = ""

        log = logger("xml_parser")

        if self.verbose:
            log.debug("launched " + self.methodname + " of " + self.classname +
                      ".")

        # check if this flag supports values

        # this xpath expression selects the value arguemnt of the given cli_switch argument under the given index number
        valueSupport = iptflags_config.xpath('/flags/flag[@index="' +
                                             str(indexNumber) +
                                             '"]//*[@cli_switch="' + flagname +
                                             '"]/@value')
        valueSupport = valueSupport[0]

        if valueSupport == "no":
            self.flagstr = self.flagname + ' '
        else:

            if not self.flagvalue:
                self.flagstr = ''
            else:
                self.flagstr = self.flagname + ' ' + self.flagvalue + ' '

        return self.flagstr
    def __init__(self, fwconfigpath, interface, xmlconfig, verbose):
        self.classname = "abyle_config_parse"
        self.verbose = verbose
        self.fwconfigpath = fwconfigpath
        self.pinterface = interface
        self.xmlconfig = xmlconfig
        self.configarr = []
        self.configvar = ''

        log = logger("xml_config_parser")

        if self.verbose:
            log.debug(self.classname + " object created.")

        try:
            if self.pinterface == "default":
                self.abyle_config = etree.parse(self.fwconfigpath +
                                                self.xmlconfig)
                if self.verbose:
                    log.debug("trying to parse " + self.fwconfigpath +
                              self.xmlconfig)
            else:
                self.abyle_config = etree.parse(self.fwconfigpath +
                                                'interfaces/' +
                                                self.pinterface + '/' +
                                                self.xmlconfig)
                if self.verbose:
                    log.debug("trying to parse " + self.fwconfigpath +
                              'interfaces/' + self.pinterface + '/' +
                              self.xmlconfig)
        except (IOError):
            log.error(str(sys.exc_info()[1]))
示例#6
0
    def buildUpFinish(self, verbose):
        self.verbose = verbose

        log = logger("abyle-firewall")

        self.defaultrules = self.default_config.getDefaultRules("foot")
        log.info("SETTING UP DEFAULT RULES:")
        for drule in self.defaultrules:
            log.info("default-rule: " + drule)
            stdOut, stdErr = self.executioner.run(self.iptablesbin + " " + drule, self.dryrun)
示例#7
0
    def buildUpFinish(self, verbose):
        self.verbose = verbose

        log = logger("abyle-firewall")

        self.defaultrules = self.default_config.getDefaultRules("foot")
        log.info("SETTING UP DEFAULT RULES:")
        for drule in self.defaultrules:
            log.info("default-rule: " + drule)
            stdOut, stdErr = self.executioner.run(
                self.iptablesbin + ' ' + drule, self.dryrun)
    def getConfig(self, configstr):
        self.methodname = "getConfig(self," + configstr + ")"
        self.configstr = configstr
        self.configarr = []
        self.configvar = ''

        log = logger("xml_config_parser")

        if self.verbose:
            log.debug("launched " + self.methodname + " of " + self.classname +
                      ".")

        if self.configstr == "excluded_interfaces":
            #for self.configtag in self.abyle_config.getElementsByTagName("interface"):
            configwalk = etree.iterwalk(self.abyle_config,
                                        events=("start", "end"),
                                        tag=str("interface"))
            for action, elem, in configwalk:
                if action in ('start'):
                    attributes = elem.attrib
                    if str(attributes.get("excluded")).upper() == "YES":
                        if self.verbose:
                            log.debug(elem.text)
                        self.configarr.append(elem.text)

            return self.configarr

        else:

            #for self.configtag in self.abyle_config.getElementsByTagName(self.configstr):
            configwalk = etree.iterwalk(self.abyle_config,
                                        events=("start", "end"),
                                        tag=str(self.configstr))
            for action, elem, in configwalk:
                if action in ('start'):
                    if self.verbose:
                        log.debug(elem.text)
                    self.configarr.append(elem.text)

            try:
                self.configvar = self.configarr[1]
                return self.configarr
            except (IndexError):
                return self.configarr[0]
    def getConfig(self,configstr):
        self.methodname="getConfig(self,"+configstr+")"
        self.configstr = configstr
        self.configarr = []
        self.configvar = ''

        log = logger("xml_config_parser")

        if self.verbose:
           log.debug("launched "+self.methodname+" of "+self.classname+".")

        if self.configstr == "excluded_interfaces":
            #for self.configtag in self.abyle_config.getElementsByTagName("interface"):
            configwalk = etree.iterwalk(self.abyle_config,events=("start","end"),tag=str("interface"))
            for action, elem, in configwalk:
                if action in ('start'):
                   attributes = elem.attrib
                   if str(attributes.get("excluded")).upper() == "YES":
                        if self.verbose:
                            log.debug(elem.text)
                        self.configarr.append(elem.text)

            return self.configarr



        else:

            #for self.configtag in self.abyle_config.getElementsByTagName(self.configstr):
            configwalk = etree.iterwalk(self.abyle_config,events=("start","end"),tag=str(self.configstr))
            for action, elem, in configwalk:
                if action in ('start'):
                   if self.verbose:
                       log.debug(elem.text)
                   self.configarr.append(elem.text)

            try:
                self.configvar = self.configarr[1]
                return self.configarr
            except (IndexError):
                return self.configarr[0]
    def __init__(self, fwconfigpath, interface, rulesfile, ipt_xmlconfig,
                 excludedInterfaces, verbose):
        self.classname = "abyleparse"
        self.verbose = verbose
        self.fwconfigpath = fwconfigpath
        self.pinterface = interface
        self.rulesfile = rulesfile
        self.iptflagsfile = ipt_xmlconfig
        self.rulesarray = []
        self.iptflags_dict = {}
        self.excludedInterfaces = excludedInterfaces
        self.allowping = ""
        log = logger("xml_parser")

        if self.verbose:
            log.debug(self.classname + " object created")

        try:
            #old            self.iptflags_config = xml.dom.minidom.parse(self.fwconfigpath+self.iptflagsfile).documentElement
            self.iptflags_config = etree.parse(self.fwconfigpath +
                                               self.iptflagsfile)
            if self.excludedInterfaces.count(self.pinterface) > 0:
                #old self.rules_config = xml.dom.minidom.parse(self.fwconfigpath+self.rulesfile)
                self.rules_config = etree.parse(self.fwconfigpath +
                                                self.rulesfile)

            elif self.pinterface == "default":
                #old self.rules_config = xml.dom.minidom.parse(self.fwconfigpath+self.rulesfile)
                self.rules_config = etree.parse(self.fwconfigpath +
                                                self.rulesfile)
            else:
                # old self.rules_config = xml.dom.minidom.parse(self.fwconfigpath+'interfaces/'+self.pinterface+'/'+self.rulesfile)
                self.rules_config = etree.parse(self.fwconfigpath +
                                                'interfaces/' +
                                                self.pinterface + '/' +
                                                self.rulesfile)
        except (IOError):
            log.error(sys.exc_info()[1])
示例#11
0
    def __init__(self, dryrun, iptablesbin, fwconfigpath, rulesfile,
                 ipt_xmlconfig, xmlconfig, echocmd, logfile, verbose):
        self.naptime = 10  # milliseconds
        self.dryrun = dryrun
        self.iptablesbin = iptablesbin
        self.fwconfigpath = fwconfigpath
        self.rulesfile = rulesfile
        self.ipt_xmlconfig = ipt_xmlconfig
        self.xmlconfig = xmlconfig
        self.logfile = logfile
        self.verbose = verbose

        self.executioner = abyle_execute()

        self.echocmd = echocmd

        global_config = abyle_config_parse(fwconfigpath, "default", xmlconfig,
                                           self.verbose)

        self.excludedInterfaces = global_config.getConfig(
            "excluded_interfaces")

        try:
            self.tcpabort_file = global_config.getConfig("tcpabortfile")
        except IndexError:
            self.tcpabort_file = "/proc/sys/net/ipv4/tcpicmpbcastfile_abort_on_overflow"

        try:
            self.icmpbcastreply_file = global_config.getConfig("icmpbcastfile")
        except IndexError:
            self.icmpbcastreply_file = "/proc/sys/net/ipv4/icmp_echo_ignore_broadcasts"

        try:
            self.dynaddresshack_file = global_config.getConfig(
                "dynaddresshackfile")
        except IndexError:
            self.dynaddresshack_file = "/proc/sys/net/ipv4/ip_dynaddr"

        try:
            self.ipv4conf_path = global_config.getConfig("ipv4confpath")
        except IndexError:
            self.ipv4conf_path = "/proc/sys/net/ipv4/conf/"

        try:
            self.antispoofing_file = global_config.getConfig(
                "antispoofingfile")
        except IndexError:
            self.antispoofing_file = "rp_filter"

        try:
            self.syncookiefile = global_config.getConfig("syncookiefile")
        except IndexError:
            self.syncookiefile = "/proc/sys/net/ipv4/tcp_syncookies"

        try:
            self.ipv4forwardfile = global_config.getConfig("ipv4forwardfile")
        except IndexError:
            self.ipv4forwardfile = "/proc/sys/net/ipv4/ip_forward"

        try:
            self.syncookie = str(global_config.getConfig("syncookie")).upper()
        except IndexError:
            self.syncookie = "YES"

        try:
            self.ipv4forward = str(
                global_config.getConfig("ipv4forward")).upper()
        except IndexError:
            self.syncookie = "NO"

        try:
            self.tcpabort = str(global_config.getConfig("aborttcp")).upper()
        except IndexError:
            self.tcpabort = "NO"

        try:
            self.icmpbcastreply = str(
                global_config.getConfig("answericmpbroadcast")).upper()
        except IndexError:
            self.icmpbcastreply = "NO"

        try:
            self.dynaddresshack = str(
                global_config.getConfig("dynaddresshack")).upper()
        except IndexError:
            self.dynaddresshack = "NO"

        try:
            self.proxyarp_file = global_config.getConfig("proxyarpfile")
        except IndexError:
            self.proxyarp_file = "proxy_arp"

        try:
            self.srouting_file = global_config.getConfig("sroutingfile")
        except IndexError:
            self.srouting_file = "accept_source_route"

        try:
            self.icmpredirects_file = global_config.getConfig("icmprdrsfile")
        except IndexError:
            self.icmpredirects_file = "accept_redirects"

        try:
            self.secureicmpredirects_file = global_config.getConfig(
                "icmpsecurerdrsfile")
        except IndexError:
            self.secureicmpredirects_file = "secure_redirects"

        try:
            self.martians_file = global_config.getConfig("martiansfile")
        except IndexError:
            self.martians_file = "log_martians"

        try:
            self.bootprelay_file = global_config.getConfig("bootprelayfile")
        except IndexError:
            self.bootprelay_file = "bootp_relay"

        log = logger("firewall")

        if not self.tcpabort == "NO":
            stdOut, stdErr = self.executioner.run(
                self.echocmd + ' 1 > ' + self.tcpabort_file, self.dryrun)
            log.info("ipv4 send TCP-RST on full buffer is activated")
        else:
            stdOut, stdErr = self.executioner.run(
                self.echocmd + ' 0 > ' + self.tcpabort_file, self.dryrun)
            log.info("ipv4 send TCP-RST on full buffer is deactivated")

        if not self.icmpbcastreply == "NO":
            stdOut, stdErr = self.executioner.run(
                self.echocmd + ' 1 > ' + self.icmpbcastreply_file, self.dryrun)
            log.info("ipv4 reply to ICMP Broadcasts is deactivated")
        else:
            stdOut, stdErr = self.executioner.run(
                self.echocmd + ' 0 > ' + self.icmpbcastreply_file, self.dryrun)
            log.info("ipv4 reply to ICMP Broadcasts is activated")

        if not self.dynaddresshack == "NO":
            stdOut, stdErr = self.executioner.run(
                self.echocmd + ' 1 > ' + self.dynaddresshack_file, self.dryrun)
            log.info("ipv4 dynamic address hack activated")
        else:
            stdOut, stdErr = self.executioner.run(
                self.echocmd + ' 0 > ' + self.dynaddresshack_file, self.dryrun)
            log.info("ipv4 dynamic address hack deactivated")

        if not self.ipv4forward == "NO":
            stdOut, stdErr = self.executioner.run(
                self.echocmd + ' 1 > ' + self.ipv4forwardfile, self.dryrun)
            log.info("ipv4 forwarding activated")
        else:
            stdOut, stdErr = self.executioner.run(
                self.echocmd + ' 0 > ' + self.ipv4forwardfile, self.dryrun)
            log.info("ipv4 forwarding deactivated")

        if not self.syncookie == "NO":
            stdOut, stdErr = self.executioner.run(
                self.echocmd + ' 1 > ' + self.syncookiefile, self.dryrun)
            log.info("syncookie activated")
        else:
            stdOut, stdErr = self.executioner.run(
                self.echocmd + ' 0 > ' + self.syncookiefile, self.dryrun)
            log.info("syncookie deactivated")

        self.default_config = abyleparse(self.fwconfigpath, "default",
                                         self.rulesfile, self.ipt_xmlconfig,
                                         self.excludedInterfaces, self.verbose)
        self.defaultrules = self.default_config.getDefaultRules("head")

        for drule in self.defaultrules:
            log.info("default-rule: " + drule)
            stdOut, stdErr = self.executioner.run(
                self.iptablesbin + ' ' + drule, self.dryrun)
示例#12
0
import re
import os
import string
import time
import datetime
import sys
from abyle_xmlparser import abyleparse
from abyle_execute import abyle_execute
from abyle_config_xmlparser import abyle_config_parse
from xml.sax.handler import ContentHandler
from xml.sax import make_parser
from abyle_log import logger

control = logger("abyle-control")


class abyle_firewall:
    def __init__(self, dryrun, iptablesbin, fwconfigpath, rulesfile,
                 ipt_xmlconfig, xmlconfig, echocmd, logfile, verbose):
        self.naptime = 10  # milliseconds
        self.dryrun = dryrun
        self.iptablesbin = iptablesbin
        self.fwconfigpath = fwconfigpath
        self.rulesfile = rulesfile
        self.ipt_xmlconfig = ipt_xmlconfig
        self.xmlconfig = xmlconfig
        self.logfile = logfile
        self.verbose = verbose

        self.executioner = abyle_execute()
    def getAbstractXmlRules(self, xpathToMainNode):
        self.methodname = "getAbstractXmlRules(self," + xpathToMainNode + ")"

        log = logger("xml_parser")

        if self.verbose:
            log.debug("launched " + self.methodname + " of " + self.classname +
                      ".")

        # xpathToMainNode example for access rules: "/interface/rules/traffic"

        self.abstractRulesArray = []
        self.iptflags_indecies = []

        if self.allowping == "yes":
            self.rules_config = etree.parse(self.fwconfigpath + self.rulesfile)

        if xpathToMainNode.find("masquerading") > 0:
            self.rules_config = etree.parse(self.fwconfigpath + 'interfaces/' +
                                            self.pinterface + '/' +
                                            self.rulesfile)

        # parse the iptables flags config file, getIpTablesFlags returns:
        # -  a dict of iptablesflags e.g.: 11 -> destination or 12 -> destination-port
        # -  a sorted array of all available index numbers e.g: 1,2,3,...,12
        # -  the iptables cli switch for the interface argument: e.g: -i
        # -  special flag iptables cli switch for portforwarding destination
        # -  transparent proxy to-port flag
        # -  masquerading interface flag (outside instead of inside)
        # -  subflag dictionary
        self.iptflags_dict, interface, portfwdDestFlag, transproxyToPortFlag, outsideInterfaceFlag, subflags_dict, subflags_cliswitch_dict = self.getIpTablesFlags(
        )

        # extract keys (index numbers) in an array and sort it
        #self.iptflags_indecies = list(self.iptflags_dict.keys())
        for tempIndex in list(self.iptflags_dict.keys()):
            self.iptflags_indecies.append(int(tempIndex))
        self.iptflags_indecies.sort()

        if self.verbose:
            log.debug(self.methodname + " - self.iptflags_indecies (sorted) " +
                      str(self.iptflags_indecies) + ".")

        if xpathToMainNode.find("head") > 0:
            blockchain = self.rules_config.xpath(
                "/interface/blockruleshead/@blockchain")
            blockchain = blockchain[0]
            blockchain_create_string = " -N " + blockchain
            self.abstractRulesArray.append(blockchain_create_string)

        if xpathToMainNode.find("masquerading") > 0:
            self.interfacestr = outsideInterfaceFlag + ' ' + self.pinterface + ' '
        else:
            # set the interface string to e.g.: -i eth0
            self.interfacestr = interface + ' ' + self.pinterface + ' '

        # get list of rules e.g. all traffic nodes or all portforwarding nodes
        abstractNodes = self.rules_config.xpath(xpathToMainNode)

        if self.verbose:
            log.debug(self.methodname + " - abstractNodes " +
                      str(abstractNodes) + ".")

        cnt = 0
        for node in abstractNodes:
            # get list of all attributes of an rule node
            #abstractAttributeNodes = abstractNodes[cnt].xpath("./@*")
            abstractAttributeNodes = abstractNodes[cnt].keys()
            if self.verbose:
                log.debug(self.methodname + " - " + str(node.tag) +
                          " abstractNode AttributeNames " +
                          str(abstractNodes[cnt].keys()) + ".")
#                log.debug(self.methodname+" - "+str(node.tag)+" attributes "+str(abstractAttributeNodes)+".")
            self.attributestr = ""
            tempDestIpStr = ""
            tempDestPortStr = ""
            tempForwardPortStr = ""

            # loop through iptables flags index number list to build the right order
            for indexNumber in self.iptflags_indecies:

                # get the value of a flag out if the iptables flag dict, e.g.: indexNumber=12 then flag_value = destination
                flag_value = self.iptflags_dict[str(indexNumber)][0].text

                # loop through all found attribute nodes
                for attribute in abstractAttributeNodes:

                    # test if the attribute name is equal to the string in flag value
                    if attribute == flag_value:

                        try:
                            # parse the file with xpath and get the attributenode cli_switch under cfgname which has the searched indexNumber
                            flag_cli_arg_node = self.iptflags_config.xpath(
                                "/flags/flag[@index=" + str(indexNumber) +
                                "]/cfgname/@cli_switch")

                            #print (flag_cli_arg_node)
                            # extract the value if the attribute node [0] = assuming that the index is unique
                            flag_cli_arg = flag_cli_arg_node[0]

                            # check and build the attribute string with flagCheck()
                            attributeTmpstr = self.flagCheck(
                                str(abstractNodes[cnt].get(attribute)),
                                flag_cli_arg, indexNumber,
                                self.iptflags_config)

                        except (KeyError):
                            log.error(sys.exc_info()[1])
                            sys.exit(1)

                        if xpathToMainNode.find(
                                "portforwarding"
                        ) > 0 and attribute == "destination":
                            tempDestIpStr = abstractNodes[cnt].get(attribute)

                        elif xpathToMainNode.find(
                                "portforwarding"
                        ) > 0 and attribute == "destination-port":
                            tempDestPortStr = abstractNodes[cnt].get(attribute)

                        elif xpathToMainNode.find(
                                "portforwarding"
                        ) > 0 and attribute == "forward-port":
                            tempForwardPortStr = abstractNodes[cnt].get(
                                attribute)

                        elif xpathToMainNode.find(
                                "transparentproxy"
                        ) > 0 and attribute == "destination":
                            tempDestIpStr = abstractNodes[cnt].get(attribute)

                        elif xpathToMainNode.find(
                                "transparentproxy"
                        ) > 0 and attribute == "destination-port":
                            tempDestPortStr = abstractNodes[cnt].get(attribute)

                        else:
                            # append the temp string to the self.attributestr
                            self.attributestr = self.attributestr + attributeTmpstr

                        hasSubflags = "no"
                        for key in subflags_dict.keys():
                            if str(key) == str(indexNumber):
                                hasSubflags = "yes"

                        if hasSubflags == "yes":
                            subattributeTmpstr = ""
                            tempSubflagsArray = subflags_dict[
                                indexNumber].split(';')
                            tempSubflagsCliswitchArray = subflags_cliswitch_dict[
                                indexNumber].split(';')

                            subflagcnt = 0
                            for subflag_value in tempSubflagsArray:

                                for attribute in abstractAttributeNodes:

                                    if attribute.name == subflag_value:

                                        subattributeTmpstr = self.flagCheck(
                                            attribute.value,
                                            tempSubflagsCliswitchArray[
                                                subflagcnt], indexNumber,
                                            self.iptflags_config)
                                        self.attributestr = self.attributestr + subattributeTmpstr

                                subflagcnt = subflagcnt + 1

            cnt = cnt + 1

            self.attributestrForward = ""

            if xpathToMainNode.find("portforwarding") > 0:

                # append interface string to the attribute string

                # build the iptablescommand for the PREROUTING chain of the nat table and the FORWARD chain
                if not self.pinterface == "default":
                    self.attributestr = self.interfacestr + self.attributestr

                self.attributestrForward = self.attributestr
                self.attributestrForward = re.sub("PREROUTING", "FORWARD",
                                                  self.attributestrForward)
                self.attributestrForward = re.sub("DNAT", "ACCEPT",
                                                  self.attributestrForward)
                self.attributestrForward = re.sub("-t nat", "",
                                                  self.attributestrForward)
                self.attributestrForward = re.sub("--dport \d{1,5}", "",
                                                  self.attributestrForward)
                self.attributestrForward = self.attributestrForward + " --destination-port " + tempDestPortStr + " --destination " + tempDestIpStr

                self.attributestr = self.attributestr + "--dport " + tempForwardPortStr + " " + portfwdDestFlag + ' ' + tempDestIpStr + ":" + tempDestPortStr

            elif xpathToMainNode.find("transparentproxy") > 0:
                self.attributestr = self.interfacestr + self.attributestr + transproxyToPortFlag + ' ' + tempDestPortStr

            else:
                if not self.pinterface == "default":
                    self.attributestr = self.interfacestr + self.attributestr

            # append the string to the rules array
            self.abstractRulesArray.append(self.attributestr)

            if not self.attributestrForward == "":
                self.abstractRulesArray.append(self.attributestrForward)

        return self.abstractRulesArray
示例#14
0
#from xml.dom.minidom import *
import re
import sys
#from xml.dom.minidom import Node
from abyle_output import abyle_output
from abyle_log import logger

log = logger("xml_parser")
try:
    from lxml import etree
except (ImportError):
    log.error("xml parser import error, please install python lxml package")
    sys.exit(1)

class abyleparse:
    def __init__(self, fwconfigpath, interface, rulesfile, ipt_xmlconfig, excludedInterfaces, verbose):
        self.classname = "abyleparse"
        self.verbose=verbose
        self.fwconfigpath = fwconfigpath
        self.pinterface = interface
        self.rulesfile = rulesfile
        self.iptflagsfile = ipt_xmlconfig
        self.rulesarray = []
        self.iptflags_dict = {}
        self.excludedInterfaces = excludedInterfaces
        self.allowping = ""
        log = logger("xml_parser")

        if self.verbose:
           log.debug(self.classname+" object created")
#import xml.dom.minidom
import re
import sys

#from xml.dom.minidom import Node
from abyle_output import abyle_output
from abyle_log import logger

log = logger("xml_config_parser")

try:
    from lxml import etree
except (ImportError):
    log.error("xml parser import error, please install python lxml package")
    sys.exit(1)

class abyle_config_parse:
    def __init__(self, fwconfigpath, interface, xmlconfig, verbose):
        self.classname = "abyle_config_parse"
        self.verbose=verbose
        self.fwconfigpath = fwconfigpath
        self.pinterface = interface
        self.xmlconfig = xmlconfig
        self.configarr = []
        self.configvar = ''

        log = logger("xml_config_parser")

        if self.verbose:
           log.debug(self.classname+" object created.")
#import xml.dom.minidom
import re
import sys

#from xml.dom.minidom import Node
from abyle_output import abyle_output
from abyle_log import logger

log = logger("xml_config_parser")

try:
    from lxml import etree
except (ImportError):
    log.error("xml parser import error, please install python lxml package")
    sys.exit(1)


class abyle_config_parse:
    def __init__(self, fwconfigpath, interface, xmlconfig, verbose):
        self.classname = "abyle_config_parse"
        self.verbose = verbose
        self.fwconfigpath = fwconfigpath
        self.pinterface = interface
        self.xmlconfig = xmlconfig
        self.configarr = []
        self.configvar = ''

        log = logger("xml_config_parser")

        if self.verbose:
            log.debug(self.classname + " object created.")
示例#17
0
    def buildUp(self, protectedif, fwconfigpath, verbose):
        self.verbose = verbose

        self.protectedif = protectedif
        self.fwconfigpath = fwconfigpath

        log = logger("abyle-firewall")
        self.control = control
        if self.protectedif in self.excludedInterfaces:
            log.start_stop("securing " + self.protectedif, "EXCLUDED")
        else:
            log.start_stop("securing " + self.protectedif)

        if (
            os.path.exists(self.fwconfigpath + "/" + "interfaces/" + self.protectedif)
            or self.excludedInterfaces.count(self.protectedif) > 0
        ):

            if self.excludedInterfaces.count(self.protectedif) == 0:

                tempFileStr = self.fwconfigpath + "interfaces/" + self.protectedif + "/" + self.xmlconfig
                checkWellformed = self.check_well_formedness(tempFileStr)
                if checkWellformed != "ok":
                    log.error(checkWellformed)
                    sys.exit(1)
                else:
                    log.info(
                        self.fwconfigpath
                        + "interfaces/"
                        + self.protectedif
                        + "/"
                        + self.xmlconfig
                        + " is a well-formed xml"
                    )

                # parse the config file
                self.if_config = abyle_config_parse(self.fwconfigpath, self.protectedif, self.xmlconfig, self.verbose)

                try:
                    self.antispoofing = self.if_config.getConfig("antispoofing")
                except IndexError:
                    self.antispoofing = "NO"

                try:
                    self.proxyarp = self.if_config.getConfig("proxyarp")
                except IndexError:
                    self.proxyarp = "NO"

                try:
                    self.srouting = self.if_config.getConfig("sourcerouting")
                except IndexError:
                    self.srouting = "NO"

                try:
                    self.icmprdrs = self.if_config.getConfig("icmpredirects")
                except IndexError:
                    self.icmprdrs = "NO"

                try:
                    self.sicmprdrs = self.if_config.getConfig("secureicmpredirects")
                except IndexError:
                    self.sicmprdrs = "NO"

                try:
                    self.martians = self.if_config.getConfig("martianslogging")
                except IndexError:
                    self.martians = "NO"

                try:
                    self.bootprelay = self.if_config.getConfig("drop0slash8packets")
                except IndexError:
                    self.bootprelay = "NO"

                try:
                    self.logging = self.if_config.getConfig("logging")
                except IndexError:
                    self.logging = "NO"

                try:
                    self.allowping = self.if_config.getConfig("allowping")
                except IndexError:
                    self.allowping = "NO"

                try:
                    self.masquerading = self.if_config.getConfig("masquerading")
                except IndexError:
                    self.masquerading = "NO"

                try:
                    self.portforwarding = self.if_config.getConfig("portforwarding")
                except IndexError:
                    self.portforwarding = "NO"

                try:
                    self.tproxy = self.if_config.getConfig("transparent_proxy")
                except IndexError:
                    self.tproxy = "NO"

                # end parse the config file

                self.antispoofing = str(self.antispoofing).upper()
                self.proxyarp = str(self.proxyarp).upper()
                self.srouting = str(self.srouting).upper()
                self.icmprdrs = str(self.icmprdrs).upper()
                self.sicmprdrs = str(self.sicmprdrs).upper()
                self.martians = str(self.martians).upper()
                self.bootprelay = str(self.bootprelay).upper()
                self.logging = str(self.logging).upper()
                self.allowping = str(self.allowping).upper()
                self.masquerading = str(self.masquerading).upper()
                self.portforwarding = str(self.portforwarding).upper()
                self.tproxy = str(self.tproxy).upper()

                # interface specific protections

                if self.proxyarp == "YES":
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + " 1 > " + self.ipv4conf_path + self.protectedif + "/" + self.proxyarp_file,
                        self.dryrun,
                    )
                    log.info("proxy arp activated for " + self.protectedif)
                else:
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + " 0 > " + self.ipv4conf_path + self.protectedif + "/" + self.proxyarp_file,
                        self.dryrun,
                    )
                    log.info("proxy arp deactivated for " + self.protectedif)

                if self.srouting == "YES":
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + " 1 > " + self.ipv4conf_path + self.protectedif + "/" + self.srouting_file,
                        self.dryrun,
                    )
                    log.info("allow source routing activated for " + self.protectedif)
                else:
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + " 0 > " + self.ipv4conf_path + self.protectedif + "/" + self.srouting_file,
                        self.dryrun,
                    )
                    log.info("allow source routing deactivated for " + self.protectedif)

                if self.icmprdrs == "YES":
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + " 1 > " + self.ipv4conf_path + self.protectedif + "/" + self.icmpredirects_file,
                        self.dryrun,
                    )
                    log.info("icmp redirects activated for " + self.protectedif)
                else:
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + " 0 > " + self.ipv4conf_path + self.protectedif + "/" + self.icmpredirects_file,
                        self.dryrun,
                    )
                    log.info("icmp redirects deactivated for " + self.protectedif)

                if self.sicmprdrs == "YES":
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd
                        + " 1 > "
                        + self.ipv4conf_path
                        + self.protectedif
                        + "/"
                        + self.secureicmpredirects_file,
                        self.dryrun,
                    )
                    log.info("secure icmp redirects activated for " + self.protectedif)
                else:
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd
                        + " 0 > "
                        + self.ipv4conf_path
                        + self.protectedif
                        + "/"
                        + self.secureicmpredirects_file,
                        self.dryrun,
                    )
                    log.info("secure icmp redirects deactivated for " + self.protectedif)

                if self.martians == "YES":
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + " 1 > " + self.ipv4conf_path + self.protectedif + "/" + self.martians_file,
                        self.dryrun,
                    )
                    log.info("martians logging activated for " + self.protectedif)
                else:
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + " 0 > " + self.ipv4conf_path + self.protectedif + "/" + self.martians_file,
                        self.dryrun,
                    )
                    log.info("martians logging deactivated for " + self.protectedif)

                if self.bootprelay == "YES":
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + " 1 > " + self.ipv4conf_path + self.protectedif + "/" + self.bootprelay_file,
                        self.dryrun,
                    )
                    log.info("dropping packets from 0/8 activated for " + self.protectedif)
                else:
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + " 0 > " + self.ipv4conf_path + self.protectedif + "/" + self.bootprelay_file,
                        self.dryrun,
                    )
                    log.info("dropping packets from 0/8 deactivated for " + self.protectedif)

                if self.antispoofing == "YES":
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + " 1 > " + self.ipv4conf_path + self.protectedif + "/" + self.antispoofing_file,
                        self.dryrun,
                    )
                    log.info("anti spoofing activated for " + self.protectedif)
                else:
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + " 0 > " + self.ipv4conf_path + self.protectedif + "/" + self.antispoofing_file,
                        self.dryrun,
                    )
                    log.info("anti spoofing deactivated for " + self.protectedif)

            self.if_config = abyleparse(
                self.fwconfigpath,
                self.protectedif,
                self.rulesfile,
                self.ipt_xmlconfig,
                self.excludedInterfaces,
                self.verbose,
            )
            self.rules = self.if_config.getRules()
            log_rules = logger("firewall-rule")

            for rule in self.rules:
                time.sleep(self.naptime / 1000.0)
                log_rules.info(self.protectedif + " " + rule)
                stdOut, stdErr = self.executioner.run(self.iptablesbin + " " + rule, self.dryrun)

            if self.excludedInterfaces.count(self.protectedif) == 0:
                if self.portforwarding == "YES":
                    self.portforwarding = self.if_config.getPortforwarding()
                    for portfwd in self.portforwarding:
                        log.info(self.protectedif + " " + portfwd)
                        stdOut, stdErr = self.executioner.run(self.iptablesbin + " " + portfwd, self.dryrun)
                else:
                    log.info(self.protectedif + " " + "PORTFORWARDING DISABLED")

                if self.tproxy == "YES":
                    self.tproxy = self.if_config.getTproxy()
                    for transproxy in self.tproxy:
                        log.info(self.protectedif + " " + transproxy)
                        stdOut, stdErr = self.executioner.run(self.iptablesbin + " " + transproxy, self.dryrun)
                else:
                    log.info(self.protectedif + " " + "TRANSPARENT PROXY DISABLED")

                if self.logging == "YES":
                    self.logging = self.if_config.getLogging()
                    for log in self.logging:
                        log.info(self.protectedif + " " + log)
                        stdOut, stdErr = self.executioner.run(self.iptablesbin + " " + log, self.dryrun)
                else:
                    log.info(self.protectedif + " " + "LOGGING DISABLED")

                if self.allowping == "YES":
                    self.allowping = self.if_config.getAllowPing()
                    for ap in self.allowping:
                        log.info(self.protectedif + " " + ap)
                        stdOut, stdErr = self.executioner.run(self.iptablesbin + " " + ap, self.dryrun)
                else:
                    log.info(self.protectedif + " " + "ALLOWPING DISABLED")

                if self.masquerading == "YES":
                    self.masquerading = self.if_config.getMasquerading()
                    for mg in self.masquerading:
                        log.info(self.protectedif + " " + mg)
                        stdOut, stdErr = self.executioner.run(self.iptablesbin + " " + mg, self.dryrun)
                else:
                    log.info(self.protectedif + " " + "MASQUERADING DISABLED")

        else:
            log.error(
                "no directory found for interface " + self.protectedif + " in " + self.fwconfigpath + "interfaces/"
            )
示例#18
0
    def buildUp(self, protectedif, fwconfigpath, verbose):
        self.verbose = verbose

        self.protectedif = protectedif
        self.fwconfigpath = fwconfigpath

        log = logger("abyle-firewall")
        self.control = control
        if self.protectedif in self.excludedInterfaces:
            log.start_stop("securing " + self.protectedif, "EXCLUDED")
        else:
            log.start_stop("securing " + self.protectedif)

        if os.path.exists(self.fwconfigpath + '/' + 'interfaces/' +
                          self.protectedif) or self.excludedInterfaces.count(
                              self.protectedif) > 0:

            if self.excludedInterfaces.count(self.protectedif) == 0:

                tempFileStr = self.fwconfigpath + 'interfaces/' + self.protectedif + '/' + self.xmlconfig
                checkWellformed = self.check_well_formedness(tempFileStr)
                if checkWellformed != "ok":
                    log.error(checkWellformed)
                    sys.exit(1)
                else:
                    log.info(self.fwconfigpath + "interfaces/" +
                             self.protectedif + "/" + self.xmlconfig +
                             " is a well-formed xml")

                #parse the config file
                self.if_config = abyle_config_parse(self.fwconfigpath,
                                                    self.protectedif,
                                                    self.xmlconfig,
                                                    self.verbose)

                try:
                    self.antispoofing = self.if_config.getConfig(
                        "antispoofing")
                except IndexError:
                    self.antispoofing = "NO"

                try:
                    self.proxyarp = self.if_config.getConfig("proxyarp")
                except IndexError:
                    self.proxyarp = "NO"

                try:
                    self.srouting = self.if_config.getConfig("sourcerouting")
                except IndexError:
                    self.srouting = "NO"

                try:
                    self.icmprdrs = self.if_config.getConfig("icmpredirects")
                except IndexError:
                    self.icmprdrs = "NO"

                try:
                    self.sicmprdrs = self.if_config.getConfig(
                        "secureicmpredirects")
                except IndexError:
                    self.sicmprdrs = "NO"

                try:
                    self.martians = self.if_config.getConfig("martianslogging")
                except IndexError:
                    self.martians = "NO"

                try:
                    self.bootprelay = self.if_config.getConfig(
                        "drop0slash8packets")
                except IndexError:
                    self.bootprelay = "NO"

                try:
                    self.logging = self.if_config.getConfig("logging")
                except IndexError:
                    self.logging = "NO"

                try:
                    self.allowping = self.if_config.getConfig("allowping")
                except IndexError:
                    self.allowping = "NO"

                try:
                    self.masquerading = self.if_config.getConfig(
                        "masquerading")
                except IndexError:
                    self.masquerading = "NO"

                try:
                    self.portforwarding = self.if_config.getConfig(
                        "portforwarding")
                except IndexError:
                    self.portforwarding = "NO"

                try:
                    self.tproxy = self.if_config.getConfig("transparent_proxy")
                except IndexError:
                    self.tproxy = "NO"

                # end parse the config file

                self.antispoofing = str(self.antispoofing).upper()
                self.proxyarp = str(self.proxyarp).upper()
                self.srouting = str(self.srouting).upper()
                self.icmprdrs = str(self.icmprdrs).upper()
                self.sicmprdrs = str(self.sicmprdrs).upper()
                self.martians = str(self.martians).upper()
                self.bootprelay = str(self.bootprelay).upper()
                self.logging = str(self.logging).upper()
                self.allowping = str(self.allowping).upper()
                self.masquerading = str(self.masquerading).upper()
                self.portforwarding = str(self.portforwarding).upper()
                self.tproxy = str(self.tproxy).upper()

                # interface specific protections

                if self.proxyarp == "YES":
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + ' 1 > ' + self.ipv4conf_path +
                        self.protectedif + '/' + self.proxyarp_file,
                        self.dryrun)
                    log.info("proxy arp activated for " + self.protectedif)
                else:
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + ' 0 > ' + self.ipv4conf_path +
                        self.protectedif + '/' + self.proxyarp_file,
                        self.dryrun)
                    log.info("proxy arp deactivated for " + self.protectedif)

                if self.srouting == "YES":
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + ' 1 > ' + self.ipv4conf_path +
                        self.protectedif + '/' + self.srouting_file,
                        self.dryrun)
                    log.info("allow source routing activated for " +
                             self.protectedif)
                else:
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + ' 0 > ' + self.ipv4conf_path +
                        self.protectedif + '/' + self.srouting_file,
                        self.dryrun)
                    log.info("allow source routing deactivated for " +
                             self.protectedif)

                if self.icmprdrs == "YES":
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + ' 1 > ' + self.ipv4conf_path +
                        self.protectedif + '/' + self.icmpredirects_file,
                        self.dryrun)
                    log.info("icmp redirects activated for " +
                             self.protectedif)
                else:
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + ' 0 > ' + self.ipv4conf_path +
                        self.protectedif + '/' + self.icmpredirects_file,
                        self.dryrun)
                    log.info("icmp redirects deactivated for " +
                             self.protectedif)

                if self.sicmprdrs == "YES":
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + ' 1 > ' + self.ipv4conf_path +
                        self.protectedif + '/' + self.secureicmpredirects_file,
                        self.dryrun)
                    log.info("secure icmp redirects activated for " +
                             self.protectedif)
                else:
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + ' 0 > ' + self.ipv4conf_path +
                        self.protectedif + '/' + self.secureicmpredirects_file,
                        self.dryrun)
                    log.info("secure icmp redirects deactivated for " +
                             self.protectedif)

                if self.martians == "YES":
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + ' 1 > ' + self.ipv4conf_path +
                        self.protectedif + '/' + self.martians_file,
                        self.dryrun)
                    log.info("martians logging activated for " +
                             self.protectedif)
                else:
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + ' 0 > ' + self.ipv4conf_path +
                        self.protectedif + '/' + self.martians_file,
                        self.dryrun)
                    log.info("martians logging deactivated for " +
                             self.protectedif)

                if self.bootprelay == "YES":
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + ' 1 > ' + self.ipv4conf_path +
                        self.protectedif + '/' + self.bootprelay_file,
                        self.dryrun)
                    log.info("dropping packets from 0/8 activated for " +
                             self.protectedif)
                else:
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + ' 0 > ' + self.ipv4conf_path +
                        self.protectedif + '/' + self.bootprelay_file,
                        self.dryrun)
                    log.info("dropping packets from 0/8 deactivated for " +
                             self.protectedif)

                if self.antispoofing == "YES":
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + ' 1 > ' + self.ipv4conf_path +
                        self.protectedif + '/' + self.antispoofing_file,
                        self.dryrun)
                    log.info("anti spoofing activated for " + self.protectedif)
                else:
                    stdOut, stdErr = self.executioner.run(
                        self.echocmd + ' 0 > ' + self.ipv4conf_path +
                        self.protectedif + '/' + self.antispoofing_file,
                        self.dryrun)
                    log.info("anti spoofing deactivated for " +
                             self.protectedif)

            self.if_config = abyleparse(self.fwconfigpath, self.protectedif,
                                        self.rulesfile, self.ipt_xmlconfig,
                                        self.excludedInterfaces, self.verbose)
            self.rules = self.if_config.getRules()
            log_rules = logger("firewall-rule")

            for rule in self.rules:
                time.sleep(self.naptime / 1000.0)
                log_rules.info(self.protectedif + " " + rule)
                stdOut, stdErr = self.executioner.run(
                    self.iptablesbin + ' ' + rule, self.dryrun)

            if self.excludedInterfaces.count(self.protectedif) == 0:
                if self.portforwarding == "YES":
                    self.portforwarding = self.if_config.getPortforwarding()
                    for portfwd in self.portforwarding:
                        log.info(self.protectedif + " " + portfwd)
                        stdOut, stdErr = self.executioner.run(
                            self.iptablesbin + ' ' + portfwd, self.dryrun)
                else:
                    log.info(self.protectedif + " " +
                             "PORTFORWARDING DISABLED")

                if self.tproxy == "YES":
                    self.tproxy = self.if_config.getTproxy()
                    for transproxy in self.tproxy:
                        log.info(self.protectedif + " " + transproxy)
                        stdOut, stdErr = self.executioner.run(
                            self.iptablesbin + ' ' + transproxy, self.dryrun)
                else:
                    log.info(self.protectedif + " " +
                             "TRANSPARENT PROXY DISABLED")

                if self.logging == "YES":
                    self.logging = self.if_config.getLogging()
                    for log in self.logging:
                        log.info(self.protectedif + " " + log)
                        stdOut, stdErr = self.executioner.run(
                            self.iptablesbin + ' ' + log, self.dryrun)
                else:
                    log.info(self.protectedif + " " + "LOGGING DISABLED")

                if self.allowping == "YES":
                    self.allowping = self.if_config.getAllowPing()
                    for ap in self.allowping:
                        log.info(self.protectedif + " " + ap)
                        stdOut, stdErr = self.executioner.run(
                            self.iptablesbin + ' ' + ap, self.dryrun)
                else:
                    log.info(self.protectedif + " " + "ALLOWPING DISABLED")

                if self.masquerading == "YES":
                    self.masquerading = self.if_config.getMasquerading()
                    for mg in self.masquerading:
                        log.info(self.protectedif + " " + mg)
                        stdOut, stdErr = self.executioner.run(
                            self.iptablesbin + ' ' + mg, self.dryrun)
                else:
                    log.info(self.protectedif + " " + "MASQUERADING DISABLED")

        else:
            log.error("no directory found for interface " + self.protectedif +
                      " in " + self.fwconfigpath + "interfaces/")
示例#19
0
    def getAbstractXmlRules(self, xpathToMainNode):
        self.methodname="getAbstractXmlRules(self,"+xpathToMainNode+")"

        log = logger("xml_parser")

        if self.verbose:
           log.debug("launched "+self.methodname+" of "+self.classname+".")

        # xpathToMainNode example for access rules: "/interface/rules/traffic"

        self.abstractRulesArray = []
        self.iptflags_indecies = []

        if self.allowping == "yes":
            self.rules_config = etree.parse(self.fwconfigpath+self.rulesfile)

        if xpathToMainNode.find("masquerading") > 0:
            self.rules_config = etree.parse(self.fwconfigpath+'interfaces/'+self.pinterface+'/'+self.rulesfile)

        # parse the iptables flags config file, getIpTablesFlags returns:
        # -  a dict of iptablesflags e.g.: 11 -> destination or 12 -> destination-port
        # -  a sorted array of all available index numbers e.g: 1,2,3,...,12
        # -  the iptables cli switch for the interface argument: e.g: -i
        # -  special flag iptables cli switch for portforwarding destination
        # -  transparent proxy to-port flag
        # -  masquerading interface flag (outside instead of inside)
        # -  subflag dictionary
        self.iptflags_dict, interface, portfwdDestFlag, transproxyToPortFlag, outsideInterfaceFlag, subflags_dict, subflags_cliswitch_dict = self.getIpTablesFlags()

        # extract keys (index numbers) in an array and sort it
        #self.iptflags_indecies = list(self.iptflags_dict.keys())
        for tempIndex in list(self.iptflags_dict.keys()):
               self.iptflags_indecies.append(int(tempIndex))
        self.iptflags_indecies.sort()

        if self.verbose:
           log.debug(self.methodname+" - self.iptflags_indecies (sorted) "+str(self.iptflags_indecies)+".")

        if xpathToMainNode.find("head") > 0:
            blockchain = self.rules_config.xpath("/interface/blockruleshead/@blockchain")
            blockchain = blockchain[0]
            blockchain_create_string = " -N "+blockchain
            self.abstractRulesArray.append(blockchain_create_string)

        if xpathToMainNode.find("masquerading") > 0:
            self.interfacestr = outsideInterfaceFlag+' '+self.pinterface+' '
        else:
            # set the interface string to e.g.: -i eth0
            self.interfacestr = interface+' '+self.pinterface+' '

        # get list of rules e.g. all traffic nodes or all portforwarding nodes
        abstractNodes = self.rules_config.xpath(xpathToMainNode)


        if self.verbose:
           log.debug(self.methodname+" - abstractNodes "+str(abstractNodes)+".")

        cnt=0
        for node in abstractNodes:
            # get list of all attributes of an rule node
            #abstractAttributeNodes = abstractNodes[cnt].xpath("./@*")
            abstractAttributeNodes = abstractNodes[cnt].keys()
            if self.verbose:
                log.debug(self.methodname+" - "+str(node.tag)+" abstractNode AttributeNames "+str(abstractNodes[cnt].keys())+".")
#                log.debug(self.methodname+" - "+str(node.tag)+" attributes "+str(abstractAttributeNodes)+".")
            self.attributestr = ""
            tempDestIpStr = ""
            tempDestPortStr = ""
            tempForwardPortStr = ""




            # loop through iptables flags index number list to build the right order
            for indexNumber in self.iptflags_indecies:

                # get the value of a flag out if the iptables flag dict, e.g.: indexNumber=12 then flag_value = destination
                flag_value = self.iptflags_dict[str(indexNumber)][0].text

                # loop through all found attribute nodes
                for attribute in abstractAttributeNodes:

                    # test if the attribute name is equal to the string in flag value
                    if attribute == flag_value:

                        try:
                            # parse the file with xpath and get the attributenode cli_switch under cfgname which has the searched indexNumber
                            flag_cli_arg_node = self.iptflags_config.xpath("/flags/flag[@index="+str(indexNumber)+"]/cfgname/@cli_switch")

                            #print (flag_cli_arg_node)
                            # extract the value if the attribute node [0] = assuming that the index is unique
                            flag_cli_arg = flag_cli_arg_node[0]


                            # check and build the attribute string with flagCheck()
                            attributeTmpstr = self.flagCheck(str(abstractNodes[cnt].get(attribute)),flag_cli_arg, indexNumber, self.iptflags_config)



                        except (KeyError):
                            log.error(sys.exc_info()[1])
                            sys.exit(1)

			

                        if xpathToMainNode.find("portforwarding") > 0 and attribute == "destination" :
                            tempDestIpStr = abstractNodes[cnt].get(attribute)

                        elif xpathToMainNode.find("portforwarding") > 0 and attribute == "destination-port":
                            tempDestPortStr = abstractNodes[cnt].get(attribute)

                        elif xpathToMainNode.find("portforwarding") > 0 and attribute == "forward-port":
                            tempForwardPortStr = abstractNodes[cnt].get(attribute)

                        elif xpathToMainNode.find("transparentproxy") > 0 and attribute == "destination":
                            tempDestIpStr = abstractNodes[cnt].get(attribute)

                        elif xpathToMainNode.find("transparentproxy") > 0 and attribute == "destination-port":
                            tempDestPortStr = abstractNodes[cnt].get(attribute)

                        else:
                            # append the temp string to the self.attributestr
                            self.attributestr = self.attributestr+attributeTmpstr

                        hasSubflags = "no"
                        for key in subflags_dict.keys():
                            if str(key) == str(indexNumber):
                                hasSubflags = "yes"

                        if hasSubflags == "yes":
                            subattributeTmpstr = ""
                            tempSubflagsArray = subflags_dict[indexNumber].split(';')
                            tempSubflagsCliswitchArray = subflags_cliswitch_dict[indexNumber].split(';')

                            subflagcnt = 0
                            for subflag_value in tempSubflagsArray:

                                for attribute in abstractAttributeNodes:

                                    if attribute.name == subflag_value:

                                        subattributeTmpstr = self.flagCheck(attribute.value,tempSubflagsCliswitchArray[subflagcnt], indexNumber, self.iptflags_config)
                                        self.attributestr = self.attributestr+subattributeTmpstr

                                subflagcnt = subflagcnt + 1


            cnt = cnt + 1

            self.attributestrForward = ""

            if xpathToMainNode.find("portforwarding") > 0:

                # append interface string to the attribute string

                # build the iptablescommand for the PREROUTING chain of the nat table and the FORWARD chain
                if not self.pinterface == "default":
                    self.attributestr = self.interfacestr+self.attributestr


                self.attributestrForward = self.attributestr
                self.attributestrForward = re.sub("PREROUTING","FORWARD",self.attributestrForward)
                self.attributestrForward = re.sub("DNAT","ACCEPT",self.attributestrForward)
                self.attributestrForward = re.sub("-t nat","",self.attributestrForward)
                self.attributestrForward = re.sub("--dport \d{1,5}","",self.attributestrForward)
                self.attributestrForward = re.sub(r"--destination \b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b","",self.attributestrForward)
                self.attributestrForward = self.attributestrForward+" --destination-port "+tempDestPortStr+" --destination "+tempDestIpStr

                self.attributestr = self.attributestr+"--dport "+tempForwardPortStr+" "+portfwdDestFlag+' '+tempDestIpStr+":"+tempDestPortStr



            elif xpathToMainNode.find("transparentproxy") > 0:
                self.attributestr = self.interfacestr+self.attributestr+transproxyToPortFlag+' '+tempDestPortStr

            else:
                if not self.pinterface == "default":
                    self.attributestr = self.interfacestr+self.attributestr

            # append the string to the rules array
            self.abstractRulesArray.append(self.attributestr)

            if not self.attributestrForward == "":
                self.abstractRulesArray.append(self.attributestrForward)




        return self.abstractRulesArray
示例#20
0
import re
import os
import string
import time
import datetime
import sys
from abyle_xmlparser import abyleparse
from abyle_execute import abyle_execute
from abyle_config_xmlparser import abyle_config_parse
from xml.sax.handler import ContentHandler
from xml.sax import make_parser
from abyle_log import logger

control = logger("abyle-control")


class abyle_firewall:
    def __init__(
        self, dryrun, iptablesbin, fwconfigpath, rulesfile, ipt_xmlconfig, xmlconfig, echocmd, logfile, verbose
    ):
        self.naptime = 10  # milliseconds
        self.dryrun = dryrun
        self.iptablesbin = iptablesbin
        self.fwconfigpath = fwconfigpath
        self.rulesfile = rulesfile
        self.ipt_xmlconfig = ipt_xmlconfig
        self.xmlconfig = xmlconfig
        self.logfile = logfile
        self.verbose = verbose

        self.executioner = abyle_execute()
示例#21
0
    def __init__(
        self, dryrun, iptablesbin, fwconfigpath, rulesfile, ipt_xmlconfig, xmlconfig, echocmd, logfile, verbose
    ):
        self.naptime = 10  # milliseconds
        self.dryrun = dryrun
        self.iptablesbin = iptablesbin
        self.fwconfigpath = fwconfigpath
        self.rulesfile = rulesfile
        self.ipt_xmlconfig = ipt_xmlconfig
        self.xmlconfig = xmlconfig
        self.logfile = logfile
        self.verbose = verbose

        self.executioner = abyle_execute()

        self.echocmd = echocmd

        global_config = abyle_config_parse(fwconfigpath, "default", xmlconfig, self.verbose)

        self.excludedInterfaces = global_config.getConfig("excluded_interfaces")

        try:
            self.tcpabort_file = global_config.getConfig("tcpabortfile")
        except IndexError:
            self.tcpabort_file = "/proc/sys/net/ipv4/tcpicmpbcastfile_abort_on_overflow"

        try:
            self.icmpbcastreply_file = global_config.getConfig("icmpbcastfile")
        except IndexError:
            self.icmpbcastreply_file = "/proc/sys/net/ipv4/icmp_echo_ignore_broadcasts"

        try:
            self.dynaddresshack_file = global_config.getConfig("dynaddresshackfile")
        except IndexError:
            self.dynaddresshack_file = "/proc/sys/net/ipv4/ip_dynaddr"

        try:
            self.ipv4conf_path = global_config.getConfig("ipv4confpath")
        except IndexError:
            self.ipv4conf_path = "/proc/sys/net/ipv4/conf/"

        try:
            self.antispoofing_file = global_config.getConfig("antispoofingfile")
        except IndexError:
            self.antispoofing_file = "rp_filter"

        try:
            self.syncookiefile = global_config.getConfig("syncookiefile")
        except IndexError:
            self.syncookiefile = "/proc/sys/net/ipv4/tcp_syncookies"

        try:
            self.ipv4forwardfile = global_config.getConfig("ipv4forwardfile")
        except IndexError:
            self.ipv4forwardfile = "/proc/sys/net/ipv4/ip_forward"

        try:
            self.syncookie = str(global_config.getConfig("syncookie")).upper()
        except IndexError:
            self.syncookie = "YES"

        try:
            self.ipv4forward = str(global_config.getConfig("ipv4forward")).upper()
        except IndexError:
            self.syncookie = "NO"

        try:
            self.tcpabort = str(global_config.getConfig("aborttcp")).upper()
        except IndexError:
            self.tcpabort = "NO"

        try:
            self.icmpbcastreply = str(global_config.getConfig("answericmpbroadcast")).upper()
        except IndexError:
            self.icmpbcastreply = "NO"

        try:
            self.dynaddresshack = str(global_config.getConfig("dynaddresshack")).upper()
        except IndexError:
            self.dynaddresshack = "NO"

        try:
            self.proxyarp_file = global_config.getConfig("proxyarpfile")
        except IndexError:
            self.proxyarp_file = "proxy_arp"

        try:
            self.srouting_file = global_config.getConfig("sroutingfile")
        except IndexError:
            self.srouting_file = "accept_source_route"

        try:
            self.icmpredirects_file = global_config.getConfig("icmprdrsfile")
        except IndexError:
            self.icmpredirects_file = "accept_redirects"

        try:
            self.secureicmpredirects_file = global_config.getConfig("icmpsecurerdrsfile")
        except IndexError:
            self.secureicmpredirects_file = "secure_redirects"

        try:
            self.martians_file = global_config.getConfig("martiansfile")
        except IndexError:
            self.martians_file = "log_martians"

        try:
            self.bootprelay_file = global_config.getConfig("bootprelayfile")
        except IndexError:
            self.bootprelay_file = "bootp_relay"

        log = logger("firewall")

        if not self.tcpabort == "NO":
            stdOut, stdErr = self.executioner.run(self.echocmd + " 1 > " + self.tcpabort_file, self.dryrun)
            log.info("ipv4 send TCP-RST on full buffer is activated")
        else:
            stdOut, stdErr = self.executioner.run(self.echocmd + " 0 > " + self.tcpabort_file, self.dryrun)
            log.info("ipv4 send TCP-RST on full buffer is deactivated")

        if not self.icmpbcastreply == "NO":
            stdOut, stdErr = self.executioner.run(self.echocmd + " 1 > " + self.icmpbcastreply_file, self.dryrun)
            log.info("ipv4 reply to ICMP Broadcasts is deactivated")
        else:
            stdOut, stdErr = self.executioner.run(self.echocmd + " 0 > " + self.icmpbcastreply_file, self.dryrun)
            log.info("ipv4 reply to ICMP Broadcasts is activated")

        if not self.dynaddresshack == "NO":
            stdOut, stdErr = self.executioner.run(self.echocmd + " 1 > " + self.dynaddresshack_file, self.dryrun)
            log.info("ipv4 dynamic address hack activated")
        else:
            stdOut, stdErr = self.executioner.run(self.echocmd + " 0 > " + self.dynaddresshack_file, self.dryrun)
            log.info("ipv4 dynamic address hack deactivated")

        if not self.ipv4forward == "NO":
            stdOut, stdErr = self.executioner.run(self.echocmd + " 1 > " + self.ipv4forwardfile, self.dryrun)
            log.info("ipv4 forwarding activated")
        else:
            stdOut, stdErr = self.executioner.run(self.echocmd + " 0 > " + self.ipv4forwardfile, self.dryrun)
            log.info("ipv4 forwarding deactivated")

        if not self.syncookie == "NO":
            stdOut, stdErr = self.executioner.run(self.echocmd + " 1 > " + self.syncookiefile, self.dryrun)
            log.info("syncookie activated")
        else:
            stdOut, stdErr = self.executioner.run(self.echocmd + " 0 > " + self.syncookiefile, self.dryrun)
            log.info("syncookie deactivated")

        self.default_config = abyleparse(
            self.fwconfigpath, "default", self.rulesfile, self.ipt_xmlconfig, self.excludedInterfaces, self.verbose
        )
        self.defaultrules = self.default_config.getDefaultRules("head")

        for drule in self.defaultrules:
            log.info("default-rule: " + drule)
            stdOut, stdErr = self.executioner.run(self.iptablesbin + " " + drule, self.dryrun)
#from xml.dom.minidom import *
import re
import sys
#from xml.dom.minidom import Node
from abyle_output import abyle_output
from abyle_log import logger

log = logger("xml_parser")
try:
    from lxml import etree
except (ImportError):
    log.error("xml parser import error, please install python lxml package")
    sys.exit(1)


class abyleparse:
    def __init__(self, fwconfigpath, interface, rulesfile, ipt_xmlconfig,
                 excludedInterfaces, verbose):
        self.classname = "abyleparse"
        self.verbose = verbose
        self.fwconfigpath = fwconfigpath
        self.pinterface = interface
        self.rulesfile = rulesfile
        self.iptflagsfile = ipt_xmlconfig
        self.rulesarray = []
        self.iptflags_dict = {}
        self.excludedInterfaces = excludedInterfaces
        self.allowping = ""
        log = logger("xml_parser")

        if self.verbose:
import sys
from abyle_output import abyle_output
from xml.dom.minidom import *
import codecs
from abyle_log import logger

log = logger("abyle_config_xmlwriter")

try:
    from lxml import etree
except (ImportError):
    log.error("xml config parser import error, please install python xpath modules")
    sys.exit(1)

class abyle_config_write:
    def __init__(self, fwconfigpath, interface, xmlconfig):
        self.fwconfigpath = fwconfigpath
        self.pinterface = interface
        self.xmlconfig = xmlconfig
        self.xmlfile = ""
        self.buildednode = ""


        try:
            if self.pinterface == "default":
                self.abyle_config = xml.dom.minidom.parse(self.fwconfigpath+self.xmlconfig)
                self.xmlfile = self.fwconfigpath+self.xmlconfig
            else:
                self.abyle_config = xml.dom.minidom.parse(self.fwconfigpath+'interfaces/'+self.pinterface+'/'+self.xmlconfig)
                self.xmlfile = self.fwconfigpath+'interfaces/'+self.pinterface+'/'+self.xmlconfig
        except (IOError):