def main(options):

    log.info("firewallconfigdecryptor %s" % FCD_VERSION)

    if options.debug:  #or settings['General']['debug']:
        # TODO: fix this
        import logging
        logger = logging.getLogger("FCD")
        logger.setLevel(logging.DEBUG)

    #else:
    #    log.info("No input file specified. Exiting")
    #    raise SystemExit

    try:
        parse_input(options)
        #, timestamp,build_options=build_options, grid=options.grid)
    except ParserException, e:
        log.error("Unable to parse device configurations", exc_info=True)
        sys.exit()
def main(options):

    log.info("firewallconfigdecryptor %s" % FCD_VERSION)

    if options.debug: #or settings['General']['debug']:
        # TODO: fix this
        import logging
        logger = logging.getLogger("FCD")
        logger.setLevel(logging.DEBUG)

    #else:
    #    log.info("No input file specified. Exiting")
    #    raise SystemExit

    try:
        parse_input(options)
            #, timestamp,build_options=build_options, grid=options.grid)
    except ParserException,e:
        log.error("Unable to parse device configurations", exc_info=True)
        sys.exit()
def parse_input(options):
    """ validate and parse input high-level description file"""
    if options.config:
        log.info("Parsing device configuration files located in : %s" %
                 (options.config))
        InputParser().ParseDeviceConfigurations(options.config)
    def ProcessStaticRoutes(self,firewalls, all_zones, file_contents):
        interface_gateways = dict()
        self.potential_route_errors = []
        self.unallocated_gateways =[]
        # Extract any gateways from static routes
        for host in file_contents:
            for line in file_contents[host]:
                # TODO: check ^route (space) still works with asa
                p = re.search('^route ',line)
                q = re.search('^ip route ', line)
                if p:
                    interface_name= line.split(' ')[1]
                    network= ipaddr.IPv4Network("%s/%s" % (line.split(' ')[2],line.split(' ')[3]))
                    gateway_ip=ipaddr.IPv4Address(line.split(' ')[4])
                    # Pragmatic choice of network directly connected to gateway (we don't have real gateway configs to verify)
                    gateway = Gateway(gateway_ip, [network])
                    if not interface_gateways.has_key(gateway.ipaddress):
                       interface_gateways[gateway.ipaddress] = gateway

                    else:
                        # Multiple routes for same gateway
                        #..check non-redundant route
                        is_redundant=False
                        for existing_network in interface_gateways[gateway.ipaddress].network_addresses:
                            if (existing_network == ipaddr.IPv4Network('0.0.0.0/0.0.0.0') or
                                existing_network.__contains__(network)):
                                self.potential_route_errors = []
                                if (not self.potential_route_errors.__contains__(line)):
                                    self.potential_route_errors.append(line)
                                is_redundant= True
                                break
                        if not is_redundant:
                            interface_gateways[gateway.ipaddress].network_addresses.append(network) #add

                if q:
                    line=line.replace('ip route','')
                    network= ipaddr.IPv4Network("%s/%s" % (line.split(' ')[1],line.split(' ')[2]))
                    gateway_ip=ipaddr.IPv4Address(line.split(' ')[3])
                    # Pragmatic choice of network directly connected to gateway (we don't have real gateway configs to veify)
                    gateway = Gateway(gateway_ip, [network])
                    if not interface_gateways.has_key(gateway.ipaddress):
                       interface_gateways[gateway.ipaddress] = gateway

                    else:
                        # Multiple routes for same gateway
                        #..check non-redundant route
                        is_redundant=False
                        for existing_network in interface_gateways[gateway.ipaddress].network_addresses:
                            if (existing_network == ipaddr.IPv4Network('0.0.0.0/0.0.0.0') or
                                existing_network.__contains__(network)):
                                self.potential_route_errors = []
                                if (not self.potential_route_errors.__contains__(line)):
                                    self.potential_route_errors.append(line)
                                is_redundant= True
                                break
                        if not is_redundant:
                            interface_gateways[gateway.ipaddress].network_addresses.append(network) #append

            fw_zones=[]
            # Find the firewall zones
            for interfaces in all_zones.values():
                if interfaces.has_key('management_data_interface'):
                    fw_zones.append(interfaces['management_data_interface'])

            log.info("Linking Gateways to Zones..")
            # Link each gateway found to appropriate zone
            count=1
            for gateway in interface_gateways.values():
                existing_gateway=False
                for fw_zone in fw_zones:
                    if fw_zone.ipaddress_list.__contains__(gateway.ipaddress):
                        # Gateway is an existing firewall/router..no need to create new
                        existing_gateway=True
                        break
                if existing_gateway: continue

                gateway_allocated=False
                for interfaces in all_zones.values():
                    if gateway_allocated: break
                    for zone in interfaces.values():
                        if gateway_allocated: break
                        if zone.ContainsSubnetOrIpaddress(gateway.ipaddress):
                            # gateway can potentially have ACLs and behave as a firewall
                            #..so until we know more about it, treat it as a firewall and keep separate
                            zone.AddGateway(gateway)
                            gateway_allocated=True

                            gateway_name="gw %s"%gateway.ipaddress
                            if not all_zones.has_key(gateway_name):
                                all_zones[gateway_name]=dict()
                            # Gateway connected to respective zone via E0/0
                            all_zones[gateway_name]["Ethernet0/0"]= zone
                            # Firewall-Zone connected to gateway via mdi
                            all_zones[gateway_name]["management_data_interface"]=SecurityZone("fwz(%s)"%gateway_name,[ipaddr.IPv4Network("%s/%s"%(gateway.ipaddress,32))],gateway_name)
                            # Networks (i.e. Unknown-Zones) connected to gateway via E0/1
                            unknown_zone_id="UZ%s"%count
                            all_zones[gateway_name]["Ethernet0/1"]=SecurityZone(unknown_zone_id,gateway.network_addresses,gateway_name)
                            count+=1

                            # Update firewalls list
                            if not firewalls.has_key(gateway_name):
                               firewalls[gateway_name]= Firewall(gateway_name)
                            firewalls[gateway_name].interfaces["Ethernet0/0"]=FirewallInterface("Ethernet0/0","Ethernet0/0","gw_%s"%zone.zone_id,zone.ipaddress_list)
                            firewalls[gateway_name].interfaces["Ethernet0/1"]=FirewallInterface("Ethernet0/1","Ethernet0/1","gw_%s"%unknown_zone_id,gateway.network_addresses)
                            firewalls[gateway_name].interfaces["management_data_interface"]=FirewallInterface("management_data_interface","management_data_interface","management_data_interface",ipaddr.IPv4Network("%s/%s"%(gateway.ipaddress,32)))

                            replace_ip=None
                            excluded=None
                            for ip in zone.ipaddress_list:
                                if ip.__contains__(gateway.ipaddress):
                                    excluded=ip.address_exclude(ipaddr.IPv4Network("%s/32"%gateway.ipaddress))
                                    replace_ip=ip
                                    break
                            if replace_ip!=None: zone.ipaddress_list.remove(replace_ip)
                            for ip in excluded:
                                zone.ipaddress_list.append(ip)

                if (not gateway_allocated) and (not self.unallocated_gateways.__contains__(gateway.ipaddress)):
                    self.unallocated_gateways.append(gateway.ipaddress)
def parse_input(options):
    """ validate and parse input high-level description file"""
    if options.config:
       log.info("Parsing device configuration files located in : %s"%(options.config))
       InputParser().ParseDeviceConfigurations(options.config)