Example #1
0
 def cache_rulebase(self):
     """
     Method to cache a handle to the rulebase 
     """
     rulebase = policies.Rulebase()
     self.fw_hndl.add(rulebase)
     print policies.SecurityRule.refreshall(rulebase)
     self.rulebase = rulebase
Example #2
0
def get_rulebase(device):
    # Build the rulebase

    rulebase = policies.Rulebase()
    device.add(rulebase)

    policies.SecurityRule.refreshall(rulebase)
    return rulebase
Example #3
0
def check_security_rules(device):
    output = device.op("show system info")

    print("System info: {}".format(output))

    rulebase = policies.Rulebase()
    device.add(rulebase)
    current_security_rules = policies.SecurityRule.refreshall(rulebase)

    print('Current security rules: {}'.format(len(current_security_rules)))
    for rule in current_security_rules:
        print('- {}'.format(rule.name))
def get_rulebase(device, devicegroup):
    # Build the rulebase
    if isinstance(device, firewall.Firewall):
        rulebase = policies.Rulebase()
        device.add(rulebase)
    elif isinstance(device, panorama.Panorama):
        dg = panorama.DeviceGroup(devicegroup)
        device.add(dg)
        rulebase = policies.PreRulebase()
        dg.add(rulebase)
    else:
        return False
    policies.SecurityRule.refreshall(rulebase)
    return rulebase
Example #5
0
def main():
    argument_spec = dict(
        ip_address=dict(required=True),
        password=dict(no_log=True),
        username=dict(default='admin'),
        api_key=dict(no_log=True),
        vsys_id=dict(default='vsys1'),
        rule_type=dict(required=True, choices=['security', 'nat']),
        source_zone=dict(default=None),
        source_ip=dict(default=None),
        source_user=dict(default=None),
        source_port=dict(default=None, type=int),
        to_interface=dict(default=None),
        destination_zone=dict(default=None),
        category=dict(default=None),
        application=dict(default=None),
        protocol=dict(default=None, type=int),
        destination_ip=dict(default=None),
        destination_port=dict(default=None, type=int)
    )
    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False,
                           required_one_of=[['api_key', 'password']])
    if not HAS_LIB:
        module.fail_json(msg='Missing required libraries.')

    ip_address = module.params["ip_address"]
    password = module.params["password"]
    username = module.params['username']
    api_key = module.params['api_key']
    vsys_id = module.params['vsys_id']
    rule_type = module.params['rule_type']
    source_zone = module.params['source_zone']
    source_ip = module.params['source_ip']
    source_user = module.params['source_user']
    source_port = module.params['source_port']
    to_interface = module.params['to_interface']
    destination_zone = module.params['destination_zone']
    destination_ip = module.params['destination_ip']
    destination_port = module.params['destination_port']
    category = module.params['category']
    application = module.params['application']
    protocol = module.params['protocol']

    # Create the device with the appropriate pandevice type
    device = base.PanDevice.create_from_device(ip_address, username, password, api_key=api_key)

    # Fail the module if this is a Panorama instance
    if isinstance(device, panorama.Panorama):
        module.fail_json(
            failed=1,
            msg='Panorama is not supported.'
        )

    # Create and attach security and NAT rulebases. Then populate them.
    sec_rule_base = nat_rule_base = policies.Rulebase()
    device.add(sec_rule_base)
    device.add(nat_rule_base)
    policies.SecurityRule.refreshall(sec_rule_base)
    policies.NatRule.refreshall(nat_rule_base)

    # Which action shall we take on the object?
    if rule_type == 'security':
        # Search for the object
        test_string = create_security_test(
            source_ip=source_ip,
            source_user=source_user,
            destination_ip=destination_ip,
            destination_port=destination_port,
            application=application,
            protocol=protocol,
            category=category
        )
    elif rule_type == 'nat':
        test_string = create_nat_test(
            source_zone=source_zone,
            source_ip=source_ip,
            source_port=source_port,
            to_interface=to_interface,
            destination_zone=destination_zone,
            destination_ip=destination_ip,
            destination_port=destination_port,
            protocol=protocol
        )

    # Submit the op command with the appropriate test string
    try:
        response = device.op(cmd=test_string, vsys=vsys_id)
    except PanXapiError:
        exc = get_exception()
        module.fail_json(msg=exc.message)

    if response.find('result/rules').__len__() == 1:
        rule_name = response.find('result/rules/entry').text.split(';')[0]
    elif rule_type == 'nat':
        module.exit_json(msg='No matching NAT rule.')
    else:
        module.fail_json(msg='Rule match failed. Please check playbook syntax.')

    if rule_type == 'security':
        rule_match = sec_rule_base.find(rule_name, policies.SecurityRule)
    elif rule_type == 'nat':
        rule_match = nat_rule_base.find(rule_name, policies.NatRule)

    # Print out the rule
    module.exit_json(
        stdout_lines=json.dumps(xmltodict.parse(rule_match.element_str()), indent=2),
        msg='Rule matched'
    )
def main():
    argument_spec = dict(
        ip_address=dict(required=True),
        password=dict(no_log=True),
        username=dict(default='admin'),
        api_key=dict(no_log=True),
        application=dict(default=None),
        source_zone=dict(default=None),
        destination_zone=dict(default=None),
        source_ip=dict(default=None),
        destination_ip=dict(default=None),
        source_port=dict(default=None),
        destination_port=dict(default=None),
        protocol=dict(default=None, choices=['tcp', 'udp']),
        tag_name=dict(default=None),
        devicegroup=dict(default=None)
    )
    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False,
                           required_one_of=[['api_key', 'password']]
                           )
    if not HAS_LIB:
        module.fail_json(msg='Missing required libraries.')

    ip_address = module.params["ip_address"]
    password = module.params["password"]
    username = module.params['username']
    api_key = module.params['api_key']
    application = module.params['application']
    source_zone = module.params['source_zone']
    source_ip = module.params['source_ip']
    source_port = module.params['source_port']
    destination_zone = module.params['destination_zone']
    destination_ip = module.params['destination_ip']
    destination_port = module.params['destination_port']
    protocol = module.params['protocol']
    tag_name = module.params['tag_name']
    devicegroup = module.params['devicegroup']

    # Create the device with the appropriate pandevice type
    device = base.PanDevice.create_from_device(ip_address, username, password, api_key=api_key)

    # Grab the global objects
    objects.AddressObject.refreshall(device)
    objects.AddressGroup.refreshall(device)
    objects.ServiceObject.refreshall(device)
    objects.ServiceGroup.refreshall(device)
    objects.Tag.refreshall(device)

    # If Panorama, validate the devicegroup and grab the devicegroup objects
    dev_group = None
    if devicegroup and isinstance(device, panorama.Panorama):
        dev_group = get_devicegroup(device, devicegroup)
        if dev_group:
            device.add(dev_group)
            objects.AddressObject.refreshall(dev_group)
            objects.AddressGroup.refreshall(dev_group)
            objects.ServiceObject.refreshall(dev_group)
            objects.ServiceGroup.refreshall(dev_group)
            objects.Tag.refreshall(dev_group)
        else:
            module.fail_json(
                failed=1,
                msg='\'%s\' device group not found in Panorama. Is the name correct?' % devicegroup
            )

    # Build the rulebase and produce list
    rulebase = get_rulebase(device, dev_group)
    rulelist = rulebase.children
    hitbase = policies.Rulebase()
    loose_match = True

    # Process each rule
    for rule in rulelist:
        hitlist = []

        if source_zone:
            source_zone_match = False
            if loose_match and 'any' in rule.fromzone:
                source_zone_match = True
            else:
                for object_string in rule.fromzone:
                    if object_string == source_zone:
                        source_zone_match = True
            hitlist.append(source_zone_match)

        if destination_zone:
            destination_zone_match = False
            if loose_match and 'any' in rule.tozone:
                destination_zone_match = True
            else:
                for object_string in rule.tozone:
                    if object_string == destination_zone:
                        destination_zone_match = True
            hitlist.append(destination_zone_match)

        if source_ip:
            source_ip_match = False
            if loose_match and 'any' in rule.source:
                source_ip_match = True
            else:
                for object_string in rule.source:
                    # Get a valid AddressObject or AddressGroup
                    obj = get_object(device, dev_group, object_string)
                    # Otherwise the object_string is not an object and should be handled differently
                    if obj is False:
                        if '-' in object_string:
                            obj = ipaddress.ip_address(source_ip)
                            source_range = object_string.split('-')
                            source_lower = ipaddress.ip_address(source_range[0])
                            source_upper = ipaddress.ip_address(source_range[1])
                            if source_lower <= obj <= source_upper:
                                source_ip_match = True
                        else:
                            if source_ip == object_string:
                                source_ip_match = True
                    if isinstance(obj, objects.AddressObject) and addr_in_obj(source_ip, obj):
                        source_ip_match = True
                    elif isinstance(obj, objects.AddressGroup) and obj.static_value:
                        for member_string in obj.static_value:
                            member = get_object(device, dev_group, member_string)
                            if addr_in_obj(source_ip, member):
                                source_ip_match = True
            hitlist.append(source_ip_match)

        if destination_ip:
            destination_ip_match = False
            if loose_match and 'any' in rule.destination:
                destination_ip_match = True
            else:
                for object_string in rule.destination:
                    # Get a valid AddressObject or AddressGroup
                    obj = get_object(device, dev_group, object_string)
                    # Otherwise the object_string is not an object and should be handled differently
                    if obj is False:
                        if '-' in object_string:
                            obj = ipaddress.ip_address(destination_ip)
                            destination_range = object_string.split('-')
                            destination_lower = ipaddress.ip_address(destination_range[0])
                            destination_upper = ipaddress.ip_address(destination_range[1])
                            if destination_lower <= obj <= destination_upper:
                                destination_ip_match = True
                        else:
                            if destination_ip == object_string:
                                destination_ip_match = True
                    if isinstance(obj, objects.AddressObject) and addr_in_obj(destination_ip, obj):
                        destination_ip_match = True
                    elif isinstance(obj, objects.AddressGroup) and obj.static_value:
                        for member_string in obj.static_value:
                            member = get_object(device, dev_group, member_string)
                            if addr_in_obj(destination_ip, member):
                                destination_ip_match = True
            hitlist.append(destination_ip_match)

        if source_port:
            source_port_match = False
            orientation = 'source'
            if loose_match and (rule.service[0] == 'any'):
                source_port_match = True
            elif rule.service[0] == 'application-default':
                source_port_match = False  # Fix this once apps are supported
            else:
                service_list = []
                service_list = get_services(device, dev_group, rule.service, service_list)
                for obj in service_list:
                    if port_in_svc(orientation, source_port, protocol, obj):
                        source_port_match = True
                        break
            hitlist.append(source_port_match)

        if destination_port:
            destination_port_match = False
            orientation = 'destination'
            if loose_match and (rule.service[0] == 'any'):
                destination_port_match = True
            elif rule.service[0] == 'application-default':
                destination_port_match = False  # Fix this once apps are supported
            else:
                service_list = []
                service_list = get_services(device, dev_group, rule.service, service_list)
                for obj in service_list:
                    if port_in_svc(orientation, destination_port, protocol, obj):
                        destination_port_match = True
                        break
            hitlist.append(destination_port_match)

        if tag_name:
            tag_match = False
            if rule.tag:
                for object_string in rule.tag:
                    obj = get_tag(device, dev_group, object_string)
                    if obj and (obj.name == tag_name):
                        tag_match = True
            hitlist.append(tag_match)

        # Add to hit rulebase
        if False not in hitlist:
            hitbase.add(rule)

    # Dump the hit rulebase
    if hitbase.children:
        output_string = xmltodict.parse(hitbase.element_str())
        module.exit_json(
            stdout_lines=json.dumps(output_string, indent=2),
            msg='%s of %s rules matched' % (hitbase.children.__len__(), rulebase.children.__len__())
        )
    else:
        module.fail_json(msg='No matching rules found.')