sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def create(self, name, action='permit', goto=None, finish=False, call=None, comment=None, add_pos=None, after=None, before=None, **match_condition): """ Create a route map rule. You can provide match conditions by using keyword arguments specifying the required types. You can also create the route map rule and add match conditions after. :param str name: name for this rule :param str action: permit or deny :param str goto: specify a rule section to goto after if there is a match condition. This will override the finish parameter :param bool finish: finish stops the processing after a match condition. If finish is False, processing will continue to the next rule. :param RouteMap call: call another route map after matching. :param str comment: optional comment for the rule :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :param match_condition: keyword values identifying initial values for the match condition. Valid keyword arguments are 'access_list', 'next_hop', 'metric' and 'peer_address'. You can also optionally pass the keyword 'match_condition' with an instance of MatchCondition. :raises CreateRuleFailed: failure to insert rule with reason :raises ElementNotFound: if references elements in a match condition this can be raised when the element specified is not found. .. seealso:: :class:`~MatchCondition` for valid elements and expected values for each type. """ json = {'name': name, 'action': action, 'finish': finish, 'goto': goto.href if goto else None, 'call_route_map_ref': None if not call else call.href, 'comment': comment} if not match_condition: json.update(match_condition=[]) else: if 'match_condition' in match_condition: conditions = match_condition.pop('match_condition') else: conditions = MatchCondition() if 'peer_address' in match_condition: conditions.add_peer_address( match_condition.pop('peer_address')) if 'next_hop' in match_condition: conditions.add_next_hop( match_condition.pop('next_hop')) if 'metric' in match_condition: conditions.add_metric( match_condition.pop('metric')) if 'access_list' in match_condition: conditions.add_access_list( match_condition.pop('access_list')) json.update(match_condition=conditions.conditions) params = None href = self.href if add_pos is not None: href = self.add_at_position(add_pos) elif before or after: params = self.add_before_after(before, after) return ElementCreator( self.__class__, exception=CreateRuleFailed, href=href, params=params, json=json)
Create a route map rule. You can provide match conditions by using keyword arguments specifying the required types. You can also create the route map rule and add match conditions after. :param str name: name for this rule :param str action: permit or deny :param str goto: specify a rule section to goto after if there is a match condition. This will override the finish parameter :param bool finish: finish stops the processing after a match condition. If finish is False, processing will continue to the next rule. :param RouteMap call: call another route map after matching. :param str comment: optional comment for the rule :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :param match_condition: keyword values identifying initial values for the match condition. Valid keyword arguments are 'access_list', 'next_hop', 'metric' and 'peer_address'. You can also optionally pass the keyword 'match_condition' with an instance of MatchCondition. :raises CreateRuleFailed: failure to insert rule with reason :raises ElementNotFound: if references elements in a match condition this can be raised when the element specified is not found. .. seealso:: :class:`~MatchCondition` for valid elements and expected values for each type.
entailment
def search_rule(self, search): """ Search the RouteMap policy using a search string :param str search: search string for a contains match against the rule name and comments field :rtype: list(RouteMapRule) """ return [RouteMapRule(**rule) for rule in self.make_request( resource='search_rule', params={'filter': search})]
Search the RouteMap policy using a search string :param str search: search string for a contains match against the rule name and comments field :rtype: list(RouteMapRule)
entailment
def create(cls, name, certificate): """ Create a new external VPN CA for signing internal gateway certificates. :param str name: Name of VPN CA :param str certificate: file name, path or certificate string. :raises CreateElementFailed: Failed creating cert with reason :rtype: VPNCertificateCA """ json = {'name': name, 'certificate': certificate} return ElementCreator(cls, json)
Create a new external VPN CA for signing internal gateway certificates. :param str name: Name of VPN CA :param str certificate: file name, path or certificate string. :raises CreateElementFailed: Failed creating cert with reason :rtype: VPNCertificateCA
entailment
def _create(self, common_name, public_key_algorithm='rsa', signature_algorithm='rsa_sha_512', key_length=2048, signing_ca=None): """ Internal method called as a reference from the engine.vpn node """ if signing_ca is None: signing_ca = VPNCertificateCA.objects.filter('Internal RSA').first() cert_auth = element_resolver(signing_ca) return ElementCreator( GatewayCertificate, exception=CertificateError, href=self.internal_gateway.get_relation('generate_certificate'), json={ 'common_name': common_name, 'public_key_algorithm': public_key_algorithm, 'signature_algorithm': signature_algorithm, 'public_key_length': key_length, 'certificate_authority_href': cert_auth})
Internal method called as a reference from the engine.vpn node
entailment
def create(cls, name, min_dst_port, max_dst_port=None, min_src_port=None, max_src_port=None, protocol_agent=None, comment=None): """ Create the TCP service :param str name: name of tcp service :param int min_dst_port: minimum destination port value :param int max_dst_port: maximum destination port value :param int min_src_port: minimum source port value :param int max_src_port: maximum source port value :param str,ProtocolAgent protocol_agent: optional protocol agent for this service :param str comment: optional comment for service :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: TCPService """ max_dst_port = max_dst_port if max_dst_port is not None else '' json = {'name': name, 'min_dst_port': min_dst_port, 'max_dst_port': max_dst_port, 'min_src_port': min_src_port, 'max_src_port': max_src_port, 'protocol_agent_ref': element_resolver(protocol_agent) or None, 'comment': comment} return ElementCreator(cls, json)
Create the TCP service :param str name: name of tcp service :param int min_dst_port: minimum destination port value :param int max_dst_port: maximum destination port value :param int min_src_port: minimum source port value :param int max_src_port: maximum source port value :param str,ProtocolAgent protocol_agent: optional protocol agent for this service :param str comment: optional comment for service :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: TCPService
entailment
def create(cls, name, protocol_number, protocol_agent=None, comment=None): """ Create the IP Service :param str name: name of ip-service :param int protocol_number: ip proto number for this service :param str,ProtocolAgent protocol_agent: optional protocol agent for this service :param str comment: optional comment :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: IPService """ json = {'name': name, 'protocol_number': protocol_number, 'protocol_agent_ref': element_resolver(protocol_agent) or None, 'comment': comment} return ElementCreator(cls, json)
Create the IP Service :param str name: name of ip-service :param int protocol_number: ip proto number for this service :param str,ProtocolAgent protocol_agent: optional protocol agent for this service :param str comment: optional comment :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: IPService
entailment
def create(cls, name, frame_type='eth2', value1=None, comment=None): """ Create an ethernet service :param str name: name of service :param str frame_type: ethernet frame type, eth2 :param str value1: hex code representing ethertype field :param str comment: optional comment :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: EthernetService """ json = {'frame_type': frame_type, 'name': name, 'value1': int(value1, 16), 'comment': comment} return ElementCreator(cls, json)
Create an ethernet service :param str name: name of service :param str frame_type: ethernet frame type, eth2 :param str value1: hex code representing ethertype field :param str comment: optional comment :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: EthernetService
entailment
def custom_range(self, start_time, end_time=None): """ Provide a custom range for the search query. Start time and end time are expected to be naive ``datetime`` objects converted to milliseconds. When submitting the query, it is strongly recommended to set the timezone matching the local client making the query. Example of finding all records on 9/2/2017 from 06:25:30 to 06:26:30 in the local time zone CST:: dt_start = datetime(2017, 9, 2, 6, 25, 30, 0) dt_end = datetime(2017, 9, 2, 6, 26, 30, 0) query = LogQuery() query.format.timezone('CST') query.time_range.custom_range( datetime_to_ms(dt_start), datetime_to_ms(dt_end)) for record in query.fetch_batch(): print(record) Last two minutes from current (py2):: now = datetime.now() start_time = int((now - timedelta(minutes=2)).strftime('%s'))*1000 Specific start time (py2):: p2time = datetime.strptime("1.8.2017 08:26:42,76", "%d.%m.%Y %H:%M:%S,%f").strftime('%s') p2time = int(s)*1000 Specific start time (py3):: p3time = datetime.strptime("1.8.2017 08:40:42,76", "%d.%m.%Y %H:%M:%S,%f") p3time.timestamp() * 1000 :param int start_time: search start time in milliseconds. Start time represents the oldest timestamp. :param int end_time: search end time in milliseconds. End time represents the newest timestamp. """ if end_time is None: end_time = current_millis() self.data.update( start_ms=start_time, end_ms=end_time) return self
Provide a custom range for the search query. Start time and end time are expected to be naive ``datetime`` objects converted to milliseconds. When submitting the query, it is strongly recommended to set the timezone matching the local client making the query. Example of finding all records on 9/2/2017 from 06:25:30 to 06:26:30 in the local time zone CST:: dt_start = datetime(2017, 9, 2, 6, 25, 30, 0) dt_end = datetime(2017, 9, 2, 6, 26, 30, 0) query = LogQuery() query.format.timezone('CST') query.time_range.custom_range( datetime_to_ms(dt_start), datetime_to_ms(dt_end)) for record in query.fetch_batch(): print(record) Last two minutes from current (py2):: now = datetime.now() start_time = int((now - timedelta(minutes=2)).strftime('%s'))*1000 Specific start time (py2):: p2time = datetime.strptime("1.8.2017 08:26:42,76", "%d.%m.%Y %H:%M:%S,%f").strftime('%s') p2time = int(s)*1000 Specific start time (py3):: p3time = datetime.strptime("1.8.2017 08:40:42,76", "%d.%m.%Y %H:%M:%S,%f") p3time.timestamp() * 1000 :param int start_time: search start time in milliseconds. Start time represents the oldest timestamp. :param int end_time: search end time in milliseconds. End time represents the newest timestamp.
entailment
def pem_as_string(cert): """ Only return False if the certificate is a file path. Otherwise it is a file object or raw string and will need to be fed to the file open context. """ if hasattr(cert, 'read'): # File object - return as is return cert cert = cert.encode('utf-8') if isinstance(cert, unicode) else cert if re.match(_PEM_RE, cert): return True return False
Only return False if the certificate is a file path. Otherwise it is a file object or raw string and will need to be fed to the file open context.
entailment
def load_cert_chain(chain_file): """ Load the certificates from the chain file. :raises IOError: Failure to read specified file :raises ValueError: Format issues with chain file or missing entries :return: list of cert type matches """ if hasattr(chain_file, 'read'): cert_chain = chain_file.read() else: with open(chain_file, 'rb') as f: cert_chain = f.read() if not cert_chain: raise ValueError('Certificate chain file is empty!') cert_type_matches = [] for match in _PEM_RE.finditer(cert_chain): cert_type_matches.append((match.group(1), match.group(0))) if not cert_type_matches: raise ValueError('No certificate types were found. Valid types ' 'are: {}'.format(CERT_TYPES)) return cert_type_matches
Load the certificates from the chain file. :raises IOError: Failure to read specified file :raises ValueError: Format issues with chain file or missing entries :return: list of cert type matches
entailment
def import_certificate(self, certificate): """ Import a valid certificate. Certificate can be either a file path or a string of the certificate. If string certificate, it must include the -----BEGIN CERTIFICATE----- string. :param str certificate_file: fully qualified path to certificate file :raises CertificateImportError: failure to import cert with reason :raises IOError: file not found, permissions, etc. :return: None """ multi_part = 'signed_certificate' if self.typeof == 'tls_server_credentials'\ else 'certificate' self.make_request( CertificateImportError, method='create', resource='certificate_import', headers = {'content-type': 'multipart/form-data'}, files={ multi_part: open(certificate, 'rb') if not \ pem_as_string(certificate) else certificate })
Import a valid certificate. Certificate can be either a file path or a string of the certificate. If string certificate, it must include the -----BEGIN CERTIFICATE----- string. :param str certificate_file: fully qualified path to certificate file :raises CertificateImportError: failure to import cert with reason :raises IOError: file not found, permissions, etc. :return: None
entailment
def import_intermediate_certificate(self, certificate): """ Import a valid certificate. Certificate can be either a file path or a string of the certificate. If string certificate, it must include the -----BEGIN CERTIFICATE----- string. :param str certificate: fully qualified path or string :raises CertificateImportError: failure to import cert with reason :raises IOError: file not found, permissions, etc. :return: None """ self.make_request( CertificateImportError, method='create', resource='intermediate_certificate_import', headers = {'content-type': 'multipart/form-data'}, files={ 'signed_certificate': open(certificate, 'rb') if not \ pem_as_string(certificate) else certificate })
Import a valid certificate. Certificate can be either a file path or a string of the certificate. If string certificate, it must include the -----BEGIN CERTIFICATE----- string. :param str certificate: fully qualified path or string :raises CertificateImportError: failure to import cert with reason :raises IOError: file not found, permissions, etc. :return: None
entailment
def export_intermediate_certificate(self, filename=None): """ Export the intermediate certificate. Returned certificate will be in string format. If filename is provided, the certificate will also be saved to the file specified. :raises CertificateExportError: error exporting certificate, can occur if no intermediate certificate is available. :rtype: str or None """ result = self.make_request( CertificateExportError, raw_result=True, resource='intermediate_certificate_export') if filename is not None: save_to_file(filename, result.content) return return result.content
Export the intermediate certificate. Returned certificate will be in string format. If filename is provided, the certificate will also be saved to the file specified. :raises CertificateExportError: error exporting certificate, can occur if no intermediate certificate is available. :rtype: str or None
entailment
def import_private_key(self, private_key): """ Import a private key. The private key can be a path to a file or the key in string format. If in string format, the key must start with -----BEGIN. Key types supported are PRIVATE RSA KEY and PRIVATE KEY. :param str private_key: fully qualified path to private key file :raises CertificateImportError: failure to import cert with reason :raises IOError: file not found, permissions, etc. :return: None """ self.make_request( CertificateImportError, method='create', resource='private_key_import', headers = {'content-type': 'multipart/form-data'}, files={ 'private_key': open(private_key, 'rb') if not \ pem_as_string(private_key) else private_key })
Import a private key. The private key can be a path to a file or the key in string format. If in string format, the key must start with -----BEGIN. Key types supported are PRIVATE RSA KEY and PRIVATE KEY. :param str private_key: fully qualified path to private key file :raises CertificateImportError: failure to import cert with reason :raises IOError: file not found, permissions, etc. :return: None
entailment
def get(self, rel): """ Get the resource by rel name :param str rel_name: name of rel :raises UnsupportedEntryPoint: entry point not found in this version of the API """ for link in self._entry_points: if link.get('rel') == rel: return link.get('href') raise UnsupportedEntryPoint( "The specified entry point '{}' was not found in this " "version of the SMC API. Check the element documentation " "to determine the correct version and specify the api_version " "parameter during session.login() if necessary.".format(rel))
Get the resource by rel name :param str rel_name: name of rel :raises UnsupportedEntryPoint: entry point not found in this version of the API
entailment
def on_open(self): """ Once the connection is made, start the query off and start an event loop to wait for a signal to stop. Results are yielded within receive(). """ def event_loop(): logger.debug(pformat(self.query.request)) self.send(json.dumps(self.query.request)) while not self.event.is_set(): #print('Waiting around on the socket: %s' % self.gettimeout()) self.event.wait(self.gettimeout()) logger.debug('Event loop terminating.') self.thread = threading.Thread( target=event_loop) self.thread.setDaemon(True) self.thread.start()
Once the connection is made, start the query off and start an event loop to wait for a signal to stop. Results are yielded within receive().
entailment
def send_message(self, message): """ Send a message down the socket. The message is expected to have a `request` attribute that holds the message to be serialized and sent. """ if self.connected: self.send( json.dumps(message.request))
Send a message down the socket. The message is expected to have a `request` attribute that holds the message to be serialized and sent.
entailment
def receive(self): """ Generator yielding results from the web socket. Results will come as they are received. Even though socket select has a timeout, the SMC will not reply with a message more than every two minutes. """ try: itr = 0 while self.connected: r, w, e = select.select( (self.sock, ), (), (), 10.0) if r: message = json.loads(self.recv()) if 'fetch' in message: self.fetch_id = message['fetch'] if 'failure' in message: raise InvalidFetch(message['failure']) if 'records' in message: if 'added' in message['records']: num = len(message['records']['added']) else: num = len(message['records']) logger.debug('Query returned %s records.', num) if self.max_recv: itr += 1 if 'end' in message: logger.debug('Received end message: %s' % message['end']) yield message break yield message if self.max_recv and self.max_recv <= itr: break except (Exception, KeyboardInterrupt, SystemExit, FetchAborted) as e: logger.info('Caught exception in receive: %s -> %s', type(e), str(e)) if isinstance(e, (SystemExit, InvalidFetch)): # propagate SystemExit, InvalidFetch raise finally: if self.connected: if self.fetch_id: self.send(json.dumps({'abort': self.fetch_id})) self.close() if self.thread: self.event.set() while self.thread.isAlive(): self.event.wait(1) logger.info('Closed web socket connection normally.')
Generator yielding results from the web socket. Results will come as they are received. Even though socket select has a timeout, the SMC will not reply with a message more than every two minutes.
entailment
def LoadElement(href, only_etag=False): """ Return an instance of a element as a ElementCache dict used as a cache. :rtype ElementCache """ request = SMCRequest(href=href) request.exception = FetchElementFailed result = request.read() if only_etag: return result.etag return ElementCache( result.json, etag=result.etag)
Return an instance of a element as a ElementCache dict used as a cache. :rtype ElementCache
entailment
def ElementCreator(cls, json, **kwargs): """ Helper method for creating elements. If the created element type is a SubElement class type, provide href value as kwargs since that class type does not have a direct entry point. This is a lazy load that will provide only the meta for the element. Additional attribute access will load the full data. :param Element,SubElement cls: class for creating :param dict json: json payload :param SMCException exception: exception class to override :return: instance of type Element with meta :rtype: Element """ if 'exception' not in kwargs: kwargs.update(exception=CreateElementFailed) href = kwargs.pop('href') if 'href' in kwargs else cls.href result = SMCRequest( href=href, json=json, **kwargs).create() element = cls( name=json.get('name'), type=cls.typeof, href=result.href) if result.user_session.in_atomic_block: result.user_session.transactions.append(element) return element
Helper method for creating elements. If the created element type is a SubElement class type, provide href value as kwargs since that class type does not have a direct entry point. This is a lazy load that will provide only the meta for the element. Additional attribute access will load the full data. :param Element,SubElement cls: class for creating :param dict json: json payload :param SMCException exception: exception class to override :return: instance of type Element with meta :rtype: Element
entailment
def ElementFactory(href, smcresult=None, raise_exc=None): """ Factory returns an object of type Element when only the href is provided. :param str href: string href to fetch :param SMCResult smcresult: optional SMCResult. If provided, the request fetch will be skipped :param Exception raise_exc: exception to raise if fetch failed """ if smcresult is None: smcresult = SMCRequest(href=href).read() if smcresult.json: cache = ElementCache(smcresult.json, etag=smcresult.etag) typeof = lookup_class(cache.type) instance = typeof( name=cache.get('name'), href=href, type=cache.type) instance.data = cache return instance if raise_exc and smcresult.msg: raise raise_exc(smcresult.msg)
Factory returns an object of type Element when only the href is provided. :param str href: string href to fetch :param SMCResult smcresult: optional SMCResult. If provided, the request fetch will be skipped :param Exception raise_exc: exception to raise if fetch failed
entailment
def etag(self, href): """ ETag can be None if a subset of element json is using this container, such as the case with Routing. """ if self and self._etag is None: self._etag = LoadElement(href, only_etag=True) return self._etag
ETag can be None if a subset of element json is using this container, such as the case with Routing.
entailment
def get_link(self, rel): """ Return link for specified resource """ if rel in self.links: return self.links[rel] raise ResourceNotFound('Resource requested: %r is not available ' 'on this element.' % rel)
Return link for specified resource
entailment
def get(cls, name, raise_exc=True): """ Get the element by name. Does an exact match by element type. :param str name: name of element :param bool raise_exc: optionally disable exception. :raises ElementNotFound: if element does not exist :rtype: Element """ element = cls.objects.filter(name, exact_match=True).first() if \ name is not None else None if not element and raise_exc: raise ElementNotFound('Cannot find specified element: %s, type: ' '%s' % (name, cls.__name__)) return element
Get the element by name. Does an exact match by element type. :param str name: name of element :param bool raise_exc: optionally disable exception. :raises ElementNotFound: if element does not exist :rtype: Element
entailment
def get_or_create(cls, filter_key=None, with_status=False, **kwargs): """ Convenience method to retrieve an Element or create if it does not exist. If an element does not have a `create` classmethod, then it is considered read-only and the request will be redirected to :meth:`~get`. Any keyword arguments passed except the optional filter_key will be used in a create() call. If filter_key is provided, this should define an attribute and value to use for an exact match on the element. Valid attributes are ones required on the elements ``create`` method or can be viewed by the elements class docs. If no filter_key is provided, the name field will be used to find the element. :: >>> Network.get_or_create( filter_key={'ipv4_network': '123.123.123.0/24'}, name='mynetwork', ipv4_network='123.123.123.0/24') Network(name=mynetwork) The kwargs should be used to satisfy the elements ``create`` classmethod parameters to create in the event it cannot be found. :param dict filter_key: filter key represents the data attribute and value to use to find the element. If none is provided, the name field will be used. :param kwargs: keyword arguments mapping to the elements ``create`` method. :param bool with_status: if set to True, a tuple is returned with (Element, created), where the second tuple item indicates if the element has been created or not. :raises CreateElementFailed: could not create element with reason :raises ElementNotFound: if read-only element does not exist :return: element instance by type :rtype: Element """ was_created = False if 'name' not in kwargs: raise ElementNotFound('Name field is a required parameter ' 'for all create or update_or_create type operations on an element') if filter_key: elements = cls.objects.filter(**filter_key) element = elements.first() if elements.exists() else None else: try: element = cls.get(kwargs.get('name')) except ElementNotFound: if not hasattr(cls, 'create'): raise CreateElementFailed('%s: %r not found and this element ' 'type does not have a create method.' % (cls.__name__, kwargs['name'])) element = None if not element: params = {k: v() if callable(v) else v for k, v in kwargs.items()} try: element = cls.create(**params) was_created = True except TypeError: raise CreateElementFailed('%s: %r not found and missing ' 'constructor arguments to properly create.' % (cls.__name__, kwargs['name'])) if with_status: return element, was_created return element
Convenience method to retrieve an Element or create if it does not exist. If an element does not have a `create` classmethod, then it is considered read-only and the request will be redirected to :meth:`~get`. Any keyword arguments passed except the optional filter_key will be used in a create() call. If filter_key is provided, this should define an attribute and value to use for an exact match on the element. Valid attributes are ones required on the elements ``create`` method or can be viewed by the elements class docs. If no filter_key is provided, the name field will be used to find the element. :: >>> Network.get_or_create( filter_key={'ipv4_network': '123.123.123.0/24'}, name='mynetwork', ipv4_network='123.123.123.0/24') Network(name=mynetwork) The kwargs should be used to satisfy the elements ``create`` classmethod parameters to create in the event it cannot be found. :param dict filter_key: filter key represents the data attribute and value to use to find the element. If none is provided, the name field will be used. :param kwargs: keyword arguments mapping to the elements ``create`` method. :param bool with_status: if set to True, a tuple is returned with (Element, created), where the second tuple item indicates if the element has been created or not. :raises CreateElementFailed: could not create element with reason :raises ElementNotFound: if read-only element does not exist :return: element instance by type :rtype: Element
entailment
def update_or_create(cls, filter_key=None, with_status=False, **kwargs): """ Update or create the element. If the element exists, update it using the kwargs provided if the provided kwargs after resolving differences from existing values. When comparing values, strings and ints are compared directly. If a list is provided and is a list of strings, it will be compared and updated if different. If the list contains unhashable elements, it is skipped. To handle complex comparisons, override this method on the subclass and process the comparison seperately. If an element does not have a `create` classmethod, then it is considered read-only and the request will be redirected to :meth:`~get`. Provide a ``filter_key`` dict key/value if you want to match the element by a specific attribute and value. If no filter_key is provided, the name field will be used to find the element. :: >>> host = Host('kali') >>> print(host.address) 12.12.12.12 >>> host = Host.update_or_create(name='kali', address='10.10.10.10') >>> print(host, host.address) Host(name=kali) 10.10.10.10 :param dict filter_key: filter key represents the data attribute and value to use to find the element. If none is provided, the name field will be used. :param kwargs: keyword arguments mapping to the elements ``create`` method. :param bool with_status: if set to True, a 3-tuple is returned with (Element, modified, created), where the second and third tuple items are booleans indicating the status :raises CreateElementFailed: could not create element with reason :raises ElementNotFound: if read-only element does not exist :return: element instance by type :rtype: Element """ updated = False # Providing this flag will return before updating and require the calling # class to call update if changes were made. defer_update = kwargs.pop('defer_update', False) if defer_update: with_status = True element, created = cls.get_or_create(filter_key=filter_key, with_status=True, **kwargs) if not created: for key, value in kwargs.items(): # Callable, Element or string if callable(value): value = value() elif isinstance(value, Element): value = value.href # Retrieve the 'type' of instance attribute. This is used to # serialize attributes that resolve href's to elements. It # provides a common structure but also prevents the fetching # of the href to element when doing an equality comparison attr_type = getattr(type(element), key, None) if isinstance(attr_type, ElementRef): attr_name = getattr(attr_type, 'attr', None) if element.data.get(attr_name) != value: element.data[attr_name] = value updated = True continue elif isinstance(attr_type, ElementList): value_hrefs = element_resolver(value) # Resolve the elements to href attr_name = getattr(attr_type, 'attr', None) if set(element.data.get(attr_name, [])) != set(value_hrefs): element.data[attr_name] = value_hrefs updated = True continue # Type is not 'special', therefore we are expecting only strings, # integer types or list of strings. Complex data structures # will be handled later through encapsulation and __eq__, __hash__ # for comparison. The keys value type here is going to assume the # provided value is of the right type as the key may not necessarily # exist in the cached json. if isinstance(value, (string_types, int)): # also covers bool val = getattr(element, key, None) if val != value: element.data[key] = value updated = True elif isinstance(value, list) and all(isinstance(s, string_types) for s in value): # List of simple strings (assuming the attribute is also!) if set(value) ^ set(element.data.get(key, [])): element.data[key] = value updated = True # Complex lists, objects, etc will fall down here and be skipped. # To process these, provide defer_update=True, override update_or_create, # process the complex object deltas and call update() if updated and not defer_update: element.update() if with_status: return element, updated, created return element
Update or create the element. If the element exists, update it using the kwargs provided if the provided kwargs after resolving differences from existing values. When comparing values, strings and ints are compared directly. If a list is provided and is a list of strings, it will be compared and updated if different. If the list contains unhashable elements, it is skipped. To handle complex comparisons, override this method on the subclass and process the comparison seperately. If an element does not have a `create` classmethod, then it is considered read-only and the request will be redirected to :meth:`~get`. Provide a ``filter_key`` dict key/value if you want to match the element by a specific attribute and value. If no filter_key is provided, the name field will be used to find the element. :: >>> host = Host('kali') >>> print(host.address) 12.12.12.12 >>> host = Host.update_or_create(name='kali', address='10.10.10.10') >>> print(host, host.address) Host(name=kali) 10.10.10.10 :param dict filter_key: filter key represents the data attribute and value to use to find the element. If none is provided, the name field will be used. :param kwargs: keyword arguments mapping to the elements ``create`` method. :param bool with_status: if set to True, a 3-tuple is returned with (Element, modified, created), where the second and third tuple items are booleans indicating the status :raises CreateElementFailed: could not create element with reason :raises ElementNotFound: if read-only element does not exist :return: element instance by type :rtype: Element
entailment
def add_category(self, category): """ Category Tags are used to characterize an element by a type identifier. They can then be searched and returned as a group of elements. If the category tag specified does not exist, it will be created. This change will take effect immediately. :param list tags: list of category tag names to add to this element :type tags: list(str) :raises ElementNotFound: Category tag element name not found :return: None .. seealso:: :class:`smc.elements.other.Category` """ assert isinstance(category, list), 'Category input was expecting list.' from smc.elements.other import Category for tag in category: category = Category(tag) try: category.add_element(self.href) except ElementNotFound: Category.create(name=tag) category.add_element(self.href)
Category Tags are used to characterize an element by a type identifier. They can then be searched and returned as a group of elements. If the category tag specified does not exist, it will be created. This change will take effect immediately. :param list tags: list of category tag names to add to this element :type tags: list(str) :raises ElementNotFound: Category tag element name not found :return: None .. seealso:: :class:`smc.elements.other.Category`
entailment
def export(self, filename='element.zip'): """ Export this element. Usage:: engine = Engine('myfirewall') extask = engine.export(filename='fooexport.zip') while not extask.done(): extask.wait(3) print("Finished download task: %s" % extask.message()) print("File downloaded to: %s" % extask.filename) :param str filename: filename to store exported element :raises TaskRunFailed: invalid permissions, invalid directory, or this element is a system element and cannot be exported. :return: DownloadTask .. note:: It is not possible to export system elements """ from smc.administration.tasks import Task return Task.download(self, 'export', filename)
Export this element. Usage:: engine = Engine('myfirewall') extask = engine.export(filename='fooexport.zip') while not extask.done(): extask.wait(3) print("Finished download task: %s" % extask.message()) print("File downloaded to: %s" % extask.filename) :param str filename: filename to store exported element :raises TaskRunFailed: invalid permissions, invalid directory, or this element is a system element and cannot be exported. :return: DownloadTask .. note:: It is not possible to export system elements
entailment
def referenced_by(self): """ Show all references for this element. A reference means that this element is being used, for example, in a policy rule, as a member of a group, etc. :return: list referenced elements :rtype: list(Element) """ href = fetch_entry_point('references_by_element') return [Element.from_meta(**ref) for ref in self.make_request( method='create', href=href, json={'value': self.href})]
Show all references for this element. A reference means that this element is being used, for example, in a policy rule, as a member of a group, etc. :return: list referenced elements :rtype: list(Element)
entailment
def history(self): """ .. versionadded:: 0.5.7 Requires SMC version >= 6.3.2 Obtain the history of this element. This will not chronicle every modification made over time, but instead a current snapshot with historical information such as when the element was created, by whom, when it was last modified and it's current state. :raises ResourceNotFound: If not running SMC version >= 6.3.2 :rtype: History """ from smc.core.resource import History return History(**self.make_request(resource='history'))
.. versionadded:: 0.5.7 Requires SMC version >= 6.3.2 Obtain the history of this element. This will not chronicle every modification made over time, but instead a current snapshot with historical information such as when the element was created, by whom, when it was last modified and it's current state. :raises ResourceNotFound: If not running SMC version >= 6.3.2 :rtype: History
entailment
def duplicate(self, name): """ .. versionadded:: 0.5.8 Requires SMC version >= 6.3.2 Duplicate this element. This is a shortcut method that will make a direct copy of the element under the new name and type. :param str name: name for the duplicated element :raises ActionCommandFailed: failed to duplicate the element :return: the newly created element :rtype: Element """ dup = self.make_request( method='update', raw_result=True, resource='duplicate', params={'name': name}) return type(self)(name=name, href=dup.href, type=type(self).typeof)
.. versionadded:: 0.5.8 Requires SMC version >= 6.3.2 Duplicate this element. This is a shortcut method that will make a direct copy of the element under the new name and type. :param str name: name for the duplicated element :raises ActionCommandFailed: failed to duplicate the element :return: the newly created element :rtype: Element
entailment
def get(self, location_name): """ Get a contact address by location name :param str location_name: name of location :return: return contact address element or None :rtype: ContactAddress """ location_ref = location_helper(location_name, search_only=True) if location_ref: for location in self: if location.location_ref == location_ref: return location
Get a contact address by location name :param str location_name: name of location :return: return contact address element or None :rtype: ContactAddress
entailment
def update_or_create(self, location, contact_addresses, with_status=False, overwrite_existing=False, **kw): """ Update or create a contact address and location pair. If the location does not exist it will be automatically created. If the server already has a location assigned with the same name, the contact address specified will be added if it doesn't already exist (Management and Log Server can have multiple address for a single location). :param list(str) contact_addresses: list of contact addresses for the specified location :param str location: location to place the contact address in :param bool overwrite_existing: if you want to replace existing location to address mappings set this to True. Otherwise if the location exists, only new addresses are appended :param bool with_status: if set to True, a 3-tuple is returned with (Element, modified, created), where the second and third tuple items are booleans indicating the status :raises UpdateElementFailed: failed to update element with reason :rtype: MultiContactAddress """ updated, created = False, False location_ref = location_helper(location) if location_ref in self: for loc in self: if loc.location_ref == location_ref: if overwrite_existing: loc['addresses'][:] = contact_addresses updated = True else: for ca in contact_addresses: if ca not in loc.addresses: loc['addresses'].append(ca) updated = True else: self.data.setdefault('multi_contact_addresses', []).append( dict(addresses=contact_addresses, location_ref=location_ref)) created = True if updated or created: self.update() if with_status: return self, updated, created return self
Update or create a contact address and location pair. If the location does not exist it will be automatically created. If the server already has a location assigned with the same name, the contact address specified will be added if it doesn't already exist (Management and Log Server can have multiple address for a single location). :param list(str) contact_addresses: list of contact addresses for the specified location :param str location: location to place the contact address in :param bool overwrite_existing: if you want to replace existing location to address mappings set this to True. Otherwise if the location exists, only new addresses are appended :param bool with_status: if set to True, a 3-tuple is returned with (Element, modified, created), where the second and third tuple items are booleans indicating the status :raises UpdateElementFailed: failed to update element with reason :rtype: MultiContactAddress
entailment
def contact_addresses(self): """ Provides a reference to contact addresses used by this server. Obtain a reference to manipulate or iterate existing contact addresses:: >>> from smc.elements.servers import ManagementServer >>> mgt_server = ManagementServer.objects.first() >>> for contact_address in mgt_server.contact_addresses: ... contact_address ... ContactAddress(location=Default,addresses=[u'1.1.1.1']) ContactAddress(location=foolocation,addresses=[u'12.12.12.12']) :rtype: MultiContactAddress """ return MultiContactAddress( href=self.get_relation('contact_addresses'), type=self.typeof, name=self.name)
Provides a reference to contact addresses used by this server. Obtain a reference to manipulate or iterate existing contact addresses:: >>> from smc.elements.servers import ManagementServer >>> mgt_server = ManagementServer.objects.first() >>> for contact_address in mgt_server.contact_addresses: ... contact_address ... ContactAddress(location=Default,addresses=[u'1.1.1.1']) ContactAddress(location=foolocation,addresses=[u'12.12.12.12']) :rtype: MultiContactAddress
entailment
def create(cls, name, address, proxy_port=8080, username=None, password=None, secondary=None, comment=None): """ Create a new HTTP Proxy service. Proxy must define at least one primary address but can optionally also define a list of secondary addresses. :param str name: Name of the proxy element :param str address: Primary address for proxy :param int proxy_port: proxy port (default: 8080) :param str username: optional username for authentication (default: None) :param str password: password for username if defined (default: None) :param str comment: optional comment :param list secondary: secondary list of proxy server addresses :raises CreateElementFailed: Failed to create the proxy element :rtype: HttpProxy """ json = { 'name': name, 'address': address, 'comment': comment, 'http_proxy_port': proxy_port, 'http_proxy_username': username if username else '', 'http_proxy_password': password if password else '', 'secondary': secondary if secondary else []} return ElementCreator(cls, json)
Create a new HTTP Proxy service. Proxy must define at least one primary address but can optionally also define a list of secondary addresses. :param str name: Name of the proxy element :param str address: Primary address for proxy :param int proxy_port: proxy port (default: 8080) :param str username: optional username for authentication (default: None) :param str password: password for username if defined (default: None) :param str comment: optional comment :param list secondary: secondary list of proxy server addresses :raises CreateElementFailed: Failed to create the proxy element :rtype: HttpProxy
entailment
def create(cls, name, address, time_to_live=20, update_interval=10, secondary=None, comment=None): """ Create a DNS Server element. :param str name: Name of DNS Server :param str address: IP address for DNS Server element :param int time_to_live: Defines how long a DNS entry can be cached before querying the DNS server again (default: 20) :param int update_interval: Defines how often the DNS entries can be updated to the DNS server if the link status changes constantly (default: 10) :param list secondary: a secondary set of IP address for this element :raises CreateElementFailed: Failed to create with reason :rtype: DNSServer """ json = { 'name': name, 'address': address, 'comment': comment, 'time_to_live': time_to_live, 'update_interval': update_interval, 'secondary': secondary if secondary else []} return ElementCreator(cls, json)
Create a DNS Server element. :param str name: Name of DNS Server :param str address: IP address for DNS Server element :param int time_to_live: Defines how long a DNS entry can be cached before querying the DNS server again (default: 20) :param int update_interval: Defines how often the DNS entries can be updated to the DNS server if the link status changes constantly (default: 10) :param list secondary: a secondary set of IP address for this element :raises CreateElementFailed: Failed to create with reason :rtype: DNSServer
entailment
def create(cls, name, address, inspected_service, secondary=None, balancing_mode='ha', proxy_service='generic', location=None, comment=None, add_x_forwarded_for=False, trust_host_header=False, **kw): """ Create a Proxy Server element :param str name: name of proxy server element :param str address: address of element. Can be a single FQDN or comma separated list of IP addresses :param list secondary: list of secondary IP addresses :param str balancing_mode: how to balance traffic, valid options are ha (first available server), src, dst, srcdst (default: ha) :param str proxy_service: which proxy service to use for next hop, options are generic or forcepoint_ap-web_cloud :param str,Element location: location for this proxy server :param bool add_x_forwarded_for: add X-Forwarded-For header when using the Generic Proxy forwarding method (default: False) :param bool trust_host_header: trust the host header when using the Generic Proxy forwarding method (default: False) :param dict inspected_service: inspection services dict. Valid keys are service_type and port. Service type valid values are HTTP, HTTPS, FTP or SMTP and are case sensitive :param str comment: optional comment :param kw: keyword arguments are used to collect settings when the proxy_service value is forcepoint_ap-web_cloud. Valid keys are `fp_proxy_key`, `fp_proxy_key_id`, `fp_proxy_user_id`. The fp_proxy_key is the password value. All other values are of type int """ json = {'name': name, 'comment': comment, 'secondary': secondary or [], 'http_proxy': proxy_service, 'balancing_mode': balancing_mode, 'inspected_service': inspected_service, 'trust_host_header': trust_host_header, 'add_x_forwarded_for': add_x_forwarded_for, 'location_ref': element_resolver(location) } addresses = address.split(',') json.update(address=addresses.pop(0)) json.update(ip_address=addresses if 'ip_address' not in kw else kw['ip_address']) if proxy_service == 'forcepoint_ap-web_cloud': for key in ('fp_proxy_key', 'fp_proxy_key_id', 'fp_proxy_user_id'): if key not in kw: raise CreateElementFailed('Missing required fp key when adding a ' 'proxy server to forward to forcepoint. Missing key: %s' % key) json[key] = kw.get(key) return ElementCreator(cls, json)
Create a Proxy Server element :param str name: name of proxy server element :param str address: address of element. Can be a single FQDN or comma separated list of IP addresses :param list secondary: list of secondary IP addresses :param str balancing_mode: how to balance traffic, valid options are ha (first available server), src, dst, srcdst (default: ha) :param str proxy_service: which proxy service to use for next hop, options are generic or forcepoint_ap-web_cloud :param str,Element location: location for this proxy server :param bool add_x_forwarded_for: add X-Forwarded-For header when using the Generic Proxy forwarding method (default: False) :param bool trust_host_header: trust the host header when using the Generic Proxy forwarding method (default: False) :param dict inspected_service: inspection services dict. Valid keys are service_type and port. Service type valid values are HTTP, HTTPS, FTP or SMTP and are case sensitive :param str comment: optional comment :param kw: keyword arguments are used to collect settings when the proxy_service value is forcepoint_ap-web_cloud. Valid keys are `fp_proxy_key`, `fp_proxy_key_id`, `fp_proxy_user_id`. The fp_proxy_key is the password value. All other values are of type int
entailment
def flush_parent_cache(node): """ Flush parent cache will recurse back up the tree and wipe the cache from each parent node reference on the given element. This allows the objects to be reused and a clean way to force the object to update itself if attributes or methods are referenced after update. """ if node._parent is None: node._del_cache() return node._del_cache() flush_parent_cache(node._parent)
Flush parent cache will recurse back up the tree and wipe the cache from each parent node reference on the given element. This allows the objects to be reused and a clean way to force the object to update itself if attributes or methods are referenced after update.
entailment
def from_meta(node): """ Helper method that reolves a routing node to element. Rather than doing a lookup and fetch, the routing node provides the information to build the element from meta alone. :rtype: Element """ # Version SMC < 6.4 if 'related_element_type' not in node.data: return Element.from_href( node.data.get('href')) # SMC Version >= 6.4 - more efficient because it builds the # element by meta versus requiring a query return Element.from_meta( name=node.data.get('name'), type=node.related_element_type, href=node.data.get('href'))
Helper method that reolves a routing node to element. Rather than doing a lookup and fetch, the routing node provides the information to build the element from meta alone. :rtype: Element
entailment
def route_level(root, level): """ Helper method to recurse the current node and return the specified routing node level. """ def recurse(nodes): for node in nodes: if node.level == level: routing_node.append(node) else: recurse(node) routing_node = [] recurse(root) return routing_node
Helper method to recurse the current node and return the specified routing node level.
entailment
def gateway_by_type(self, type=None, on_network=None): # @ReservedAssignment """ Return gateways for the specified node. You can also specify type to find only gateways of a specific type. Valid types are: bgp_peering, netlink, ospfv2_area. :param RoutingNode self: the routing node to check :param str type: bgp_peering, netlink, ospfv2_area :param str on_network: if network is specified, should be CIDR and specifies a filter to only return gateways on that network when an interface has multiple :return: tuple of RoutingNode(interface,network,gateway) :rtype: list """ gateways = route_level(self, 'gateway') if not type: for gw in gateways: yield gw else: for node in gateways: #TODO: Change to type == node.related_element_type when # only supporting SMC >= 6.4 if type == node.routing_node_element.typeof: # If the parent is level interface, this is a tunnel interface # where the gateway is bound to interface versus network parent = node._parent if parent.level == 'interface': interface = parent network = None else: network = parent interface = network._parent if on_network is not None: if network and network.ip == on_network: yield (interface, network, node) else: yield (interface, network, node)
Return gateways for the specified node. You can also specify type to find only gateways of a specific type. Valid types are: bgp_peering, netlink, ospfv2_area. :param RoutingNode self: the routing node to check :param str type: bgp_peering, netlink, ospfv2_area :param str on_network: if network is specified, should be CIDR and specifies a filter to only return gateways on that network when an interface has multiple :return: tuple of RoutingNode(interface,network,gateway) :rtype: list
entailment
def _which_ip_protocol(element): """ Validate the protocol addresses for the element. Most elements can have an IPv4 or IPv6 address assigned on the same element. This allows elements to be validated and placed on the right network. :return: boolean tuple :rtype: tuple(ipv4, ipv6) """ try: if element.typeof in ('host', 'router'): return getattr(element, 'address', False), getattr(element, 'ipv6_address', False) elif element.typeof == 'netlink': gateway = element.gateway if gateway.typeof == 'router': return getattr(gateway, 'address', False), getattr(gateway, 'ipv6_address', False) # It's an engine, return true elif element.typeof == 'network': return getattr(element, 'ipv4_network', False), getattr(element, 'ipv6_network', False) except AttributeError: pass # Always return true so that the calling function assumes the element # is valid for the routing node. This could fail when submitting but # we don't want to prevent adding elements yet since this could change return True, True
Validate the protocol addresses for the element. Most elements can have an IPv4 or IPv6 address assigned on the same element. This allows elements to be validated and placed on the right network. :return: boolean tuple :rtype: tuple(ipv4, ipv6)
entailment
def del_invalid_routes(engine, nicids): """ Helper method to run through and delete any routes that are tagged as invalid or to_delete by a list of nicids. Since we could have a list of routes, iterate from top level engine routing node to avoid fetch exceptions. Route list should be a list of nicids as str. :param list nicids: list of nicids :raises DeleteElementFailed: delete element failed with reason """ nicids = map(str, nicids) for interface in engine.routing: if interface.nicid in nicids: if getattr(interface, 'to_delete', False): # Delete the invalid interface interface.delete() continue for network in interface: if getattr(network, 'invalid', False) or \ getattr(network, 'to_delete', False): network.delete()
Helper method to run through and delete any routes that are tagged as invalid or to_delete by a list of nicids. Since we could have a list of routes, iterate from top level engine routing node to avoid fetch exceptions. Route list should be a list of nicids as str. :param list nicids: list of nicids :raises DeleteElementFailed: delete element failed with reason
entailment
def related_element_type(self): """ .. versionadded:: 0.6.0 Requires SMC version >= 6.4 Related element type defines the 'type' of element at this routing or antispoofing node level. :rtype: str """ if 'related_element_type' in self.data: return self.data.get('related_element_type') return None if self.dynamic_nicid or (self.nicid and '.' in self.nicid) else \ Element.from_href(self.data.get('href')).typeof
.. versionadded:: 0.6.0 Requires SMC version >= 6.4 Related element type defines the 'type' of element at this routing or antispoofing node level. :rtype: str
entailment
def as_tree(self, level=0): """ Display the routing tree representation in string format :rtype: str """ ret = '--' * level + repr(self) + '\n' for routing_node in self: ret += routing_node.as_tree(level+1) return ret
Display the routing tree representation in string format :rtype: str
entailment
def get(self, interface_id): """ Obtain routing configuration for a specific interface by ID. .. note:: If interface is a VLAN, you must use a str to specify the interface id, such as '3.13' (interface 3, VLAN 13) :param str,int interface_id: interface identifier :raises InterfaceNotFound: invalid interface for engine :return: Routing element, or None if not found :rtype: Routing """ for interface in self: if interface.nicid == str(interface_id) or \ interface.dynamic_nicid == str(interface_id): return interface raise InterfaceNotFound('Specified interface {} does not exist on ' 'this engine.'.format(interface_id))
Obtain routing configuration for a specific interface by ID. .. note:: If interface is a VLAN, you must use a str to specify the interface id, such as '3.13' (interface 3, VLAN 13) :param str,int interface_id: interface identifier :raises InterfaceNotFound: invalid interface for engine :return: Routing element, or None if not found :rtype: Routing
entailment
def add_traffic_handler(self, netlink, netlink_gw=None, network=None): """ Add a traffic handler to a routing node. A traffic handler can be either a static netlink or a multilink traffic handler. If ``network`` is not specified and the interface has multiple IP addresses, the traffic handler will be added to all ipv4 addresses. Add a pre-defined netlink to the route table of interface 0:: engine = Engine('vm') rnode = engine.routing.get(0) rnode.add_traffic_handler(StaticNetlink('mynetlink')) Add a pre-defined netlink only to a specific network on an interface with multiple addresses. Specify a netlink_gw for the netlink:: rnode = engine.routing.get(0) rnode.add_traffic_handler( StaticNetlink('mynetlink'), netlink_gw=[Router('myrtr'), Host('myhost')], network='172.18.1.0/24') :param StaticNetlink,Multilink netlink: netlink element :param list(Element) netlink_gw: list of elements that should be destinations for this netlink. Typically these may be of type host, router, group, server, network or engine. :param str network: if network specified, only add OSPF to this network on interface :raises UpdateElementFailed: failure updating routing :raises ModificationAborted: Change must be made at the interface level :raises ElementNotFound: ospf area not found :return: Status of whether the route table was updated :rtype: bool """ routing_node_gateway = RoutingNodeGateway(netlink, destinations=[] if not netlink_gw else netlink_gw) return self._add_gateway_node('netlink', routing_node_gateway, network)
Add a traffic handler to a routing node. A traffic handler can be either a static netlink or a multilink traffic handler. If ``network`` is not specified and the interface has multiple IP addresses, the traffic handler will be added to all ipv4 addresses. Add a pre-defined netlink to the route table of interface 0:: engine = Engine('vm') rnode = engine.routing.get(0) rnode.add_traffic_handler(StaticNetlink('mynetlink')) Add a pre-defined netlink only to a specific network on an interface with multiple addresses. Specify a netlink_gw for the netlink:: rnode = engine.routing.get(0) rnode.add_traffic_handler( StaticNetlink('mynetlink'), netlink_gw=[Router('myrtr'), Host('myhost')], network='172.18.1.0/24') :param StaticNetlink,Multilink netlink: netlink element :param list(Element) netlink_gw: list of elements that should be destinations for this netlink. Typically these may be of type host, router, group, server, network or engine. :param str network: if network specified, only add OSPF to this network on interface :raises UpdateElementFailed: failure updating routing :raises ModificationAborted: Change must be made at the interface level :raises ElementNotFound: ospf area not found :return: Status of whether the route table was updated :rtype: bool
entailment
def add_ospf_area(self, ospf_area, ospf_interface_setting=None, network=None, communication_mode='NOT_FORCED', unicast_ref=None): """ Add OSPF Area to this routing node. Communication mode specifies how the interface will interact with the adjacent OSPF environment. Please see SMC API documentation for more in depth information on each option. If the interface has multiple networks nested below, all networks will receive the OSPF area by default unless the ``network`` parameter is specified. OSPF cannot be applied to IPv6 networks. Example of adding an area to interface routing node:: area = OSPFArea('area0') #obtain area resource #Set on routing interface 0 interface = engine.routing.get(0) interface.add_ospf_area(area) .. note:: If UNICAST is specified, you must also provide a unicast_ref of element type Host to identify the remote host. If no unicast_ref is provided, this is skipped :param OSPFArea ospf_area: OSPF area instance or href :param OSPFInterfaceSetting ospf_interface_setting: used to override the OSPF settings for this interface (optional) :param str network: if network specified, only add OSPF to this network on interface :param str communication_mode: NOT_FORCED|POINT_TO_POINT|PASSIVE|UNICAST :param Element unicast_ref: Element used as unicast gw (required for UNICAST) :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failure updating routing :raises ElementNotFound: ospf area not found :return: Status of whether the route table was updated :rtype: bool """ communication_mode = communication_mode.upper() destinations=[] if not ospf_interface_setting else [ospf_interface_setting] if communication_mode == 'UNICAST' and unicast_ref: destinations.append(unicast_ref) routing_node_gateway = RoutingNodeGateway( ospf_area, communication_mode=communication_mode, destinations=destinations) return self._add_gateway_node('ospfv2_area', routing_node_gateway, network)
Add OSPF Area to this routing node. Communication mode specifies how the interface will interact with the adjacent OSPF environment. Please see SMC API documentation for more in depth information on each option. If the interface has multiple networks nested below, all networks will receive the OSPF area by default unless the ``network`` parameter is specified. OSPF cannot be applied to IPv6 networks. Example of adding an area to interface routing node:: area = OSPFArea('area0') #obtain area resource #Set on routing interface 0 interface = engine.routing.get(0) interface.add_ospf_area(area) .. note:: If UNICAST is specified, you must also provide a unicast_ref of element type Host to identify the remote host. If no unicast_ref is provided, this is skipped :param OSPFArea ospf_area: OSPF area instance or href :param OSPFInterfaceSetting ospf_interface_setting: used to override the OSPF settings for this interface (optional) :param str network: if network specified, only add OSPF to this network on interface :param str communication_mode: NOT_FORCED|POINT_TO_POINT|PASSIVE|UNICAST :param Element unicast_ref: Element used as unicast gw (required for UNICAST) :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failure updating routing :raises ElementNotFound: ospf area not found :return: Status of whether the route table was updated :rtype: bool
entailment
def add_bgp_peering(self, bgp_peering, external_bgp_peer=None, network=None): """ Add a BGP configuration to this routing interface. If the interface has multiple ip addresses, all networks will receive the BGP peering by default unless the ``network`` parameter is specified. Example of adding BGP to an interface by ID:: interface = engine.routing.get(0) interface.add_bgp_peering( BGPPeering('mypeer'), ExternalBGPPeer('neighbor')) :param BGPPeering bgp_peering: BGP Peer element :param ExternalBGPPeer,Engine external_bgp_peer: peer element or href :param str network: if network specified, only add OSPF to this network on interface :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failed to add BGP :return: Status of whether the route table was updated :rtype: bool """ destination = [external_bgp_peer] if external_bgp_peer else [] routing_node_gateway = RoutingNodeGateway(bgp_peering, destinations=destination) return self._add_gateway_node('bgp_peering', routing_node_gateway, network)
Add a BGP configuration to this routing interface. If the interface has multiple ip addresses, all networks will receive the BGP peering by default unless the ``network`` parameter is specified. Example of adding BGP to an interface by ID:: interface = engine.routing.get(0) interface.add_bgp_peering( BGPPeering('mypeer'), ExternalBGPPeer('neighbor')) :param BGPPeering bgp_peering: BGP Peer element :param ExternalBGPPeer,Engine external_bgp_peer: peer element or href :param str network: if network specified, only add OSPF to this network on interface :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failed to add BGP :return: Status of whether the route table was updated :rtype: bool
entailment
def add_static_route(self, gateway, destination, network=None): """ Add a static route to this route table. Destination can be any element type supported in the routing table such as a Group of network members. Since a static route gateway needs to be on the same network as the interface, provide a value for `network` if an interface has multiple addresses on different networks. :: >>> engine = Engine('ve-1') >>> itf = engine.routing.get(0) >>> itf.add_static_route( gateway=Router('tmprouter'), destination=[Group('routegroup')]) :param Element gateway: gateway for this route (Router, Host) :param Element destination: destination network/s for this route. :type destination: list(Host, Router, ..) :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failure to update routing table :return: Status of whether the route table was updated :rtype: bool """ routing_node_gateway = RoutingNodeGateway(gateway, destinations=destination) return self._add_gateway_node('router', routing_node_gateway, network)
Add a static route to this route table. Destination can be any element type supported in the routing table such as a Group of network members. Since a static route gateway needs to be on the same network as the interface, provide a value for `network` if an interface has multiple addresses on different networks. :: >>> engine = Engine('ve-1') >>> itf = engine.routing.get(0) >>> itf.add_static_route( gateway=Router('tmprouter'), destination=[Group('routegroup')]) :param Element gateway: gateway for this route (Router, Host) :param Element destination: destination network/s for this route. :type destination: list(Host, Router, ..) :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failure to update routing table :return: Status of whether the route table was updated :rtype: bool
entailment
def add_dynamic_gateway(self, networks): """ A dynamic gateway object creates a router object that is attached to a DHCP interface. You can associate networks with this gateway address to identify networks for routing on this interface. :: route = engine.routing.get(0) route.add_dynamic_gateway([Network('mynetwork')]) :param list Network: list of network elements to add to this DHCP gateway :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failure to update routing table :return: Status of whether the route table was updated :rtype: bool """ routing_node_gateway = RoutingNodeGateway(dynamic_classid='gateway', destinations=networks or []) return self._add_gateway_node('dynamic_netlink', routing_node_gateway)
A dynamic gateway object creates a router object that is attached to a DHCP interface. You can associate networks with this gateway address to identify networks for routing on this interface. :: route = engine.routing.get(0) route.add_dynamic_gateway([Network('mynetwork')]) :param list Network: list of network elements to add to this DHCP gateway :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failure to update routing table :return: Status of whether the route table was updated :rtype: bool
entailment
def _add_gateway_node_on_tunnel(self, routing_node_gateway): """ Add a gateway node on a tunnel interface. Tunnel interface elements are attached to the interface level and not directly nested under the networks node. :param RouteNodeGateway routing_node_gateway: routing node gateway instance :return: Whether a change was made or not :rtype: bool """ modified = False peering = [next_hop for next_hop in self if next_hop.routing_node_element == routing_node_gateway.routing_node_element] if not peering: self.data.setdefault('routing_node', []).append( routing_node_gateway) modified = True # Have peering else: peers = [node.routing_node_element for peer in peering for node in peer] for destination in routing_node_gateway.destinations: if destination not in peers: peering[0].data.setdefault('routing_node', []).append( {'level': 'any', 'href': destination.href, 'name': destination.name}) modified = True if modified: self.update() return modified
Add a gateway node on a tunnel interface. Tunnel interface elements are attached to the interface level and not directly nested under the networks node. :param RouteNodeGateway routing_node_gateway: routing node gateway instance :return: Whether a change was made or not :rtype: bool
entailment
def _add_gateway_node(self, gw_type, routing_node_gateway, network=None): """ Add a gateway node to existing routing tree. Gateways are only added if they do not already exist. If they do exist, check the destinations of the existing gateway and add destinations that are not already there. A current limitation is that if a gateway doesn't exist and the destinations specified do not have IP addresses that are valid, they are still added (i.e. IPv4 gateway with IPv6 destination is considered invalid). :param Routing self: the routing node, should be the interface routing node :param str gw_type: type of gateway, i.e. netlink, ospfv2_area, etc :param RoutingNodeGateway route_node_gateway: gateway element :param str network: network to bind to. If none, all networks :return: Whether a change was made or not :rtype: bool """ if self.level != 'interface': raise ModificationAborted('You must make this change from the ' 'interface routing level. Current node: {}'.format(self)) if self.related_element_type == 'tunnel_interface': return self._add_gateway_node_on_tunnel(routing_node_gateway) # Find any existing gateways routing_node = list(gateway_by_type(self, type=gw_type, on_network=network)) _networks = [netwk for netwk in self if netwk.ip == network] if network is \ not None else list(self) # Routing Node Gateway to add as Element gateway_element_type = routing_node_gateway.routing_node_element modified = False for network in _networks: # Short circuit for dynamic interfaces if getattr(network, 'dynamic_classid', None): network.data.setdefault('routing_node', []).append( routing_node_gateway) modified = True break # Used for comparison to this_network_node = network.routing_node_element if routing_node and any(netwk for _intf, netwk, gw in routing_node if netwk.routing_node_element == this_network_node and gateway_element_type == gw.routing_node_element): # A gateway exists on this network for gw in network: if gw.routing_node_element == gateway_element_type: existing_dests = [node.routing_node_element for node in gw] for destination in routing_node_gateway.destinations: is_valid_destination = False if destination not in existing_dests: dest_ipv4, dest_ipv6 = _which_ip_protocol(destination) if len(network.ip.split(':')) > 1: # IPv6 if dest_ipv6: is_valid_destination = True else: if dest_ipv4: is_valid_destination = True if is_valid_destination: gw.data.setdefault('routing_node', []).append( {'level': 'any', 'href': destination.href, 'name': destination.name}) modified = True else: # Gateway doesn't exist gw_ipv4, gw_ipv6 = _which_ip_protocol(gateway_element_type) # ipv4, ipv6 or both if len(network.ip.split(':')) > 1: if gw_ipv6: network.data.setdefault('routing_node', []).append( routing_node_gateway) modified = True else: # IPv4 if gw_ipv4: network.data.setdefault('routing_node', []).append( routing_node_gateway) modified = True if modified: self.update() return modified
Add a gateway node to existing routing tree. Gateways are only added if they do not already exist. If they do exist, check the destinations of the existing gateway and add destinations that are not already there. A current limitation is that if a gateway doesn't exist and the destinations specified do not have IP addresses that are valid, they are still added (i.e. IPv4 gateway with IPv6 destination is considered invalid). :param Routing self: the routing node, should be the interface routing node :param str gw_type: type of gateway, i.e. netlink, ospfv2_area, etc :param RoutingNodeGateway route_node_gateway: gateway element :param str network: network to bind to. If none, all networks :return: Whether a change was made or not :rtype: bool
entailment
def remove_route_gateway(self, element, network=None): """ Remove a route element by href or Element. Use this if you want to remove a netlink or a routing element such as BGP or OSPF. Removing is done from within the routing interface context. :: interface0 = engine.routing.get(0) interface0.remove_route_gateway(StaticNetlink('mynetlink')) Only from a specific network on a multi-address interface:: interface0.remove_route_gateway( StaticNetlink('mynetlink'), network='172.18.1.0/24') :param str,Element element: element to remove from this routing node :param str network: if network specified, only add OSPF to this network on interface :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failure to update routing table :return: Status of whether the entry was removed (i.e. or not found) :rtype: bool """ if self.level not in ('interface',): raise ModificationAborted('You must make this change from the ' 'interface routing level. Current node: {}'.format(self)) node_changed = False element = element_resolver(element) for network in self: # Tunnel Interface binds gateways to the interface if network.level == 'gateway' and network.data.get('href') == element: network.delete() node_changed = True break for gateway in network: if gateway.data.get('href') == element: gateway.delete() node_changed = True return node_changed
Remove a route element by href or Element. Use this if you want to remove a netlink or a routing element such as BGP or OSPF. Removing is done from within the routing interface context. :: interface0 = engine.routing.get(0) interface0.remove_route_gateway(StaticNetlink('mynetlink')) Only from a specific network on a multi-address interface:: interface0.remove_route_gateway( StaticNetlink('mynetlink'), network='172.18.1.0/24') :param str,Element element: element to remove from this routing node :param str network: if network specified, only add OSPF to this network on interface :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failure to update routing table :return: Status of whether the entry was removed (i.e. or not found) :rtype: bool
entailment
def add(self, element): """ Add an entry to this antispoofing node level. Entry can be either href or network elements specified in :py:class:`smc.elements.network` :: if0 = engine.antispoofing.get(0) if0.add(Network('foonet')) :param Element element: entry to add, i.e. Network('mynetwork'), Host(..) :raises CreateElementFailed: failed adding entry :raises ElementNotFound: element entry specified not in SMC :return: whether entry was added :rtype: bool """ if self.level == 'interface': for network in self: if from_meta(network) == element: return False self.data['antispoofing_node'].append({ 'antispoofing_node': [], 'auto_generated': 'false', 'href': element.href, 'level': self.level, 'validity': 'enable', 'name': element.name}) self.update() return True return False
Add an entry to this antispoofing node level. Entry can be either href or network elements specified in :py:class:`smc.elements.network` :: if0 = engine.antispoofing.get(0) if0.add(Network('foonet')) :param Element element: entry to add, i.e. Network('mynetwork'), Host(..) :raises CreateElementFailed: failed adding entry :raises ElementNotFound: element entry specified not in SMC :return: whether entry was added :rtype: bool
entailment
def remove(self, element): """ Remove a specific user added element from the antispoofing tables of a given interface. This will not remove autogenerated or system level entries. :param Element element: element to remove :return: remove element if it exists and return bool :rtype: bool """ if self.level == 'interface': len_before_change = len(self) _nodes = [] for network in self: if from_meta(network) != element: _nodes.append(network.data) else: if network.autogenerated: # Make sure it was user added _nodes.append(network.data) if len(_nodes) != len_before_change: self.data['antispoofing_node'] = _nodes self.update() return True return False
Remove a specific user added element from the antispoofing tables of a given interface. This will not remove autogenerated or system level entries. :param Element element: element to remove :return: remove element if it exists and return bool :rtype: bool
entailment
def create(self, source, destination, gateway_ip, comment=None): """ Add a new policy route to the engine. :param str source: network address with /cidr :param str destination: network address with /cidr :param str gateway: IP address, must be on source network :param str comment: optional comment """ self.items.append(dict( source=source, destination=destination, gateway_ip=gateway_ip, comment=comment))
Add a new policy route to the engine. :param str source: network address with /cidr :param str destination: network address with /cidr :param str gateway: IP address, must be on source network :param str comment: optional comment
entailment
def delete(self, **kw): """ Delete a policy route from the engine. You can delete using a single field or multiple fields for a more exact match. Use a keyword argument to delete a route by any valid attribute. :param kw: use valid Route keyword values to delete by exact match """ delete_by = [] for field, val in kw.items(): if val is not None: delete_by.append(field) self.items[:] = [route for route in self.items if not all(route.get(field) == kw.get(field) for field in delete_by)]
Delete a policy route from the engine. You can delete using a single field or multiple fields for a more exact match. Use a keyword argument to delete a route by any valid attribute. :param kw: use valid Route keyword values to delete by exact match
entailment
def create(cls, name, address=None, ipv6_address=None, secondary=None, comment=None): """ Create the host element :param str name: Name of element :param str address: ipv4 address of host object (optional if ipv6) :param str ipv6_address: ipv6 address (optional if ipv4) :param list secondary: secondary ip addresses (optional) :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: Host .. note:: Either ipv4 or ipv6 address is required """ address = address if address else None ipv6_address = ipv6_address if ipv6_address else None secondaries = [] if secondary is None else secondary json = {'name': name, 'address': address, 'ipv6_address': ipv6_address, 'secondary': secondaries, 'comment': comment} return ElementCreator(cls, json)
Create the host element :param str name: Name of element :param str address: ipv4 address of host object (optional if ipv6) :param str ipv6_address: ipv6 address (optional if ipv4) :param list secondary: secondary ip addresses (optional) :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: Host .. note:: Either ipv4 or ipv6 address is required
entailment
def add_secondary(self, address, append_lists=False): """ Add secondary IP addresses to this host element. If append_list is True, then add to existing list. Otherwise overwrite. :param list address: ip addresses to add in IPv4 or IPv6 format :param bool append_list: add to existing or overwrite (default: append) :return: None """ self.update( secondary=address, append_lists=append_lists)
Add secondary IP addresses to this host element. If append_list is True, then add to existing list. Otherwise overwrite. :param list address: ip addresses to add in IPv4 or IPv6 format :param bool append_list: add to existing or overwrite (default: append) :return: None
entailment
def create(cls, name, ip_range, comment=None): """ Create an AddressRange element :param str name: Name of element :param str iprange: iprange of element :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: AddressRange """ json = {'name': name, 'ip_range': ip_range, 'comment': comment} return ElementCreator(cls, json)
Create an AddressRange element :param str name: Name of element :param str iprange: iprange of element :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: AddressRange
entailment
def create(cls, name, ipv4_network=None, ipv6_network=None, comment=None): """ Create the network element :param str name: Name of element :param str ipv4_network: network cidr (optional if ipv6) :param str ipv6_network: network cidr (optional if ipv4) :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: Network .. note:: Either an ipv4_network or ipv6_network must be specified """ ipv4_network = ipv4_network if ipv4_network else None ipv6_network = ipv6_network if ipv6_network else None json = {'name': name, 'ipv4_network': ipv4_network, 'ipv6_network': ipv6_network, 'comment': comment} return ElementCreator(cls, json)
Create the network element :param str name: Name of element :param str ipv4_network: network cidr (optional if ipv6) :param str ipv6_network: network cidr (optional if ipv4) :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: Network .. note:: Either an ipv4_network or ipv6_network must be specified
entailment
def build_sub_expression(name, ne_ref=None, operator='union'): """ Static method to build and return the proper json for a sub-expression. A sub-expression would be the grouping of network elements used as a target match. For example, (network A or network B) would be considered a sub-expression. This can be used to compound sub-expressions before calling create. :param str name: name of sub-expression :param list ne_ref: network elements references :param str operator: exclusion (negation), union, intersection (default: union) :return: JSON of subexpression. Use in :func:`~create` constructor """ ne_ref = [] if ne_ref is None else ne_ref json = {'name': name, 'ne_ref': ne_ref, 'operator': operator} return json
Static method to build and return the proper json for a sub-expression. A sub-expression would be the grouping of network elements used as a target match. For example, (network A or network B) would be considered a sub-expression. This can be used to compound sub-expressions before calling create. :param str name: name of sub-expression :param list ne_ref: network elements references :param str operator: exclusion (negation), union, intersection (default: union) :return: JSON of subexpression. Use in :func:`~create` constructor
entailment
def create(cls, name, ne_ref=None, operator='exclusion', sub_expression=None, comment=None): """ Create the expression :param str name: name of expression :param list ne_ref: network element references for expression :param str operator: 'exclusion' (negation), 'union', 'intersection' (default: exclusion) :param dict sub_expression: sub expression used :param str comment: optional comment :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: Expression """ sub_expression = [] if sub_expression is None else [sub_expression] json = {'name': name, 'operator': operator, 'ne_ref': ne_ref, 'sub_expression': sub_expression, 'comment': comment} return ElementCreator(cls, json)
Create the expression :param str name: name of expression :param list ne_ref: network element references for expression :param str operator: 'exclusion' (negation), 'union', 'intersection' (default: exclusion) :param dict sub_expression: sub expression used :param str comment: optional comment :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: Expression
entailment
def download(self, filename=None, as_type='zip'): """ Download the IPList. List format can be either zip, text or json. For large lists, it is recommended to use zip encoding. Filename is required for zip downloads. :param str filename: Name of file to save to (required for zip) :param str as_type: type of format to download in: txt,json,zip (default: zip) :raises IOError: problem writing to destination filename :return: None """ headers = None if as_type in ['zip', 'txt', 'json']: if as_type == 'zip': if filename is None: raise MissingRequiredInput('Filename must be specified when ' 'downloading IPList as a zip file.') filename = '{}'.format(filename) elif as_type == 'txt': headers = {'accept': 'text/plain'} elif as_type == 'json': headers = {'accept': 'application/json'} result = self.make_request( FetchElementFailed, raw_result=True, resource='ip_address_list', filename=filename, headers=headers) return result.json if as_type == 'json' else result.content
Download the IPList. List format can be either zip, text or json. For large lists, it is recommended to use zip encoding. Filename is required for zip downloads. :param str filename: Name of file to save to (required for zip) :param str as_type: type of format to download in: txt,json,zip (default: zip) :raises IOError: problem writing to destination filename :return: None
entailment
def upload(self, filename=None, json=None, as_type='zip'): """ Upload an IPList to the SMC. The contents of the upload are not incremental to what is in the existing IPList. So if the intent is to add new entries, you should first retrieve the existing and append to the content, then upload. The only upload type that can be done without loading a file as the source is as_type='json'. :param str filename: required for zip/txt uploads :param str json: required for json uploads :param str as_type: type of format to upload in: txt|json|zip (default) :raises IOError: filename specified cannot be loaded :raises CreateElementFailed: element creation failed with reason :return: None """ headers = {'content-type': 'multipart/form-data'} params = None files = None if filename: files = {'ip_addresses': open(filename, 'rb')} if as_type == 'json': headers = {'accept': 'application/json', 'content-type': 'application/json'} elif as_type == 'txt': params = {'format': 'txt'} self.make_request( CreateElementFailed, method='create', resource='ip_address_list', headers=headers, files=files, json=json, params=params)
Upload an IPList to the SMC. The contents of the upload are not incremental to what is in the existing IPList. So if the intent is to add new entries, you should first retrieve the existing and append to the content, then upload. The only upload type that can be done without loading a file as the source is as_type='json'. :param str filename: required for zip/txt uploads :param str json: required for json uploads :param str as_type: type of format to upload in: txt|json|zip (default) :raises IOError: filename specified cannot be loaded :raises CreateElementFailed: element creation failed with reason :return: None
entailment
def update_or_create(cls, append_lists=True, with_status=False, **kwargs): """ Update or create an IPList. :param bool append_lists: append to existing IP List :param dict kwargs: provide at minimum the name attribute and optionally match the create constructor values :raises FetchElementFailed: Reason for retrieval failure """ was_created, was_modified = False, False element = None try: element = cls.get(kwargs.get('name')) if append_lists: iplist = element.iplist diff = [i for i in kwargs.get('iplist', []) if i not in iplist] if diff: iplist.extend(diff) else: iplist = [] else: iplist = kwargs.get('iplist', []) if iplist: element.upload(json={'ip': iplist}, as_type='json') was_modified = True except ElementNotFound: element = cls.create( kwargs.get('name'), iplist = kwargs.get('iplist', [])) was_created = True if with_status: return element, was_modified, was_created return element
Update or create an IPList. :param bool append_lists: append to existing IP List :param dict kwargs: provide at minimum the name attribute and optionally match the create constructor values :raises FetchElementFailed: Reason for retrieval failure
entailment
def create(cls, name, iplist=None, comment=None): """ Create an IP List. It is also possible to add entries by supplying a list of IPs/networks, although this is optional. You can also use upload/download to add to the iplist. :param str name: name of ip list :param list iplist: list of ipaddress :param str comment: optional comment :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: IPList """ json = {'name': name, 'comment': comment} result = ElementCreator(cls, json) if result and iplist is not None: element = IPList(name) element.make_request( CreateElementFailed, method='create', resource='ip_address_list', json={'ip': iplist}) return result
Create an IP List. It is also possible to add entries by supplying a list of IPs/networks, although this is optional. You can also use upload/download to add to the iplist. :param str name: name of ip list :param list iplist: list of ipaddress :param str comment: optional comment :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: IPList
entailment
def update_or_create(cls, name, engine, translation_values=None, with_status=False): """ Update or create an Alias and it's mappings. :param str name: name of alias :param Engine engine: engine to modify alias translation values :param list(str,Element) translation_values: translation values as elements. Can be None if you want to unset any existing values :param bool with_status: if set to True, a 3-tuple is returned with (Element, modified, created), where the second and third tuple items are booleans indicating the status :raises ElementNotFound: specified engine or translation values are not found in the SMC :raises UpdateElementFailed: update failed with reason :raises CreateElementFailed: create failed with reason :rtype: Element """ updated, created = False, False alias = cls.get(name, raise_exc=False) if not alias: alias = cls.create(name) created = True elements = element_resolver(translation_values) if translation_values \ else [] if not created: # possible update # Does alias already exist with a value alias_value = [_alias for _alias in engine.data.get('alias_value', []) if _alias.get('alias_ref') == alias.href] if alias_value: if not elements: alias_value[0].update(translated_element=None) updated = True else: t_values = alias_value[0].get('translated_element') if set(t_values) ^ set(elements): t_values[:] = elements updated = True if elements and (created or not updated): engine.data.setdefault('alias_value', []).append( {'alias_ref': alias.href, 'translated_element': elements}) updated = True if updated: engine.update() if with_status: return alias, updated, created return alias
Update or create an Alias and it's mappings. :param str name: name of alias :param Engine engine: engine to modify alias translation values :param list(str,Element) translation_values: translation values as elements. Can be None if you want to unset any existing values :param bool with_status: if set to True, a 3-tuple is returned with (Element, modified, created), where the second and third tuple items are booleans indicating the status :raises ElementNotFound: specified engine or translation values are not found in the SMC :raises UpdateElementFailed: update failed with reason :raises CreateElementFailed: create failed with reason :rtype: Element
entailment
def _from_engine(cls, data, alias_list): """ Return an alias for the engine. The data is dict provided when calling engine.alias_resolving(). The alias list is the list of aliases pre-fetched from Alias.objects.all(). This will return an Alias element by taking the alias_ref and finding the name in the alias list. :rtype: Alias """ for alias in alias_list: href = data.get('alias_ref') if alias.href == href: _alias = Alias(alias.name, href=href) _alias.resolved_value = data.get('resolved_value') _alias.typeof = alias._meta.type return _alias
Return an alias for the engine. The data is dict provided when calling engine.alias_resolving(). The alias list is the list of aliases pre-fetched from Alias.objects.all(). This will return an Alias element by taking the alias_ref and finding the name in the alias list. :rtype: Alias
entailment
def resolve(self, engine): """ Resolve this Alias to a specific value. Specify the engine by name to find it's value. :: alias = Alias('$$ Interface ID 0.ip') alias.resolve('smcpython-fw') :param str engine: name of engine to resolve value :raises ElementNotFound: if alias not found on engine :return: alias resolving values :rtype: list """ if not self.resolved_value: result = self.make_request( ElementNotFound, href=self.get_relation('resolve'), params={'for': engine}) self.resolved_value = result.get('resolved_value') return self.resolved_value
Resolve this Alias to a specific value. Specify the engine by name to find it's value. :: alias = Alias('$$ Interface ID 0.ip') alias.resolve('smcpython-fw') :param str engine: name of engine to resolve value :raises ElementNotFound: if alias not found on engine :return: alias resolving values :rtype: list
entailment
def fetch_as_element(self, **kw): """ Fetch the blacklist and return as an instance of Element. :return: generator returning element instances :rtype: BlacklistEntry """ clone = self.copy() # Replace all filters with a combined filter bldata = TextFormat(field_format='name') # Preserve resolving fields for new filter if 'resolving' in self.format.data: bldata.set_resolving(**self.format.data['resolving']) # Resolve the entry ID to match SMC blid = TextFormat(field_format='pretty') blid.field_ids([LogField.BLACKLISTENTRYID]) combined = CombinedFormat(bldata=bldata, blid=blid) clone.update_format(combined) for list_of_results in clone.fetch_raw(**kw): for entry in list_of_results: data = entry.get('bldata') data.update(**entry.get('blid')) yield BlacklistEntry(**data)
Fetch the blacklist and return as an instance of Element. :return: generator returning element instances :rtype: BlacklistEntry
entailment
def source_ports(self): """ Source ports for this blacklist entry. If no ports are specified (i.e. ALL ports), 'ANY' is returned. :rtype: str """ start_port = self.blacklist.get('BlacklistEntrySourcePort') if start_port is not None: return '{}-{}'.format( start_port, self.blacklist.get('BlacklistEntrySourcePortRange')) return 'ANY'
Source ports for this blacklist entry. If no ports are specified (i.e. ALL ports), 'ANY' is returned. :rtype: str
entailment
def dest_ports(self): """ Destination ports for this blacklist entry. If no ports are specified, 'ANY' is returned. :rtype: str """ start_port = self.blacklist.get('BlacklistEntryDestinationPort') if start_port is not None: return '{}-{}'.format( start_port, self.blacklist.get('BlacklistEntryDestinationPortRange')) return 'ANY'
Destination ports for this blacklist entry. If no ports are specified, 'ANY' is returned. :rtype: str
entailment
def name(self): """ Name attribute of rule element """ return self._meta.name if self._meta.name else \ 'Rule @%s' % self.tag
Name attribute of rule element
entailment
def move_rule_after(self, other_rule): """ Add this rule after another. This process will make a copy of the existing rule and add after the specified rule. If this raises an exception, processing is stopped. Otherwise the original rule is then deleted. You must re-retrieve the new element after running this operation as new references will be created. :param other_rule Rule: rule where this rule will be positioned after :raises CreateRuleFailed: failed to duplicate this rule, no move is made """ self.make_request( CreateRuleFailed, href=other_rule.get_relation('add_after'), method='create', json=self) self.delete()
Add this rule after another. This process will make a copy of the existing rule and add after the specified rule. If this raises an exception, processing is stopped. Otherwise the original rule is then deleted. You must re-retrieve the new element after running this operation as new references will be created. :param other_rule Rule: rule where this rule will be positioned after :raises CreateRuleFailed: failed to duplicate this rule, no move is made
entailment
def create_rule_section(self, name, add_pos=None, after=None, before=None): """ Create a rule section in a Firewall Policy. To specify a specific numbering position for the rule section, use the `add_pos` field. If no position or before/after is specified, the rule section will be placed at the top which will encapsulate all rules below. Create a rule section for the relavant policy:: policy = FirewallPolicy('mypolicy') policy.fw_ipv4_access_rules.create_rule_section(name='attop') # For NAT rules policy.fw_ipv4_nat_rules.create_rule_section(name='mysection', add_pos=5) :param str name: create a rule section by name :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :raises MissingRequiredInput: when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified. :raises CreateRuleFailed: rule creation failure :return: the created ipv4 rule :rtype: IPv4Rule """ href = self.href params = None if add_pos is not None: href = self.add_at_position(add_pos) elif before or after: params = self.add_before_after(before, after) return ElementCreator( self.__class__, exception=CreateRuleFailed, href=href, params=params, json={'comment': name})
Create a rule section in a Firewall Policy. To specify a specific numbering position for the rule section, use the `add_pos` field. If no position or before/after is specified, the rule section will be placed at the top which will encapsulate all rules below. Create a rule section for the relavant policy:: policy = FirewallPolicy('mypolicy') policy.fw_ipv4_access_rules.create_rule_section(name='attop') # For NAT rules policy.fw_ipv4_nat_rules.create_rule_section(name='mysection', add_pos=5) :param str name: create a rule section by name :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :raises MissingRequiredInput: when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified. :raises CreateRuleFailed: rule creation failure :return: the created ipv4 rule :rtype: IPv4Rule
entailment
def create(self, name, sources=None, destinations=None, services=None, action='allow', log_options=None, authentication_options=None, connection_tracking=None, is_disabled=False, vpn_policy=None, mobile_vpn=False, add_pos=None, after=None, before=None, sub_policy=None, comment=None, **kw): """ Create a layer 3 firewall rule :param str name: name of rule :param sources: source/s for rule :type sources: list[str, Element] :param destinations: destination/s for rule :type destinations: list[str, Element] :param services: service/s for rule :type services: list[str, Element] :param action: allow,continue,discard,refuse,enforce_vpn, apply_vpn,forward_vpn, blacklist (default: allow) :type action: Action or str :param LogOptions log_options: LogOptions object :param ConnectionTracking connection_tracking: custom connection tracking settings :param AuthenticationOptions authentication_options: options for auth if any :param PolicyVPN,str vpn_policy: policy element or str href; required for enforce_vpn, use_vpn and apply_vpn actions :param bool mobile_vpn: if using a vpn action, you can set mobile_vpn to True and omit the vpn_policy setting if you want this VPN to apply to any mobile VPN based on the policy VPN associated with the engine :param str,Element sub_policy: sub policy required when rule has an action of 'jump'. Can be the FirewallSubPolicy element or href. :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :param str comment: optional comment for this rule :raises MissingRequiredInput: when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified. :raises CreateRuleFailed: rule creation failure :return: the created ipv4 rule :rtype: IPv4Rule """ rule_values = self.update_targets(sources, destinations, services) rule_values.update(name=name, comment=comment) if isinstance(action, Action): rule_action = action else: rule_action = Action() rule_action.action = action if not rule_action.action in self._actions: raise CreateRuleFailed('Action specified is not valid for this ' 'rule type; action: {}'.format(rule_action.action)) if rule_action.action in ('apply_vpn', 'enforce_vpn', 'forward_vpn'): if vpn_policy is None and not mobile_vpn: raise MissingRequiredInput('You must either specify a vpn_policy or set ' 'mobile_vpn when using a rule with a VPN action') if mobile_vpn: rule_action.mobile_vpn = True else: try: vpn = element_resolver(vpn_policy) # VPNPolicy rule_action.vpn = vpn except ElementNotFound: raise MissingRequiredInput('Cannot find VPN policy specified: {}, ' .format(vpn_policy)) elif rule_action.action == 'jump': try: rule_action.sub_policy = element_resolver(sub_policy) except ElementNotFound: raise MissingRequiredInput('Cannot find sub policy specified: {} ' .format(sub_policy)) #rule_values.update(action=rule_action.data) log_options = LogOptions() if not log_options else log_options if connection_tracking is not None: rule_action.connection_tracking_options.update(**connection_tracking) auth_options = AuthenticationOptions() if not authentication_options \ else authentication_options rule_values.update( action=rule_action.data, options=log_options.data, authentication_options=auth_options.data, is_disabled=is_disabled) params = None href = self.href if add_pos is not None: href = self.add_at_position(add_pos) elif before or after: params = self.add_before_after(before, after) return ElementCreator( self.__class__, exception=CreateRuleFailed, href=href, params=params, json=rule_values)
Create a layer 3 firewall rule :param str name: name of rule :param sources: source/s for rule :type sources: list[str, Element] :param destinations: destination/s for rule :type destinations: list[str, Element] :param services: service/s for rule :type services: list[str, Element] :param action: allow,continue,discard,refuse,enforce_vpn, apply_vpn,forward_vpn, blacklist (default: allow) :type action: Action or str :param LogOptions log_options: LogOptions object :param ConnectionTracking connection_tracking: custom connection tracking settings :param AuthenticationOptions authentication_options: options for auth if any :param PolicyVPN,str vpn_policy: policy element or str href; required for enforce_vpn, use_vpn and apply_vpn actions :param bool mobile_vpn: if using a vpn action, you can set mobile_vpn to True and omit the vpn_policy setting if you want this VPN to apply to any mobile VPN based on the policy VPN associated with the engine :param str,Element sub_policy: sub policy required when rule has an action of 'jump'. Can be the FirewallSubPolicy element or href. :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :param str comment: optional comment for this rule :raises MissingRequiredInput: when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified. :raises CreateRuleFailed: rule creation failure :return: the created ipv4 rule :rtype: IPv4Rule
entailment
def create(self, name, sources=None, destinations=None, services=None, action='allow', is_disabled=False, logical_interfaces=None, add_pos=None, after=None, before=None, comment=None): """ Create an Ethernet rule :param str name: name of rule :param sources: source/s for rule :type sources: list[str, Element] :param destinations: destination/s for rule :type destinations: list[str, Element] :param services: service/s for rule :type services: list[str, Element] :param str action: \|allow\|continue\|discard\|refuse\|blacklist :param bool is_disabled: whether to disable rule or not :param list logical_interfaces: logical interfaces by name :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :raises MissingReuqiredInput: when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified. :raises CreateRuleFailed: rule creation failure :return: newly created rule :rtype: EthernetRule """ rule_values = self.update_targets(sources, destinations, services) rule_values.update(name=name, comment=comment) rule_values.update(is_disabled=is_disabled) if isinstance(action, Action): rule_action = action else: rule_action = Action() rule_action.action = action if not rule_action.action in self._actions: raise CreateRuleFailed('Action specified is not valid for this ' 'rule type; action: {}' .format(rule_action.action)) rule_values.update(action=rule_action.data) rule_values.update(self.update_logical_if(logical_interfaces)) params = None href = self.href if add_pos is not None: href = self.add_at_position(add_pos) else: params = self.add_before_after(before, after) return ElementCreator( self.__class__, exception=CreateRuleFailed, href=href, params=params, json=rule_values)
Create an Ethernet rule :param str name: name of rule :param sources: source/s for rule :type sources: list[str, Element] :param destinations: destination/s for rule :type destinations: list[str, Element] :param services: service/s for rule :type services: list[str, Element] :param str action: \|allow\|continue\|discard\|refuse\|blacklist :param bool is_disabled: whether to disable rule or not :param list logical_interfaces: logical interfaces by name :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :raises MissingReuqiredInput: when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified. :raises CreateRuleFailed: rule creation failure :return: newly created rule :rtype: EthernetRule
entailment
def _severity_by_name(name): """ Return the severity integer value by it's name. If not found, return 'information'. :rtype: int """ for intvalue, sevname in SEVERITY.items(): if name.lower() == sevname: return intvalue return 1
Return the severity integer value by it's name. If not found, return 'information'. :rtype: int
entailment
def situation_parameters(self): """ Situation parameters defining detection logic for the context. This will return a list of SituationParameter indicating how the detection is made, i.e. regular expression, integer value, etc. :rtype: list(SituationParameter) """ for param in self.data.get('situation_parameters', []): cache = ElementCache(data=self.make_request(href=param)) yield type('SituationParameter', (SituationParameter,), { 'data': cache})(name=cache.name, type=cache.type, href=param)
Situation parameters defining detection logic for the context. This will return a list of SituationParameter indicating how the detection is made, i.e. regular expression, integer value, etc. :rtype: list(SituationParameter)
entailment
def parameter_values(self): """ Parameter values for this inspection situation. This correlate to the the situation_context. :rtype: list(SituationParameterValue) """ for param in self.data.get('parameter_values', []): cache = ElementCache(data=self.make_request(href=param)) name = '{}'.format(cache.type.title()).replace('_', '') yield type(name, (SituationParameterValue,), { 'data': cache})(name=cache.name, type=cache.type, href=param)
Parameter values for this inspection situation. This correlate to the the situation_context. :rtype: list(SituationParameterValue)
entailment
def create(cls, name, situation_context, attacker=None, target=None, severity='information', situation_type=None, description=None, comment=None): """ Create an inspection situation. :param str name: name of the situation :param InspectionSituationContext situation_context: The situation context type used to define this situation. Identifies the proper parameter that identifies how the situation is defined (i.e. regex, etc). :param str attacker: Attacker information, used to identify last packet the triggers attack and is only used for blacklisting. Values can be packet_source, packet_destination, connection_source, or connection_destination :param str target: Target information, used to identify the last packet that triggers the attack and is only used for blacklisting. Values can be packet_source, packet_destination, connection_source, or connection_destination :param str severity: severity for this situation. Valid values are critical, high, low, information :param str description: optional description :param str comment: optional comment """ try: json = { 'name': name, 'comment': comment, 'description': description, 'situation_context_ref': situation_context.href, 'attacker': attacker, 'victim': target, 'severity': _severity_by_name(severity)} element = ElementCreator(cls, json) tag = situation_type or SituationTag('User Defined Situations') tag.add_element(element) return element except ElementNotFound as e: raise CreateElementFailed('{}. Inspection Situation Contexts require SMC ' 'version 6.5 and above.'.format(str(e)))
Create an inspection situation. :param str name: name of the situation :param InspectionSituationContext situation_context: The situation context type used to define this situation. Identifies the proper parameter that identifies how the situation is defined (i.e. regex, etc). :param str attacker: Attacker information, used to identify last packet the triggers attack and is only used for blacklisting. Values can be packet_source, packet_destination, connection_source, or connection_destination :param str target: Target information, used to identify the last packet that triggers the attack and is only used for blacklisting. Values can be packet_source, packet_destination, connection_source, or connection_destination :param str severity: severity for this situation. Valid values are critical, high, low, information :param str description: optional description :param str comment: optional comment
entailment
def create_regular_expression(self, regexp): """ Create a regular expression for this inspection situation context. The inspection situation must be using an inspection context that supports regex. :param str regexp: regular expression string :raises CreateElementFailed: failed to modify the situation """ for parameter in self.situation_context.situation_parameters: if parameter.type == 'regexp': return self.add_parameter_value( 'reg_exp_situation_parameter_values', **{'parameter_ref': parameter.href, 'reg_exp': regexp}) # Treat as raw string raise CreateElementFailed('The situation does not support a regular ' 'expression as a context value.')
Create a regular expression for this inspection situation context. The inspection situation must be using an inspection context that supports regex. :param str regexp: regular expression string :raises CreateElementFailed: failed to modify the situation
entailment
def download(self, filename=None): """ Download snapshot to filename :param str filename: fully qualified path including filename .zip :raises EngineCommandFailed: IOError occurred downloading snapshot :return: None """ if not filename: filename = '{}{}'.format(self.name, '.zip') try: self.make_request( EngineCommandFailed, resource='content', filename=filename) except IOError as e: raise EngineCommandFailed("Snapshot download failed: {}" .format(e))
Download snapshot to filename :param str filename: fully qualified path including filename .zip :raises EngineCommandFailed: IOError occurred downloading snapshot :return: None
entailment
def upload(self, engine, timeout=5, wait_for_finish=False, **kw): """ Upload policy to specific device. Using wait for finish returns a poller thread for monitoring progress:: policy = FirewallPolicy('_NSX_Master_Default') poller = policy.upload('myfirewall', wait_for_finish=True) while not poller.done(): poller.wait(3) print(poller.task.progress) print("Task finished: %s" % poller.message()) :param str engine: name of device to upload policy to :raises: TaskRunFailed :return: TaskOperationPoller """ return Task.execute(self, 'upload', params={'filter': engine}, timeout=timeout, wait_for_finish=wait_for_finish, **kw)
Upload policy to specific device. Using wait for finish returns a poller thread for monitoring progress:: policy = FirewallPolicy('_NSX_Master_Default') poller = policy.upload('myfirewall', wait_for_finish=True) while not poller.done(): poller.wait(3) print(poller.task.progress) print("Task finished: %s" % poller.message()) :param str engine: name of device to upload policy to :raises: TaskRunFailed :return: TaskOperationPoller
entailment
def search_rule(self, search): """ Search a rule for a rule tag or name value Result will be the meta data for rule (name, href, type) Searching for a rule in specific policy:: f = FirewallPolicy(policy) search = f.search_rule(searchable) :param str search: search string :return: rule elements matching criteria :rtype: list(Element) """ result = self.make_request( resource='search_rule', params={'filter': search}) if result: results = [] for data in result: typeof = data.get('type') if 'ethernet' in typeof: klazz = lookup_class('ethernet_rule') elif typeof in [ 'ips_ipv4_access_rule', 'l2_interface_ipv4_access_rule']: klazz = lookup_class('layer2_ipv4_access_rule') else: klazz = lookup_class(typeof) results.append(klazz(**data)) return results return []
Search a rule for a rule tag or name value Result will be the meta data for rule (name, href, type) Searching for a rule in specific policy:: f = FirewallPolicy(policy) search = f.search_rule(searchable) :param str search: search string :return: rule elements matching criteria :rtype: list(Element)
entailment
def rule_counters(self, engine, duration_type='one_week', duration=0, start_time=0): """ .. versionadded:: 0.5.6 Obtain rule counters for this policy. Requires SMC >= 6.2 Rule counters can be obtained for a given policy and duration for those counters can be provided in duration_type. A custom start range can also be provided. :param Engine engine: the target engine to obtain rule counters from :param str duration_type: duration for obtaining rule counters. Valid options are: one_day, one_week, one_month, six_months, one_year, custom, since_last_upload :param int duration: if custom set for duration type, specify the duration in seconds (Default: 0) :param int start_time: start time in milliseconds (Default: 0) :raises: ActionCommandFailed :return: list of rule counter objects :rtype: RuleCounter """ json = {'target_ref': engine.href, 'duration_type': duration_type} return [RuleCounter(**rule) for rule in self.make_request( method='create', resource='rule_counter', json=json)]
.. versionadded:: 0.5.6 Obtain rule counters for this policy. Requires SMC >= 6.2 Rule counters can be obtained for a given policy and duration for those counters can be provided in duration_type. A custom start range can also be provided. :param Engine engine: the target engine to obtain rule counters from :param str duration_type: duration for obtaining rule counters. Valid options are: one_day, one_week, one_month, six_months, one_year, custom, since_last_upload :param int duration: if custom set for duration type, specify the duration in seconds (Default: 0) :param int start_time: start time in milliseconds (Default: 0) :raises: ActionCommandFailed :return: list of rule counter objects :rtype: RuleCounter
entailment
def create(cls, name, nat=False, mobile_vpn_toplogy_mode=None, vpn_profile=None): """ Create a new policy based VPN :param name: name of vpn policy :param bool nat: whether to apply NAT to the VPN (default False) :param mobile_vpn_toplogy_mode: whether to allow remote vpn :param VPNProfile vpn_profile: reference to VPN profile, or uses default :rtype: PolicyVPN """ vpn_profile = element_resolver(vpn_profile) or \ VPNProfile('VPN-A Suite').href json = {'mobile_vpn_topology_mode': mobile_vpn_toplogy_mode, 'name': name, 'nat': nat, 'vpn_profile': vpn_profile} try: return ElementCreator(cls, json) except CreateElementFailed as err: raise CreatePolicyFailed(err)
Create a new policy based VPN :param name: name of vpn policy :param bool nat: whether to apply NAT to the VPN (default False) :param mobile_vpn_toplogy_mode: whether to allow remote vpn :param VPNProfile vpn_profile: reference to VPN profile, or uses default :rtype: PolicyVPN
entailment
def enable_disable_nat(self): """ Enable or disable NAT on this policy. If NAT is disabled, it will be enabled and vice versa. :return: None """ if self.nat: self.data['nat'] = False else: self.data['nat'] = True
Enable or disable NAT on this policy. If NAT is disabled, it will be enabled and vice versa. :return: None
entailment
def add_mobile_gateway(self, gateway): """ Add a mobile VPN gateway to this policy VPN. Example of adding or removing a mobile VPN gateway:: policy_vpn = PolicyVPN('myvpn') policy_vpn.open() policy_vpn.add_mobile_vpn_gateway(ExternalGateway('extgw3')) for mobile_gateway in policy_vpn.mobile_gateway_node: if mobile_gateway.gateway == ExternalGateway('extgw3'): mobile_gateway.delete() policy_vpn.save() policy_vpn.close() :param Engine,ExternalGateway gateway: An external gateway, engine or href for the mobile gateway :raises PolicyCommandFailed: could not add gateway """ try: gateway = gateway.vpn.internal_gateway.href # Engine except AttributeError: gateway = element_resolver(gateway) # External Gateway self.make_request( PolicyCommandFailed, method='create', resource='mobile_gateway_node', json={'gateway': gateway, 'node_usage': 'mobile'})
Add a mobile VPN gateway to this policy VPN. Example of adding or removing a mobile VPN gateway:: policy_vpn = PolicyVPN('myvpn') policy_vpn.open() policy_vpn.add_mobile_vpn_gateway(ExternalGateway('extgw3')) for mobile_gateway in policy_vpn.mobile_gateway_node: if mobile_gateway.gateway == ExternalGateway('extgw3'): mobile_gateway.delete() policy_vpn.save() policy_vpn.close() :param Engine,ExternalGateway gateway: An external gateway, engine or href for the mobile gateway :raises PolicyCommandFailed: could not add gateway
entailment
def add_internal_gateway_to_vpn(internal_gateway_href, vpn_policy, vpn_role='central'): """ Add an internal gateway (managed engine node) to a VPN policy based on the internal gateway href. :param str internal_gateway_href: href for engine internal gw :param str vpn_policy: name of vpn policy :param str vpn_role: central|satellite :return: True for success :rtype: bool """ try: vpn = PolicyVPN(vpn_policy) vpn.open() if vpn_role == 'central': vpn.add_central_gateway(internal_gateway_href) else: vpn.add_satellite_gateway(internal_gateway_href) vpn.save() vpn.close() except ElementNotFound: return False return True
Add an internal gateway (managed engine node) to a VPN policy based on the internal gateway href. :param str internal_gateway_href: href for engine internal gw :param str vpn_policy: name of vpn policy :param str vpn_role: central|satellite :return: True for success :rtype: bool
entailment
def enable_disable(self): """ Enable or disable the tunnel link between endpoints. :raises UpdateElementFailed: failed with reason :return: None """ if self.enabled: self.update(enabled=False) else: self.update(enabled=True)
Enable or disable the tunnel link between endpoints. :raises UpdateElementFailed: failed with reason :return: None
entailment
def prepare_blacklist(src, dst, duration=3600, src_port1=None, src_port2=None, src_proto='predefined_tcp', dst_port1=None, dst_port2=None, dst_proto='predefined_tcp'): """ Create a blacklist entry. A blacklist can be added directly from the engine node, or from the system context. If submitting from the system context, it becomes a global blacklist. This will return the properly formatted json to submit. :param src: source address, with cidr, i.e. 10.10.10.10/32 or 'any' :param dst: destination address with cidr, i.e. 1.1.1.1/32 or 'any' :param int duration: length of time to blacklist Both the system and engine context blacklist allow kw to be passed to provide additional functionality such as adding source and destination ports or port ranges and specifying the protocol. The following parameters define the ``kw`` that can be passed. The following example shows creating an engine context blacklist using additional kw:: engine.blacklist('1.1.1.1/32', '2.2.2.2/32', duration=3600, src_port1=1000, src_port2=1500, src_proto='predefined_udp', dst_port1=3, dst_port2=3000, dst_proto='predefined_udp') :param int src_port1: start source port to limit blacklist :param int src_port2: end source port to limit blacklist :param str src_proto: source protocol. Either 'predefined_tcp' or 'predefined_udp'. (default: 'predefined_tcp') :param int dst_port1: start dst port to limit blacklist :param int dst_port2: end dst port to limit blacklist :param str dst_proto: dst protocol. Either 'predefined_tcp' or 'predefined_udp'. (default: 'predefined_tcp') .. note:: if blocking a range of ports, use both src_port1 and src_port2, otherwise providing only src_port1 is adequate. The same applies to dst_port1 / dst_port2. In addition, if you provide src_portX but not dst_portX (or vice versa), the undefined port side definition will default to all ports. """ json = {} directions = {src: 'end_point1', dst: 'end_point2'} for direction, key in directions.items(): json[key] = {'address_mode': 'any'} if \ 'any' in direction.lower() else {'address_mode': 'address', 'ip_network': direction} if src_port1: json.setdefault('end_point1').update( port1=src_port1, port2=src_port2 or src_port1, port_mode=src_proto) if dst_port1: json.setdefault('end_point2').update( port1=dst_port1, port2=dst_port2 or dst_port1, port_mode=dst_proto) json.update(duration=duration) return json
Create a blacklist entry. A blacklist can be added directly from the engine node, or from the system context. If submitting from the system context, it becomes a global blacklist. This will return the properly formatted json to submit. :param src: source address, with cidr, i.e. 10.10.10.10/32 or 'any' :param dst: destination address with cidr, i.e. 1.1.1.1/32 or 'any' :param int duration: length of time to blacklist Both the system and engine context blacklist allow kw to be passed to provide additional functionality such as adding source and destination ports or port ranges and specifying the protocol. The following parameters define the ``kw`` that can be passed. The following example shows creating an engine context blacklist using additional kw:: engine.blacklist('1.1.1.1/32', '2.2.2.2/32', duration=3600, src_port1=1000, src_port2=1500, src_proto='predefined_udp', dst_port1=3, dst_port2=3000, dst_proto='predefined_udp') :param int src_port1: start source port to limit blacklist :param int src_port2: end source port to limit blacklist :param str src_proto: source protocol. Either 'predefined_tcp' or 'predefined_udp'. (default: 'predefined_tcp') :param int dst_port1: start dst port to limit blacklist :param int dst_port2: end dst port to limit blacklist :param str dst_proto: dst protocol. Either 'predefined_tcp' or 'predefined_udp'. (default: 'predefined_tcp') .. note:: if blocking a range of ports, use both src_port1 and src_port2, otherwise providing only src_port1 is adequate. The same applies to dst_port1 / dst_port2. In addition, if you provide src_portX but not dst_portX (or vice versa), the undefined port side definition will default to all ports.
entailment
def add_element(self, element): """ Element can be href or type :py:class:`smc.base.model.Element` :: >>> from smc.elements.other import Category >>> category = Category('foo') >>> category.add_element(Host('kali')) :param str,Element element: element to add to tag :raises: ModificationFailed: failed adding element :return: None """ element = element_resolver(element) self.make_request( ModificationFailed, method='create', resource='category_add_element', json={'value': element})
Element can be href or type :py:class:`smc.base.model.Element` :: >>> from smc.elements.other import Category >>> category = Category('foo') >>> category.add_element(Host('kali')) :param str,Element element: element to add to tag :raises: ModificationFailed: failed adding element :return: None
entailment
def add_category_tag(self, tags, append_lists=True): """ Add this category to a category tag (group). This provides drop down filters in the SMC UI by category tag. :param list tags: category tag by name :param bool append_lists: append to existing tags or overwrite default: append) :type tags: list(str) :return: None """ tags = element_resolver(tags) self.update( category_parent_ref=tags, append_lists=append_lists)
Add this category to a category tag (group). This provides drop down filters in the SMC UI by category tag. :param list tags: category tag by name :param bool append_lists: append to existing tags or overwrite default: append) :type tags: list(str) :return: None
entailment
def remove_category(self, categories): """ Remove a category from this Category Tag (group). :param list categories: categories to remove :type categories: list(str,Element) :return: None """ categories = element_resolver(categories) diff = [category for category in self.data['category_child_ref'] if category not in categories] self.update(category_child_ref=diff)
Remove a category from this Category Tag (group). :param list categories: categories to remove :type categories: list(str,Element) :return: None
entailment
def add_entry(self, src, dst, duration=3600, src_port1=None, src_port2=None, src_proto='predefined_tcp', dst_port1=None, dst_port2=None, dst_proto='predefined_tcp'): """ Create a blacklist entry. A blacklist can be added directly from the engine node, or from the system context. If submitting from the system context, it becomes a global blacklist. This will return the properly formatted json to submit. :param src: source address, with cidr, i.e. 10.10.10.10/32 or 'any' :param dst: destination address with cidr, i.e. 1.1.1.1/32 or 'any' :param int duration: length of time to blacklist Both the system and engine context blacklist allow kw to be passed to provide additional functionality such as adding source and destination ports or port ranges and specifying the protocol. The following parameters define the ``kw`` that can be passed. The following example shows creating an engine context blacklist using additional kw:: engine.blacklist('1.1.1.1/32', '2.2.2.2/32', duration=3600, src_port1=1000, src_port2=1500, src_proto='predefined_udp', dst_port1=3, dst_port2=3000, dst_proto='predefined_udp') :param int src_port1: start source port to limit blacklist :param int src_port2: end source port to limit blacklist :param str src_proto: source protocol. Either 'predefined_tcp' or 'predefined_udp'. (default: 'predefined_tcp') :param int dst_port1: start dst port to limit blacklist :param int dst_port2: end dst port to limit blacklist :param str dst_proto: dst protocol. Either 'predefined_tcp' or 'predefined_udp'. (default: 'predefined_tcp') .. note:: if blocking a range of ports, use both src_port1 and src_port2, otherwise providing only src_port1 is adequate. The same applies to dst_port1 / dst_port2. In addition, if you provide src_portX but not dst_portX (or vice versa), the undefined port side definition will default to all ports. """ self.entries.setdefault('entries', []).append(prepare_blacklist( src, dst, duration, src_port1, src_port2, src_proto, dst_port1, dst_port2, dst_proto))
Create a blacklist entry. A blacklist can be added directly from the engine node, or from the system context. If submitting from the system context, it becomes a global blacklist. This will return the properly formatted json to submit. :param src: source address, with cidr, i.e. 10.10.10.10/32 or 'any' :param dst: destination address with cidr, i.e. 1.1.1.1/32 or 'any' :param int duration: length of time to blacklist Both the system and engine context blacklist allow kw to be passed to provide additional functionality such as adding source and destination ports or port ranges and specifying the protocol. The following parameters define the ``kw`` that can be passed. The following example shows creating an engine context blacklist using additional kw:: engine.blacklist('1.1.1.1/32', '2.2.2.2/32', duration=3600, src_port1=1000, src_port2=1500, src_proto='predefined_udp', dst_port1=3, dst_port2=3000, dst_proto='predefined_udp') :param int src_port1: start source port to limit blacklist :param int src_port2: end source port to limit blacklist :param str src_proto: source protocol. Either 'predefined_tcp' or 'predefined_udp'. (default: 'predefined_tcp') :param int dst_port1: start dst port to limit blacklist :param int dst_port2: end dst port to limit blacklist :param str dst_proto: dst protocol. Either 'predefined_tcp' or 'predefined_udp'. (default: 'predefined_tcp') .. note:: if blocking a range of ports, use both src_port1 and src_port2, otherwise providing only src_port1 is adequate. The same applies to dst_port1 / dst_port2. In addition, if you provide src_portX but not dst_portX (or vice versa), the undefined port side definition will default to all ports.
entailment
def update_or_create(cls, append_lists=True, with_status=False, remove_members=False, **kwargs): """ Update or create group entries. If the group exists, the members will be updated. Set append_lists=True to add new members to the list, or False to reset the list to the provided members. If setting remove_members, this will override append_lists if set. :param bool append_lists: add to existing members, if any :param bool remove_members: remove specified members instead of appending or overwriting :paran dict kwargs: keyword arguments to satisfy the `create` constructor if the group needs to be created. :raises CreateElementFailed: could not create element with reason :return: element instance by type :rtype: Element """ was_created, was_modified = False, False element = None try: element = cls.get(kwargs.get('name')) was_modified = element.update_members( kwargs.get('members', []), append_lists=append_lists, remove_members=remove_members) except ElementNotFound: element = cls.create( kwargs.get('name'), members = kwargs.get('members', [])) was_created = True if with_status: return element, was_modified, was_created return element
Update or create group entries. If the group exists, the members will be updated. Set append_lists=True to add new members to the list, or False to reset the list to the provided members. If setting remove_members, this will override append_lists if set. :param bool append_lists: add to existing members, if any :param bool remove_members: remove specified members instead of appending or overwriting :paran dict kwargs: keyword arguments to satisfy the `create` constructor if the group needs to be created. :raises CreateElementFailed: could not create element with reason :return: element instance by type :rtype: Element
entailment
def update_members(self, members, append_lists=False, remove_members=False): """ Update group members with member list. Set append=True to append to existing members, or append=False to overwrite. :param list members: new members for group by href or Element :type members: list[str, Element] :param bool append_lists: whether to append :param bool remove_members: remove members from the group :return: bool was modified or not """ if members: elements = [element_resolver(element) for element in members] if remove_members: element = [e for e in self.members if e not in elements] if set(element) == set(self.members): remove_members = element = False append_lists = False elif append_lists: element = [e for e in elements if e not in self.members] else: element = list(set(elements)) if element or remove_members: self.update( element=element, append_lists=append_lists) return True return False
Update group members with member list. Set append=True to append to existing members, or append=False to overwrite. :param list members: new members for group by href or Element :type members: list[str, Element] :param bool append_lists: whether to append :param bool remove_members: remove members from the group :return: bool was modified or not
entailment