sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def element_attribute_by_href(href, attr_name): """ The element href is known and you want to retrieve a specific attribute from that element. For example, if you want a specific attribute by it's name:: search.element_attribute_by_href(href_to_resource, 'name') :param str href: href of element :param str attr_name: name of attribute :return: str value of attribute """ if href: element = fetch_json_by_href(href) if element.json: return element.json.get(attr_name)
The element href is known and you want to retrieve a specific attribute from that element. For example, if you want a specific attribute by it's name:: search.element_attribute_by_href(href_to_resource, 'name') :param str href: href of element :param str attr_name: name of attribute :return: str value of attribute
entailment
def element_by_href_as_smcresult(href, params=None): """ Get specified element returned as an SMCResult object :param href: href direct link to object :return: :py:class:`smc.api.web.SMCResult` with etag, href and element field holding json, else None """ if href: element = fetch_json_by_href(href, params=params) if element: return element
Get specified element returned as an SMCResult object :param href: href direct link to object :return: :py:class:`smc.api.web.SMCResult` with etag, href and element field holding json, else None
entailment
def element_as_smcresult_use_filter(name, _filter): """ Return SMCResult object and use search filter to find object :param name: name of element to find :param _filter: filter to use, i.e. tcp_service, host, etc :return: :py:class:`smc.api.web.SMCResult` """ if name: element = fetch_meta_by_name(name, filter_context=_filter) if element.msg: return element if element.json: return element_by_href_as_smcresult(element.json.pop().get('href'))
Return SMCResult object and use search filter to find object :param name: name of element to find :param _filter: filter to use, i.e. tcp_service, host, etc :return: :py:class:`smc.api.web.SMCResult`
entailment
def element_href_by_batch(list_to_find, filter=None): # @ReservedAssignment """ Find batch of entries by name. Reduces number of find calls from calling class. :param list list_to_find: list of names to find :param filter: optional filter, i.e. 'tcp_service', 'host', etc :return: list: {name: href, name: href}, href may be None if not found """ try: if filter: return [{k: element_href_use_filter(k, filter) for k in list_to_find}] return [{k: element_href(k) for k in list_to_find}] except TypeError: logger.error("{} is not iterable".format(list_to_find))
Find batch of entries by name. Reduces number of find calls from calling class. :param list list_to_find: list of names to find :param filter: optional filter, i.e. 'tcp_service', 'host', etc :return: list: {name: href, name: href}, href may be None if not found
entailment
def all_elements_by_type(name): """ Get specified elements based on the entry point verb from SMC api To get the entry points available, you can get these from the session:: session.cache.entry_points Execution will get the entry point for the element type, then get all elements that match. For example:: search.all_elements_by_type('host') :param name: top level entry point name :raises: `smc.api.exceptions.UnsupportedEntryPoint` :return: list with json representation of name match, else None """ if name: entry = element_entry_point(name) if entry: # in case an invalid entry point is specified result = element_by_href_as_json(entry) return result
Get specified elements based on the entry point verb from SMC api To get the entry points available, you can get these from the session:: session.cache.entry_points Execution will get the entry point for the element type, then get all elements that match. For example:: search.all_elements_by_type('host') :param name: top level entry point name :raises: `smc.api.exceptions.UnsupportedEntryPoint` :return: list with json representation of name match, else None
entailment
def fetch_json_by_name(name): """ Fetch json based on the element name First gets the href based on a search by name, then makes a second query to obtain the element json :method: GET :param str name: element name :return: :py:class:`smc.api.web.SMCResult` """ result = fetch_meta_by_name(name) if result.href: result = fetch_json_by_href(result.href) return result
Fetch json based on the element name First gets the href based on a search by name, then makes a second query to obtain the element json :method: GET :param str name: element name :return: :py:class:`smc.api.web.SMCResult`
entailment
def fetch_json_by_href(href, params=None): """ Fetch json for element by using href. Params should be key/value pairs. For example {'filter': 'myfilter'} :method: GET :param str href: href of the element :params dict params: optional search query parameters :return: :py:class:`smc.api.web.SMCResult` """ result = SMCRequest(href=href, params=params).read() if result: result.href = href return result
Fetch json for element by using href. Params should be key/value pairs. For example {'filter': 'myfilter'} :method: GET :param str href: href of the element :params dict params: optional search query parameters :return: :py:class:`smc.api.web.SMCResult`
entailment
def create(cls, name, negotiation_expiration=200000, negotiation_retry_timer=500, negotiation_retry_max_number=32, negotiation_retry_timer_max=7000, certificate_cache_crl_validity=90000, mobike_after_sa_update=False, mobike_before_sa_update=False, mobike_no_rrc=True): """ Create a new gateway setting profile. :param str name: name of profile :param int negotiation_expiration: expire after (ms) :param int negotiation_retry_timer: retry time length (ms) :param int negotiation_retry_max_num: max number of retries allowed :param int negotiation_retry_timer_max: maximum length for retry (ms) :param int certificate_cache_crl_validity: cert cache validity (seconds) :param boolean mobike_after_sa_update: Whether the After SA flag is set for Mobike Policy :param boolean mobike_before_sa_update: Whether the Before SA flag is set for Mobike Policy :param boolean mobike_no_rrc: Whether the No RRC flag is set for Mobike Policy :raises CreateElementFailed: failed creating profile :return: instance with meta :rtype: GatewaySettings """ json = {'name': name, 'negotiation_expiration': negotiation_expiration, 'negotiation_retry_timer': negotiation_retry_timer, 'negotiation_retry_max_number': negotiation_retry_max_number, 'negotiation_retry_timer_max': negotiation_retry_timer_max, 'certificate_cache_crl_validity': certificate_cache_crl_validity, 'mobike_after_sa_update': mobike_after_sa_update, 'mobike_before_sa_update': mobike_before_sa_update, 'mobike_no_rrc': mobike_no_rrc} return ElementCreator(cls, json)
Create a new gateway setting profile. :param str name: name of profile :param int negotiation_expiration: expire after (ms) :param int negotiation_retry_timer: retry time length (ms) :param int negotiation_retry_max_num: max number of retries allowed :param int negotiation_retry_timer_max: maximum length for retry (ms) :param int certificate_cache_crl_validity: cert cache validity (seconds) :param boolean mobike_after_sa_update: Whether the After SA flag is set for Mobike Policy :param boolean mobike_before_sa_update: Whether the Before SA flag is set for Mobike Policy :param boolean mobike_no_rrc: Whether the No RRC flag is set for Mobike Policy :raises CreateElementFailed: failed creating profile :return: instance with meta :rtype: GatewaySettings
entailment
def create(cls, name, trust_all_cas=True): """ Create new External Gateway :param str name: name of test_external gateway :param bool trust_all_cas: whether to trust all internal CA's (default: True) :return: instance with meta :rtype: ExternalGateway """ json = {'name': name, 'trust_all_cas': trust_all_cas} return ElementCreator(cls, json)
Create new External Gateway :param str name: name of test_external gateway :param bool trust_all_cas: whether to trust all internal CA's (default: True) :return: instance with meta :rtype: ExternalGateway
entailment
def update_or_create(cls, name, external_endpoint=None, vpn_site=None, trust_all_cas=True, with_status=False): """ Update or create an ExternalGateway. The ``external_endpoint`` and ``vpn_site`` parameters are expected to be a list of dicts with key/value pairs to satisfy the respective elements create constructor. VPN Sites will represent the final state of the VPN site list. ExternalEndpoint that are pre-existing will not be deleted if not provided in the ``external_endpoint`` parameter, however existing elements will be updated as specified. :param str name: name of external gateway :param list(dict) external_endpoint: list of dict items with key/value to satisfy ExternalEndpoint.create constructor :param list(dict) vpn_site: list of dict items with key/value to satisfy VPNSite.create constructor :param bool with_status: If set to True, returns a 3-tuple of (ExternalGateway, modified, created), where modified and created is the boolean status for operations performed. :raises ValueError: missing required argument/s for constructor argument :rtype: ExternalGateway """ if external_endpoint: for endpoint in external_endpoint: if 'name' not in endpoint: raise ValueError('External endpoints are configured ' 'but missing the name parameter.') if vpn_site: for site in vpn_site: if 'name' not in site: raise ValueError('VPN sites are configured but missing ' 'the name parameter.') # Make sure VPN sites are resolvable before continuing sites = [element_resolver(element, do_raise=True) for element in site.get('site_element', [])] site.update(site_element=sites) updated = False created = False try: extgw = ExternalGateway.get(name) except ElementNotFound: extgw = ExternalGateway.create(name, trust_all_cas) created = True if external_endpoint: for endpoint in external_endpoint: _, modified, was_created = ExternalEndpoint.update_or_create( extgw, with_status=True, **endpoint) if was_created or modified: updated = True if vpn_site: for site in vpn_site: _, modified, was_created = VPNSite.update_or_create(extgw, name=site['name'], site_element=site.get('site_element'), with_status=True) if was_created or modified: updated = True if with_status: return extgw, updated, created return extgw
Update or create an ExternalGateway. The ``external_endpoint`` and ``vpn_site`` parameters are expected to be a list of dicts with key/value pairs to satisfy the respective elements create constructor. VPN Sites will represent the final state of the VPN site list. ExternalEndpoint that are pre-existing will not be deleted if not provided in the ``external_endpoint`` parameter, however existing elements will be updated as specified. :param str name: name of external gateway :param list(dict) external_endpoint: list of dict items with key/value to satisfy ExternalEndpoint.create constructor :param list(dict) vpn_site: list of dict items with key/value to satisfy VPNSite.create constructor :param bool with_status: If set to True, returns a 3-tuple of (ExternalGateway, modified, created), where modified and created is the boolean status for operations performed. :raises ValueError: missing required argument/s for constructor argument :rtype: ExternalGateway
entailment
def create(self, name, address=None, enabled=True, balancing_mode='active', ipsec_vpn=True, nat_t=False, force_nat_t=False, dynamic=False, ike_phase1_id_type=None, ike_phase1_id_value=None): """ Create an test_external endpoint. Define common settings for that specify the address, enabled, nat_t, name, etc. You can also omit the IP address if the endpoint is dynamic. In that case, you must also specify the ike_phase1 settings. :param str name: name of test_external endpoint :param str address: address of remote host :param bool enabled: True|False (default: True) :param str balancing_mode: active :param bool ipsec_vpn: True|False (default: True) :param bool nat_t: True|False (default: False) :param bool force_nat_t: True|False (default: False) :param bool dynamic: is a dynamic VPN (default: False) :param int ike_phase1_id_type: If using a dynamic endpoint, you must set this value. Valid options: 0=DNS name, 1=Email, 2=DN, 3=IP Address :param str ike_phase1_id_value: value of ike_phase1_id. Required if ike_phase1_id_type and dynamic set. :raises CreateElementFailed: create element with reason :return: newly created element :rtype: ExternalEndpoint """ json = {'name': name, 'address': address, 'balancing_mode': balancing_mode, 'dynamic': dynamic, 'enabled': enabled, 'nat_t': nat_t, 'force_nat_t': force_nat_t, 'ipsec_vpn': ipsec_vpn} if dynamic: json.pop('address') json.update( ike_phase1_id_type=ike_phase1_id_type, ike_phase1_id_value=ike_phase1_id_value) return ElementCreator( self.__class__, href=self.href, json=json)
Create an test_external endpoint. Define common settings for that specify the address, enabled, nat_t, name, etc. You can also omit the IP address if the endpoint is dynamic. In that case, you must also specify the ike_phase1 settings. :param str name: name of test_external endpoint :param str address: address of remote host :param bool enabled: True|False (default: True) :param str balancing_mode: active :param bool ipsec_vpn: True|False (default: True) :param bool nat_t: True|False (default: False) :param bool force_nat_t: True|False (default: False) :param bool dynamic: is a dynamic VPN (default: False) :param int ike_phase1_id_type: If using a dynamic endpoint, you must set this value. Valid options: 0=DNS name, 1=Email, 2=DN, 3=IP Address :param str ike_phase1_id_value: value of ike_phase1_id. Required if ike_phase1_id_type and dynamic set. :raises CreateElementFailed: create element with reason :return: newly created element :rtype: ExternalEndpoint
entailment
def update_or_create(cls, external_gateway, name, with_status=False, **kw): """ Update or create external endpoints for the specified external gateway. An ExternalEndpoint is considered unique based on the IP address for the endpoint (you cannot add two external endpoints with the same IP). If the external endpoint is dynamic, then the name is the unique identifier. :param ExternalGateway external_gateway: external gateway reference :param str name: name of the ExternalEndpoint. This is only used as a direct match if the endpoint is dynamic. Otherwise the address field in the keyword arguments will be used as you cannot add multiple external endpoints with the same IP address. :param bool with_status: If set to True, returns a 3-tuple of (ExternalEndpoint, modified, created), where modified and created is the boolean status for operations performed. :param dict kw: keyword arguments to satisfy ExternalEndpoint.create constructor :raises CreateElementFailed: Failed to create external endpoint with reason :raises ElementNotFound: If specified ExternalGateway is not valid :return: if with_status=True, return tuple(ExternalEndpoint, created). Otherwise return only ExternalEndpoint. """ if 'address' in kw: external_endpoint = external_gateway.external_endpoint.get_contains( '({})'.format(kw['address'])) else: external_endpoint = external_gateway.external_endpoint.get_contains(name) updated = False created = False if external_endpoint: # Check for changes for name, value in kw.items(): # Check for differences before updating if getattr(external_endpoint, name, None) != value: external_endpoint.data[name] = value updated = True if updated: external_endpoint.update() else: external_endpoint = external_gateway.external_endpoint.create( name, **kw) created = True if with_status: return external_endpoint, updated, created return external_endpoint
Update or create external endpoints for the specified external gateway. An ExternalEndpoint is considered unique based on the IP address for the endpoint (you cannot add two external endpoints with the same IP). If the external endpoint is dynamic, then the name is the unique identifier. :param ExternalGateway external_gateway: external gateway reference :param str name: name of the ExternalEndpoint. This is only used as a direct match if the endpoint is dynamic. Otherwise the address field in the keyword arguments will be used as you cannot add multiple external endpoints with the same IP address. :param bool with_status: If set to True, returns a 3-tuple of (ExternalEndpoint, modified, created), where modified and created is the boolean status for operations performed. :param dict kw: keyword arguments to satisfy ExternalEndpoint.create constructor :raises CreateElementFailed: Failed to create external endpoint with reason :raises ElementNotFound: If specified ExternalGateway is not valid :return: if with_status=True, return tuple(ExternalEndpoint, created). Otherwise return only ExternalEndpoint.
entailment
def enable_disable(self): """ Enable or disable this endpoint. If enabled, it will be disabled and vice versa. :return: None """ if self.enabled: self.data['enabled'] = False else: self.data['enabled'] = True self.update()
Enable or disable this endpoint. If enabled, it will be disabled and vice versa. :return: None
entailment
def enable_disable_force_nat_t(self): """ Enable or disable NAT-T on this endpoint. If enabled, it will be disabled and vice versa. :return: None """ if self.force_nat_t: self.data['force_nat_t'] = False else: self.data['force_nat_t'] = True self.update()
Enable or disable NAT-T on this endpoint. If enabled, it will be disabled and vice versa. :return: None
entailment
def create(self, name, site_element): """ Create a VPN site for an internal or external gateway :param str name: name of site :param list site_element: list of protected networks/hosts :type site_element: list[str,Element] :raises CreateElementFailed: create element failed with reason :return: href of new element :rtype: str """ site_element = element_resolver(site_element) json = { 'name': name, 'site_element': site_element} return ElementCreator( self.__class__, href=self.href, json=json)
Create a VPN site for an internal or external gateway :param str name: name of site :param list site_element: list of protected networks/hosts :type site_element: list[str,Element] :raises CreateElementFailed: create element failed with reason :return: href of new element :rtype: str
entailment
def update_or_create(cls, external_gateway, name, site_element=None, with_status=False): """ Update or create a VPN Site elements or modify an existing VPN site based on value of provided site_element list. The resultant VPN site end result will be what is provided in the site_element argument (can also be an empty list to clear existing). :param ExternalGateway external_gateway: The external gateway for this VPN site :param str name: name of the VPN site :param list(str,Element) site_element: list of resolved Elements to add to the VPN site :param bool with_status: If set to True, returns a 3-tuple of (VPNSite, modified, created), where modified and created is the boolean status for operations performed. :raises ElementNotFound: ExternalGateway or unresolved site_element """ site_element = [] if not site_element else site_element site_elements = [element_resolver(element) for element in site_element] vpn_site = external_gateway.vpn_site.get_exact(name) updated = False created = False if vpn_site: # If difference, reset if set(site_elements) != set(vpn_site.data.get('site_element', [])): vpn_site.data['site_element'] = site_elements vpn_site.update() updated = True else: vpn_site = external_gateway.vpn_site.create( name=name, site_element=site_elements) created = True if with_status: return vpn_site, updated, created return vpn_site
Update or create a VPN Site elements or modify an existing VPN site based on value of provided site_element list. The resultant VPN site end result will be what is provided in the site_element argument (can also be an empty list to clear existing). :param ExternalGateway external_gateway: The external gateway for this VPN site :param str name: name of the VPN site :param list(str,Element) site_element: list of resolved Elements to add to the VPN site :param bool with_status: If set to True, returns a 3-tuple of (VPNSite, modified, created), where modified and created is the boolean status for operations performed. :raises ElementNotFound: ExternalGateway or unresolved site_element
entailment
def add_site_element(self, element): """ Add a site element or list of elements to this VPN. :param list element: list of Elements or href's of vpn site elements :type element: list(str,Network) :raises UpdateElementFailed: fails due to reason :return: None """ element = element_resolver(element) self.data['site_element'].extend(element) self.update()
Add a site element or list of elements to this VPN. :param list element: list of Elements or href's of vpn site elements :type element: list(str,Network) :raises UpdateElementFailed: fails due to reason :return: None
entailment
def location_helper(name, search_only=False): """ Location finder by name. If location doesn't exist, create it and return the href :param str,Element name: location to resolve. If the location is by name, it will be retrieved or created, if href, returned and if Location, href returned. If None, settings an elements location to None will set it to the Default location. :param bool search_only: only search for the location, if not found do not create :return str href: href of location if search_only is not False :rtype: str or None """ try: return name.href except AttributeError: if name and name.startswith('http'): return name except ElementNotFound: return Location.create(name=name.name).href if not \ search_only else None # Get all locations; tmp to support earlier 6.x versions. if name is not None: locations = [location for location in Search.objects.entry_point( 'location') if location.name == name] if not locations: return Location.create(name=name).href if not search_only \ else None return locations[0].href
Location finder by name. If location doesn't exist, create it and return the href :param str,Element name: location to resolve. If the location is by name, it will be retrieved or created, if href, returned and if Location, href returned. If None, settings an elements location to None will set it to the Default location. :param bool search_only: only search for the location, if not found do not create :return str href: href of location if search_only is not False :rtype: str or None
entailment
def zone_helper(zone): """ Zone finder by name. If zone doesn't exist, create it and return the href :param str zone: name of zone (if href, will be returned as is) :return str href: href of zone """ if zone is None: return None elif isinstance(zone, Zone): return zone.href elif zone.startswith('http'): return zone return Zone.get_or_create(name=zone).href
Zone finder by name. If zone doesn't exist, create it and return the href :param str zone: name of zone (if href, will be returned as is) :return str href: href of zone
entailment
def logical_intf_helper(interface): """ Logical Interface finder by name. Create if it doesn't exist. This is useful when adding logical interfaces to for inline or capture interfaces. :param interface: logical interface name :return str href: href of logical interface """ if interface is None: return LogicalInterface.get_or_create(name='default_eth').href elif isinstance(interface, LogicalInterface): return interface.href elif interface.startswith('http'): return interface return LogicalInterface.get_or_create(name=interface).href
Logical Interface finder by name. Create if it doesn't exist. This is useful when adding logical interfaces to for inline or capture interfaces. :param interface: logical interface name :return str href: href of logical interface
entailment
def change_password(self, password): """ Change user password. Change is committed immediately. :param str password: new password :return: None """ self.make_request( ModificationFailed, method='update', resource='change_password', params={'password': password})
Change user password. Change is committed immediately. :param str password: new password :return: None
entailment
def add_permission(self, permission): """ Add a permission to this Admin User. A role defines permissions that can be enabled or disabled. Elements define the target for permission operations and can be either Access Control Lists, Engines or Policy elements. Domain specifies where the access is granted. The Shared Domain is default unless specific domain provided. Change is committed at end of method call. :param permission: permission/s to add to admin user :type permission: list(Permission) :raises UpdateElementFailed: failed updating admin user :return: None """ if 'permissions' not in self.data: self.data['superuser'] = False self.data['permissions'] = {'permission':[]} for p in permission: self.data['permissions']['permission'].append(p.data) self.update()
Add a permission to this Admin User. A role defines permissions that can be enabled or disabled. Elements define the target for permission operations and can be either Access Control Lists, Engines or Policy elements. Domain specifies where the access is granted. The Shared Domain is default unless specific domain provided. Change is committed at end of method call. :param permission: permission/s to add to admin user :type permission: list(Permission) :raises UpdateElementFailed: failed updating admin user :return: None
entailment
def permissions(self): """ Return each permission role mapping for this Admin User. A permission role will have 3 fields: * Domain * Role (Viewer, Operator, etc) * Elements (Engines, Policies, or ACLs) :return: permissions as list :rtype: list(Permission) """ if 'permissions' in self.data: _permissions = self.data['permissions']['permission'] return [Permission(**perm) for perm in _permissions] return []
Return each permission role mapping for this Admin User. A permission role will have 3 fields: * Domain * Role (Viewer, Operator, etc) * Elements (Engines, Policies, or ACLs) :return: permissions as list :rtype: list(Permission)
entailment
def create(cls, name, local_admin=False, allow_sudo=False, superuser=False, enabled=True, engine_target=None, can_use_api=True, console_superuser=False, allowed_to_login_in_shared=True, comment=None): """ Create an admin user account. .. versionadded:: 0.6.2 Added can_use_api, console_superuser, and allowed_to_login_in_shared. Requires SMC >= SMC 6.4 :param str name: name of account :param bool local_admin: is a local admin only :param bool allow_sudo: allow sudo on engines :param bool can_use_api: can log in to SMC API :param bool console_superuser: can this user sudo via SSH/console :param bool allowed_to_login_in_shared: can this user log in to the shared domain :param bool superuser: is a super administrator :param bool enabled: is account enabled :param list engine_target: engine to allow remote access to :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: AdminUser """ engines = [] if engine_target is None else engine_target json = {'name': name, 'enabled': enabled, 'allow_sudo': allow_sudo, 'console_superuser': console_superuser, 'allowed_to_login_in_shared': allowed_to_login_in_shared, 'engine_target': engines, 'local_admin': local_admin, 'superuser': superuser, 'can_use_api': can_use_api, 'comment': comment} return ElementCreator(cls, json)
Create an admin user account. .. versionadded:: 0.6.2 Added can_use_api, console_superuser, and allowed_to_login_in_shared. Requires SMC >= SMC 6.4 :param str name: name of account :param bool local_admin: is a local admin only :param bool allow_sudo: allow sudo on engines :param bool can_use_api: can log in to SMC API :param bool console_superuser: can this user sudo via SSH/console :param bool allowed_to_login_in_shared: can this user log in to the shared domain :param bool superuser: is a super administrator :param bool enabled: is account enabled :param list engine_target: engine to allow remote access to :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: AdminUser
entailment
def change_engine_password(self, password): """ Change Engine password for engines on allowed list. :param str password: password for engine level :raises ModificationFailed: failed setting password on engine :return: None """ self.make_request( ModificationFailed, method='update', resource='change_engine_password', params={'password': password})
Change Engine password for engines on allowed list. :param str password: password for engine level :raises ModificationFailed: failed setting password on engine :return: None
entailment
def create(cls, name, enabled=True, superuser=True): """ Create a new API Client. Once client is created, you can create a new password by:: >>> client = ApiClient.create('myclient') >>> print(client) ApiClient(name=myclient) >>> client.change_password('mynewpassword') :param str name: name of client :param bool enabled: enable client :param bool superuser: is superuser account :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: ApiClient """ json = { 'enabled': enabled, 'name': name, 'superuser': superuser} return ElementCreator(cls, json)
Create a new API Client. Once client is created, you can create a new password by:: >>> client = ApiClient.create('myclient') >>> print(client) ApiClient(name=myclient) >>> client.change_password('mynewpassword') :param str name: name of client :param bool enabled: enable client :param bool superuser: is superuser account :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: ApiClient
entailment
def _create(cls, name, node_type, physical_interfaces, nodes=1, loopback_ndi=None, log_server_ref=None, domain_server_address=None, enable_antivirus=False, enable_gti=False, sidewinder_proxy_enabled=False, default_nat=False, location_ref=None, enable_ospf=None, ospf_profile=None, snmp_agent=None, comment=None): """ Create will return the engine configuration as a dict that is a representation of the engine. The creating class will also add engine specific requirements before constructing the request and sending to SMC (which will serialize the dict to json). :param name: name of engine :param str node_type: comes from class attribute of engine type :param dict physical_interfaces: physical interface list of dict :param int nodes: number of nodes for engine :param str log_server_ref: href of log server :param list domain_server_address: dns addresses """ node_list = [] for nodeid in range(1, nodes + 1): # start at nodeid=1 node_list.append(Node._create( name, node_type, nodeid, loopback_ndi)) domain_server_list = [] if domain_server_address: for num, server in enumerate(domain_server_address): try: domain_server = {'rank': num, 'ne_ref' : server.href} except AttributeError: domain_server = {'rank': num, 'value': server} domain_server_list.append(domain_server) # Set log server reference, if not explicitly provided if not log_server_ref and node_type is not 'virtual_fw_node': log_server_ref = LogServer.objects.first().href base_cfg = { 'name': name, 'nodes': node_list, 'domain_server_address': domain_server_list, 'log_server_ref': log_server_ref, 'physicalInterfaces': physical_interfaces} if enable_antivirus: antivirus = { 'antivirus': { 'antivirus_enabled': True, 'antivirus_update': 'daily', 'virus_log_level': 'stored', 'virus_mirror': 'update.nai.com/Products/CommonUpdater'}} base_cfg.update(antivirus) if enable_gti: gti = {'gti_settings': { 'file_reputation_context': 'gti_cloud_only'}} base_cfg.update(gti) if sidewinder_proxy_enabled: base_cfg.update(sidewinder_proxy_enabled=True) if default_nat: base_cfg.update(default_nat=True) if location_ref: base_cfg.update(location_ref=location_helper(location_ref) \ if location_ref else None) if snmp_agent: snmp_agent_ref = SNMPAgent(snmp_agent.pop('snmp_agent_ref')).href base_cfg.update( snmp_agent_ref=snmp_agent_ref, **snmp_agent) if enable_ospf: if not ospf_profile: # get default profile ospf_profile = OSPFProfile('Default OSPFv2 Profile').href ospf = {'dynamic_routing': { 'ospfv2': { 'enabled': True, 'ospfv2_profile_ref': ospf_profile} }} base_cfg.update(ospf) base_cfg.update(comment=comment) return base_cfg
Create will return the engine configuration as a dict that is a representation of the engine. The creating class will also add engine specific requirements before constructing the request and sending to SMC (which will serialize the dict to json). :param name: name of engine :param str node_type: comes from class attribute of engine type :param dict physical_interfaces: physical interface list of dict :param int nodes: number of nodes for engine :param str log_server_ref: href of log server :param list domain_server_address: dns addresses
entailment
def rename(self, name): """ Rename the firewall engine, nodes, and internal gateway (VPN gw) :return: None """ for node in self.nodes: node.rename(name) self.update(name=name) self.vpn.rename(name)
Rename the firewall engine, nodes, and internal gateway (VPN gw) :return: None
entailment
def location(self): """ The location for this engine. May be None if no specific location has been assigned. :param value: location to assign engine. Can be name, str href, or Location element. If name, it will be automatically created if a Location with the same name doesn't exist. :raises UpdateElementFailed: failure to update element :return: Location element or None """ location = Element.from_href(self.location_ref) if location and location.name == 'Default': return None return location
The location for this engine. May be None if no specific location has been assigned. :param value: location to assign engine. Can be name, str href, or Location element. If name, it will be automatically created if a Location with the same name doesn't exist. :raises UpdateElementFailed: failure to update element :return: Location element or None
entailment
def nodes(self): """ Return a list of child nodes of this engine. This can be used to iterate to obtain access to node level operations :: >>> print(list(engine.nodes)) [Node(name=myfirewall node 1)] >>> engine.nodes.get(0) Node(name=myfirewall node 1) :return: nodes for this engine :rtype: SubElementCollection(Node) """ resource = sub_collection( self.get_relation( 'nodes'), Node) resource._load_from_engine(self, 'nodes') return resource
Return a list of child nodes of this engine. This can be used to iterate to obtain access to node level operations :: >>> print(list(engine.nodes)) [Node(name=myfirewall node 1)] >>> engine.nodes.get(0) Node(name=myfirewall node 1) :return: nodes for this engine :rtype: SubElementCollection(Node)
entailment
def permissions(self): """ Retrieve the permissions for this engine instance. :: >>> from smc.core.engine import Engine >>> engine = Engine('myfirewall') >>> for x in engine.permissions: ... print(x) ... AccessControlList(name=ALL Elements) AccessControlList(name=ALL Firewalls) :raises UnsupportedEngineFeature: requires SMC version >= 6.1 :return: access control list permissions :rtype: list(AccessControlList) """ acl_list = list(AccessControlList.objects.all()) def acl_map(elem_href): for elem in acl_list: if elem.href == elem_href: return elem acls = self.make_request( UnsupportedEngineFeature, resource='permissions') for acl in acls['granted_access_control_list']: yield(acl_map(acl))
Retrieve the permissions for this engine instance. :: >>> from smc.core.engine import Engine >>> engine = Engine('myfirewall') >>> for x in engine.permissions: ... print(x) ... AccessControlList(name=ALL Elements) AccessControlList(name=ALL Firewalls) :raises UnsupportedEngineFeature: requires SMC version >= 6.1 :return: access control list permissions :rtype: list(AccessControlList)
entailment
def pending_changes(self): """ Pending changes provides insight into changes on an engine that are pending approval or disapproval. Feature requires SMC >= v6.2. :raises UnsupportedEngineFeature: SMC version >= 6.2 is required to support pending changes :rtype: PendingChanges """ if 'pending_changes' in self.data.links: return PendingChanges(self) raise UnsupportedEngineFeature( 'Pending changes is an unsupported feature on this engine: {}' .format(self.type))
Pending changes provides insight into changes on an engine that are pending approval or disapproval. Feature requires SMC >= v6.2. :raises UnsupportedEngineFeature: SMC version >= 6.2 is required to support pending changes :rtype: PendingChanges
entailment
def alias_resolving(self): """ Alias definitions with resolved values as defined on this engine. Aliases can be used in rules to simplify multiple object creation :: fw = Engine('myfirewall') for alias in fw.alias_resolving(): print(alias, alias.resolved_value) ... (Alias(name=$$ Interface ID 0.ip), [u'10.10.0.1']) (Alias(name=$$ Interface ID 0.net), [u'10.10.0.0/24']) (Alias(name=$$ Interface ID 1.ip), [u'10.10.10.1']) :return: generator of aliases :rtype: Alias """ alias_list = list(Alias.objects.all()) for alias in self.make_request(resource='alias_resolving'): yield Alias._from_engine(alias, alias_list)
Alias definitions with resolved values as defined on this engine. Aliases can be used in rules to simplify multiple object creation :: fw = Engine('myfirewall') for alias in fw.alias_resolving(): print(alias, alias.resolved_value) ... (Alias(name=$$ Interface ID 0.ip), [u'10.10.0.1']) (Alias(name=$$ Interface ID 0.net), [u'10.10.0.0/24']) (Alias(name=$$ Interface ID 1.ip), [u'10.10.10.1']) :return: generator of aliases :rtype: Alias
entailment
def blacklist_bulk(self, blacklist): """ Add blacklist entries to the engine node in bulk. For blacklist to work, you must also create a rule with action "Apply Blacklist". First create your blacklist entries using :class:`smc.elements.other.Blacklist` then provide the blacklist to this method. :param blacklist Blacklist: pre-configured blacklist entries .. note:: This method requires SMC version >= 6.4 """ self.make_request( EngineCommandFailed, method='create', resource='blacklist', json=blacklist.entries)
Add blacklist entries to the engine node in bulk. For blacklist to work, you must also create a rule with action "Apply Blacklist". First create your blacklist entries using :class:`smc.elements.other.Blacklist` then provide the blacklist to this method. :param blacklist Blacklist: pre-configured blacklist entries .. note:: This method requires SMC version >= 6.4
entailment
def blacklist_show(self, **kw): """ .. versionadded:: 0.5.6 Requires pip install smc-python-monitoring Blacklist show requires that you install the smc-python-monitoring package. To obtain blacklist entries from the engine you need to use this extension to plumb the websocket to the session. If you need more granular controls over the blacklist such as filtering by source and destination address, use the smc-python-monitoring package directly. Blacklist entries that are returned from this generator have a delete() method that can be called to simplify removing entries. A simple query would look like:: for bl_entry in engine.blacklist_show(): print(bl_entry) :param kw: keyword arguments passed to blacklist query. Common setting is to pass max_recv=20, which specifies how many "receive" batches will be retrieved from the SMC for the query. At most, 200 results can be returned in a single query. If max_recv=5, then 1000 results can be returned if they exist. If less than 1000 events are available, the call will be blocking until 5 receives has been reached. :return: generator of results :rtype: :class:`smc_monitoring.monitors.blacklist.BlacklistEntry` """ try: from smc_monitoring.monitors.blacklist import BlacklistQuery except ImportError: pass else: query = BlacklistQuery(self.name) for record in query.fetch_as_element(**kw): yield record
.. versionadded:: 0.5.6 Requires pip install smc-python-monitoring Blacklist show requires that you install the smc-python-monitoring package. To obtain blacklist entries from the engine you need to use this extension to plumb the websocket to the session. If you need more granular controls over the blacklist such as filtering by source and destination address, use the smc-python-monitoring package directly. Blacklist entries that are returned from this generator have a delete() method that can be called to simplify removing entries. A simple query would look like:: for bl_entry in engine.blacklist_show(): print(bl_entry) :param kw: keyword arguments passed to blacklist query. Common setting is to pass max_recv=20, which specifies how many "receive" batches will be retrieved from the SMC for the query. At most, 200 results can be returned in a single query. If max_recv=5, then 1000 results can be returned if they exist. If less than 1000 events are available, the call will be blocking until 5 receives has been reached. :return: generator of results :rtype: :class:`smc_monitoring.monitors.blacklist.BlacklistEntry`
entailment
def add_route(self, gateway, network): """ Add a route to engine. Specify gateway and network. If this is the default gateway, use a network address of 0.0.0.0/0. .. note: This will fail if the gateway provided does not have a corresponding interface on the network. :param str gateway: gateway of an existing interface :param str network: network address in cidr format :raises EngineCommandFailed: invalid route, possibly no network :return: None """ self.make_request( EngineCommandFailed, method='create', resource='add_route', params={'gateway': gateway, 'network': network})
Add a route to engine. Specify gateway and network. If this is the default gateway, use a network address of 0.0.0.0/0. .. note: This will fail if the gateway provided does not have a corresponding interface on the network. :param str gateway: gateway of an existing interface :param str network: network address in cidr format :raises EngineCommandFailed: invalid route, possibly no network :return: None
entailment
def routing_monitoring(self): """ Return route table for the engine, including gateway, networks and type of route (dynamic, static). Calling this can take a few seconds to retrieve routes from the engine. Find all routes for engine resource:: >>> engine = Engine('sg_vm') >>> for route in engine.routing_monitoring: ... route ... Route(route_network=u'0.0.0.0', route_netmask=0, route_gateway=u'10.0.0.1', route_type=u'Static', dst_if=1, src_if=-1) ... :raises EngineCommandFailed: routes cannot be retrieved :return: list of route elements :rtype: SerializedIterable(Route) """ try: result = self.make_request( EngineCommandFailed, resource='routing_monitoring') return Route(result) except SMCConnectionError: raise EngineCommandFailed('Timed out waiting for routes')
Return route table for the engine, including gateway, networks and type of route (dynamic, static). Calling this can take a few seconds to retrieve routes from the engine. Find all routes for engine resource:: >>> engine = Engine('sg_vm') >>> for route in engine.routing_monitoring: ... route ... Route(route_network=u'0.0.0.0', route_netmask=0, route_gateway=u'10.0.0.1', route_type=u'Static', dst_if=1, src_if=-1) ... :raises EngineCommandFailed: routes cannot be retrieved :return: list of route elements :rtype: SerializedIterable(Route)
entailment
def virtual_resource(self): """ Available on a Master Engine only. To get all virtual resources call:: engine.virtual_resource.all() :raises UnsupportedEngineFeature: master engine only :rtype: CreateCollection(VirtualResource) """ resource = create_collection( self.get_relation( 'virtual_resources', UnsupportedEngineFeature), VirtualResource) resource._load_from_engine(self, 'virtualResources') return resource
Available on a Master Engine only. To get all virtual resources call:: engine.virtual_resource.all() :raises UnsupportedEngineFeature: master engine only :rtype: CreateCollection(VirtualResource)
entailment
def add_interface(self, interface): """ Add interface is a lower level option to adding interfaces directly to the engine. The interface is expected to be an instance of Layer3PhysicalInterface, Layer2PhysicalInterface, TunnelInterface, or ClusterInterface. The engines instance cache is flushed after this call is made to provide an updated cache after modification. .. seealso:: :class:`smc.core.engine.interface.update_or_create` :param PhysicalInterface,TunnelInterface interface: instance of pre-created interface :return: None """ self.make_request( EngineCommandFailed, method='create', href=self.get_relation(interface.typeof), json=interface) self._del_cache()
Add interface is a lower level option to adding interfaces directly to the engine. The interface is expected to be an instance of Layer3PhysicalInterface, Layer2PhysicalInterface, TunnelInterface, or ClusterInterface. The engines instance cache is flushed after this call is made to provide an updated cache after modification. .. seealso:: :class:`smc.core.engine.interface.update_or_create` :param PhysicalInterface,TunnelInterface interface: instance of pre-created interface :return: None
entailment
def refresh(self, timeout=3, wait_for_finish=False, **kw): """ Refresh existing policy on specified device. This is an asynchronous call that will return a 'follower' link that can be queried to determine the status of the task. :: poller = engine.refresh() while not poller.done(): poller.wait(5) print('Percentage complete {}%'.format(poller.task.progress)) :param int timeout: timeout between queries :raises TaskRunFailed: refresh failed, possibly locked policy :rtype: TaskOperationPoller """ return Task.execute(self, 'refresh', timeout=timeout, wait_for_finish=wait_for_finish, **kw)
Refresh existing policy on specified device. This is an asynchronous call that will return a 'follower' link that can be queried to determine the status of the task. :: poller = engine.refresh() while not poller.done(): poller.wait(5) print('Percentage complete {}%'.format(poller.task.progress)) :param int timeout: timeout between queries :raises TaskRunFailed: refresh failed, possibly locked policy :rtype: TaskOperationPoller
entailment
def generate_snapshot(self, filename='snapshot.zip'): """ Generate and retrieve a policy snapshot from the engine This is blocking as file is downloaded :param str filename: name of file to save file to, including directory path :raises EngineCommandFailed: snapshot failed, possibly invalid filename specified :return: None """ try: self.make_request( EngineCommandFailed, resource='generate_snapshot', filename=filename) except IOError as e: raise EngineCommandFailed( 'Generate snapshot failed: {}'.format(e))
Generate and retrieve a policy snapshot from the engine This is blocking as file is downloaded :param str filename: name of file to save file to, including directory path :raises EngineCommandFailed: snapshot failed, possibly invalid filename specified :return: None
entailment
def add_site(self, name, site_elements=None): """ Add a VPN site with site elements to this engine. VPN sites identify the sites with protected networks to be included in the VPN. Add a network and new VPN site:: >>> net = Network.get_or_create(name='wireless', ipv4_network='192.168.5.0/24') >>> engine.vpn.add_site(name='wireless', site_elements=[net]) VPNSite(name=wireless) >>> list(engine.vpn.sites) [VPNSite(name=dingo - Primary Site), VPNSite(name=wireless)] :param str name: name for VPN site :param list site_elements: network elements for VPN site :type site_elements: list(str,Element) :raises ElementNotFound: if site element is not found :raises UpdateElementFailed: failed to add vpn site :rtype: VPNSite .. note:: Update is immediate for this operation. """ site_elements = site_elements if site_elements else [] return self.sites.create( name, site_elements)
Add a VPN site with site elements to this engine. VPN sites identify the sites with protected networks to be included in the VPN. Add a network and new VPN site:: >>> net = Network.get_or_create(name='wireless', ipv4_network='192.168.5.0/24') >>> engine.vpn.add_site(name='wireless', site_elements=[net]) VPNSite(name=wireless) >>> list(engine.vpn.sites) [VPNSite(name=dingo - Primary Site), VPNSite(name=wireless)] :param str name: name for VPN site :param list site_elements: network elements for VPN site :type site_elements: list(str,Element) :raises ElementNotFound: if site element is not found :raises UpdateElementFailed: failed to add vpn site :rtype: VPNSite .. note:: Update is immediate for this operation.
entailment
def generate_certificate(self, common_name, public_key_algorithm='rsa', signature_algorithm='rsa_sha_512', key_length=2048, signing_ca=None): """ Generate an internal gateway certificate used for VPN on this engine. Certificate request should be an instance of VPNCertificate. :param: str common_name: common name for certificate :param str public_key_algorithm: public key type to use. Valid values rsa, dsa, ecdsa. :param str signature_algorithm: signature algorithm. Valid values dsa_sha_1, dsa_sha_224, dsa_sha_256, rsa_md5, rsa_sha_1, rsa_sha_256, rsa_sha_384, rsa_sha_512, ecdsa_sha_1, ecdsa_sha_256, ecdsa_sha_384, ecdsa_sha_512. (Default: rsa_sha_512) :param int key_length: length of key. Key length depends on the key type. For example, RSA keys can be 1024, 2048, 3072, 4096. See SMC documentation for more details. :param str,VPNCertificateCA signing_ca: by default will use the internal RSA CA :raises CertificateError: error generating certificate :return: GatewayCertificate """ return GatewayCertificate._create(self, common_name, public_key_algorithm, signature_algorithm, key_length, signing_ca)
Generate an internal gateway certificate used for VPN on this engine. Certificate request should be an instance of VPNCertificate. :param: str common_name: common name for certificate :param str public_key_algorithm: public key type to use. Valid values rsa, dsa, ecdsa. :param str signature_algorithm: signature algorithm. Valid values dsa_sha_1, dsa_sha_224, dsa_sha_256, rsa_md5, rsa_sha_1, rsa_sha_256, rsa_sha_384, rsa_sha_512, ecdsa_sha_1, ecdsa_sha_256, ecdsa_sha_384, ecdsa_sha_512. (Default: rsa_sha_512) :param int key_length: length of key. Key length depends on the key type. For example, RSA keys can be 1024, 2048, 3072, 4096. See SMC documentation for more details. :param str,VPNCertificateCA signing_ca: by default will use the internal RSA CA :raises CertificateError: error generating certificate :return: GatewayCertificate
entailment
def create(self, name, vfw_id, domain='Shared Domain', show_master_nic=False, connection_limit=0, comment=None): """ Create a new virtual resource. Called through engine reference:: engine.virtual_resource.create(....) :param str name: name of virtual resource :param int vfw_id: virtual fw identifier :param str domain: name of domain to install, (default Shared) :param bool show_master_nic: whether to show the master engine NIC ID's in the virtual instance :param int connection_limit: whether to limit number of connections for this instance :return: href of new virtual resource :rtype: str """ allocated_domain = domain_helper(domain) json = {'name': name, 'connection_limit': connection_limit, 'show_master_nic': show_master_nic, 'vfw_id': vfw_id, 'comment': comment, 'allocated_domain_ref': allocated_domain} return ElementCreator(self.__class__, json=json, href=self.href)
Create a new virtual resource. Called through engine reference:: engine.virtual_resource.create(....) :param str name: name of virtual resource :param int vfw_id: virtual fw identifier :param str domain: name of domain to install, (default Shared) :param bool show_master_nic: whether to show the master engine NIC ID's in the virtual instance :param int connection_limit: whether to limit number of connections for this instance :return: href of new virtual resource :rtype: str
entailment
def enable(self, snmp_agent, snmp_location=None, snmp_interface=None): """ Enable SNMP on the engine. Specify a list of interfaces by ID to enable only on those interfaces. Only interfaces that have NDI's are supported. :param str,Element snmp_agent: the SNMP agent reference for this engine :param str snmp_location: the SNMP location identifier for the engine :param list snmp_interface: list of interface IDs to enable SNMP :raises ElementNotFound: unable to resolve snmp_agent :raises InterfaceNotFound: specified interface by ID not found """ agent = element_resolver(snmp_agent) snmp_interface = [] if not snmp_interface else snmp_interface interfaces = self._iface_dict(snmp_interface) self.engine.data.update( snmp_agent_ref=agent, snmp_location=snmp_location if snmp_location else '', snmp_interface=interfaces)
Enable SNMP on the engine. Specify a list of interfaces by ID to enable only on those interfaces. Only interfaces that have NDI's are supported. :param str,Element snmp_agent: the SNMP agent reference for this engine :param str snmp_location: the SNMP location identifier for the engine :param list snmp_interface: list of interface IDs to enable SNMP :raises ElementNotFound: unable to resolve snmp_agent :raises InterfaceNotFound: specified interface by ID not found
entailment
def update_configuration(self, **kwargs): """ Update the SNMP configuration using any kwargs supported in the `enable` constructor. Return whether a change was made. You must call update on the engine to commit any changes. :param dict kwargs: keyword arguments supported by enable constructor :rtype: bool """ updated = False if 'snmp_agent' in kwargs: kwargs.update(snmp_agent_ref=kwargs.pop('snmp_agent')) snmp_interface = kwargs.pop('snmp_interface', None) for name, value in kwargs.items(): _value = element_resolver(value) if getattr(self.engine, name, None) != _value: self.engine.data[name] = _value updated = True if snmp_interface is not None: _snmp_interface = getattr(self.engine, 'snmp_interface', []) if not len(snmp_interface) and len(_snmp_interface): self.engine.data.update(snmp_interface=[]) updated = True elif len(snmp_interface): if set(self._nicids) ^ set(map(str, snmp_interface)): self.engine.data.update( snmp_interface=self._iface_dict(snmp_interface)) updated = True return updated
Update the SNMP configuration using any kwargs supported in the `enable` constructor. Return whether a change was made. You must call update on the engine to commit any changes. :param dict kwargs: keyword arguments supported by enable constructor :rtype: bool
entailment
def interface(self): """ Return a list of physical interfaces that the SNMP agent is bound to. :rtype: list(PhysicalInterface) """ nics = set([nic.get('nicid') for nic in \ getattr(self.engine, 'snmp_interface', [])]) return [self.engine.interface.get(nic) for nic in nics]
Return a list of physical interfaces that the SNMP agent is bound to. :rtype: list(PhysicalInterface)
entailment
def enable(self, interface_id, dns_relay_profile=None): """ Enable the DNS Relay service on this engine. :param int interface_id: interface id to enable relay :param str,DNSRelayProfile dns_relay_profile: DNSRelayProfile element or str href :raises EngineCommandFailed: interface not found :raises ElementNotFound: profile not found :return: None """ if not dns_relay_profile: # Use default href = DNSRelayProfile('Cache Only').href else: href = element_resolver(dns_relay_profile) intf = self.engine.interface.get(interface_id) self.engine.data.update(dns_relay_profile_ref=href) self.engine.data.update(dns_relay_interface=intf.ndi_interfaces)
Enable the DNS Relay service on this engine. :param int interface_id: interface id to enable relay :param str,DNSRelayProfile dns_relay_profile: DNSRelayProfile element or str href :raises EngineCommandFailed: interface not found :raises ElementNotFound: profile not found :return: None
entailment
def disable(self): """ Disable DNS Relay on this engine :return: None """ self.engine.data.update(dns_relay_interface=[]) self.engine.data.pop('dns_relay_profile_ref', None)
Disable DNS Relay on this engine :return: None
entailment
def remove(self, values): """ Remove DNS entries from this ranked DNS list. A DNS entry can be either a raw IP Address, or an element of type :class:`smc.elements.network.Host` or :class:`smc.elements.servers.DNSServer`. :param list values: list of IP addresses, Host and/or DNSServer elements. :return: None """ removables = [] for value in values: if value in self: removables.append(value) if removables: self.entries[:] = [entry._asdict() for entry in self if entry.value not in removables and not entry.element in removables] # Rerank to maintain order for i, entry in enumerate(self.entries): entry.update(rank='{}'.format(i))
Remove DNS entries from this ranked DNS list. A DNS entry can be either a raw IP Address, or an element of type :class:`smc.elements.network.Host` or :class:`smc.elements.servers.DNSServer`. :param list values: list of IP addresses, Host and/or DNSServer elements. :return: None
entailment
def enable(self, policy): """ Set a layer 2 interface policy. :param str,Element policy: an InterfacePolicy or str href :raises LoadPolicyFailed: Invalid policy specified :raises ElementNotFound: InterfacePolicy not found :return: None """ if hasattr(policy, 'href'): if not isinstance(policy, InterfacePolicy): raise LoadPolicyFailed('Invalid policy type specified. The policy' 'type must be InterfacePolicy') self.update(l2_interface_policy_ref=element_resolver(policy))
Set a layer 2 interface policy. :param str,Element policy: an InterfacePolicy or str href :raises LoadPolicyFailed: Invalid policy specified :raises ElementNotFound: InterfacePolicy not found :return: None
entailment
def create(cls, name, template='High-Security IPS Template'): """ Create an IPS Policy :param str name: Name of policy :param str template: name of template :raises CreatePolicyFailed: policy failed to create :return: IPSPolicy """ try: if cls.typeof == 'ips_template_policy' and template is None: fw_template = None else: fw_template = IPSTemplatePolicy(template).href except ElementNotFound: raise LoadPolicyFailed( 'Cannot find specified firewall template: {}'.format(template)) json = { 'name': name, 'template': fw_template} try: return ElementCreator(cls, json) except CreateElementFailed as err: raise CreatePolicyFailed(err)
Create an IPS Policy :param str name: Name of policy :param str template: name of template :raises CreatePolicyFailed: policy failed to create :return: IPSPolicy
entailment
def get(self, *args, **kwargs): """ Get an element from the iterable by an arg or kwarg. Args can be a single positional argument that is an index value to retrieve. If the specified index is out of range, None is returned. Otherwise use kwargs to provide a key/value. The key is expected to be a valid attribute of the iterated class. For example, to get an element that has a attribute name of 'foo', pass name='foo'. :raises ValueError: An argument was missing :return: the specified item, type is based on what is returned by this iterable, may be None """ if self: if args: index = args[0] if index <= len(self) -1: return self[args[0]] return None elif kwargs: key, value = kwargs.popitem() for item in self.items: if getattr(item, key, None) == value: return item else: raise ValueError('Missing argument. You must provide an ' 'arg or kwarg to fetch an element from the collection.')
Get an element from the iterable by an arg or kwarg. Args can be a single positional argument that is an index value to retrieve. If the specified index is out of range, None is returned. Otherwise use kwargs to provide a key/value. The key is expected to be a valid attribute of the iterated class. For example, to get an element that has a attribute name of 'foo', pass name='foo'. :raises ValueError: An argument was missing :return: the specified item, type is based on what is returned by this iterable, may be None
entailment
def upload_as_zip(name, filename): """ Upload an IPList as a zip file. Useful when IPList is very large. This is the default upload format for IPLists. :param str name: name of IPList :param str filename: name of zip file to upload, full path :return: None """ location = list(IPList.objects.filter(name)) if location: iplist = location[0] return iplist.upload(filename=filename)
Upload an IPList as a zip file. Useful when IPList is very large. This is the default upload format for IPLists. :param str name: name of IPList :param str filename: name of zip file to upload, full path :return: None
entailment
def upload_as_text(name, filename): """ Upload the IPList as text from a file. :param str name: name of IPList :param str filename: name of text file to upload :return: None """ location = list(IPList.objects.filter(name)) if location: iplist = location[0] return iplist.upload(filename=filename, as_type='txt')
Upload the IPList as text from a file. :param str name: name of IPList :param str filename: name of text file to upload :return: None
entailment
def upload_as_json(name, mylist): """ Upload the IPList as json payload. :param str name: name of IPList :param list: list of IPList entries :return: None """ location = list(IPList.objects.filter(name)) if location: iplist = location[0] return iplist.upload(json=mylist, as_type='json')
Upload the IPList as json payload. :param str name: name of IPList :param list: list of IPList entries :return: None
entailment
def download_as_zip(name, filename): """ Download IPList with zip compression. Recommended for IPLists of larger sizes. This is the default format for downloading IPLists. :param str name: name of IPList :param str filename: name of filename for IPList """ location = list(IPList.objects.filter(name)) if location: iplist = location[0] return iplist.download(filename=filename)
Download IPList with zip compression. Recommended for IPLists of larger sizes. This is the default format for downloading IPLists. :param str name: name of IPList :param str filename: name of filename for IPList
entailment
def download_as_text(name, filename): """ Download IPList as text to specified filename. :param str name: name of IPList :param str filename: name of file for IPList download """ location = list(IPList.objects.filter(name)) if location: iplist = location[0] return iplist.download(filename=filename, as_type='txt')
Download IPList as text to specified filename. :param str name: name of IPList :param str filename: name of file for IPList download
entailment
def download_as_json(name): """ Download IPList as json. This would allow for easily manipulation of the IPList, but generally recommended only for smaller lists :param str name: name of IPList :return: None """ location = list(IPList.objects.filter(name)) if location: iplist = location[0] return iplist.download(as_type='json')
Download IPList as json. This would allow for easily manipulation of the IPList, but generally recommended only for smaller lists :param str name: name of IPList :return: None
entailment
def create_iplist_with_data(name, iplist): """ Create an IPList with initial list contents. :param str name: name of IPList :param list iplist: list of IPList IP's, networks, etc :return: href of list location """ iplist = IPList.create(name=name, iplist=iplist) return iplist
Create an IPList with initial list contents. :param str name: name of IPList :param list iplist: list of IPList IP's, networks, etc :return: href of list location
entailment
def enable(self, ospf_profile=None, router_id=None): """ Enable OSPF on this engine. For master engines, enable OSPF on the virtual firewall. Once enabled on the engine, add an OSPF area to an interface:: engine.dynamic_routing.ospf.enable() interface = engine.routing.get(0) interface.add_ospf_area(OSPFArea('myarea')) :param str,OSPFProfile ospf_profile: OSPFProfile element or str href; if None, use default profile :param str router_id: single IP address router ID :raises ElementNotFound: OSPF profile not found :return: None """ ospf_profile = element_resolver(ospf_profile) if ospf_profile \ else OSPFProfile('Default OSPFv2 Profile').href self.data.update( enabled=True, ospfv2_profile_ref=ospf_profile, router_id=router_id)
Enable OSPF on this engine. For master engines, enable OSPF on the virtual firewall. Once enabled on the engine, add an OSPF area to an interface:: engine.dynamic_routing.ospf.enable() interface = engine.routing.get(0) interface.add_ospf_area(OSPFArea('myarea')) :param str,OSPFProfile ospf_profile: OSPFProfile element or str href; if None, use default profile :param str router_id: single IP address router ID :raises ElementNotFound: OSPF profile not found :return: None
entailment
def update_configuration(self, **kwargs): """ Update the OSPF configuration using kwargs that match the `enable` constructor. :param dict kwargs: keyword arguments matching enable constructor. :return: whether change was made :rtype: bool """ updated = False if 'ospf_profile' in kwargs: kwargs.update(ospfv2_profile_ref=kwargs.pop('ospf_profile')) for name, value in kwargs.items(): _value = element_resolver(value) if self.data.get(name) != _value: self.data[name] = _value updated = True return updated
Update the OSPF configuration using kwargs that match the `enable` constructor. :param dict kwargs: keyword arguments matching enable constructor. :return: whether change was made :rtype: bool
entailment
def create(cls, name, interface_settings_ref=None, area_id=1, area_type='normal', outbound_filters=None, inbound_filters=None, shortcut_capable_area=False, ospfv2_virtual_links_endpoints_container=None, ospf_abr_substitute_container=None, comment=None, **kwargs): """ Create a new OSPF Area :param str name: name of OSPFArea configuration :param str,OSPFInterfaceSetting interface_settings_ref: an OSPFInterfaceSetting element or href. If None, uses the default system profile :param str name: area id :param str area_type: \|normal\|stub\|not_so_stubby\|totally_stubby\| totally_not_so_stubby :param list outbound_filters: reference to an IPAccessList and or IPPrefixList. You can only have one outbound prefix or access list :param list inbound_filters: reference to an IPAccessList and or IPPrefixList. You can only have one outbound prefix or access list :param shortcut_capable_area: True|False :param list ospfv2_virtual_links_endpoints_container: virtual link endpoints :param list ospf_abr_substitute_container: substitute types: \|aggregate\|not_advertise\|substitute_with :param str comment: optional comment :raises CreateElementFailed: failed to create with reason :rtype: OSPFArea """ interface_settings_ref = element_resolver(interface_settings_ref) or \ OSPFInterfaceSetting('Default OSPFv2 Interface Settings').href if 'inbound_filters_ref' in kwargs: inbound_filters = kwargs.get('inbound_filters_ref') if 'outbound_filters_ref' in kwargs: outbound_filters = kwargs.get('outbound_filters_ref') json = {'name': name, 'area_id': area_id, 'area_type': area_type, 'comment': comment, 'inbound_filters_ref': element_resolver(inbound_filters), 'interface_settings_ref': interface_settings_ref, 'ospf_abr_substitute_container': ospf_abr_substitute_container, 'ospfv2_virtual_links_endpoints_container': ospfv2_virtual_links_endpoints_container, 'outbound_filters_ref': element_resolver(outbound_filters), 'shortcut_capable_area': shortcut_capable_area} return ElementCreator(cls, json)
Create a new OSPF Area :param str name: name of OSPFArea configuration :param str,OSPFInterfaceSetting interface_settings_ref: an OSPFInterfaceSetting element or href. If None, uses the default system profile :param str name: area id :param str area_type: \|normal\|stub\|not_so_stubby\|totally_stubby\| totally_not_so_stubby :param list outbound_filters: reference to an IPAccessList and or IPPrefixList. You can only have one outbound prefix or access list :param list inbound_filters: reference to an IPAccessList and or IPPrefixList. You can only have one outbound prefix or access list :param shortcut_capable_area: True|False :param list ospfv2_virtual_links_endpoints_container: virtual link endpoints :param list ospf_abr_substitute_container: substitute types: \|aggregate\|not_advertise\|substitute_with :param str comment: optional comment :raises CreateElementFailed: failed to create with reason :rtype: OSPFArea
entailment
def create(cls, name, dead_interval=40, hello_interval=10, hello_interval_type='normal', dead_multiplier=1, mtu_mismatch_detection=True, retransmit_interval=5, router_priority=1, transmit_delay=1, authentication_type=None, password=None, key_chain_ref=None): """ Create custom OSPF interface settings profile :param str name: name of interface settings :param int dead_interval: in seconds :param str hello_interval: in seconds :param str hello_interval_type: \|normal\|fast_hello :param int dead_multipler: fast hello packet multipler :param bool mtu_mismatch_detection: True|False :param int retransmit_interval: in seconds :param int router_priority: set priority :param int transmit_delay: in seconds :param str authentication_type: \|password\|message_digest :param str password: max 8 chars (required when authentication_type='password') :param str,Element key_chain_ref: OSPFKeyChain (required when authentication_type='message_digest') :raises CreateElementFailed: create failed with reason :return: instance with meta :rtype: OSPFInterfaceSetting """ json = {'name': name, 'authentication_type': authentication_type, 'password': password, 'key_chain_ref': element_resolver(key_chain_ref), 'dead_interval': dead_interval, 'dead_multiplier': dead_multiplier, 'hello_interval': hello_interval, 'hello_interval_type': hello_interval_type, 'mtu_mismatch_detection': mtu_mismatch_detection, 'retransmit_interval': retransmit_interval, 'router_priority': router_priority, 'transmit_delay': transmit_delay} return ElementCreator(cls, json)
Create custom OSPF interface settings profile :param str name: name of interface settings :param int dead_interval: in seconds :param str hello_interval: in seconds :param str hello_interval_type: \|normal\|fast_hello :param int dead_multipler: fast hello packet multipler :param bool mtu_mismatch_detection: True|False :param int retransmit_interval: in seconds :param int router_priority: set priority :param int transmit_delay: in seconds :param str authentication_type: \|password\|message_digest :param str password: max 8 chars (required when authentication_type='password') :param str,Element key_chain_ref: OSPFKeyChain (required when authentication_type='message_digest') :raises CreateElementFailed: create failed with reason :return: instance with meta :rtype: OSPFInterfaceSetting
entailment
def create(cls, name, key_chain_entry): """ Create a key chain with list of keys Key_chain_entry format is:: [{'key': 'xxxx', 'key_id': 1-255, 'send_key': True|False}] :param str name: Name of key chain :param list key_chain_entry: list of key chain entries :raises CreateElementFailed: create failed with reason :return: instance with meta :rtype: OSPFKeyChain """ key_chain_entry = key_chain_entry or [] json = {'name': name, 'ospfv2_key_chain_entry': key_chain_entry} return ElementCreator(cls, json)
Create a key chain with list of keys Key_chain_entry format is:: [{'key': 'xxxx', 'key_id': 1-255, 'send_key': True|False}] :param str name: Name of key chain :param list key_chain_entry: list of key chain entries :raises CreateElementFailed: create failed with reason :return: instance with meta :rtype: OSPFKeyChain
entailment
def create(cls, name, domain_settings_ref=None, external_distance=110, inter_distance=110, intra_distance=110, redistribution_entry=None, default_metric=None, comment=None): """ Create an OSPF Profile. If providing a list of redistribution entries, provide in the following dict format: {'enabled': boolean, 'metric_type': 'external_1' or 'external_2', 'metric': 2, 'type': 'kernel'} Valid types for redistribution entries are: kernel, static, connected, bgp, and default_originate. You can also provide a 'filter' key with either an IPAccessList or RouteMap element to use for further access control on the redistributed route type. If metric_type is not provided, external_1 (E1) will be used. An example of a redistribution_entry would be:: {u'enabled': True, u'metric': 123, u'metric_type': u'external_2', u'filter': RouteMap('myroutemap'), u'type': u'static'} :param str name: name of profile :param str,OSPFDomainSetting domain_settings_ref: OSPFDomainSetting element or href :param int external_distance: route metric (E1-E2) :param int inter_distance: routes learned from different areas (O IA) :param int intra_distance: routes learned from same area (O) :param list redistribution_entry: how to redistribute the OSPF routes. :raises CreateElementFailed: create failed with reason :rtype: OSPFProfile """ json = {'name': name, 'external_distance': external_distance, 'inter_distance': inter_distance, 'intra_distance': intra_distance, 'default_metric': default_metric, 'comment': comment} if redistribution_entry: json.update(redistribution_entry= _format_redist_entry(redistribution_entry)) domain_settings_ref = element_resolver(domain_settings_ref) or \ OSPFDomainSetting('Default OSPFv2 Domain Settings').href json.update(domain_settings_ref=domain_settings_ref) return ElementCreator(cls, json)
Create an OSPF Profile. If providing a list of redistribution entries, provide in the following dict format: {'enabled': boolean, 'metric_type': 'external_1' or 'external_2', 'metric': 2, 'type': 'kernel'} Valid types for redistribution entries are: kernel, static, connected, bgp, and default_originate. You can also provide a 'filter' key with either an IPAccessList or RouteMap element to use for further access control on the redistributed route type. If metric_type is not provided, external_1 (E1) will be used. An example of a redistribution_entry would be:: {u'enabled': True, u'metric': 123, u'metric_type': u'external_2', u'filter': RouteMap('myroutemap'), u'type': u'static'} :param str name: name of profile :param str,OSPFDomainSetting domain_settings_ref: OSPFDomainSetting element or href :param int external_distance: route metric (E1-E2) :param int inter_distance: routes learned from different areas (O IA) :param int intra_distance: routes learned from same area (O) :param list redistribution_entry: how to redistribute the OSPF routes. :raises CreateElementFailed: create failed with reason :rtype: OSPFProfile
entailment
def create(cls, name, abr_type='cisco', auto_cost_bandwidth=100, deprecated_algorithm=False, initial_delay=200, initial_hold_time=1000, max_hold_time=10000, shutdown_max_metric_lsa=0, startup_max_metric_lsa=0): """ Create custom Domain Settings Domain settings are referenced by an OSPFProfile :param str name: name of custom domain settings :param str abr_type: cisco|shortcut|standard :param int auto_cost_bandwidth: Mbits/s :param bool deprecated_algorithm: RFC 1518 compatibility :param int initial_delay: in milliseconds :param int initial_hold_type: in milliseconds :param int max_hold_time: in milliseconds :param int shutdown_max_metric_lsa: in seconds :param int startup_max_metric_lsa: in seconds :raises CreateElementFailed: create failed with reason :return: instance with meta :rtype: OSPFDomainSetting """ json = {'name': name, 'abr_type': abr_type, 'auto_cost_bandwidth': auto_cost_bandwidth, 'deprecated_algorithm': deprecated_algorithm, 'initial_delay': initial_delay, 'initial_hold_time': initial_hold_time, 'max_hold_time': max_hold_time, 'shutdown_max_metric_lsa': shutdown_max_metric_lsa, 'startup_max_metric_lsa': startup_max_metric_lsa} return ElementCreator(cls, json)
Create custom Domain Settings Domain settings are referenced by an OSPFProfile :param str name: name of custom domain settings :param str abr_type: cisco|shortcut|standard :param int auto_cost_bandwidth: Mbits/s :param bool deprecated_algorithm: RFC 1518 compatibility :param int initial_delay: in milliseconds :param int initial_hold_type: in milliseconds :param int max_hold_time: in milliseconds :param int shutdown_max_metric_lsa: in seconds :param int startup_max_metric_lsa: in seconds :raises CreateElementFailed: create failed with reason :return: instance with meta :rtype: OSPFDomainSetting
entailment
def create_hook(function): """ Provide a pre-filter to the create function that provides the ability to modify the element json before submitting to the SMC. To register a create hook, set on the class or top level Element class to enable this on any descendent of Element:: Element._create_hook = classmethod(myhook) The hook should be a callable and take two arguments, cls, json and return the json after modification. For example:: def myhook(cls, json): print("Called with class: %s" % cls) if 'address' in json: json['address'] = '2.2.2.2' return json """ @functools.wraps(function) def run(cls, json, **kwargs): if hasattr(cls, '_create_hook'): json = cls._create_hook(json) return function(cls, json, **kwargs) return run
Provide a pre-filter to the create function that provides the ability to modify the element json before submitting to the SMC. To register a create hook, set on the class or top level Element class to enable this on any descendent of Element:: Element._create_hook = classmethod(myhook) The hook should be a callable and take two arguments, cls, json and return the json after modification. For example:: def myhook(cls, json): print("Called with class: %s" % cls) if 'address' in json: json['address'] = '2.2.2.2' return json
entailment
def exception(function): """ If exception was specified for prepared_request, inject this into SMCRequest so it can be used for return if needed. """ @functools.wraps(function) def wrapper(*exception, **kwargs): result = function(**kwargs) if exception: result.exception = exception[0] return result return wrapper
If exception was specified for prepared_request, inject this into SMCRequest so it can be used for return if needed.
entailment
def add_snmp(data, interfaces): """ Format data for adding SNMP to an engine. :param list data: list of interfaces as provided by kw :param list interfaces: interfaces to enable SNMP by id """ snmp_interface = [] if interfaces: # Not providing interfaces will enable SNMP on all NDIs interfaces = map(str, interfaces) for interface in data: interface_id = str(interface.get('interface_id')) for if_def in interface.get('interfaces', []): _interface_id = None if 'vlan_id' in if_def: _interface_id = '{}.{}'.format( interface_id, if_def['vlan_id']) else: _interface_id = interface_id if _interface_id in interfaces and 'type' not in interface: for node in if_def.get('nodes', []): snmp_interface.append( {'address': node.get('address'), 'nicid': _interface_id}) return snmp_interface
Format data for adding SNMP to an engine. :param list data: list of interfaces as provided by kw :param list interfaces: interfaces to enable SNMP by id
entailment
def create_bulk(cls, name, interfaces=None, primary_mgt=None, backup_mgt=None, log_server_ref=None, domain_server_address=None, location_ref=None, default_nat=False, enable_antivirus=False, enable_gti=False, sidewinder_proxy_enabled=False, enable_ospf=False, ospf_profile=None, comment=None, snmp=None, **kw): """ Create a Layer 3 Firewall providing all of the interface configuration. This method provides a way to fully create the engine and all interfaces at once versus using :py:meth:`~create` and creating each individual interface after the engine exists. Example interfaces format:: interfaces=[ {'interface_id': 1}, {'interface_id': 2, 'interfaces':[{'nodes': [{'address': '2.2.2.2', 'network_value': '2.2.2.0/24'}]}], 'zone_ref': 'myzone'}, {'interface_id': 3, 'interfaces': [{'nodes': [{'address': '3.3.3.3', 'network_value': '3.3.3.0/24'}], 'vlan_id': 3, 'zone_ref': 'myzone'}, {'nodes': [{'address': '4.4.4.4', 'network_value': '4.4.4.0/24'}], 'vlan_id': 4}]}, {'interface_id': 4, 'interfaces': [{'vlan_id': 4, 'zone_ref': 'myzone'}]}, {'interface_id': 5, 'interfaces': [{'vlan_id': 5}]}, {'interface_id': 1000, 'interfaces': [{'nodes': [{'address': '10.10.10.1', 'network_value': '10.10.10.0/24'}]}], 'type': 'tunnel_interface'}] """ physical_interfaces = [] for interface in interfaces: if 'interface_id' not in interface: raise CreateEngineFailed('Interface definitions must contain the interface_id ' 'field. Failed to create engine: %s' % name) if interface.get('type', None) == 'tunnel_interface': tunnel_interface = TunnelInterface(**interface) physical_interfaces.append( {'tunnel_interface': tunnel_interface}) else: interface.update(interface='single_node_interface') interface = Layer3PhysicalInterface(primary_mgt=primary_mgt, backup_mgt=backup_mgt, **interface) physical_interfaces.append( {'physical_interface': interface}) if snmp: snmp_agent = dict( snmp_agent_ref=snmp.get('snmp_agent', ''), snmp_location=snmp.get('snmp_location', '')) snmp_agent.update( snmp_interface=add_snmp( interfaces, snmp.get('snmp_interface', []))) try: engine = super(Layer3Firewall, cls)._create( name=name, node_type='firewall_node', physical_interfaces=physical_interfaces, loopback_ndi=kw.get('loopback_ndi', []), domain_server_address=domain_server_address, log_server_ref=log_server_ref, nodes=1, enable_gti=enable_gti, enable_antivirus=enable_antivirus, sidewinder_proxy_enabled=sidewinder_proxy_enabled, default_nat=default_nat, location_ref=location_ref, enable_ospf=enable_ospf, ospf_profile=ospf_profile, snmp_agent=snmp_agent if snmp else None, comment=comment) return ElementCreator(cls, json=engine) except (ElementNotFound, CreateElementFailed) as e: raise CreateEngineFailed(e)
Create a Layer 3 Firewall providing all of the interface configuration. This method provides a way to fully create the engine and all interfaces at once versus using :py:meth:`~create` and creating each individual interface after the engine exists. Example interfaces format:: interfaces=[ {'interface_id': 1}, {'interface_id': 2, 'interfaces':[{'nodes': [{'address': '2.2.2.2', 'network_value': '2.2.2.0/24'}]}], 'zone_ref': 'myzone'}, {'interface_id': 3, 'interfaces': [{'nodes': [{'address': '3.3.3.3', 'network_value': '3.3.3.0/24'}], 'vlan_id': 3, 'zone_ref': 'myzone'}, {'nodes': [{'address': '4.4.4.4', 'network_value': '4.4.4.0/24'}], 'vlan_id': 4}]}, {'interface_id': 4, 'interfaces': [{'vlan_id': 4, 'zone_ref': 'myzone'}]}, {'interface_id': 5, 'interfaces': [{'vlan_id': 5}]}, {'interface_id': 1000, 'interfaces': [{'nodes': [{'address': '10.10.10.1', 'network_value': '10.10.10.0/24'}]}], 'type': 'tunnel_interface'}]
entailment
def create(cls, name, mgmt_ip, mgmt_network, mgmt_interface=0, log_server_ref=None, default_nat=False, reverse_connection=False, domain_server_address=None, zone_ref=None, enable_antivirus=False, enable_gti=False, location_ref=None, enable_ospf=False, sidewinder_proxy_enabled=False, ospf_profile=None, snmp=None, comment=None, **kw): """ Create a single layer 3 firewall with management interface and DNS. Provide the `interfaces` keyword argument if adding multiple additional interfaces. Interfaces can be one of any valid interface for a layer 3 firewall. Unless the interface type is specified, physical_interface is assumed. Valid interface types: - physical_interface (default if not specified) - tunnel_interface If providing all engine interfaces in a single operation, see :py:meth:`~create_bulk` for the proper format. :param str name: name of firewall engine :param str mgmt_ip: ip address of management interface :param str mgmt_network: management network in cidr format :param str log_server_ref: (optional) href to log_server instance for fw :param int mgmt_interface: (optional) interface for management from SMC to fw :param list domain_server_address: (optional) DNS server addresses :param str zone_ref: zone name, str href or zone name for management interface (created if not found) :param bool reverse_connection: should the NGFW be the mgmt initiator (used when behind NAT) :param bool default_nat: (optional) Whether to enable default NAT for outbound :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :param bool sidewinder_proxy_enabled: Enable Sidewinder proxy functionality :param str location_ref: location href or not for engine if needed to contact SMC behind NAT (created if not found) :param bool enable_ospf: whether to turn OSPF on within engine :param str ospf_profile: optional OSPF profile to use on engine, by ref :param kw: optional keyword arguments specifying additional interfaces :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine` """ interfaces = kw.pop('interfaces', []) # Add the primary interface to the interface list interface = {'interface_id': mgmt_interface, 'interface': 'single_node_interface', 'zone_ref': zone_ref, 'interfaces': [{ 'nodes': [{'address': mgmt_ip, 'network_value': mgmt_network, 'nodeid': 1, 'reverse_connection': reverse_connection}] }] } interfaces.append(interface) return Layer3Firewall.create_bulk( name=name, node_type='firewall_node', interfaces=interfaces, primary_mgt=mgmt_interface, domain_server_address=domain_server_address, log_server_ref=log_server_ref, nodes=1, enable_gti=enable_gti, enable_antivirus=enable_antivirus, sidewinder_proxy_enabled=sidewinder_proxy_enabled, default_nat=default_nat, location_ref=location_ref, enable_ospf=enable_ospf, ospf_profile=ospf_profile, snmp=snmp, comment=comment, **kw)
Create a single layer 3 firewall with management interface and DNS. Provide the `interfaces` keyword argument if adding multiple additional interfaces. Interfaces can be one of any valid interface for a layer 3 firewall. Unless the interface type is specified, physical_interface is assumed. Valid interface types: - physical_interface (default if not specified) - tunnel_interface If providing all engine interfaces in a single operation, see :py:meth:`~create_bulk` for the proper format. :param str name: name of firewall engine :param str mgmt_ip: ip address of management interface :param str mgmt_network: management network in cidr format :param str log_server_ref: (optional) href to log_server instance for fw :param int mgmt_interface: (optional) interface for management from SMC to fw :param list domain_server_address: (optional) DNS server addresses :param str zone_ref: zone name, str href or zone name for management interface (created if not found) :param bool reverse_connection: should the NGFW be the mgmt initiator (used when behind NAT) :param bool default_nat: (optional) Whether to enable default NAT for outbound :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :param bool sidewinder_proxy_enabled: Enable Sidewinder proxy functionality :param str location_ref: location href or not for engine if needed to contact SMC behind NAT (created if not found) :param bool enable_ospf: whether to turn OSPF on within engine :param str ospf_profile: optional OSPF profile to use on engine, by ref :param kw: optional keyword arguments specifying additional interfaces :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine`
entailment
def create_dynamic(cls, name, interface_id, dynamic_index=1, reverse_connection=True, automatic_default_route=True, domain_server_address=None, loopback_ndi='127.0.0.1', location_ref=None, log_server_ref=None, zone_ref=None, enable_gti=False, enable_antivirus=False, sidewinder_proxy_enabled=False, default_nat=False, comment=None, **kw): """ Create a single layer 3 firewall with only a single DHCP interface. Useful when creating virtualized FW's such as in Microsoft Azure. :param str name: name of engine :param str,int interface_id: interface ID used for dynamic interface and management :param bool reverse_connection: specifies the dynamic interface should initiate connections to management (default: True) :param bool automatic_default_route: allow SMC to create a dynamic netlink for the default route (default: True) :param list domain_server_address: list of IP addresses for engine DNS :param str loopback_ndi: IP address for a loopback NDI. When creating a dynamic engine, the `auth_request` must be set to a different interface, so loopback is created :param str location_ref: location by name for the engine :param str log_server_ref: log server reference, will use the """ interfaces = kw.pop('interfaces', []) # Add the primary interface to the interface list interface = {'interface_id': interface_id, 'interface': 'single_node_interface', 'zone_ref': zone_ref, 'interfaces': [{ 'nodes': [{'dynamic': True, 'dynamic_index': dynamic_index, 'nodeid': 1, 'reverse_connection': reverse_connection, 'automatic_default_route': automatic_default_route}] }] } interfaces.append(interface) loopback = LoopbackInterface.create( address=loopback_ndi, nodeid=1, auth_request=True, rank=1) return Layer3Firewall.create_bulk( name=name, node_type='firewall_node', primary_mgt=interface_id, interfaces=interfaces, loopback_ndi=[loopback.data], domain_server_address=domain_server_address, log_server_ref=log_server_ref, nodes=1, enable_gti=enable_gti, enable_antivirus=enable_antivirus, sidewinder_proxy_enabled=sidewinder_proxy_enabled, default_nat=default_nat, location_ref=location_ref, comment=comment, **kw)
Create a single layer 3 firewall with only a single DHCP interface. Useful when creating virtualized FW's such as in Microsoft Azure. :param str name: name of engine :param str,int interface_id: interface ID used for dynamic interface and management :param bool reverse_connection: specifies the dynamic interface should initiate connections to management (default: True) :param bool automatic_default_route: allow SMC to create a dynamic netlink for the default route (default: True) :param list domain_server_address: list of IP addresses for engine DNS :param str loopback_ndi: IP address for a loopback NDI. When creating a dynamic engine, the `auth_request` must be set to a different interface, so loopback is created :param str location_ref: location by name for the engine :param str log_server_ref: log server reference, will use the
entailment
def create(cls, name, mgmt_ip, mgmt_network, mgmt_interface=0, inline_interface='1-2', logical_interface='default_eth', log_server_ref=None, domain_server_address=None, zone_ref=None, enable_antivirus=False, enable_gti=False, comment=None): """ Create a single layer 2 firewall with management interface and inline pair :param str name: name of firewall engine :param str mgmt_ip: ip address of management interface :param str mgmt_network: management network in cidr format :param int mgmt_interface: (optional) interface for management from SMC to fw :param str inline_interface: interfaces to use for first inline pair :param str logical_interface: name, str href or LogicalInterface (created if it doesn't exist) :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param str zone_ref: zone name, str href or Zone for management interface (created if not found) :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine` """ interfaces = [] interface_id, second_interface_id = inline_interface.split('-') l2 = {'interface_id': interface_id, 'interface': 'inline_interface', 'second_interface_id': second_interface_id, 'logical_interface_ref': logical_interface} interfaces.append( {'physical_interface': Layer2PhysicalInterface(**l2)}) layer3 = {'interface_id': mgmt_interface, 'zone_ref': zone_ref, 'interfaces': [{'nodes': [ {'address': mgmt_ip, 'network_value': mgmt_network, 'nodeid': 1}]}] } interfaces.append( {'physical_interface': Layer3PhysicalInterface(primary_mgt=mgmt_interface, **layer3)}) engine = super(Layer2Firewall, cls)._create( name=name, node_type='fwlayer2_node', physical_interfaces=interfaces, domain_server_address=domain_server_address, log_server_ref=log_server_ref, nodes=1, enable_gti=enable_gti, enable_antivirus=enable_antivirus, comment=comment) try: return ElementCreator(cls, json=engine) except CreateElementFailed as e: raise CreateEngineFailed(e)
Create a single layer 2 firewall with management interface and inline pair :param str name: name of firewall engine :param str mgmt_ip: ip address of management interface :param str mgmt_network: management network in cidr format :param int mgmt_interface: (optional) interface for management from SMC to fw :param str inline_interface: interfaces to use for first inline pair :param str logical_interface: name, str href or LogicalInterface (created if it doesn't exist) :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param str zone_ref: zone name, str href or Zone for management interface (created if not found) :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine`
entailment
def create(cls, name, master_engine, virtual_resource, interfaces, default_nat=False, outgoing_intf=0, domain_server_address=None, enable_ospf=False, ospf_profile=None, comment=None, **kw): """ Create a Layer3Virtual engine for a Master Engine. Provide interfaces as a list of dict items specifying the interface details in format:: {'interface_id': 1, 'address': '1.1.1.1', 'network_value': '1.1.1.0/24', 'zone_ref': zone_by_name,href, 'comment': 'my interface comment'} :param str name: Name of this layer 3 virtual engine :param str master_engine: Name of existing master engine :param str virtual_resource: name of pre-created virtual resource :param list interfaces: dict of interface details :param bool default_nat: Whether to enable default NAT for outbound :param int outgoing_intf: outgoing interface for VE. Specifies interface number :param list interfaces: interfaces mappings passed in :param bool enable_ospf: whether to turn OSPF on within engine :param str ospf_profile: optional OSPF profile to use on engine, by ref :raises CreateEngineFailed: Failure to create with reason :raises LoadEngineFailed: master engine not found :return: :py:class:`smc.core.engine.Engine` """ virt_resource_href = None # need virtual resource reference master_engine = Engine(master_engine) for virt_resource in master_engine.virtual_resource.all(): if virt_resource.name == virtual_resource: virt_resource_href = virt_resource.href break if not virt_resource_href: raise CreateEngineFailed('Cannot find associated virtual resource for ' 'VE named: {}. You must first create a virtual resource for the ' 'master engine before you can associate a virtual engine. Cannot ' 'add VE'.format(name)) virtual_interfaces = [] for interface in interfaces: nodes = {'address': interface.get('address'), 'network_value': interface.get('network_value')} layer3 = {'interface_id': interface.get('interface_id'), 'interface': 'single_node_interface', 'comment': interface.get('comment', None), 'zone_ref': interface.get('zone_ref')} if interface.get('interface_id') == outgoing_intf: nodes.update(outgoing=True, auth_request=True) layer3['interfaces'] = [{'nodes': [nodes]}] virtual_interfaces.append( {'virtual_physical_interface': Layer3PhysicalInterface(**layer3).data.data}) engine = super(Layer3VirtualEngine, cls)._create( name=name, node_type='virtual_fw_node', physical_interfaces=virtual_interfaces, domain_server_address=domain_server_address, log_server_ref=None, # Isn't used in VE nodes=1, default_nat=default_nat, enable_ospf=enable_ospf, ospf_profile=ospf_profile, comment=comment) engine.update(virtual_resource=virt_resource_href) # Master Engine provides this service engine.pop('log_server_ref', None) try: return ElementCreator(cls, json=engine) except CreateElementFailed as e: raise CreateEngineFailed(e)
Create a Layer3Virtual engine for a Master Engine. Provide interfaces as a list of dict items specifying the interface details in format:: {'interface_id': 1, 'address': '1.1.1.1', 'network_value': '1.1.1.0/24', 'zone_ref': zone_by_name,href, 'comment': 'my interface comment'} :param str name: Name of this layer 3 virtual engine :param str master_engine: Name of existing master engine :param str virtual_resource: name of pre-created virtual resource :param list interfaces: dict of interface details :param bool default_nat: Whether to enable default NAT for outbound :param int outgoing_intf: outgoing interface for VE. Specifies interface number :param list interfaces: interfaces mappings passed in :param bool enable_ospf: whether to turn OSPF on within engine :param str ospf_profile: optional OSPF profile to use on engine, by ref :raises CreateEngineFailed: Failure to create with reason :raises LoadEngineFailed: master engine not found :return: :py:class:`smc.core.engine.Engine`
entailment
def create_bulk(cls, name, interfaces=None, nodes=2, cluster_mode='balancing', primary_mgt=None, backup_mgt=None, primary_heartbeat=None, log_server_ref=None, domain_server_address=None, location_ref=None, default_nat=False, enable_antivirus=False, enable_gti=False, comment=None, snmp=None, **kw): """ :param dict snmp: SNMP dict should have keys `snmp_agent` str defining name of SNMPAgent, `snmp_interface` which is a list of interface IDs, and optionally `snmp_location` which is a string with the SNMP location name. """ primary_heartbeat = primary_mgt if not primary_heartbeat else primary_heartbeat physical_interfaces = [] for interface in interfaces: if 'interface_id' not in interface: raise CreateEngineFailed('Interface definitions must contain the interface_id ' 'field. Failed to create engine: %s' % name) if interface.get('type', None) == 'tunnel_interface': tunnel_interface = TunnelInterface(**interface) physical_interfaces.append( {'tunnel_interface': tunnel_interface}) else: cluster_interface = ClusterPhysicalInterface( primary_mgt=primary_mgt, backup_mgt=backup_mgt, primary_heartbeat=primary_heartbeat, **interface) physical_interfaces.append( {'physical_interface': cluster_interface}) if snmp: snmp_agent = dict( snmp_agent_ref=snmp.get('snmp_agent', ''), snmp_location=snmp.get('snmp_location', '')) snmp_agent.update( snmp_interface=add_snmp( interfaces, snmp.get('snmp_interface', []))) try: engine = super(FirewallCluster, cls)._create( name=name, node_type='firewall_node', physical_interfaces=physical_interfaces, domain_server_address=domain_server_address, log_server_ref=log_server_ref, location_ref=location_ref, nodes=nodes, enable_gti=enable_gti, enable_antivirus=enable_antivirus, default_nat=default_nat, snmp_agent=snmp_agent if snmp else None, comment=comment) engine.update(cluster_mode=cluster_mode) return ElementCreator(cls, json=engine) except (ElementNotFound, CreateElementFailed) as e: raise CreateEngineFailed(e)
:param dict snmp: SNMP dict should have keys `snmp_agent` str defining name of SNMPAgent, `snmp_interface` which is a list of interface IDs, and optionally `snmp_location` which is a string with the SNMP location name.
entailment
def create(cls, name, cluster_virtual, network_value, macaddress, interface_id, nodes, vlan_id=None, cluster_mode='balancing', backup_mgt=None, primary_heartbeat=None, log_server_ref=None, domain_server_address=None, location_ref=None, zone_ref=None, default_nat=False, enable_antivirus=False, enable_gti=False, comment=None, snmp=None, **kw): """ Create a layer 3 firewall cluster with management interface and any number of nodes. If providing keyword arguments to create additional interfaces, use the same constructor arguments and pass an `interfaces` keyword argument. The constructor defined interface will be assigned as the primary management interface by default. Otherwise the engine will be created with a single interface and interfaces can be added after. .. versionchanged:: 0.6.1 Chgnged `cluster_nic` to `interface_id`, and `cluster_mask` to `network_value` :param str name: name of firewall engine :param str cluster_virtual: ip of cluster CVI :param str network_value: ip netmask of cluster CVI :param str macaddress: macaddress for packet dispatch clustering :param str interface_id: nic id to use for primary interface :param list nodes: address/network_value/nodeid combination for cluster nodes :param str vlan_id: optional VLAN id for the management interface, i.e. '15'. :param str cluster_mode: 'balancing' or 'standby' mode (default: balancing) :param str,int primary_heartbeat: optionally set the primary_heartbeat. This is automatically set to the management interface but can be overridden to use another interface if defining additional interfaces using `interfaces`. :param str,int backup_mgt: optionally set the backup management interface. This is unset unless you define additional interfaces using `interfaces`. :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param str location_ref: location href or not for engine if needed to contact SMC behind NAT (created if not found) :param str zone_ref: zone name, str href or Zone for management interface (created if not found) :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :param list interfaces: optional keyword to supply additional interfaces :param dict snmp: SNMP dict should have keys `snmp_agent` str defining name of SNMPAgent, `snmp_interface` which is a list of interface IDs, and optionally `snmp_location` which is a string with the SNMP location name. :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine` Example nodes parameter input:: [{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1}, {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2}, {'address':'5.5.5.4', 'network_value':'5.5.5.0/24', 'nodeid':3}] You can also create additional CVI+NDI, or NDI only interfaces by providing the keyword argument interfaces using the same keyword values from the constructor:: interfaces=[ {'interface_id': 1, 'macaddress': '02:02:02:02:02:03', 'interfaces': [{'cluster_virtual': '2.2.2.1', 'network_value': '2.2.2.0/24', 'nodes':[{'address': '2.2.2.2', 'network_value': '2.2.2.0/24', 'nodeid': 1}, {'address': '2.2.2.3', 'network_value': '2.2.2.0/24', 'nodeid': 2}] }] }, {'interface_id': 2, 'interfaces': [{'nodes':[{'address': '3.3.3.2', 'network_value': '3.3.3.0/24', 'nodeid': 1}, {'address': '3.3.3.3', 'network_value': '3.3.3.0/24', 'nodeid': 2}] }] }] It is also possible to define VLAN interfaces by providing the `vlan_id` keyword. Example VLAN with NDI only interfaces. If nesting the zone_ref within the interfaces list, the zone will be applied to the VLAN versus the top level interface:: interfaces=[ {'interface_id': 2, 'interfaces': [{'nodes':[{'address': '3.3.3.2', 'network_value': '3.3.3.0/24', 'nodeid': 1}, {'address': '3.3.3.3', 'network_value': '3.3.3.0/24', 'nodeid': 2}], 'vlan_id': 22, 'zone_ref': 'private-network' }, {'nodes': [{'address': '4.4.4.1', 'network_value': '4.4.4.0/24', 'nodeid': 1}, {'address': '4.4.4.2', 'network_value': '4.4.4.0/24', 'nodeid': 2}], 'vlan_id': 23, 'zone_ref': 'other_vlan' }] }] Tunnel interfaces can also be created. As all interfaces defined are assumed to be a physical interface type, you must specify the `type` parameter to indicate the interface is a tunnel interface. Tunnel interfaces do not have a macaddress or VLANs. They be configured with NDI interfaces by omitting the `cluster_virtual` and `network_value` top level attributes:: interfaces=[ {'interface_id': 1000, 'interfaces': [{'cluster_virtual': '100.100.100.1', 'network_value': '100.100.100.0/24', 'nodes':[{'address': '100.100.100.2', 'network_value': '100.100.100.0/24', 'nodeid': 1}, {'address': '100.100.100.3', 'network_value': '100.100.100.0/24', 'nodeid': 2}] }], 'zone_ref': 'AWStunnel', 'type': 'tunnel_interface' }] If setting primary_heartbeat or backup_mgt to a specific interface (the primary interface configured in the constructor will have these roles by default), you must define the interfaces in the `interfaces` keyword argument list. .. note:: If creating additional interfaces, you must at minimum provide the `interface_id` and `nodes` to create an NDI only interface. """ interfaces = kw.pop('interfaces', []) # Add the primary interface to the interface list interface = {'cluster_virtual': cluster_virtual, 'network_value': network_value, 'nodes': nodes} if vlan_id: interface.update(vlan_id=vlan_id) interfaces.append(dict( interface_id=interface_id, macaddress=macaddress, zone_ref=zone_ref, interfaces=[interface])) primary_mgt = interface_id if not vlan_id else '{}.{}'.format(interface_id, vlan_id) return FirewallCluster.create_bulk( name, interfaces=interfaces, nodes=len(nodes), cluster_mode=cluster_mode, primary_mgt=primary_mgt, backup_mgt=backup_mgt, primary_heartbeat=primary_heartbeat, log_server_ref=log_server_ref, domain_server_address=domain_server_address, location_ref=location_ref, default_nat=default_nat, enable_antivirus=enable_antivirus, enable_gti=enable_gti, comment=comment, snmp=snmp, **kw)
Create a layer 3 firewall cluster with management interface and any number of nodes. If providing keyword arguments to create additional interfaces, use the same constructor arguments and pass an `interfaces` keyword argument. The constructor defined interface will be assigned as the primary management interface by default. Otherwise the engine will be created with a single interface and interfaces can be added after. .. versionchanged:: 0.6.1 Chgnged `cluster_nic` to `interface_id`, and `cluster_mask` to `network_value` :param str name: name of firewall engine :param str cluster_virtual: ip of cluster CVI :param str network_value: ip netmask of cluster CVI :param str macaddress: macaddress for packet dispatch clustering :param str interface_id: nic id to use for primary interface :param list nodes: address/network_value/nodeid combination for cluster nodes :param str vlan_id: optional VLAN id for the management interface, i.e. '15'. :param str cluster_mode: 'balancing' or 'standby' mode (default: balancing) :param str,int primary_heartbeat: optionally set the primary_heartbeat. This is automatically set to the management interface but can be overridden to use another interface if defining additional interfaces using `interfaces`. :param str,int backup_mgt: optionally set the backup management interface. This is unset unless you define additional interfaces using `interfaces`. :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param str location_ref: location href or not for engine if needed to contact SMC behind NAT (created if not found) :param str zone_ref: zone name, str href or Zone for management interface (created if not found) :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :param list interfaces: optional keyword to supply additional interfaces :param dict snmp: SNMP dict should have keys `snmp_agent` str defining name of SNMPAgent, `snmp_interface` which is a list of interface IDs, and optionally `snmp_location` which is a string with the SNMP location name. :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine` Example nodes parameter input:: [{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1}, {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2}, {'address':'5.5.5.4', 'network_value':'5.5.5.0/24', 'nodeid':3}] You can also create additional CVI+NDI, or NDI only interfaces by providing the keyword argument interfaces using the same keyword values from the constructor:: interfaces=[ {'interface_id': 1, 'macaddress': '02:02:02:02:02:03', 'interfaces': [{'cluster_virtual': '2.2.2.1', 'network_value': '2.2.2.0/24', 'nodes':[{'address': '2.2.2.2', 'network_value': '2.2.2.0/24', 'nodeid': 1}, {'address': '2.2.2.3', 'network_value': '2.2.2.0/24', 'nodeid': 2}] }] }, {'interface_id': 2, 'interfaces': [{'nodes':[{'address': '3.3.3.2', 'network_value': '3.3.3.0/24', 'nodeid': 1}, {'address': '3.3.3.3', 'network_value': '3.3.3.0/24', 'nodeid': 2}] }] }] It is also possible to define VLAN interfaces by providing the `vlan_id` keyword. Example VLAN with NDI only interfaces. If nesting the zone_ref within the interfaces list, the zone will be applied to the VLAN versus the top level interface:: interfaces=[ {'interface_id': 2, 'interfaces': [{'nodes':[{'address': '3.3.3.2', 'network_value': '3.3.3.0/24', 'nodeid': 1}, {'address': '3.3.3.3', 'network_value': '3.3.3.0/24', 'nodeid': 2}], 'vlan_id': 22, 'zone_ref': 'private-network' }, {'nodes': [{'address': '4.4.4.1', 'network_value': '4.4.4.0/24', 'nodeid': 1}, {'address': '4.4.4.2', 'network_value': '4.4.4.0/24', 'nodeid': 2}], 'vlan_id': 23, 'zone_ref': 'other_vlan' }] }] Tunnel interfaces can also be created. As all interfaces defined are assumed to be a physical interface type, you must specify the `type` parameter to indicate the interface is a tunnel interface. Tunnel interfaces do not have a macaddress or VLANs. They be configured with NDI interfaces by omitting the `cluster_virtual` and `network_value` top level attributes:: interfaces=[ {'interface_id': 1000, 'interfaces': [{'cluster_virtual': '100.100.100.1', 'network_value': '100.100.100.0/24', 'nodes':[{'address': '100.100.100.2', 'network_value': '100.100.100.0/24', 'nodeid': 1}, {'address': '100.100.100.3', 'network_value': '100.100.100.0/24', 'nodeid': 2}] }], 'zone_ref': 'AWStunnel', 'type': 'tunnel_interface' }] If setting primary_heartbeat or backup_mgt to a specific interface (the primary interface configured in the constructor will have these roles by default), you must define the interfaces in the `interfaces` keyword argument list. .. note:: If creating additional interfaces, you must at minimum provide the `interface_id` and `nodes` to create an NDI only interface.
entailment
def create(cls, name, master_type, mgmt_ip, mgmt_network, mgmt_interface=0, log_server_ref=None, zone_ref=None, domain_server_address=None, enable_gti=False, enable_antivirus=False, comment=None): """ Create a Master Engine with management interface :param str name: name of master engine engine :param str master_type: firewall| :param str mgmt_ip: ip address for management interface :param str mgmt_network: full netmask for management :param str mgmt_interface: interface to use for mgmt (default: 0) :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine` """ interface = {'interface_id': mgmt_interface, 'interfaces': [{'nodes': [{'address': mgmt_ip, 'network_value': mgmt_network}]}], 'zone_ref': zone_ref, 'comment': comment} interface = Layer3PhysicalInterface(primary_mgt=mgmt_interface, primary_heartbeat=mgmt_interface, **interface) engine = super(MasterEngine, cls)._create( name=name, node_type='master_node', physical_interfaces=[{'physical_interface':interface}], domain_server_address=domain_server_address, log_server_ref=log_server_ref, nodes=1, enable_gti=enable_gti, enable_antivirus=enable_antivirus, comment=comment) engine.update(master_type=master_type, cluster_mode='standby') try: return ElementCreator(cls, json=engine) except CreateElementFailed as e: raise CreateEngineFailed(e)
Create a Master Engine with management interface :param str name: name of master engine engine :param str master_type: firewall| :param str mgmt_ip: ip address for management interface :param str mgmt_network: full netmask for management :param str mgmt_interface: interface to use for mgmt (default: 0) :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine`
entailment
def create(cls, name, master_type, macaddress, nodes, mgmt_interface=0, log_server_ref=None, domain_server_address=None, enable_gti=False, enable_antivirus=False, comment=None, **kw): """ Create Master Engine Cluster :param str name: name of master engine engine :param str master_type: firewall| :param str mgmt_ip: ip address for management interface :param str mgmt_netmask: full netmask for management :param str mgmt_interface: interface to use for mgmt (default: 0) :param list nodes: address/network_value/nodeid combination for cluster nodes :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine` Example nodes parameter input:: [{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1}, {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2}, {'address':'5.5.5.4', 'network_value':'5.5.5.0/24', 'nodeid':3}] """ primary_mgt = primary_heartbeat = mgmt_interface interface = {'interface_id': mgmt_interface, 'interfaces': [{ 'nodes': nodes }], 'macaddress': macaddress, } interface = Layer3PhysicalInterface(primary_mgt=primary_mgt, primary_heartbeat=primary_heartbeat, **interface) engine = super(MasterEngineCluster, cls)._create( name=name, node_type='master_node', physical_interfaces=[{'physical_interface': interface}], domain_server_address=domain_server_address, log_server_ref=log_server_ref, nodes=len(nodes), enable_gti=enable_gti, enable_antivirus=enable_antivirus, comment=comment) engine.update(master_type=master_type, cluster_mode='standby') try: return ElementCreator(cls, json=engine) except CreateElementFailed as e: raise CreateEngineFailed(e)
Create Master Engine Cluster :param str name: name of master engine engine :param str master_type: firewall| :param str mgmt_ip: ip address for management interface :param str mgmt_netmask: full netmask for management :param str mgmt_interface: interface to use for mgmt (default: 0) :param list nodes: address/network_value/nodeid combination for cluster nodes :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine` Example nodes parameter input:: [{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1}, {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2}, {'address':'5.5.5.4', 'network_value':'5.5.5.0/24', 'nodeid':3}]
entailment
def set_stream_logger(log_level=logging.DEBUG, format_string=None, logger_name='smc'): """ Stream logger convenience function to log to console :param int log_level: A log level as specified in the `logging` module :param str format_string: Optional format string as specified in the `logging` module """ if format_string is None: format_string = LOG_FORMAT logger = logging.getLogger(logger_name) logger.setLevel(log_level) # create console handler and set level ch = logging.StreamHandler() ch.setLevel(log_level) # create formatter formatter = logging.Formatter(format_string) # add formatter to ch ch.setFormatter(formatter) logger.addHandler(ch)
Stream logger convenience function to log to console :param int log_level: A log level as specified in the `logging` module :param str format_string: Optional format string as specified in the `logging` module
entailment
def set_file_logger(path, log_level=logging.DEBUG, format_string=None, logger_name='smc'): """ Convenience function to quickly configure any level of logging to a file. :param int log_level: A log level as specified in the `logging` module :param str format_string: Optional format string as specified in the `logging` module :param str path: Path to the log file. The file will be created if it doesn't already exist. """ if format_string is None: format_string = LOG_FORMAT log = logging.getLogger(logger_name) log.setLevel(log_level) # create file handler and set level ch = logging.FileHandler(path) ch.setLevel(log_level) # create formatter formatter = logging.Formatter(format_string) # add formatter to ch ch.setFormatter(formatter) # add ch to logger log.addHandler(ch)
Convenience function to quickly configure any level of logging to a file. :param int log_level: A log level as specified in the `logging` module :param str format_string: Optional format string as specified in the `logging` module :param str path: Path to the log file. The file will be created if it doesn't already exist.
entailment
def create(cls, name, ldap_server, isdefault=False, auth_method=None, comment=None): """ Create an External LDAP user domain. These are used as containers for retrieving user and groups from the configured LDAP server/s. If you have multiple authentication methods supported for your LDAP server, or have none configured, you can set the `auth_method` to a supported AuthenticationMethod. :param str name: name of external LDAP domain :param list(str,ActiveDirectoryServer) ldap_server: list of existing authentication servers in href or element format :param bool isdefault: set this to 'Default LDAP domain' :param str,AuthenticationMethod auth_method: authentication method to use. Usually set when multiple are defined in LDAP service or none are defined. :param str comment: optional comment :raises CreateElementFailed: failed to create :rtype: ExternalLdapUserDomain """ return ElementCreator(cls, json={'name': name, 'ldap_server': element_resolver(ldap_server), 'auth_method': element_resolver(auth_method), 'isdefault': isdefault, 'comment': comment})
Create an External LDAP user domain. These are used as containers for retrieving user and groups from the configured LDAP server/s. If you have multiple authentication methods supported for your LDAP server, or have none configured, you can set the `auth_method` to a supported AuthenticationMethod. :param str name: name of external LDAP domain :param list(str,ActiveDirectoryServer) ldap_server: list of existing authentication servers in href or element format :param bool isdefault: set this to 'Default LDAP domain' :param str,AuthenticationMethod auth_method: authentication method to use. Usually set when multiple are defined in LDAP service or none are defined. :param str comment: optional comment :raises CreateElementFailed: failed to create :rtype: ExternalLdapUserDomain
entailment
def create(cls, name, user_group=None, activation_date=None, expiration_date=None, comment=None): """ Create an internal user. Add a user example:: InternalUser.create(name='goog', comment='my comment') :param str name: name of user that is displayed in SMC :param list(str,InternalUserGroup) user_group: internal user groups which to add this user to. :param datetime activation_date: activation date as datetime object. Activation date only supports year and month/day :param datetime expiration_date: expiration date as datetime object. Expiration date only supports year and month/day :param str comment: optional comment :raises ElementNotFound: thrown if group specified does not exist :rtype: InternalUser """ json = { 'name': name, 'unique_id': 'cn={},{}'.format(name, InternalUserDomain.user_dn), 'comment': comment} limits = {'activation_date': activation_date, 'expiration_date': expiration_date} for attr, value in limits.items(): json[attr] = datetime_to_ms(value) if value else None if user_group: json.update(user_group=element_resolver(user_group)) return ElementCreator(cls, json)
Create an internal user. Add a user example:: InternalUser.create(name='goog', comment='my comment') :param str name: name of user that is displayed in SMC :param list(str,InternalUserGroup) user_group: internal user groups which to add this user to. :param datetime activation_date: activation date as datetime object. Activation date only supports year and month/day :param datetime expiration_date: expiration date as datetime object. Expiration date only supports year and month/day :param str comment: optional comment :raises ElementNotFound: thrown if group specified does not exist :rtype: InternalUser
entailment
def create(cls, name, member=None, comment=None): """ Create an internal group. An internal group will always be attached to the default (and only) InternalUserDomain within the SMC. Example of creating an internal user group:: InternalUserGroup.create(name='foogroup2', comment='mycomment') :param str name: Name of group :param list(InternalUser) member: list of internal users to add to this group :param str comment: optional comment :raises CreateElementFailed: failed to create user group :rtype: InternalUserGroup """ json={'name': name, 'unique_id': 'cn={},{}'.format(name, InternalUserDomain.user_dn), 'comment': comment} if member: json.update(member=element_resolver(member)) return ElementCreator(cls, json)
Create an internal group. An internal group will always be attached to the default (and only) InternalUserDomain within the SMC. Example of creating an internal user group:: InternalUserGroup.create(name='foogroup2', comment='mycomment') :param str name: Name of group :param list(InternalUser) member: list of internal users to add to this group :param str comment: optional comment :raises CreateElementFailed: failed to create user group :rtype: InternalUserGroup
entailment
def get_all_loopbacks(engine): """ Get all loopback interfaces for a given engine """ data = [] if 'fw_cluster' in engine.type: for cvi in engine.data.get('loopback_cluster_virtual_interface', []): data.append( LoopbackClusterInterface(cvi, engine)) for node in engine.nodes: for lb in node.data.get('loopback_node_dedicated_interface', []): data.append(LoopbackInterface(lb, engine)) return data
Get all loopback interfaces for a given engine
entailment
def get(self, address): """ Get a loopback address by it's address. Find all loopback addresses by iterating at either the node level or the engine:: loopback = engine.loopback_interface.get('127.0.0.10') :param str address: ip address of loopback :raises InterfaceNotFound: invalid interface specified :rtype: LoopbackInterface """ loopback = super(LoopbackCollection, self).get(address=address) if loopback: return loopback raise InterfaceNotFound('Loopback address specified was not found')
Get a loopback address by it's address. Find all loopback addresses by iterating at either the node level or the engine:: loopback = engine.loopback_interface.get('127.0.0.10') :param str address: ip address of loopback :raises InterfaceNotFound: invalid interface specified :rtype: LoopbackInterface
entailment
def update_or_create(self, interface): """ Collections class update or create method that can be used as a shortcut to updating or creating an interface. The interface must first be defined and provided as the argument. The interface method must have an `update_interface` method which resolves differences and adds as necessary. :param Interface interface: an instance of an interface type, either PhysicalInterface or TunnelInterface :raises EngineCommandFailed: Failed to create new interface :raises UpdateElementFailed: Failure to update element with reason :rtype: tuple :return: A tuple with (Interface, modified, created), where created and modified are booleans indicating the operations performed """ created, modified = (False, False) try: intf = self._engine.interface.get( interface.interface_id) interface, updated = intf.update_interface(interface) if updated: modified = True except InterfaceNotFound: self._engine.add_interface(interface) interface = self._engine.interface.get(interface.interface_id) created = True return interface, modified, created
Collections class update or create method that can be used as a shortcut to updating or creating an interface. The interface must first be defined and provided as the argument. The interface method must have an `update_interface` method which resolves differences and adds as necessary. :param Interface interface: an instance of an interface type, either PhysicalInterface or TunnelInterface :raises EngineCommandFailed: Failed to create new interface :raises UpdateElementFailed: Failure to update element with reason :rtype: tuple :return: A tuple with (Interface, modified, created), where created and modified are booleans indicating the operations performed
entailment
def add_cluster_virtual_interface(self, interface_id, cluster_virtual=None, network_value=None, nodes=None, zone_ref=None, comment=None): """ Add a tunnel interface on a clustered engine. For tunnel interfaces on a cluster, you can specify a CVI only, NDI interfaces, or both. This interface type is only supported on layer 3 firewall engines. :: Add a tunnel CVI and NDI: engine.tunnel_interface.add_cluster_virtual_interface( interface_id_id=3000, cluster_virtual='4.4.4.1', network_value='4.4.4.0/24', nodes=nodes) Add tunnel NDI's only: engine.tunnel_interface.add_cluster_virtual_interface( interface_id=3000, nodes=nodes) Add tunnel CVI only: engine.tunnel_interface.add_cluster_virtual_interface( interface_id=3000, cluster_virtual='31.31.31.31', network_value='31.31.31.0/24', zone_ref='myzone') :param str,int interface_id: tunnel identifier (akin to interface_id) :param str cluster_virtual: CVI ipaddress (optional) :param str network_value: CVI network; required if ``cluster_virtual`` set :param list nodes: nodes for clustered engine with address,network_value,nodeid :param str zone_ref: zone reference, can be name, href or Zone :param str comment: optional comment """ interfaces = [{'cluster_virtual': cluster_virtual, 'network_value': network_value, 'nodes': nodes if nodes else []}] interface = {'interface_id': interface_id, 'interfaces': interfaces, 'zone_ref': zone_ref, 'comment': comment} tunnel_interface = TunnelInterface(**interface) self._engine.add_interface(tunnel_interface)
Add a tunnel interface on a clustered engine. For tunnel interfaces on a cluster, you can specify a CVI only, NDI interfaces, or both. This interface type is only supported on layer 3 firewall engines. :: Add a tunnel CVI and NDI: engine.tunnel_interface.add_cluster_virtual_interface( interface_id_id=3000, cluster_virtual='4.4.4.1', network_value='4.4.4.0/24', nodes=nodes) Add tunnel NDI's only: engine.tunnel_interface.add_cluster_virtual_interface( interface_id=3000, nodes=nodes) Add tunnel CVI only: engine.tunnel_interface.add_cluster_virtual_interface( interface_id=3000, cluster_virtual='31.31.31.31', network_value='31.31.31.0/24', zone_ref='myzone') :param str,int interface_id: tunnel identifier (akin to interface_id) :param str cluster_virtual: CVI ipaddress (optional) :param str network_value: CVI network; required if ``cluster_virtual`` set :param list nodes: nodes for clustered engine with address,network_value,nodeid :param str zone_ref: zone reference, can be name, href or Zone :param str comment: optional comment
entailment
def add(self, interface_id, virtual_mapping=None, virtual_resource_name=None, zone_ref=None, comment=None): """ Add single physical interface with interface_id. Use other methods to fully add an interface configuration based on engine type. Virtual mapping and resource are only used in Virtual Engines. :param str,int interface_id: interface identifier :param int virtual_mapping: virtual firewall id mapping See :class:`smc.core.engine.VirtualResource.vfw_id` :param str virtual_resource_name: virtual resource name See :class:`smc.core.engine.VirtualResource.name` :raises EngineCommandFailed: failure creating interface :return: None """ interface = Layer3PhysicalInterface(engine=self._engine, interface_id=interface_id, zone_ref=zone_ref, comment=comment, virtual_resource_name=virtual_resource_name, virtual_mapping=virtual_mapping) return self._engine.add_interface(interface)
Add single physical interface with interface_id. Use other methods to fully add an interface configuration based on engine type. Virtual mapping and resource are only used in Virtual Engines. :param str,int interface_id: interface identifier :param int virtual_mapping: virtual firewall id mapping See :class:`smc.core.engine.VirtualResource.vfw_id` :param str virtual_resource_name: virtual resource name See :class:`smc.core.engine.VirtualResource.name` :raises EngineCommandFailed: failure creating interface :return: None
entailment
def add_capture_interface(self, interface_id, logical_interface_ref, inspect_unspecified_vlans=True, zone_ref=None, comment=None): """ Add a capture interface. Capture interfaces are supported on Layer 2 FW and IPS engines. ..note:: Capture interface are supported on Layer 3 FW/clusters for NGFW engines version >= 6.3 and SMC >= 6.3. :param str,int interface_id: interface identifier :param str logical_interface_ref: logical interface name, href or LogicalInterface. If None, 'default_eth' logical interface will be used. :param str zone_ref: zone reference, can be name, href or Zone :raises EngineCommandFailed: failure creating interface :return: None See :class:`smc.core.sub_interfaces.CaptureInterface` for more information """ capture = {'interface_id': interface_id, 'interface': 'capture_interface', 'logical_interface_ref': logical_interface_ref, 'inspect_unspecified_vlans': inspect_unspecified_vlans, 'zone_ref': zone_ref, 'comment': comment} interface = Layer2PhysicalInterface(engine=self._engine, **capture) return self._engine.add_interface(interface)
Add a capture interface. Capture interfaces are supported on Layer 2 FW and IPS engines. ..note:: Capture interface are supported on Layer 3 FW/clusters for NGFW engines version >= 6.3 and SMC >= 6.3. :param str,int interface_id: interface identifier :param str logical_interface_ref: logical interface name, href or LogicalInterface. If None, 'default_eth' logical interface will be used. :param str zone_ref: zone reference, can be name, href or Zone :raises EngineCommandFailed: failure creating interface :return: None See :class:`smc.core.sub_interfaces.CaptureInterface` for more information
entailment
def add_layer3_interface(self, interface_id, address, network_value, zone_ref=None, comment=None, **kw): """ Add a layer 3 interface on a non-clustered engine. For Layer 2 FW and IPS engines, this interface type represents a layer 3 routed (node dedicated) interface. For clusters, use the cluster related methods such as :func:`add_cluster_virtual_interface` :param str,int interface_id: interface identifier :param str address: ip address :param str network_value: network/cidr (12.12.12.0/24) :param str zone_ref: zone reference, can be name, href or Zone :param kw: keyword arguments are passed to the sub-interface during create time. If the engine is a single FW, the sub-interface type is :class:`smc.core.sub_interfaces.SingleNodeInterface`. For all other engines, the type is :class:`smc.core.sub_interfaces.NodeInterface` For example, pass 'backup_mgt=True' to enable this interface as the management backup. :raises EngineCommandFailed: failure creating interface :return: None .. note:: If an existing ip address exists on the interface and zone_ref is provided, this value will overwrite any previous zone definition. """ interfaces = {'interface_id': interface_id, 'interfaces': [{'nodes': [{'address': address, 'network_value': network_value}]}], 'zone_ref': zone_ref, 'comment': comment} interfaces.update(kw) if 'single_fw' in self._engine.type: # L2FW / IPS interfaces.update(interface='single_node_interface') try: interface = self._engine.interface.get(interface_id) interface._add_interface(**interfaces) return interface.update() except InterfaceNotFound: interface = Layer3PhysicalInterface(**interfaces) return self._engine.add_interface(interface)
Add a layer 3 interface on a non-clustered engine. For Layer 2 FW and IPS engines, this interface type represents a layer 3 routed (node dedicated) interface. For clusters, use the cluster related methods such as :func:`add_cluster_virtual_interface` :param str,int interface_id: interface identifier :param str address: ip address :param str network_value: network/cidr (12.12.12.0/24) :param str zone_ref: zone reference, can be name, href or Zone :param kw: keyword arguments are passed to the sub-interface during create time. If the engine is a single FW, the sub-interface type is :class:`smc.core.sub_interfaces.SingleNodeInterface`. For all other engines, the type is :class:`smc.core.sub_interfaces.NodeInterface` For example, pass 'backup_mgt=True' to enable this interface as the management backup. :raises EngineCommandFailed: failure creating interface :return: None .. note:: If an existing ip address exists on the interface and zone_ref is provided, this value will overwrite any previous zone definition.
entailment
def add_layer3_vlan_interface(self, interface_id, vlan_id, address=None, network_value=None, virtual_mapping=None, virtual_resource_name=None, zone_ref=None, comment=None, **kw): """ Add a Layer 3 VLAN interface. Optionally specify an address and network if assigning an IP to the VLAN. This method will also assign an IP address to an existing VLAN, or add an additional address to an existing VLAN. This method may commonly be used on a Master Engine to create VLANs for virtual firewall engines. Example of creating a VLAN and passing kwargs to define a DHCP server service on the VLAN interface:: engine = Engine('engine1') engine.physical_interface.add_layer3_vlan_interface(interface_id=20, vlan_id=20, address='20.20.20.20', network_value='20.20.20.0/24', comment='foocomment', dhcp_server_on_interface={ 'default_gateway': '20.20.20.1', 'default_lease_time': 7200, 'dhcp_address_range': '20.20.20.101-20.20.20.120', 'dhcp_range_per_node': [], 'primary_dns_server': '8.8.8.8'}) :param str,int interface_id: interface identifier :param int vlan_id: vlan identifier :param str address: optional IP address to assign to VLAN :param str network_value: network cidr if address is specified. In format: 10.10.10.0/24. :param str zone_ref: zone to use, by name, href, or Zone :param str comment: optional comment for VLAN level of interface :param int virtual_mapping: virtual engine mapping id See :class:`smc.core.engine.VirtualResource.vfw_id` :param str virtual_resource_name: name of virtual resource See :class:`smc.core.engine.VirtualResource.name` :param dict kw: keyword arguments are passed to top level of VLAN interface, not the base level physical interface. This is useful if you want to pass in a configuration that enables the DHCP server on a VLAN for example. :raises EngineCommandFailed: failure creating interface :return: None """ interfaces = {'nodes': [{'address': address, 'network_value': network_value}] if address and network_value else [], 'zone_ref': zone_ref, 'virtual_mapping': virtual_mapping, 'virtual_resource_name': virtual_resource_name, 'comment': comment} interfaces.update(**kw) _interface = {'interface_id': interface_id, 'interfaces': [interfaces]} if 'single_fw' in self._engine.type: # L2FW / IPS _interface.update(interface='single_node_interface') try: interface = self._engine.interface.get(interface_id) vlan = interface.vlan_interface.get(vlan_id) # Interface exists, so we need to update but check if VLAN already exists if vlan is None: interfaces.update(vlan_id=vlan_id) interface._add_interface(**_interface) else: _interface.update(interface_id='{}.{}'.format(interface_id, vlan_id)) vlan._add_interface(**_interface) return interface.update() except InterfaceNotFound: interfaces.update(vlan_id=vlan_id) interface = Layer3PhysicalInterface(**_interface) return self._engine.add_interface(interface)
Add a Layer 3 VLAN interface. Optionally specify an address and network if assigning an IP to the VLAN. This method will also assign an IP address to an existing VLAN, or add an additional address to an existing VLAN. This method may commonly be used on a Master Engine to create VLANs for virtual firewall engines. Example of creating a VLAN and passing kwargs to define a DHCP server service on the VLAN interface:: engine = Engine('engine1') engine.physical_interface.add_layer3_vlan_interface(interface_id=20, vlan_id=20, address='20.20.20.20', network_value='20.20.20.0/24', comment='foocomment', dhcp_server_on_interface={ 'default_gateway': '20.20.20.1', 'default_lease_time': 7200, 'dhcp_address_range': '20.20.20.101-20.20.20.120', 'dhcp_range_per_node': [], 'primary_dns_server': '8.8.8.8'}) :param str,int interface_id: interface identifier :param int vlan_id: vlan identifier :param str address: optional IP address to assign to VLAN :param str network_value: network cidr if address is specified. In format: 10.10.10.0/24. :param str zone_ref: zone to use, by name, href, or Zone :param str comment: optional comment for VLAN level of interface :param int virtual_mapping: virtual engine mapping id See :class:`smc.core.engine.VirtualResource.vfw_id` :param str virtual_resource_name: name of virtual resource See :class:`smc.core.engine.VirtualResource.name` :param dict kw: keyword arguments are passed to top level of VLAN interface, not the base level physical interface. This is useful if you want to pass in a configuration that enables the DHCP server on a VLAN for example. :raises EngineCommandFailed: failure creating interface :return: None
entailment
def add_layer3_cluster_interface(self, interface_id, cluster_virtual=None, network_value=None, macaddress=None, nodes=None, cvi_mode='packetdispatch', zone_ref=None, comment=None, **kw): """ Add cluster virtual interface. A "CVI" interface is used as a VIP address for clustered engines. Providing 'nodes' will create the node specific interfaces. You can also add a cluster address with only a CVI, or only NDI's. Add CVI only:: engine.physical_interface.add_cluster_virtual_interface( interface_id=30, cluster_virtual='30.30.30.1', network_value='30.30.30.0/24', macaddress='02:02:02:02:02:06') Add NDI's only:: engine.physical_interface.add_cluster_virtual_interface( interface_id=30, nodes=nodes) Add CVI and NDI's:: engine.physical_interface.add_cluster_virtual_interface( cluster_virtual='5.5.5.1', network_value='5.5.5.0/24', macaddress='02:03:03:03:03:03', nodes=[{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1}, {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2}]) .. versionchanged:: 0.6.1 Renamed from add_cluster_virtual_interface :param str,int interface_id: physical interface identifier :param str cluster_virtual: CVI address (VIP) for this interface :param str network_value: network value for VIP; format: 10.10.10.0/24 :param str macaddress: mandatory mac address if cluster_virtual and cluster_mask provided :param list nodes: list of dictionary items identifying cluster nodes :param str cvi_mode: packetdispatch is recommended setting :param str zone_ref: zone reference, can be name, href or Zone :param kw: key word arguments are valid NodeInterface sub-interface settings passed in during create time. For example, 'backup_mgt=True' to enable this interface as the management backup. :raises EngineCommandFailed: failure creating interface :return: None """ interfaces = [{'nodes': nodes if nodes else [], 'cluster_virtual': cluster_virtual, 'network_value': network_value}] try: interface = self._engine.interface.get(interface_id) interface._add_interface(interface_id, interfaces=interfaces) return interface.update() except InterfaceNotFound: interface = ClusterPhysicalInterface( engine=self._engine, interface_id=interface_id, interfaces=interfaces, cvi_mode=cvi_mode if macaddress else 'none', macaddress=macaddress, zone_ref=zone_ref, comment=comment, **kw) return self._engine.add_interface(interface)
Add cluster virtual interface. A "CVI" interface is used as a VIP address for clustered engines. Providing 'nodes' will create the node specific interfaces. You can also add a cluster address with only a CVI, or only NDI's. Add CVI only:: engine.physical_interface.add_cluster_virtual_interface( interface_id=30, cluster_virtual='30.30.30.1', network_value='30.30.30.0/24', macaddress='02:02:02:02:02:06') Add NDI's only:: engine.physical_interface.add_cluster_virtual_interface( interface_id=30, nodes=nodes) Add CVI and NDI's:: engine.physical_interface.add_cluster_virtual_interface( cluster_virtual='5.5.5.1', network_value='5.5.5.0/24', macaddress='02:03:03:03:03:03', nodes=[{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1}, {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2}]) .. versionchanged:: 0.6.1 Renamed from add_cluster_virtual_interface :param str,int interface_id: physical interface identifier :param str cluster_virtual: CVI address (VIP) for this interface :param str network_value: network value for VIP; format: 10.10.10.0/24 :param str macaddress: mandatory mac address if cluster_virtual and cluster_mask provided :param list nodes: list of dictionary items identifying cluster nodes :param str cvi_mode: packetdispatch is recommended setting :param str zone_ref: zone reference, can be name, href or Zone :param kw: key word arguments are valid NodeInterface sub-interface settings passed in during create time. For example, 'backup_mgt=True' to enable this interface as the management backup. :raises EngineCommandFailed: failure creating interface :return: None
entailment
def add_layer3_vlan_cluster_interface(self, interface_id, vlan_id, nodes=None, cluster_virtual=None, network_value=None, macaddress=None, cvi_mode='packetdispatch', zone_ref=None, comment=None, **kw): """ Add IP addresses to VLANs on a firewall cluster. The minimum params required are ``interface_id`` and ``vlan_id``. To create a VLAN interface with a CVI, specify ``cluster_virtual``, ``cluster_mask`` and ``macaddress``. To create a VLAN with only NDI, specify ``nodes`` parameter. Nodes data structure is expected to be in this format:: nodes=[{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1}, {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2}] :param str,int interface_id: interface id to assign VLAN. :param str,int vlan_id: vlan identifier :param list nodes: optional addresses for node interfaces (NDI's). For a cluster, each node will require an address specified using the nodes format. :param str cluster_virtual: cluster virtual ip address (optional). If specified, cluster_mask parameter is required :param str network_value: Specifies the network address, i.e. if cluster virtual is 1.1.1.1, cluster mask could be 1.1.1.0/24. :param str macaddress: (optional) if used will provide the mapping from node interfaces to participate in load balancing. :param str cvi_mode: cvi mode for cluster interface (default: packetdispatch) :param zone_ref: zone to assign, can be name, str href or Zone :param dict kw: keyword arguments are passed to top level of VLAN interface, not the base level physical interface. This is useful if you want to pass in a configuration that enables the DHCP server on a VLAN for example. :raises EngineCommandFailed: failure creating interface :return: None .. note:: If the ``interface_id`` specified already exists, it is still possible to add additional VLANs and interface addresses. """ interfaces = {'nodes': nodes if nodes else [], 'cluster_virtual': cluster_virtual, 'network_value': network_value} interfaces.update(**kw) _interface = {'interface_id': interface_id, 'interfaces': [interfaces], 'macaddress': macaddress, 'cvi_mode': cvi_mode if macaddress else 'none', 'zone_ref': zone_ref, 'comment': comment} try: interface = self._engine.interface.get(interface_id) vlan = interface.vlan_interface.get(vlan_id) # Interface exists, so we need to update but check if VLAN already exists if vlan is None: interfaces.update(vlan_id=vlan_id) interface._add_interface(**_interface) else: for k in ('macaddress', 'cvi_mode'): _interface.pop(k) _interface.update(interface_id='{}.{}'.format(interface_id, vlan_id)) vlan._add_interface(**_interface) return interface.update() except InterfaceNotFound: interfaces.update(vlan_id=vlan_id) interface = ClusterPhysicalInterface(**_interface) return self._engine.add_interface(interface)
Add IP addresses to VLANs on a firewall cluster. The minimum params required are ``interface_id`` and ``vlan_id``. To create a VLAN interface with a CVI, specify ``cluster_virtual``, ``cluster_mask`` and ``macaddress``. To create a VLAN with only NDI, specify ``nodes`` parameter. Nodes data structure is expected to be in this format:: nodes=[{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1}, {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2}] :param str,int interface_id: interface id to assign VLAN. :param str,int vlan_id: vlan identifier :param list nodes: optional addresses for node interfaces (NDI's). For a cluster, each node will require an address specified using the nodes format. :param str cluster_virtual: cluster virtual ip address (optional). If specified, cluster_mask parameter is required :param str network_value: Specifies the network address, i.e. if cluster virtual is 1.1.1.1, cluster mask could be 1.1.1.0/24. :param str macaddress: (optional) if used will provide the mapping from node interfaces to participate in load balancing. :param str cvi_mode: cvi mode for cluster interface (default: packetdispatch) :param zone_ref: zone to assign, can be name, str href or Zone :param dict kw: keyword arguments are passed to top level of VLAN interface, not the base level physical interface. This is useful if you want to pass in a configuration that enables the DHCP server on a VLAN for example. :raises EngineCommandFailed: failure creating interface :return: None .. note:: If the ``interface_id`` specified already exists, it is still possible to add additional VLANs and interface addresses.
entailment
def add_inline_interface(self, interface_id, second_interface_id, logical_interface_ref=None, vlan_id=None, second_vlan_id=None, zone_ref=None, second_zone_ref=None, failure_mode='normal', comment=None, **kw): """ Add an inline interface pair. This method is only for IPS or L2FW engine types. :param str interface_id: interface id of first interface :param str second_interface_id: second interface pair id :param str, href logical_interface_ref: logical interface by href or name :param str vlan_id: vlan ID for first interface in pair :param str second_vlan_id: vlan ID for second interface in pair :param str, href zone_ref: zone reference by name or href for first interface :param str, href second_zone_ref: zone reference by nae or href for second interface :param str failure_mode: normal or bypass :param str comment: optional comment :raises EngineCommandFailed: failure creating interface :return: None """ interface_spec = {'interface_id': interface_id, 'second_interface_id': second_interface_id, 'interface': kw.get('interface') if self._engine.type in ('single_fw', 'fw_cluster') else 'inline_interface'} _interface = {'logical_interface_ref': logical_interface_ref, 'failure_mode': failure_mode, 'zone_ref': zone_ref, 'second_zone_ref': second_zone_ref, 'comment': comment} vlan = {'vlan_id': vlan_id, 'second_vlan_id': second_vlan_id} try: inline_id = '{}-{}'.format(interface_id, second_interface_id) interface = self._engine.interface.get(inline_id) _interface.update(vlan) interface_spec.update(interfaces=[_interface]) interface._add_interface(**interface_spec) return interface.update() except InterfaceNotFound: _interface.update(interfaces=[vlan]) interface_spec.update(_interface) interface = Layer2PhysicalInterface(**interface_spec) return self._engine.add_interface(interface)
Add an inline interface pair. This method is only for IPS or L2FW engine types. :param str interface_id: interface id of first interface :param str second_interface_id: second interface pair id :param str, href logical_interface_ref: logical interface by href or name :param str vlan_id: vlan ID for first interface in pair :param str second_vlan_id: vlan ID for second interface in pair :param str, href zone_ref: zone reference by name or href for first interface :param str, href second_zone_ref: zone reference by nae or href for second interface :param str failure_mode: normal or bypass :param str comment: optional comment :raises EngineCommandFailed: failure creating interface :return: None
entailment
def add_inline_ips_interface(self, interface_id, second_interface_id, logical_interface_ref=None, vlan_id=None, failure_mode='normal', zone_ref=None, second_zone_ref=None, comment=None): """ .. versionadded:: 0.5.6 Using an inline interface on a layer 3 FW requires SMC and engine version >= 6.3. An inline IPS interface is a new interface type for Layer 3 NGFW engines version >=6.3. Traffic passing an Inline IPS interface will have a access rule default action of Allow. Inline IPS interfaces are bypass capable. When using bypass interfaces and NGFW is powered off, in an offline state or overloaded, traffic is allowed through without inspection regardless of the access rules. If the interface does not exist and a VLAN id is specified, the logical interface and zones will be applied to the top level physical interface. If adding VLANs to an existing inline ips pair, the logical and zones will be applied to the VLAN. :param str interface_id: first interface in the interface pair :param str second_interface_id: second interface in the interface pair :param str logical_interface_ref: logical interface name, href or LogicalInterface. If None, 'default_eth' logical interface will be used. :param str vlan_id: optional VLAN id for first interface pair :param str failure_mode: 'normal' or 'bypass' (default: normal). Bypass mode requires fail open interfaces. :param zone_ref: zone for first interface in pair, can be name, str href or Zone :param second_zone_ref: zone for second interface in pair, can be name, str href or Zone :param str comment: comment for this interface :raises EngineCommandFailed: failure creating interface :return: None .. note:: Only a single VLAN is supported on this inline pair type """ _interface = {'interface_id': interface_id, 'second_interface_id': second_interface_id, 'logical_interface_ref': logical_interface_ref, 'failure_mode': failure_mode, 'zone_ref': zone_ref, 'second_zone_ref': second_zone_ref, 'comment': comment, 'interface': 'inline_ips_interface', 'vlan_id': vlan_id} return self.add_inline_interface(**_interface)
.. versionadded:: 0.5.6 Using an inline interface on a layer 3 FW requires SMC and engine version >= 6.3. An inline IPS interface is a new interface type for Layer 3 NGFW engines version >=6.3. Traffic passing an Inline IPS interface will have a access rule default action of Allow. Inline IPS interfaces are bypass capable. When using bypass interfaces and NGFW is powered off, in an offline state or overloaded, traffic is allowed through without inspection regardless of the access rules. If the interface does not exist and a VLAN id is specified, the logical interface and zones will be applied to the top level physical interface. If adding VLANs to an existing inline ips pair, the logical and zones will be applied to the VLAN. :param str interface_id: first interface in the interface pair :param str second_interface_id: second interface in the interface pair :param str logical_interface_ref: logical interface name, href or LogicalInterface. If None, 'default_eth' logical interface will be used. :param str vlan_id: optional VLAN id for first interface pair :param str failure_mode: 'normal' or 'bypass' (default: normal). Bypass mode requires fail open interfaces. :param zone_ref: zone for first interface in pair, can be name, str href or Zone :param second_zone_ref: zone for second interface in pair, can be name, str href or Zone :param str comment: comment for this interface :raises EngineCommandFailed: failure creating interface :return: None .. note:: Only a single VLAN is supported on this inline pair type
entailment
def add_inline_l2fw_interface(self, interface_id, second_interface_id, logical_interface_ref=None, vlan_id=None, zone_ref=None, second_zone_ref=None, comment=None): """ .. versionadded:: 0.5.6 Requires NGFW engine >=6.3 and layer 3 FW or cluster An inline L2 FW interface is a new interface type for Layer 3 NGFW engines version >=6.3. Traffic passing an Inline Layer 2 Firewall interface will have a default action in access rules of Discard. Layer 2 Firewall interfaces are not bypass capable, so when NGFW is powered off, in an offline state or overloaded, traffic is blocked on this interface. If the interface does not exist and a VLAN id is specified, the logical interface and zones will be applied to the top level physical interface. If adding VLANs to an existing inline ips pair, the logical and zones will be applied to the VLAN. :param str interface_id: interface id; '1-2', '3-4', etc :param str logical_interface_ref: logical interface name, href or LogicalInterface. If None, 'default_eth' logical interface will be used. :param str vlan_id: optional VLAN id for first interface pair :param str vlan_id2: optional VLAN id for second interface pair :param zone_ref_intf1: zone for first interface in pair, can be name, str href or Zone :param zone_ref_intf2: zone for second interface in pair, can be name, str href or Zone :raises EngineCommandFailed: failure creating interface :return: None .. note:: Only a single VLAN is supported on this inline pair type """ _interface = {'interface_id': interface_id, 'second_interface_id': second_interface_id, 'logical_interface_ref': logical_interface_ref, 'failure_mode': 'normal', 'zone_ref': zone_ref, 'second_zone_ref': second_zone_ref, 'comment': comment, 'interface': 'inline_l2fw_interface', 'vlan_id': vlan_id} return self.add_inline_interface(**_interface)
.. versionadded:: 0.5.6 Requires NGFW engine >=6.3 and layer 3 FW or cluster An inline L2 FW interface is a new interface type for Layer 3 NGFW engines version >=6.3. Traffic passing an Inline Layer 2 Firewall interface will have a default action in access rules of Discard. Layer 2 Firewall interfaces are not bypass capable, so when NGFW is powered off, in an offline state or overloaded, traffic is blocked on this interface. If the interface does not exist and a VLAN id is specified, the logical interface and zones will be applied to the top level physical interface. If adding VLANs to an existing inline ips pair, the logical and zones will be applied to the VLAN. :param str interface_id: interface id; '1-2', '3-4', etc :param str logical_interface_ref: logical interface name, href or LogicalInterface. If None, 'default_eth' logical interface will be used. :param str vlan_id: optional VLAN id for first interface pair :param str vlan_id2: optional VLAN id for second interface pair :param zone_ref_intf1: zone for first interface in pair, can be name, str href or Zone :param zone_ref_intf2: zone for second interface in pair, can be name, str href or Zone :raises EngineCommandFailed: failure creating interface :return: None .. note:: Only a single VLAN is supported on this inline pair type
entailment
def add_dhcp_interface(self, interface_id, dynamic_index, zone_ref=None, vlan_id=None, comment=None): """ Add a DHCP interface on a single FW :param int interface_id: interface id :param int dynamic_index: index number for dhcp interface :param bool primary_mgt: whether to make this primary mgt :param str zone_ref: zone reference, can be name, href or Zone :raises EngineCommandFailed: failure creating interface :return: None See :class:`~DHCPInterface` for more information """ _interface = {'interface_id': interface_id, 'interfaces': [{'nodes': [ {'dynamic': True, 'dynamic_index': dynamic_index}], 'vlan_id': vlan_id}], 'comment': comment, 'zone_ref': zone_ref} if 'single_fw' in self._engine.type: _interface.update(interface='single_node_interface') try: interface = self._engine.interface.get(interface_id) vlan = interface.vlan_interface.get(vlan_id) # Interface exists, so we need to update but check if VLAN already exists if vlan is None: interface._add_interface(**_interface) interface.update() except InterfaceNotFound: interface = Layer3PhysicalInterface(**_interface) return self._engine.add_interface(interface)
Add a DHCP interface on a single FW :param int interface_id: interface id :param int dynamic_index: index number for dhcp interface :param bool primary_mgt: whether to make this primary mgt :param str zone_ref: zone reference, can be name, href or Zone :raises EngineCommandFailed: failure creating interface :return: None See :class:`~DHCPInterface` for more information
entailment
def add_cluster_interface_on_master_engine(self, interface_id, macaddress, nodes, zone_ref=None, vlan_id=None, comment=None): """ Add a cluster address specific to a master engine. Master engine clusters will not use "CVI" interfaces like normal layer 3 FW clusters, instead each node has a unique address and share a common macaddress. Adding multiple addresses to an interface is not supported with this method. :param str,int interface_id: interface id to use :param str macaddress: mac address to use on interface :param list nodes: interface node list :param bool is_mgmt: is this a management interface :param zone_ref: zone to use, by name, str href or Zone :param vlan_id: optional VLAN id if this should be a VLAN interface :raises EngineCommandFailed: failure creating interface :return: None """ _interface = {'interface_id': interface_id, 'macaddress': macaddress, 'interfaces': [{'nodes': nodes if nodes else [], 'vlan_id': vlan_id}], 'zone_ref': zone_ref, 'comment': comment} try: interface = self._engine.interface.get(interface_id) vlan = interface.vlan_interface.get(vlan_id) # Interface exists, so we need to update but check if VLAN already exists if vlan is None: interface._add_interface(**_interface) interface.update() except InterfaceNotFound: interface = Layer3PhysicalInterface(**_interface) return self._engine.add_interface(interface)
Add a cluster address specific to a master engine. Master engine clusters will not use "CVI" interfaces like normal layer 3 FW clusters, instead each node has a unique address and share a common macaddress. Adding multiple addresses to an interface is not supported with this method. :param str,int interface_id: interface id to use :param str macaddress: mac address to use on interface :param list nodes: interface node list :param bool is_mgmt: is this a management interface :param zone_ref: zone to use, by name, str href or Zone :param vlan_id: optional VLAN id if this should be a VLAN interface :raises EngineCommandFailed: failure creating interface :return: None
entailment
def add_tunnel_interface(self, interface_id, address, network_value, zone_ref=None, comment=None): """ Creates a tunnel interface for a virtual engine. :param str,int interface_id: the tunnel id for the interface, used as nicid also :param str address: ip address of interface :param str network_value: network cidr for interface; format: 1.1.1.0/24 :param str zone_ref: zone reference for interface can be name, href or Zone :raises EngineCommandFailed: failure during creation :return: None """ interfaces = [{'nodes': [{'address': address, 'network_value': network_value}]}] interface = {'interface_id': interface_id, 'interfaces': interfaces, 'zone_ref': zone_ref, 'comment': comment} tunnel_interface = TunnelInterface(**interface) self._engine.add_interface(tunnel_interface)
Creates a tunnel interface for a virtual engine. :param str,int interface_id: the tunnel id for the interface, used as nicid also :param str address: ip address of interface :param str network_value: network cidr for interface; format: 1.1.1.0/24 :param str zone_ref: zone reference for interface can be name, href or Zone :raises EngineCommandFailed: failure during creation :return: None
entailment