Example #1
0
def main():

    args = get_cli_arguments()
    setup_logging(args)

    # The Panorama object. This is the root object of the config tree.
    pano = panorama.Panorama(hostname=HOSTNAME,
                             api_key=APIKEY,
                             )

    # Add the devicegroup as a child of the Panorama
    if args.devicegroup is not None:
        scope = pano.add(panorama.DeviceGroup(args.devicegroup))
    else:
        scope = pano

    # Create a dynamic address group in the required scope
    addressgroup = scope.add(objects.AddressGroup(name=args.name,
                                                  dynamic_value=args.match,
                                                  description=args.description,
                                                  tag=args.tag,
                                                  ))
    # Push the new dynamic address group to the live Panorama device
    addressgroup.create()

    # Perform a commit if requested
    if args.commit or args.commitall:
        pano.commit(sync=True)
    if args.commitall:
        pano.commit_all(sync=True, sync_all=True, devicegroup=args.devicegroup)
def pan_addressgroup(pan_fw, address_group_name='', ip_address=None):
    """ Returns a PAN static IP address group object """
    current_ips = pan_objs.AddressObject.refreshall(pan_fw, add=False)
    ip_address_names = [
        ip.name for ip in current_ips if ip.value == ip_address
    ]
    if not ip_address_names:
        logging.warn('IP Address {} does not exist'.format(ip_address))
        return None
    ip_name = ip_address_names[0]
    current_addressgroups = pan_objs.AddressGroup.refreshall(pan_fw, add=False)
    current_addressgroup = [
        ao for ao in current_addressgroups if ao.name == address_group_name
    ]
    if not current_addressgroup:
        logging.warn(
            'PAN AddressGroup {} does not exist'.format(address_group_name))
        return None
    logger.debug('Found PAN AddressGroup {}'.format(address_group_name))
    current_addressgroup_static_values = set(
        current_addressgroup[0].static_value)
    addressgroup = pan_objs.AddressGroup(
        name=address_group_name,
        static_value=current_addressgroup_static_values.union(set([ip_name])))
    pan_fw.add(addressgroup)
    return addressgroup
Example #3
0
def create_object(**kwargs):
    if kwargs['addressobject']:
        newobject = objects.AddressObject(
            name=kwargs['addressobject'],
            value=kwargs['address'],
            type=kwargs['address_type'],
            description=kwargs['description'],
            tag=kwargs['tag_name']
        )
        if newobject.type and newobject.value:
            return newobject
        else:
            return False
    elif kwargs['addressgroup']:
        newobject = objects.AddressGroup(
            name=kwargs['addressgroup'],
            static_value=kwargs['static_value'],
            dynamic_value=kwargs['dynamic_value'],
            description=kwargs['description'],
            tag=kwargs['tag_name']
        )
        if newobject.static_value or newobject.dynamic_value:
            return newobject
        else:
            return False
    elif kwargs['serviceobject']:
        newobject = objects.ServiceObject(
            name=kwargs['serviceobject'],
            protocol=kwargs['protocol'],
            source_port=kwargs['source_port'],
            destination_port=kwargs['destination_port'],
            tag=kwargs['tag_name']
        )
        if newobject.protocol and newobject.destination_port:
            return newobject
        else:
            return False
    elif kwargs['servicegroup']:
        newobject = objects.ServiceGroup(
            name=kwargs['servicegroup'],
            value=kwargs['services'],
            tag=kwargs['tag_name']
        )
        if newobject.value:
            return newobject
        else:
            return False
    elif kwargs['tag_name']:
        newobject = objects.Tag(
            name=kwargs['tag_name'],
            color=kwargs['color'],
            comments=kwargs['description']
        )
        if newobject.name:
            return newobject
        else:
            return False
    else:
        return False
Example #4
0
 def setup_state_obj(self, dev, state):
     state.obj = objects.AddressGroup(
         testlib.random_name(),
         dynamic_value="'{0}' or '{1}'".format(
             state.tags[0].name, state.tags[1].name),
         description='This is my description',
         tag=state.tags[2].name,
     )
     dev.add(state.obj)
Example #5
0
 def create_address_group_object(**kwargs):
     """
     Create an Address object
     @return False or ```objects.AddressObject```
     """
     ad_object = objects.AddressGroup(name=kwargs['address_gp_name'],
                                      dynamic_value=kwargs['dynamic_value'],
                                      description=kwargs['description'],
                                      tag=kwargs['tag_name'])
     if ad_object.static_value or ad_object.dynamic_value:
         return ad_object
     else:
         return None
Example #6
0
def create_address_group_object(**kwargs):
    """
    Create an Address object

    :param kwargs: key word arguments to instantiate AddressGroup object
    @return False or ```objects.AddressObject```
    """
    ad_object = objects.AddressGroup(name=kwargs['address_gp_name'],
                                     static_value=kwargs['sag_match_filter'],
                                     description=kwargs['description'],
                                     tag=kwargs['tag_name'])
    if ad_object.static_value or ad_object.dynamic_value:
        return ad_object
    else:
        return None
Example #7
0
def create_group(group_name, member_list, desc):
    # Convert member names to pa objoects
    pa_members = []
    for m in member_list:
        m = re.sub(r'[^\w\.]', '_', m)
        res = fw.find(m, objects.AddressObject)
        if (res is None):
            print "Member Not Found Ignoring " + m
        else:
            pa_members.append(res)
    if not pa_members:
        print "Group Empty " + group_name
        return False
    # Add to device
    fw.add(objects.AddressGroup(group_name, pa_members, None, desc, tufin_tag)).create()
Example #8
0
 def setup_state_obj(self, dev, state):
     state.obj = objects.AddressGroup(
         testlib.random_name(), [x.name for x in state.aos[:2]],
     )
     dev.add(state.obj)
def main(req: func.HttpRequest) -> func.HttpResponse:
    """ Azure Function App Execution Loop """
    logger.info('Python HTTP trigger function processed a request.')
    if APP_CONFIG['authorization_code'] is None:
        auth_code = temp_auth_code()
        logger.info('AUTH_CODE environment variable not found.')
        logger.info(f'Setting AUTH_CODE = {auth_code}')
        environ['AUTH_CODE'] = auth_code
        return func.HttpResponse(
            body=
            f'A new authorization code generated. Please record this value; it will be available only at this time: {auth_code}',
            status_code=200)
    logger.info('AUTH_CODE environment variable found.')
    code = req.params.get('code')
    logger.info('Checking for valid auth code supplied in query string.')
    # TODO: check for code in req.header.
    if not code:
        return func.HttpResponse(
            body=
            'A valid authorization code must be supplied in the query string',
            status_code=401)
    elif code != APP_CONFIG['authorization_code']:
        return func.HttpResponse(body='Authorization code is invalid',
                                 status_code=401)
    logger.info('Code supplied on query string matches AUTH_CODE.')
    fw = pan_firewall(hostname=APP_CONFIG['fw_ip'],
                      api_key=APP_CONFIG['api_key'])
    try:
        req_body = req.get_json()
        nic = azure_nic(req_body)
        tags = pan_tags(pan_fw=fw, tag_names=nic['tags'])
        if tags:
            logger.info('Updating PAN Tags')
            tags[0].create_similar()
            tags[0].apply_similar()
            logger.info('Updated PAN Tags')
        ips = pan_ips(pan_fw=fw, azure_nic=nic)
        if ips:
            logger.info('Updating PAN AddressObjects')
            for ip in ips:
                logger.debug(ip.name)
            logger.info('Updated PAN AddressObjects')
        az_ip_securityzone = azure_securityzone(azure_nic=nic)
        logger.info('Security Zone for Azure {}={}'.format(
            nic['ipAddress'], az_ip_securityzone))
        pan_ip_securityzone = pan_securityzone(pan_fw=fw,
                                               ip_name='ip_' +
                                               nic['ipAddress'])
        logger.info('Security Zone for PAN {}={}'.format(
            'ip_' + nic['ipAddress'], pan_ip_securityzone))
        if pan_ip_securityzone:
            if pan_ip_securityzone != az_ip_securityzone:
                logger.debug('Removing {} from {}'.format(
                    'ip_' + nic['ipAddress'], pan_ip_securityzone))
                static_value_members = pan_addressgroup_members(
                    pan_fw=fw, name=pan_ip_securityzone)
                logger.debug(
                    'Current static_value: {}'.format(static_value_members))
                s = set(static_value_members)
                s.discard('ip_' + nic['ipAddress'])
                new_static_value_members = list(s)
                logger.debug(
                    'New static_value: {}'.format(new_static_value_members))
                former_addressgrp = pan_objs.AddressGroup(
                    name=pan_ip_securityzone,
                    static_value=new_static_value_members)
                new_addressgrp = pan_addressgroup(
                    pan_fw=fw,
                    address_group_name=az_ip_securityzone,
                    ip_address=nic['ipAddress'])
                fw.add(former_addressgrp)
                fw.add(new_addressgrp)
                addressgrps = [former_addressgrp] + [new_addressgrp]
                logger.info('AddressGroups modified')
            else:
                logger.info('AddressGroups unmodified')
                addressgrps = []
        else:
            new_addressgrp = pan_addressgroup(
                pan_fw=fw,
                address_group_name=az_ip_securityzone,
                ip_address=nic['ipAddress'])
            fw.add(new_addressgrp)
            addressgrps = [new_addressgrp]
        if addressgrps:
            logger.info('Updating PAN AddressGroups: {}'.format(addressgrps))
            for ag in addressgrps:
                ag.create()
                ag.apply()
                logger.info('Updated PAN AddressGroup: {}'.format(ag.name))
        return func.HttpResponse(body=json.dumps(nic),
                                 mimetype='application/json',
                                 status_code=200)
    except:
        pass
def main():
    argument_spec = dict(ip_address=dict(required=True),
                         username=dict(default='admin'),
                         password=dict(no_log=True),
                         api_key=dict(no_log=True),
                         name=dict(type='str', required=True),
                         static_value=dict(type='list'),
                         dynamic_value=dict(type='str'),
                         description=dict(type='str'),
                         tag=dict(type='list'),
                         device_group=dict(type='str'),
                         vsys=dict(type='str', default='vsys1'),
                         state=dict(default='present',
                                    choices=['present', 'absent']),
                         commit=dict(type='bool', default=True))
    required_one_of = [['static_value', 'dynamic_value']]
    mutually_exclusive = [['static_value', 'dynamic_value']]

    module = AnsibleModule(argument_spec=argument_spec,
                           required_one_of=required_one_of,
                           mutually_exclusive=mutually_exclusive,
                           supports_check_mode=False)

    if not HAS_LIB:
        module.fail_json(
            msg='pan-python and pandevice are required for this module.')

    ip_address = module.params['ip_address']
    username = module.params['username']
    password = module.params['password']
    api_key = module.params['api_key']
    name = module.params['name']
    static_value = module.params['static_value']
    dynamic_value = module.params['dynamic_value']
    description = module.params['description']
    tag = module.params['tag']
    device_group = module.params['device_group']
    vsys = module.params['vsys']
    state = module.params['state']
    commit = module.params['commit']

    changed = False

    try:
        device = base.PanDevice.create_from_device(ip_address,
                                                   username,
                                                   password,
                                                   api_key=api_key)

        if isinstance(device, firewall.Firewall):
            device.vsys = vsys

        if device_group:
            if device_group.lower() == 'shared':
                device_group = None
            else:
                if not get_devicegroup(device, device_group):
                    module.fail_json(msg='Could not find {} device group.'.
                                     format(device_group))

        if state == 'present':
            existing_obj = find_object(device, name, objects.AddressGroup,
                                       device_group)

            if static_value:
                new_obj = objects.AddressGroup(name,
                                               static_value=static_value,
                                               description=description,
                                               tag=tag)
            elif dynamic_value:
                new_obj = objects.AddressGroup(name,
                                               dynamic_value=dynamic_value,
                                               description=description,
                                               tag=tag)

            if not existing_obj:
                add_object(device, new_obj, device_group)
                new_obj.create()
                changed = True
            elif not existing_obj.equal(new_obj):
                if static_value:
                    existing_obj.static_value = static_value
                elif dynamic_value:
                    existing_obj.dynamic_value = dynamic_value

                existing_obj.description = description
                existing_obj.tag = tag
                existing_obj.apply()
                changed = True

        elif state == 'absent':
            existing_obj = find_object(device, name, objects.AddressGroup,
                                       device_group)

            if existing_obj:
                existing_obj.delete()
                changed = True

        if commit and changed:
            perform_commit(module, device, device_group)

    except PanDeviceError as e:
        module.fail_json(msg=e.message)

    module.exit_json(changed=changed)