Пример #1
0
def update_config(module, api, cur_cfg):
    if module.check_mode:
        # Get the current config and overlay the module parameters in order to
        # 'fake' an update.
        new_cfg = dict(cur_cfg)
        want = ans_to_rest(module.params, PARAM_MAP)
        new_cfg.update(want)
        return new_cfg

    body_params = ans_to_rest(module.params, PARAM_MAP)
    # Remove the 'interface' key as it should not be included in the param
    # list.
    del body_params['interface']
    if not body_params:
        # If body_params is empty, we aren't changing anything, so just return
        # the current config as the new config.
        return cur_cfg
    url = urljoin('gre-tunnels/', '{}'.format(module.params['interface']))
    # XXX: We're always using POST here, as it seems to work in every case that
    # PATCH would work.
    resp_code, response = api.create_config(url, body_params=body_params)
    if resp_code not in ResponseCodes.GOOD_RESP:
        msg = "Could not post new config (code: {}, resp: {})"
        raise AEDAPIError(msg.format(resp_code, response))
    return response
Пример #2
0
def update_config(module, api, cur_cfg):
    if module.check_mode:
        # Get current config and overlay the module parameters in order to
        # fake up an update.
        cur_cfg = get_general_settings(module, api)
        want = ans_to_rest(module.params, PARAM_MAP)
        cur_cfg.update(want)
        return cur_cfg

    body_params = ans_to_rest(module.params, PARAM_MAP)
    resp_code, response = api.push_config('general-settings',
                                          body_params=body_params)
    if resp_code not in ResponseCodes.GOOD_RESP:
        msg = "Could not push config (code: {}, resp: {})"
        raise AEDAPIError(msg.format(resp_code, response))
    return response
Пример #3
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        snmp_version=dict(type='str', choices=['2', '3']),
        snmp_community=dict(type='str', no_log=True),
        snmp_username=dict(type='str'),
        snmp_security_level=dict(
            type='str', choices=['noAuthNoPriv', 'authNoPriv', 'authPriv']),
        snmp_password=dict(type='str', no_log=True),
        snmp_auth_proto=dict(type='str', choices=['md5', 'sha']),
        snmp_privacy_password=dict(type='str', no_log=True),
        snmp_privacy_protocol=dict(choices=['aes', 'des']),
        secure=dict(type='bool'),
    )

    argument_spec.update(aed_argument_spec)

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    with exception_context(module, Exception):
        connection = Connection(module._socket_path)

        api = AEDAPIBase(connection)

        warnings = list()
        check_args(module, warnings)
        result = {'changed': False}

        if warnings:
            result['warnings'] = warnings

        # Get what you want and have...
        want = get_want(module, PARAM_MAP)
        have = get_have(api)

        result = {'changed': False}

        changes = get_changes(have, want)
        if changes:
            if module._diff:
                result['diff'] = {'prepared': json.dumps(changes)}
            result['changed'] = True
            if not module.check_mode:
                parsed_changes = ans_to_rest(changes, PARAM_MAP)
                resp_code, new_config = api.push_config(
                    command='snmp', body_params=parsed_changes)
                if resp_code not in ResponseCodes.GOOD_RESP:
                    module.fail_json(
                        msg='APIError: response code:{}, '
                        'response:{}'.format(resp_code, new_config))

    module.exit_json(**result)
Пример #4
0
def main():
    """
    Entry point for module execution
    """
    argument_spec = dict(
        deployment_mode=dict(choices=['monitor', 'inline', 'l3']),
        protection_active=dict(type='bool'),
        protection_level=dict(choices=['low', 'medium', 'high'])
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True
    )

    with exception_context(module, Exception):
        connection = Connection(module._socket_path)

        api = AEDAPIBase(connection)

        warnings = list()
        check_args(module, warnings)
        result = {'changed': False}

        if warnings:
            result['warnings'] = warnings

        # Get what you want and have...
        want = get_want(module, PARAM_MAP)
        have = get_have(api)

        result = {'changed': False}

        # Determine if we need a change
        changes = get_changes(have, want)
        if changes:
            if module._diff:
                result['diff'] = {'prepared': json.dumps(changes)}
            result['changed'] = True
            parsed_changes = ans_to_rest(changes, PARAM_MAP)
            if not module.check_mode:
                resp_code, new_config = api.push_config(
                    command='summary',
                    body_params=parsed_changes
                )
                if resp_code not in ResponseCodes.GOOD_RESP:
                    module.fail_json(msg='APIError: response code:{}, '
                                     'response:{}'.format(resp_code,
                                                          new_config))

        result['deployment_state'] = get_have(api)

    module.exit_json(**result)
Пример #5
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        syslog_server=dict(type='str'),
        syslog_port=dict(type='str'),
        syslog_protocol=dict(choices=['udp', 'tcp']),
        syslog_format=dict(choices=['cef', 'leef', 'legacy']),
        secure=dict(type='bool'),
    )

    argument_spec.update(aed_argument_spec)

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    with exception_context(module, Exception):
        connection = Connection(module._socket_path)

        api = AEDAPIBase(connection)

        warnings = list()
        check_args(module, warnings)
        result = {'changed': False}

        if warnings:
            result['warnings'] = warnings

        # Get what you want and have...
        want = get_want(module, PARAM_MAP)
        have = get_have(api)

        result = {'changed': False}

        changes = get_changes(have, want)
        if changes:
            if module._diff:
                result['diff'] = {'prepared': json.dumps(changes)}
            result['changed'] = True
            if not module.check_mode:
                parsed_changes = ans_to_rest(changes, PARAM_MAP)
                resp_code, new_config = api.push_config(
                    command='remote-syslog', body_params=parsed_changes)
                if resp_code not in ResponseCodes.GOOD_RESP:
                    module.fail_json(
                        msg='APIError: response code:{}, '
                        'response:{}'.format(resp_code, new_config))
            result['aed_remote_syslog_state'] = get_have(api)

    module.exit_json(**result)
Пример #6
0
def main():
    p_level_arg_spec = dict(
        appbehavior_interrupt_count=dict(type='int'),
        botnet_basic=dict(type='bool'),
        botnet_segment=dict(type='bool'),
        botnet_signatures=dict(type='bool'),
        connection_limit_enabled=dict(type='bool'),
        detect_icmp_enabled=dict(type='bool'),
        detect_icmp_bps=dict(type='int'),
        detect_icmp_rate=dict(type='int'),
        detect_syn_flood_enabled=dict(type='bool'),
        detect_syn_flood_delta_rate=dict(type='int'),
        detect_syn_flood_rate=dict(type='int'),
        dns_auth_enable=dict(type='bool'),
        dns_malform_enable=dict(type='bool'),
        dns_nx_domain_rate=dict(type='int'),
        dns_query_rate=dict(type='int'),
        dns_regex_list=dict(type='list'),
        filter_list=dict(type='list'),
        fragmentation_detection_enabled=dict(type='bool'),
        fragmentation_detection_bps=dict(type='int'),
        fragmentation_detection_pps=dict(type='int'),
        http_malform_enabled=dict(type='bool'),
        http_proxy_detect_enabled=dict(type='bool'),
        http_rate_limit_object_rate=dict(type='int'),
        http_rate_limit_request_rate=dict(type='int'),
        http_regex_list=dict(type='list'),
        idle_reset_enabled=dict(type='bool'),
        idle_reset_bit_rate=dict(type='int'),
        idle_reset_idle_timeout=dict(type='int'),
        idle_reset_init_size=dict(type='int'),
        idle_reset_init_timeout=dict(type='int'),
        idle_reset_num_idles=dict(type='int'),
        idle_reset_track_long_lived=dict(type='bool'),
        multicast_enabled=dict(type='bool'),
        private_addresses_enabled=dict(type='bool'),
        rate_based_blocking_bps=dict(type='int'),
        rate_based_blocking_pps=dict(type='int'),
        regex_enabled=dict(type='bool'),
        regex_blacklist_enable=dict(type='bool'),
        regex_include_headers=dict(type='bool'),
        regex_match_source_port=dict(type='bool'),
        regex_pattern=dict(type='list'),
        regex_tcp_ports=dict(type='list'),
        regex_udp_ports=dict(type='list'),
        reputation_enabled=dict(type='bool'),
        # reputation_assert_confidence=dict(type='bool'),
        # reputation_categories=dict(type='bool'),
        # reputation_custom_confidence=dict(type='bool'),
        # reputation_use_custom=dict(type='bool'),
        shaping_enabled=dict(type='bool'),
        shaping_bps=dict(type='int'),
        shaping_filter=dict(type='list'),
        shaping_pps=dict(type='int'),
        sip_malform_enabled=dict(type='bool'),
        sip_request_rate=dict(type='int'),
        syn_auth_enabled=dict(type='bool'),
        syn_auth_automation_enabled=dict(type='bool'),
        syn_auth_automation_threshold=dict(type='int'),
        syn_auth_destination_ports=dict(type='list'),
        syn_auth_http_auth_enabled=dict(type='bool'),
        syn_auth_http_auth_method=dict(
            choices=['java', 'redirect', 'soft_reset']),
        tls_malform_enabled=dict(type='bool'),
        udp_flood_enabled=dict(type='bool'),
        udp_flood_bps=dict(type='int'),
        udp_flood_pps=dict(type='int'),
        webcrawler_enabled=dict(type='bool'),
    )

    argument_spec = dict(name=dict(type='str', required=True),
                         present=dict(type='bool', default=True),
                         base_server_type=dict(type='str', required=True),
                         stix_enabled=dict(type='bool'),
                         protection_level_high=dict(type='dict',
                                                    options=p_level_arg_spec),
                         protection_level_low=dict(type='dict',
                                                   options=p_level_arg_spec),
                         protection_level_medium=dict(
                             type='dict', options=p_level_arg_spec))

    # TODO Is this necc'y? At this point no aed_argument_spce
    argument_spec.update(aed_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

    with exception_context(module, Exception):
        connection = Connection(module._socket_path)

        api = AEDAPIBase(connection)
        warnings = list()
        check_args(module, warnings)

        # Get what you want and have...
        have = get_have(api, module)
        want = get_want(module)

        result = {'changed': False}

        if not want['present']:
            if not have['present']:  # Does not exist yet, will not exist.
                result['no_create'] = (
                    "{} does not exist and 'present' set to False.  Will not "
                    "bother creating to just remove it.".format(want['name']))

            else:  # Must be present, so delete it
                result['delete name'] = '{}'.format(have['name'])
                result['changed'] = True

                if not module.check_mode:
                    server_type_id = have['server_type']
                    resp_code, new_config = api.delete_config(
                        command='protection-groups/server-types/{}/'.format(
                            server_type_id))
                    if resp_code not in ResponseCodes.GOOD_DEL_RESP:
                        raise AEDAPIError(
                            'APIError:did not delete {}. '
                            'response code:{}, response:{}'.format(
                                have['name'], resp_code, new_config))

            module.exit_json(**result)

        changes = get_changes(have, want)

        if changes:
            if module._diff:
                result['diff'] = {'prepared': json.dumps(changes)}
            result['changed'] = True

            # Create new ST if req'd
            if not have['present']:  # Need to create from parent_type
                base_st_name = module.params.get('base_server_type')
                resp_code, raw_config = api.get_config(
                    'protection-groups/server-types/',
                    query_params=dict(serverName=base_st_name))
                if resp_code in ResponseCodes.GOOD_RESP:
                    st_list = raw_config.get('server-types')
                    if st_list is None:
                        raise AEDAPIError(
                            'server-type "{}" does not exist, cannot '
                            'create new server-type from it.'.format(
                                base_st_name))
                else:
                    raise AEDAPIError(
                        'Failed attempting to lookup server-type {}.'.format(
                            base_st_name))
                base_new_st_on = st_list[0]['serverType']
                new_st_params = dict(serverName=want['name'],
                                     parentType=base_new_st_on)
                if not module.check_mode:
                    resp_code, new_config = api.create_config(
                        command='protection-groups/server-types/',
                        body_params=new_st_params)
                    if resp_code not in ResponseCodes.GOOD_RESP:
                        raise AEDAPIError(
                            'APIError:response while creating new '
                            'server-type. code:{}, response:{}'.format(
                                resp_code, new_config))
                # Need to rest_to_ans the new ST like a new object...
                have = get_have(api, module)
                changes = get_changes(have, want)

            parsed_changes = ans_to_rest(changes, PARAM_MAP)

            if changes.get('protection_level_high'):
                parsed_changes['protectionLevels'] = {}
                parsed_changes['protectionLevels']['high'] = (pl_ans_to_rest(
                    changes['protection_level_high'], P_LEVEL_MAP))

            if changes.get('protection_level_low'):
                parsed_changes.setdefault('protectionLevels', {})
                parsed_changes['protectionLevels']['low'] = (pl_ans_to_rest(
                    changes['protection_level_low'], P_LEVEL_MAP))

            if changes.get('protection_level_medium'):
                parsed_changes.setdefault('protectionLevels', {})
                parsed_changes['protectionLevels']['medium'] = (pl_ans_to_rest(
                    changes['protection_level_medium'], P_LEVEL_MAP))

            if parsed_changes:
                if not module.check_mode:
                    server_type_id = have['server_type']
                    resp_code, new_config = api.push_config(
                        command='protection-groups/server-types/{}/'.format(
                            server_type_id),
                        body_params=parsed_changes)
                    if resp_code not in ResponseCodes.GOOD_RESP:
                        raise AEDAPIError(
                            'APIError: Failed patching config. '
                            'response code:{}, response:{}'.format(
                                resp_code, new_config))

        result['server_types_state'] = get_have(api, module)

    module.exit_json(**result)
Пример #7
0
def main():
    """Module entry point"""

    argument_spec = dict(server_id=dict(type='str'),
                         capability=dict(type='str'),
                         requested=dict(type='str'))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

    api = AEDAPIBase(Connection(module._socket_path))

    def wait_for_changes(api):
        """Wait before panicking, requests can take
        some time to complete.

        Args:
            api (AEDApi): AEDApi instance for this connection

        Return:
            Error on time out, else true
        """

        # The /license/ API endpoints make requests to the
        # license server and the license server processes
        # this request. The API provides endpoints to
        # check the status of the request.
        # To make sure the task was competed, we much check
        # status of the request and timeout if it wasn't in
        # a given time frame. This does not mean that the
        # request will not be successful. It only prevents
        # Ansible from waiting indefinitely.

        def _sig_alarm(sig, tb):
            raise AEDAPIError('Timed out waiting 90s for license server'
                              ' to complete request. The request may or'
                              ' may not have completed successfully.')

        timeout = 90
        signal.signal(signal.SIGALRM, _sig_alarm)
        signal.alarm(timeout)
        while True:
            resp_code, response = api.get_config(command=BASE_URI +
                                                 '/progress/')
            if resp_code in ResponseCodes.GOOD_RESP:
                # Check if the request is completed
                if response['status'].upper() in ['COMPLETED.']:
                    return
            sleep(2)

    # Catch exceptions within the context and return
    # Ansible compliant error response.
    with exception_context(module, Exception):
        have = get_have(api, module)
        result = {'changed': False}
        diff = {}
        if module.params.get('server_id', None):
            want = get_want(module, SERVER_PARAM_MAP)
            changes = get_changes(have, want)
            parsed_changes = ans_to_rest(changes, SERVER_PARAM_MAP)
            if changes:
                if not module.check_mode:
                    if not have['server_id']:
                        # PUT request if no lic server is configured
                        resp_code, new_config = api.put_config(
                            command=BASE_URI + '/server/',
                            body_params=parsed_changes)
                    else:
                        # PATCH request if lic server is to be modified
                        resp_code, new_config = api.push_config(
                            command=BASE_URI + '/server/',
                            body_params=parsed_changes)
                    verify_response(resp_code, new_config)
                    wait_for_changes(api)
                result['changed'] = True
                diff.update(changes)
        if module.params.get('capability', None):
            want = get_want(module, CAPABILITIES_PARAM_MAP)
            requested = module.params.get('requested', None)
            parsed_changes = ans_to_rest(want, CAPABILITIES_PARAM_MAP)
            parsed_changes.pop('capability')
            capability = module.params.get('capability', None)
            # Make changes only if the requested
            # capability hasn't already been granted
            if have['capabilities'][0]['granted'] != requested:
                if not module.check_mode:
                    resp_code, new_config = api.put_config(
                        command=BASE_URI +
                        '/capabilities/{}/'.format(capability),
                        body_params=parsed_changes)
                    verify_response(resp_code, new_config)
                    wait_for_changes(api)
                result['changed'] = True
                diff.update(want)
        if module._diff:
            result['diff'] = {'prepared': json.dumps(diff)}
        # In check mode, `aed_license_state` key will still show the unchanged state.
        # Though, `what_changed` will show the expected changes.
        result['aed_license_state'] = get_have(api, module)
        module.exit_json(**result)
Пример #8
0
def main():
    """Program entry point"""
    argument_spec = dict(name=dict(type='str'),
                         link_propagation_up_timeout=dict(type='int'),
                         link_propagation_down_timeout=dict(type='int'),
                         addr=dict(type='str'),
                         addr_present=dict(type='bool', default='True'))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

    api = AEDAPIBase(Connection(module._socket_path))

    result = {'changed': False}

    with exception_context(module, Exception):
        have = get_have(api, module)
        want = get_want(module, PARAM_MAP)
        changes = get_changes(have, want)
        intf_name = module.params.get('name', None)
        intf_addr = module.params.get('addr', None)
        addr_present = module.params.get('addr_present')
        if not addr_present:
            changes['addr_present'] = False
        # Run only if there are any changes and
        # check mode is off.
        if changes:
            if not intf_name:
                if module._diff:
                    result['diff'] = {'prepared': json.dumps(changes)}
                parsed_changes = ans_to_rest(changes, LP_PARAM_MAP)
                if not module.check_mode:
                    resp_code, new_config = api.push_config(
                        command='mitigation-interfaces',
                        body_params=parsed_changes)
                    if resp_code not in ResponseCodes.GOOD_RESP:
                        module.fail_json(
                            msg='APIError: Failed pushing config. '
                            'response code:{}, response:{}'.format(
                                resp_code, new_config))
                result['changed'] = True
            else:
                parsed_changes = ans_to_rest(changes, INTF_PARAM_MAP)
                if not addr_present:
                    # Check if the interface has the specified address
                    # and delete it. If not, don't create just for the
                    # sake of deleting it.
                    if have['addr']:
                        if not module.check_mode:
                            resp_code, new_config = api.delete_config(
                                command='mitigation-interfaces/{}/{}/'.format(
                                    intf_name, intf_addr))
                            if resp_code not in ResponseCodes.GOOD_DEL_RESP:
                                module.fail_json(
                                    msg='APIError: Failed deleting config. '
                                    'response code: {}, response: {}'.format(
                                        resp_code, new_config))
                        result['changed'] = True
                        result['delete_interface_address'] = {
                            intf_name: intf_addr
                        }
                    else:
                        result['no_delete'] = (
                            'This interface does not have an address set. '
                            'Not creating address to only delete it.')
                else:
                    if module._diff:
                        result['diff'] = {'prepared': json.dumps(changes)}
                    if not module.check_mode:
                        resp_code, new_config = api.push_config(
                            command='mitigation-interfaces/{}/'.format(
                                intf_name),
                            body_params=parsed_changes)
                        if resp_code not in ResponseCodes.GOOD_RESP:
                            module.fail_json(
                                msg='APIError: Failed pushing config. '
                                'response code: {}, response: {}'.format(
                                    resp_code, new_config))
                    result['changed'] = True
                    result['add_interface_address'] = {intf_name: intf_addr}
            new_state = get_have(api, module)
            result['aed_interface_state'] = new_state
    module.exit_json(**result)