API Reference

Session

class smc.api.session.Session(manager=None)[source]

Session represents the clients session to the SMC. A session is obtained by calling login(). If sessions need to be long lived as might be the case when running under a web platform, a session is automatically refreshed when it expires. Best practice is to call logout() after to clear the session from the SMC. A session will be automatically closed once the python interpreter closes.

Each session will also have a single connection pool associated with it. This results in a single persistent connection to the SMC that will be re-used as needed.

property api_version

Current API Version

Return type:

str

property domain

Logged in SMC domain

Return type:

str

property entry_points

Entry points that are bound to this session. Entry points are exposed by the SMC API and provide links to top level resources

Return type:

Resource

property is_active

Is this session active. Active means there is a stored session ID for the SMC using the current account. This does not specify whether the session ID has been timed out on the server but does indicate the account has not called logout.

Return type:

bool

property is_ssl

Is this an SSL connection

Return type:

bool

login(url=None, api_key=None, login=None, pwd=None, api_version=None, timeout=None, verify=True, alt_filepath=None, domain=None, pool_maxsize=None, max_retry=None, **kwargs)[source]

Login to SMC API and retrieve a valid session. Sessions use a pool connection manager to provide dynamic scalability during times of increased load. Each session is managed by a global session manager making it possible to have more than one session per interpreter.

An example login and logout session:

from smc import session
session.login(url='http://1.1.1.1:8082', api_key='SomeSMCG3ener@t3dPwd')
.....do stuff.....
session.logout()
Parameters:
  • url (str) – ip of SMC management server

  • api_key (str) – API key created for api client in SMC

  • login (str) – Administrator user in SMC that has privilege to SMC API.

  • pwd (str) – Password for user login.

  • api_version – specify api version (optional)

  • timeout (int) – (optional): specify a timeout for initial connect; (default 10)

  • verify (str|boolean) – verify SSL connections using cert (default: verify=True) You can pass verify the path to a CA_BUNDLE file or directory with certificates of trusted CAs

  • alt_filepath (str) – If using .smcrc, alternate path+filename

  • domain (str) – domain to log in to. If domains are not configured, this field will be ignored and api client logged in to ‘Shared Domain’.

  • retry_on_busy (bool) – pass as kwarg with boolean if you want to add retries if the SMC returns HTTP 503 error during operation. You can also optionally customize this behavior and call set_retry_on_busy()

  • pool_maxsize (int) – The maximum number of connections to save in the pool.

  • max_retry (int) – The maximum number of retry.

Returns:

user session name in SessionManager

Return type:

str

Raises:

ConfigLoadError – loading cfg from ~.smcrc fails

For SSL connections, you can disable validation of the SMC SSL certificate by setting verify=False, however this is not a recommended practice.

If you want to use the SSL certificate generated and used by the SMC API server for validation, set verify=’path_to_my_dot_pem’. It is also recommended that your certificate has subjectAltName defined per RFC 2818

If SSL warnings are thrown in debug output, see: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings

Logout should be called to remove the session immediately from the SMC server.

Note

As of SMC 6.4 it is possible to give a standard Administrative user access to the SMC API. It is still possible to use an API Client by providing the api_key in the login call.

logout()[source]

Logout session from SMC

Returns:

None

property manager

Return the session manager for this session

Return type:

SessionManager

property name

Return the administrator name for this session. Can be None if the session has not yet been established.

Note

The administrator name was introduced in SMC version 6.4. Previous versions will show the unique session identifier for this session.

Return type:

str

refresh()[source]

Refresh session on 401. This is called automatically if your existing session times out and resends the operation/s which returned the error.

Raises:

SMCConnectionError – Problem re-authenticating using existing api credentials

property session_id

The session ID in header type format. Can be inserted into a connection if necessary using:

{'Cookie': session.session_id}
Return type:

str

set_retry_on_busy(total=5, backoff_factor=0.1, status_forcelist=None, **kwargs)[source]

Mount a custom retry object on the current session that allows service level retries when the SMC might reply with a Service Unavailable (503) message. This can be possible in larger environments with higher database activity. You can all this on the existing session, or provide as a dict to the login constructor.

Parameters:
  • total (int) – total retries

  • backoff_factor (float) – when to retry

  • status_forcelist (list) – list of HTTP error codes to retry on

  • method_whitelist (list) – list of methods to apply retries for, GET, POST and PUT by default

Returns:

None

property sock

get a secure socket from the pool if one is available else get a new connection

Return type:

SSLSocket

switch_domain(domain)[source]

Switch from one domain to another. You can call session.login() with a domain key value to log directly into the domain of choice or alternatively switch from domain to domain. The user must have permissions to the domain or unauthorized will be returned. In addition, when switching domains, you will be logged out of the current domain to close the connection pool associated with the previous session. This prevents potentially excessive open connections to SMC

session.login() # Log in to 'Shared Domain'
...
session.switch_domain('MyDomain')
Raises:

SMCConnectionError – Error logging in to specified domain. This typically means the domain either doesn’t exist or the user does not have privileges to that domain.

property timeout

Session timeout in seconds

Return type:

int

property url

The fully qualified SMC URL in use, includes the port number

Return type:

str

Element

class smc.base.model.ElementBase(**meta)[source]

Element base provides a meta data container and an instance cache as well as methods to retrieve aspects of an element. Meta is passed in to Element and SubElement types to provide links to resources. When a top level query is made to the SMC API, meta is returned for the element (unless a direct link query is made). The meta format include ‘href’,’type’,’name’. For example:

"href":"http://1.1.1.1:8082/6.4/elements/host/707","name":"foobar","type":"host"

Methods of the element classes are designed to expose any links or attributes of the specific element to simplify manipulation. If a method, etc is accessed that requires the elements data, the element is fetched and the elements cache (stored in data attribute) is inflated. The ETag is also retained in the element and is used when updating or deleting the element to ensure we are operating on the latest version.

Meta can be passed to constructor through as key value pairs kwargs, href=…. (only partial meta), or meta={…..} (as dict)

If meta is not provided, the meta attribute will be None

delete()[source]

Delete the element

Raises:

DeleteElementFailed – possible dependencies, record locked, etc

Returns:

None

update(*exception, **kwargs)[source]

Update the existing element and clear the instance cache. Removing the cache will ensure subsequent calls requiring element attributes will force a new fetch to obtain the latest copy.

Calling update() with no args will assume the element has already been modified directly and the data cache will be used to update. You can also override the following attributes: href, etag, json and params. If json is sent, it is expected to the be a complete payload to satisfy the update.

For kwargs, if attribute values are a list, you can pass ‘append_lists=True’ to add to an existing list, otherwise overwrite the existing (default: overwrite)

See also

To see different ways to utilize this method for updating, see: Update.

Parameters:
  • exception – pass a custom exception to throw if failure

  • kwargs – optional kwargs to update request data to server.

Raises:
Returns:

href of the element modified

Return type:

str

class smc.base.model.Element(name=None, **meta)[source]

Bases: ElementBase

Base element with common methods shared by inheriting classes. If stashing attributes on this class, be sure to prefix with an underscore to avoid having the attributes serialized when calling update.

objects(self):

Interface to element collections. All classes inheriting from Element can access collections through this class property:

for host in Host.objects.all():
        ...

Fetch a single entry:

host = Host.objects.filter('myhost')
...

For more information on collections, see: smc.base.collection.CollectionManager

add_category(category)[source]

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.

Parameters:

tags (list(str)) – list of category tag names to add to this element

Raises:

ElementNotFound – Category tag element name not found

Returns:

None

property categories

Search categories assigned to this element

>>> from smc.elements.network import Host
>>> Host('kali').categories
[Category(name=foo), Category(name=foocategory)]
Return type:

list(Category)

property comment

Comment for element

duplicate(name)[source]

New in version 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.

Parameters:

name (str) – name for the duplicated element

Raises:

ActionCommandFailed – failed to duplicate the element

Returns:

the newly created element

Return type:

Element

export(filename='element.zip')[source]

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)
Parameters:

filename (str) – filename to store exported element

Raises:

TaskRunFailed – invalid permissions, invalid directory, or this element is a system element and cannot be exported.

Returns:

DownloadTask

Note

It is not possible to export system elements

classmethod get(name, raise_exc=True)[source]

Get the element by name. Does an exact match by element type.

Parameters:
  • name (str) – name of element

  • raise_exc (bool) – optionally disable exception.

Raises:

ElementNotFound – if element does not exist

Return type:

Element

classmethod get_or_create(filter_key=None, with_status=False, **kwargs)[source]

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 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.

Parameters:
  • filter_key (dict) – filter key represents the data attribute and value to use to find the element. If none is provided, the name field will be used.

  • kwargs – keyword arguments mapping to the elements create method.

  • with_status (bool) – 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:
Returns:

element instance by type

Return type:

Element

property history

New in version 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

Return type:

History

is_locked()[source]

Locked flag for element

lock(reason_for=None)[source]

Locks this element with an optional reason.

Raises:

ResourceNotFound – If not running on supported SMC version

property name

Name of element

property referenced_by

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.

Returns:

list referenced elements

Return type:

list(Element)

rename(name)[source]

Rename this element.

Parameters:

name (str) – new name of element

Raises:

UpdateElementFailed – update failed with reason

Returns:

None

unlock()[source]

Unlocks this element.

Raises:

ResourceNotFound – If not running on supported SMC version

classmethod update_or_create(filter_key=None, with_status=False, **kwargs)[source]

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 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
Parameters:
  • filter_key (dict) – filter key represents the data attribute and value to use to find the element. If none is provided, the name field will be used.

  • kwargs – keyword arguments mapping to the elements create method.

  • with_status (bool) – 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:
Returns:

element instance by type

Return type:

Element

class smc.base.model.SubElement(**meta)[source]

Bases: ElementBase

SubElement is the base class for elements that do not have direct entry points in the SMC and instead are obtained through a reference. They are not ‘loaded’ directly as are classes that inherit from Element.

class smc.base.model.UserElement(name, **meta)[source]

Bases: Element

User element mixin for LDAP of Internal Domains.

property name

Name of element

property unique_id

Fully qualified unique DN for this entry

Return type:

str

class smc.core.resource.History(creation_time=None, creator=None, creator_name=None, is_locked=None, is_obsolete=None, is_trashed=None, last_modification_time=None, modifier=None, modifier_name=None, follower=None, in_progress=None, last_message=None, progress=None, success=None, waiting_inputs=None)[source]

History description of this element. This will provide basic information about the element such as when it was created, last modified along with the accounts making the modifications.

Variables:
  • is_locked (bool) – is this record currently locked

  • is_osbsolete (bool) – is this record obsoleted

  • is_trashed (bool) – is the record in the trash bin

property created_by

The account that created this element. Returned as an Element.

Return type:

Element

property last_modified

When the element was last modified as a datetime object

Return type:

datetime

property modified_by

The account that last modified this element.

Return type:

Element

property when_created

When the element was created as a datetime object

Return type:

datetime

Administration

Access Rights

Access Rights provide the ability to create administrative accounts and assign or create specific access control lists and roles to these accounts.

AccessControlList

class smc.administration.access_rights.AccessControlList(name=None, **meta)[source]

Bases: Element

An ACL is assigned to an AdminUser to grant limited access permissions to either Engines, Policies or Domains. The access control list will have ‘granted elements’ that represent the elements that apply to this permission. The SMC provides default ACL’s that can be used or new ones can be created. Find all available ACL’s:

>>> AccessControlList.objects.all()
add_permission(elements)[source]

Add permission/s to this ACL. By default this change is committed after the method is called.

Parameters:

elements (list(str,Element)) – Elements to grant access to. Can be engines, policies, or other ACLs

Raises:

UpdateElementFailed – Failed updating permissions

Returns:

None

classmethod create(name, granted_element=None)[source]

Create a new ACL

Parameters:
  • name (str) – Name of ACL

  • granted_elements (list(str,Element)) – Elements to grant access to. Can be engines, policies or other acl’s.

Raises:

CreateElementFailed – failed creating ACL

Returns:

instance with meta

Return type:

AccessControlList

property permissions

Elements associated to this permission. Granted elements can be Engines, Policies or other Access Control Lists.

Returns:

Element class deriving from smc.base.model.Element

remove_permission(elements)[source]

Remove permission/s to this ACL. Change is committed at end of method call.

Parameters:

elements (list(str,Element)) – list of element/s to remove

Raises:

UpdateElementFailed – Failed modifying permissions

Returns:

None

Administrators

User module to hold accounts related to users (admin or local) in the SMC

You can create an Admin User, enable superuser, enable/disable the account, assign local access to engines, and change the account password for SMC or engine access.

It is possible to fully provision an Admin User with specific permissions and roles and initial password.

Create the admin:

admin = AdminUser.create(name='auditor', superuser=False)

Note

If the Admin User should have unrestricted access, set superuser=True and skip the below sections related to adding permissions and roles.

Permissions relate to elements that the user will have access to (Policies, Engines or AccessControlLists) and the domain where the privileges apply (default is ‘Shared Domain’).

Create a permission using the default domain of Shared, granting access to a specific engine and firewall policy:

permission = Permission.create(
    elements=[Engine('vm'), FirewallPolicy('VM Policy')],
    role=Role('Viewer'))

Create a second permission granting access to all firewalls in the domain ‘mydomain’:

domain_perm = Permission.create(
    elements=[AccessControlList('ALL Firewalls')],
    role=Role('Owner'),
    domain=AdminDomain('mydomain'))

Add the permissions to the Admin User:

admin.add_permission([permission, domain_perm])

Set an initial password for the Admin User:

admin.change_password('Newpassword1')

Note

Roles are used to define what granular controls will be available to the assigned user, such as read/read write/all. AccessControlLists encapsulate elements into a single container for re-use.

class smc.elements.user.AdminUser(name=None, **meta)[source]

Bases: UserMixin, Element

Represents an Adminitrator account on the SMC Use the constructor to create the user.

Create an Admin:

>>> AdminUser.create(name='admin', superuser=True)
AdminUser(name=admin)

If modifications are required after you can access the admin and make changes:

admin = AdminUser('admin')
admin.change_password('mynewpassword1')
admin.enable_disable()

Attributes available:

Variables:
  • allow_sudo (bool) – is this account allowed to sudo on an engine.

  • local_admin (bool) – is the admin a local admin

  • superuser (bool) – is this account a superuser for SMC

change_engine_password(password)[source]

Change Engine password for engines on allowed list.

Parameters:

password (str) – password for engine level

Raises:

ModificationFailed – failed setting password on engine

Returns:

None

classmethod create(name, local_admin=False, allow_sudo=False, superuser=False, enabled=True, engine_target=None, can_use_api=True, console_superuser=False, allowed_to_login_in_shared=True, auth_method=None, comment=None, permissions=None, ldap_user_href=None, ldap_group_href=None)[source]

Create an admin user account.

New in version 0.6.2: Added can_use_api, console_superuser, and allowed_to_login_in_shared. Requires SMC >= SMC 6.4

Parameters:
  • name (str) – name of account

  • local_admin (bool) – is a local admin only

  • allow_sudo (bool) – allow sudo on engines

  • can_use_api (bool) – can log in to SMC API

  • console_superuser (bool) – can this user sudo via SSH/console

  • allowed_to_login_in_shared (bool) – can this user log in to the shared domain

  • superuser (bool) – is a super administrator

  • auth_method – authentication method

  • enabled (bool) – is account enabled

  • engine_target (list) – engine to allow remote access to

  • comment – object comment

:param permissions object in case SMC admin is not superuser :param ldap_user_href External user href to link as SMC admin :param ldap_group_href External user href to link as SMC admin :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: AdminUser

property enabled

Read only enabled status

Return type:

bool

property password_meta_data

Provides creation_date and expiration_date of the password for AdminUser,ApiClient and WebPortalAdminUser. :return: PasswordMetaData : PasswordMetaData contains creation_date and expiration_date.

class smc.elements.user.ApiClient(name=None, **meta)[source]

Bases: UserMixin, Element

Represents an API Client

classmethod create(name, enabled=True, superuser=True)[source]

Create a new API Client. Once client is created, you can create a new password by:

>>> client = ApiClient.create('myclient')
>>> print(client)
ApiClient(name=myclient)
>>> client.change_password('mynewpassword')
Parameters:
  • name (str) – name of client

  • enabled (bool) – enable client

  • superuser (bool) – is superuser account

Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

ApiClient

class smc.elements.user.PasswordMetaData(value)[source]

Bases: NestedDict

Represents the password meta-data for AdminUser, ApiClient and WebPortalAdminUser. it provides creation_date and expiration_date of the password for AdminUser,ApiClient and WebPortalAdminUser

class smc.elements.user.UserMixin[source]

Bases: object

User Mixin class providing common operations for Admin Users and API Clients.

add_permission(permission)[source]

Add a permission to this Admin User. A role defines permissions that can be enabled or disabled. Elements define the target for permission operations and can be either Access Control Lists, Engines or Policy elements. Domain specifies where the access is granted. The Shared Domain is default unless specific domain provided. Change is committed at end of method call.

Parameters:

permission (list(Permission)) – permission/s to add to admin user

Raises:

UpdateElementFailed – failed updating admin user

Returns:

None

change_password(password)[source]

Change user password. Change is committed immediately.

Parameters:

password (str) – new password

Returns:

None

enable_disable()[source]

Toggle enable and disable of administrator account. Change is committed immediately.

Raises:

UpdateElementFailed – failed with reason

Returns:

None

generate_password()[source]

Generate a random password for this user.

Returns:

random password

Return type:

str

property permissions

Return each permission role mapping for this Admin User. A permission role will have 3 fields:

  • Domain

  • Role (Viewer, Operator, etc)

  • Elements (Engines, Policies, or ACLs)

Returns:

permissions as list

Return type:

list(Permission)

class smc.elements.user.WebPortalAdminUser(name=None, **meta)[source]

Bases: UserMixin, Element

This represents a Web Portal User.It is an element that defines the details of a single person

that is allowed to log on to the Web Portal, the Browser-based service that allows users to view logs, Policy Snapshots, and reports

Create a Web Portal Admin User:

>>> WebPortalAdminUser.create(name='admin')

If modifications are required after you can access the admin and make changes:

admin = WebPortalAdminUser('admin')
admin.change_password('mynewpassword1')
admin.enable_disable()
classmethod create(name, enabled=True, granted_engine=None, console_superuser=False, log_service_enabled=True, policy_service_enabled=True, report_service_enabled=True, show_inspection_policy=True, show_main_policy=True, show_only_ip_addresses=True, show_sub_policy=True, show_template_policy=False, show_upload_comment=True, show_upload_history=True, granted_template_policy=None, granted_sub_policy=None, granted_report_design=None, filter_tag=None, comment=None)[source]

Create a web portal admin user account.

New in version 0.6.2: Added can_use_api, console_superuser, and allowed_to_login_in_shared. Requires SMC >= SMC 6.4

Parameters:
  • name (str) – name of account

  • enabled (bool) – is account enabled

  • granted_engine (list) – The list of Granted Engines

  • console_superuser (bool) – can this user sudo via SSH/console.

  • log_service_enabled (bool) – check if the log service enabled?

  • policy_service_enabled (bool) – check if the policy service enabled.

  • report_service_enabled (bool) – Is the report service enabled?

  • show_inspection_policy (bool) – Should we display the inspection policy?

  • show_main_policy (bool) – Should we display the main policy?

  • show_only_ip_addresses (bool) – Should we display only the IP Addresses of elements?

  • show_sub_policy (bool) – Should we display the sub policy?

  • show_template_policy (bool) – Should we display the template policy?

  • show_upload_comment (bool) – Should we display the upload comment?

  • show_upload_history (bool) – Should we display the upload history?

  • granted_template_policy (list) – The list of Granted Template Policies. null value means ANY.

  • granted_sub_policy (list) – The list of Granted Sub Policies. null value means ANY

  • granted_report_design (list) – The list of Granted Report Designs. null value means ANY.

  • filter_tag (list) – The list of Filter expression tags for the log browsing. null value means ANY.

  • comment (str) – comment,

Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

WebPortalAdminUser

Permission

class smc.administration.access_rights.Permission(granted_elements=None, role_ref=None, granted_domain_ref=None)[source]

Permissions are added to admin users that do not have super user access rights. An Admin User can also have multiple permissions. There are three primary fields associated with a permission:

  • Domain to grant access

  • Elements to grant access to (Engines, Policies or AccessControlLists)

  • Role

A permission might be used to grant read-only access to specific policies or firewalls (read-only vs read write). It can also be specific to the Admin Domain.

classmethod create(elements, role, domain=None)[source]

Create a permission.

Parameters:
  • granted_elements (list(str,Element)) – Elements for this permission. Can be engines, policies or ACLs

  • role (str,Role) – role for this permission

  • domain (str,Element) – domain to apply (default: Shared Domain)

Return type:

Permission

property domain

Domain this permission applies to. Shared Domain if unspecified.

Return type:

AdminDomain

property granted_elements

List of elements this permission has rights to. Elements will be of type Engine, Policy or ACLs

Return type:

list(Element)

property role

Specific Role assigned to this permission. A role is what allows read/write access to specific operations on the granted elements

Return type:

Role

Roles

Administrator Role elements specify a restricted set of permissions that include the right to create, edit, and delete elements.

Each administrator can have several different Administrator Roles applied to different sets of elements. There are some default Administrator Roles, but if you want to customize the permissions in any way, you must create custom Administrator Role elements.

Create a new role is done by using the create classmethod. By default the role will not have any permissions set:

>>> from smc.administration.role import Role
>>> role = Role.create(name='mynewrole')

A role has many attributes (mostly boolean) that can be enabled, therefore the simplest way to create a new role is to duplicate an existing role.

>>> list(Role.objects.all())
[Role(name=myeditor), Role(name=Logs Viewer), Role(name=Reports Manager), Role(name=Owner),
 Role(name=Viewer), Role(name=Operator), Role(name=Monitor), Role(name=Editor),
 Role(name=Superuser)]
...

Duplicate an existing role to simplify making modifications on permissions:

>>> role = Role('Editor')
>>> role.duplicate('customeditor')
Role(name=customeditor)

To enable or disable role permissions, use the enable/disable option after retrieving the Role resource.

Available and current permission settings can be found by calling permissions attribute:

>>> role = Role('newrole')
>>> role.permissions
[{'alert_mgmt': False}, {'send_advanced_commands': False}, {'license_mgmt': False},
 {'element_edit': False}, {'view_edit_report': False}, {'view_system_alerts': False},
 {'view_logs': False}, {'vpn_mgmt': False}, {'log_pruning_mgmt': False},
 {'updates_and_upgrades_mgmt': False}, {'auth_server_user_mgmt': False}, {'view_audit': False},
 {'element_delete': False}, {'element_create': False}, {'upload_policy': False},
 {'send_commands': False}, {'backup_mgmt': False}, {'element_view_content': True},
 {'log_mgmt': False}, {'bookmark_manage': True}, {'admin_mgmt': False}, {'name': 'newrole'},
 {'overview_manage': True}, {'internal_user_mgmt': False}, {'refresh_policy': False}]

Then enable specific roles by specifying the keys to enable:

>>> role.enable(['element_create', 'upload_policy'])

Also disable specific roles:

>>> role.disable(['element_create', 'upload_policy'])

Once modification is complete, call update on the role:

>>> role.update()
'http://172.18.1.151:8082/6.4/elements/role/10'
class smc.administration.role.Role(name=None, **meta)[source]

Bases: Element

Role class represents granular access control rights that can be applied to specific elements (Engines, Policies or Access Control Lists).

classmethod create(name, comment=None)[source]

Create a new role. The role will not have any permissions by default so it will be required to call enable on the role after creation.

Parameters:
  • name (str) – name of role

  • comment (str) – comment for role

Raises:

CreateElementFailed – failed to create role

Return type:

Role

disable(values)[source]

Disable specific permissions on this role. Use permissions to view valid permission settings and current value/s. Change is committed immediately.

Parameters:

values (list) – list of values by allowed types

Returns:

None

enable(values)[source]

Enable specific permissions on this role. Use permissions to view valid permission settings and current value/s. Change is committed immediately.

Parameters:

values (list) – list of values by allowed types

Returns:

None

property permissions

Return valid permissions and setting for this role. Permissions are returned as a list of dict items, {permission: state}. State for the permission is either True or False. Use enable() and disable() to toggle role settings.

Returns:

list of permission settings

Return type:

list(dict)

Alert Configuration

AlertChain

class smc.elements.alerts.AlertChain(name=None, **meta)[source]

This represents an Alert Chain.

classmethod create(name, final_action=None, alert_chain_ref=None, comment=None)[source]

Create the custom alert :param str name: name of alert chain :param str comment: optional comment :param str final_action: optional final_action

possible values:

1)none: stop policy processing without acknowledging. 2)acknowledge: stop policy processing and acknowledge. 3)redirect: redirect to another alert chain. 4)return: return to the next policy rule.

Parameters:

alert_chain_ref (obj) – The redirect alert chain. object of AlertChain.

Raises:

CreateElementFailed – failed creating element with reason

Returns:

instance with meta of alert chain

Return type:

AlertChain

AlertChainRule

class smc.elements.alerts.AlertChainRule(**meta)[source]

This represents a Alert Chain Rule for Alert Chain Policy.

static create(self, name, alert_channel=None, destination=None, delay=0, admin_name=[], amount=None, notify_first_block=0, period=0, comment=None)[source]
Parameters:
  • self (object) – object of AlertChain.

  • name (str) – name of alert chain rule.

  • alert_channel (str) – The alert channel, default is Delay channel.Valid values are below smtp: SMTP channel. sms: SMS channel. snmp: SNMP channel. custom_script: Custom script channel. delay: Delay channel. user_notification: User notification channel.

  • destination (str) – destination address

  • delay (int) – The delay before the next notification, in minutes.

  • admin_name (list) – List of admin users. Used in the case of User notification channel.

  • amount (int) – The maximum number of notifications to be sent before activating

moderation. :param int notify_first_block: Indicates whether we shall notify the first blocked notification upon moderation activation. :param int period: The period during which notifications are tracked before activating moderation. period need to be mentioned in minutes. :param str comment: descript of element. :raises CreateElementFailed: failed creating element with reason :return: instance with meta of alert chain rule :rtype: AlertChainRule

AlertPolicy

class smc.elements.alerts.AlertPolicy(name=None, **meta)[source]

This represents an Alert Policy.

add_alert_rule(name, alert_chain_ref=None, match_sender_ref=[], alert_and_situation_ref=[], min_severity=1, max_severity=10, rule_validity_times=[], comment=None)[source]

creation of the element of type alert_rule. :param object self: object of AlertPolicy. :param str name: name of alert rule. :param str(AlertChain) alert_chain_ref: The Alert Chain. :param str match_sender_ref: The senders. If empty, it is considered as ANY. :param list alert_and_situation_ref: The alerts and situations. If empty, it is considered

as ANY.

Parameters:
  • min_severity (int) – The minimum value for the severity (value between 1 and 10)

  • max_severity (int) – The maximum value for the severity (value between 1 and 10)

  • rule_validity_times (list) – The rule’s validity to a specific time period. During the specified time period, the rule matches. Outside the specified time period, the rule does not match and the matching continues to the next rule.

  • comment (str) – descript of element.

Raises:

CreateElementFailed – failed creating element with reason

Returns:

instance with meta of alert rule

Return type:

AlertRule

classmethod create(name, comment=None)[source]

Create the custom alert :param str name: name of alert policy :param str comment: optional comment :raises CreateElementFailed: failed creating element with reason :return: instance with meta of alert policy :rtype: AlertPolicy

AlertRule

class smc.elements.alerts.AlertRule(**meta)[source]

This represents Alert Rule for Alert Policy.

static create(self, name, alert_chain_ref=None, match_sender_ref=[], alert_and_situation_ref=[], min_severity=1, max_severity=10, rule_validity_times=[], comment=None)[source]

creation of the element of type alert_rule. :param object self: object of AlertPolicy. :param str name: name of alert rule. :param str(AlertChain) alert_chain_ref: The Alert Chain. :param list match_sender_ref: The senders. If empty, it is considered as ANY. :param list alert_and_situation_ref: The alerts and situations. If empty, it is considered

as ANY.

Parameters:
  • min_severity (int) – The minimum value for the severity (value between 1 and 10):Matches the rule to only Situations with the specified Severity value(s). For example, if your rule is general and matches a wide range of Situations, you may want to create two similar rules: one for less severe Situations and one for more Severe situations. Useful in rules that contain Tags in the Situation cell.

  • max_severity (int) – The maximum value for the severity (value between 1 and 10):Matches the rule to only Situations with the specified Severity value(s). For example if your rule is general and matches a wide range of Situations, you may want to create two similar rules: one for less severe Situations and one for more Severe situations. Useful in rules that contain Tags in the Situation cell.

  • rule_validity_times (list) – The rule’s validity to a specific time period. During the specified time period, the rule matches. Outside the specified time period, the rule does not match and the matching continues to the next rule.

  • comment (str) – descript of element.

Raises:

CreateElementFailed – failed creating element with reason

Returns:

instance with meta of alert rule

Return type:

AlertRule

Certificates

TLSCommon

TLS Common module provides mixin methods that are common to certificate handling in SMC. Importing certificates and private keys can be done by providing a file where the certificates/keys are stored, or providing in string format.

class smc.administration.certificates.tls_common.ImportExportCertificate[source]

Mixin to provide certificate import and export methods to relevant classes.

export_certificate(filename=None)[source]

Export the 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

Return type:

str or None

import_certificate(certificate)[source]

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.

Parameters:

certificate_file (str) – fully qualified path to certificate file

Raises:
Returns:

None

class smc.administration.certificates.tls_common.ImportExportIntermediate[source]

Mixin to provide import and export capabilities for intermediate certificates

export_intermediate_certificate(filename=None)[source]

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.

Return type:

str or None

import_intermediate_certificate(certificate)[source]

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.

Parameters:

certificate (str) – fully qualified path or string

Raises:
Returns:

None

class smc.administration.certificates.tls_common.ImportPrivateKey[source]

Mixin to provide import capabilities to relevant classes that require private keys.

import_private_key(private_key)[source]

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.

Parameters:

private_key (str) – fully qualified path to private key file

Raises:
Returns:

None

TLSServerCredential

TLS module provides interactions related to importing TLS Server Credentials for inbound SSL decryption, as well as client protection certificates used for outbound decryption.

To properly decrypt inbound TLS connections, you must provide the Stonesoft FW with a valid certificate and private key. Within SMC these certificate types are known as TLS Server Credentials.

Once you have imported these certificates, you must then assign them to the relevant engines that will perform the decryption services. Lastly you will need a rule that enables HTTPS with decryption.

First start by importing the TLS Server Credential class:

>>> from smc.administration.certificates.tls import TLSServerCredential

If you want to create a TLS Server Credential in steps, the process is as follows:

tls = TLSServerCredential.create(name)    # Create the certificate element
tls.import_certificate(certificate) # Import the certificate
tls.import_private_key(private_key) # Import the private key
tls.import_intermediate_certificate(intermediate) # Import intermediate certificate (optional)

Otherwise, use helper methods that allow you to do this in a single step.

For example, creating the TLS credential from certificate files:

>>> tls = TLSServerCredential.import_signed(
              name='server.test.local',
              certificate='/pathto/server.crt',
              private_key='/pathto/server.key',
              intermediate=None)  # <-- You can also include intermediate certificates
>>> tls
TLSServerCredential(name=server.test.local)

Note

Certificate, private key and intermediate certificates can also be specified in raw string format and must start with the BEGIN CERTIFICATE, etc common syntax.

You can also import certificates from a certificate chain file. When doing so, the certificates are expected to be in the order: server certificate, intermediate/s, root certificate. You can optionally also add the private key to the chain file or provide it separately:

tls = TLSServerCredential.import_from_chain(
    name='fromchain', certificate_file='/path/cert.chain',
    private_key='/path/priv.key')

Note

If multiple intermediate certificates are added, only the first one is imported into the TLS Server Credential. In addition, the root certificate is ignored and should be imported using TLSCertificateAuthority.create().

It is also possible to create self signed certificates using the SMC CA:

>>> tls = TLSServerCredential.create_self_signed(
    name='server.test.local', common_name='CN=server.test.local')
>>> tls
TLSServerCredential(name=server.test.local)

If you would rather use the SMC to generate the CSR and have the request signed by an external CA you can call TLSServerCredential.create_csr() and export the request:

>>> tls = TLSServerCredential.create_csr(name='public.test.local',
                                         common_name='CN=public.test.local')
>>> tls.certificate_export()
'-----BEGIN CERTIFICATE REQUEST-----
MIIEXTCCAkcCAQAwHDEaMBgGA1UEAwwRcHVibGljLnRlc3QubG9jYWwwggIiMA0G
CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC68xcXrWQ5E25nkTfmgmPQiWVPwf
....
....
-----END CERTIFICATE REQUEST-----'

Optionally export the request to a local file:

>>> tls = TLSServerCredential.create_csr(
    name='public2.test.local', common_name='CN=public2.test.local')
>>> tls.certificate_export(filename='public2.test.local.csr')

If you use an external CA for signing your certficiates, you can also import that as a TLS Certificate Authority. The link between the certificates and root CA will be made automatically:

TLSCertificateAuthority.create(
    name='myrootca',
    certificate='/path/to/cert/or/string')

Once you have the TLS Server Credentials within SMC, you can then assign them to the relevant engines:

>>> from smc.core.engine import Engine
>>> from smc.administration.certificates import TLSServerCredential
>>> engine = Engine('myfirewall')
>>> engine.tls_inspection.add_tls_credential([TLSServerCredential('public.test.local'),
                                              TLSServerCredential('server.test.local')])
>>> engine.tls_inspection.server_credentials
[TLSServerCredential(name=public.test.local), TLSServerCredential(name=server.test.local)]

Note

It is possible to import and export certificates from the SMC, but it is not possible to export private keys.

class smc.administration.certificates.tls.TLSServerCredential(name=None, **meta)[source]

Bases: ImportExportIntermediate, ImportPrivateKey, ImportExportCertificate, Element

If you want to inspect TLS traffic for which an internal server is the destination, you must create a TLS Credentials element to store the private key and certificate of the server.

The private key and certificate allow the firewall to decrypt TLS traffic for which the internal server is the destination so that it can be inspected.

After a TLSServerCredential has been created, you must apply this to the engine performing decryption and create the requisite policy rule that uses SSL decryption.

Variables:

certificate_state (str) – State of the certificate. Available states are ‘request’ and ‘certificate’. If the state is ‘request’, this represents a CSR and needs to be signed.

classmethod create(name)[source]

Create an empty certificate. This will only create the element in the SMC and will then require that you import the server certificate, intermediate (optional) and private key.

Raises:

CreateElementFailed – failed creating element

Return type:

TLSServerCredential

classmethod create_csr(*args, **kwargs)[source]

Create a certificate signing request.

Parameters:
  • name (str) – name of TLS Server Credential

  • rcommon_name (str) – common name for certificate. An example would be: “CN=CommonName,O=Organization,OU=Unit,C=FR,ST=PACA,L=Nice”. At minimum, a “CN” is required.

  • public_key_algorithm (str) – public key type to use. Valid values rsa, dsa, ecdsa.

  • signature_algorithm (str) – signature algorithm. Valid values dsa_sha_1, dsa_sha_224, dsa_sha_256, rsa_md5, rsa_sha_1, rsa_sha_256, rsa_sha_384, rsa_sha_512, ecdsa_sha_1, ecdsa_sha_256, ecdsa_sha_384, ecdsa_sha_512. (Default: rsa_sha_512)

  • key_length (int) – length of key. Key length depends on the key type. For example, RSA keys can be 1024, 2048, 3072, 4096. See SMC documentation for more details.

Raises:

CreateElementFailed – failed to create CSR

Return type:

TLSServerCredential

classmethod create_self_signed(name, common_name, public_key_algorithm='rsa', signature_algorithm='rsa_sha_512', key_length=4096)[source]

Create a self signed certificate. This is a convenience method that first calls create_csr(), then calls self_sign() on the returned TLSServerCredential object.

Parameters:
  • name (str) – name of TLS Server Credential

  • rcommon_name (str) – common name for certificate. An example would be: “CN=CommonName,O=Organization,OU=Unit,C=FR,ST=PACA,L=Nice”. At minimum, a “CN” is required.

  • public_key_algorithm (str) – public key type to use. Valid values rsa, dsa, ecdsa.

  • signature_algorithm (str) – signature algorithm. Valid values dsa_sha_1, dsa_sha_224, dsa_sha_256, rsa_md5, rsa_sha_1, rsa_sha_256, rsa_sha_384, rsa_sha_512, ecdsa_sha_1, ecdsa_sha_256, ecdsa_sha_384, ecdsa_sha_512. (Default: rsa_sha_512)

  • key_length (int) – length of key. Key length depends on the key type. For example, RSA keys can be 1024, 2048, 3072, 4096. See SMC documentation for more details.

Raises:
Return type:

TLSServerCredential

classmethod import_from_chain(name, certificate_file, private_key=None)[source]

Import the server certificate, intermediate and optionally private key from a certificate chain file. The expected format of the chain file follows RFC 4346. In short, the server certificate should come first, followed by any intermediate certificates, optionally followed by the root trusted authority. The private key can be anywhere in this order. See https://tools.ietf.org/html/rfc4346#section-7.4.2.

Note

There is no validation done on the certificates, therefore the order is assumed to be true. In addition, the root certificate will not be imported and should be separately imported as a trusted root CA using create

If the certificate chain file has only two entries, it is assumed to be the server certificate and root certificate (no intermediates). In which case only the certificate is imported. If the chain file has 3 or more entries (all certificates), it will import the first as the server certificate, 2nd as the intermediate and ignore the root cert.

You can optionally provide a seperate location for a private key file if this is not within the chain file contents.

Warning

A private key is required to create a valid TLS Server Credential.

Parameters:
  • name (str) – name of TLS Server Credential

  • certificate_file (str) – fully qualified path to chain file or file object

  • private_key (str) – fully qualified path to chain file or file object

Raises:
  • IOError – error occurred reading or finding specified file

  • ValueError – Format issues with chain file or empty

Return type:

TLSServerCredential

classmethod import_signed(name, certificate, private_key, intermediate=None)[source]

Import a signed certificate and private key to SMC, and optionally an intermediate certificate. The certificate and the associated private key must be compatible with OpenSSL and be in PEM format. The certificate and private key can be imported as a raw string, file path or file object. If importing as a string, be sure the string has carriage returns after each line and the final END CERTIFICATE line.

Import a certificate and private key:

>>> tls = TLSServerCredential.import_signed(
        name='server2.test.local',
        certificate='mydir/server.crt',
        private_key='mydir/server.key')
>>> tls
TLSServerCredential(name=server2.test.local)
Parameters:
  • name (str) – name of TLSServerCredential

  • certificate (str) – fully qualified to the certificate file, string or file object

  • private_key (str) – fully qualified to the private key file, string or file object

  • intermediate (str) – fully qualified to the intermediate file, string or file object

Raises:
Return type:

TLSServerCredential

self_sign()[source]

Self sign the certificate in ‘request’ state.

Raises:

ActionCommandFailed – failed to sign with reason

property valid_from

New in version 0.6.0: Requires SMC version >= 6.3.4

The valid from datetime for this TLS Server Credential.

Return type:

datetime.datetime

property valid_to

New in version 0.6.0: Requires SMC version >= 6.3.4

The expiration (valid to) datetime for this TLS Server Credential.

Return type:

datetime.datetime

TLSProfile

class smc.administration.certificates.tls.TLSProfile(name=None, **meta)[source]

Bases: Element

New in version 0.6.2: Requires SMC >= 6.4

Represents a TLS Profile. Contains common parameters for establishing TLS based connections. TLS Profiles are used in various configuration areas such as SSL VPN portal and Active Directory (when using TLS) connections.

classmethod create(name, tls_version, use_only_subject_alt_name=False, accept_wildcard=False, check_revocation=True, tls_cryptography_suites=None, crl_delay=0, ocsp_delay=0, ignore_network_issues=False, tls_trusted_ca_ref=None, comment=None)[source]

Create a TLS Profile. By default the SMC will have a default NIST TLS Profile but it is also possible to create a custom profile to provide special TLS handling.

Parameters:
  • name (str) – name of TLS Profile

  • tls_verison (str) – supported tls verison, valid options are TLSv1.1, TLSv1.2, TLSv1.3

  • use_only_subject_alt_name (bool) – Use Only Subject Alt Name when the TLS identity is a DNS name

  • accept_wildcard (bool) – Does server identity check accept wildcards

  • check_revocation (bool) – Is certificate revocation checked

  • tls_cryptography_suites (str,TLSCryptographySuite) – allowed cryptography suites for this profile. Uses NIST profile if not specified

  • crl_delay (int) – Delay time (hours) for fetching CRL

  • ocsp_delay (int) – Ignore OCSP failure for (hours)

  • ignore_network_issues (bool) – Ignore revocation check failures due to network issues

  • tls_trusted_ca_ref (list) – Trusted Certificate Authorities, empty list means trust any

  • comment (str) – optional comment

Raises:
Return type:

TLSProfile

TLSIdentity

class smc.administration.certificates.tls.TLSIdentity(tls_field, tls_value)[source]

Bases: NestedDict

New in version 0.6.2: Requires SMC >= 6.4

A TLS Identity represents a field and value pair that will be used to validate a TLS certificate. This can be used in various areas where TLS is used such as VPN.

Valid tls field types are:

DNSName IPAddress CommonName DistinguishedName SHA-1 SHA-256 SHA-512 MD5 Email user_principal_name

TLSCryptographySuite

class smc.administration.certificates.tls.TLSCryptographySuite(name=None, **meta)[source]

Bases: Element

This represents a TLS Cryptography Suite Set used in various configurations that require a TLS Profile such as SSL VPN Tunneling, Reverse Web Proxy, ActiveDirectory TLS, etc.

static ciphers(from_suite=None)[source]

This is a helper method that will return all of the cipher strings used in a specified TLSCryptographySuite or returns the system default NIST profile list of ciphers. This can be used as a helper to identify the ciphers to specify/add when creating a new TLSCryptographySuite.

Return type:

dict

classmethod create(name, comment=None, **ciphers)[source]

Create a new TLSCryptographySuite. The ciphers kwargs should be a dict with the cipher suite string as key and boolean value to indicate if this cipher should be enabled. To obtain the valid cipher suite string name, use the following method:

cipher_strings = TLSCryptographySuite.ciphers()

Then to create a custom cipher suite, provide the ciphers as a dict of kwargs. In this example, create a TLS Crypto Suite that only enables AES 256 bit ciphers:

only256 = dict(((cipher, True) for cipher in TLSCryptographySuite.ciphers()
    if 'aes_256' in cipher))

mytls = TLSCryptographySuite.create(name='mytls', **only256)
Parameters:
  • name (str) – name of this TLS Crypto suite

  • ciphers (dict) – dict of ciphers with cipher string as key and bool as value, True enables the cipher

Raises:

CreateElementFailed – failed to create element with reason

Return type:

TLSCryptographySuite

TLSCertificateAuthority

class smc.administration.certificates.tls.TLSCertificateAuthority(name=None, **meta)[source]

Bases: ImportExportCertificate, Element

TLS Certificate authorities. When using TLS Server Credentials for decryption, import the root CA for the any TLS Server certificates the leverage the root CA.

Variables:
  • certificate (str) – base64 encoded certificate for this CA

  • crl_checking_enabled (bool) – whether CRL checking is turned on

  • internal_ca (bool) – is this an internal CA (default: false)

  • oscp_checking_enabled (bool) – is OSCP validation enabled

classmethod create(name, certificate)[source]

Create a TLS CA. The certificate must be compatible with OpenSSL and be in PEM format. The certificate can be either a file with the Root CA, or a raw string starting with BEGIN CERTIFICATE, etc. When creating a TLS CA, you must also import the CA certificate. Once the CA is created, it is possible to import a different certificate to map to the CA if necessary.

Parameters:
  • name (str) – name of root CA

  • certificate (str,file) – The root CA contents

Raises:
Return type:

TLSCertificateAuthority

ClientProtectionCA

class smc.administration.certificates.tls.ClientProtectionCA(name=None, **meta)[source]

Bases: ImportPrivateKey, ImportExportCertificate, Element

Changed in version 0.7.0: Deprecated create method

Client Protection Certificate Authority elements are used to inspect TLS traffic between an internal client and an external server for outbound decryption.

When an internal client makes a connection to an external server that uses TLS, the engine generates a substitute certificate that allows it to establish a secure connection with the internal client. The Client Protection Certificate Authority element contains the credentials the engine uses to sign the substitute certificate it generates.

Variables:
  • certificate (str) – base64 encoded certificate for this CA

  • crl_checking_enabled (bool) – whether CRL checking is turned on

  • internal_ca (bool) – is this an internal CA (default: false)

  • oscp_checking_enabled (bool) – is OSCP validation enabled

Note

If the engine does not use a signing certificate that is already trusted by users web browsers when it signs the substitute certificates it generates, users receive warnings about invalid certificates. To avoid these warnings, you must either import a signing certificate that is already trusted, or configure users web browsers to trust the engine signing certificate.

classmethod create_self_signed(name, public_key_algorithm='rsa', life_time=365, key_length=2048, **kwargs)[source]

Changed in version 0.7.0: prefix and password argument deprecated in SMC > 6.5.1.

Create a self signed client protection CA. To prevent browser warnings during decryption, you must trust the signing certificate in the client browsers.

Parameters:
  • name (str) – Name of this ex: “SG Root CA” Used as Key. Real common name will be derivated at creation time with a uniqueId.

  • public_key_algorithm – public key algorithm, either rsa, dsa or ecdsa

  • life_time (str,int) – lifetime in days for CA

  • key_length (int) – length in bits, either 1024 or 2048

Raises:
Return type:

ClientProtectionCA

classmethod import_signed(name, certificate, private_key)[source]

Import a signed certificate and private key as a client protection CA.

This is a shortcut method to the 3 step process:

  • Create CA with name

  • Import certificate

  • Import private key

Create the CA:

ClientProtectionCA.import_signed(
    name='myclientca',
    certificate_file='/pathto/server.crt'
    private_key_file='/pathto/server.key')
Parameters:
  • name (str) – name of client protection CA

  • certificate_file (str) – fully qualified path or string of certificate

  • private_key_file (str) – fully qualified path or string of private key

Raises:
Return type:

ClientProtectionCA

VPNCertificateCA

GatewayCertificate

Domains

class smc.administration.system.AdminDomain(name=None, **meta)[source]

Bases: Element

Administrative domain element. Domains are used to provide object based segmentation within SMC. If domains are in use, you can log in directly to a domain to modify contents within that domain.

Find all available domains:

>>> list(AdminDomain.objects.all())
[AdminDomain(name=Shared Domain)]
>>> admindomain_obj = AdminDomain(name=mydomain)
>>> admindomain_obj.announcement_enabled
    True
>>> admindomain_obj.announcement_message
    test
>>> admindomain_obj.update(announcement_enabled=False)
>>> admindomain_obj.announcement_enabled
    False

Note

Admin Domains require and SMC license.

property announcement_enabled

Display flag of announcement message :rtype: bool

property announcement_message

Announcement message to be displayed before the login window. :rtype: str

property category_filter_system

Flag to know if we need to show system elements :@rtype: bool

property contact_number

Contact Number :rtype: str

classmethod create(name, announcement_enabled=False, announcement_message=None, contact_email=None, contact_number=None, category_filter_system=True, show_not_categorized=True, user_alert_check=[], comment=None)[source]

Create a new Admin Domain element for SMC objects.

Example:

>>> admindomain_obj=AdminDomain.create(name='mydomain',announcement_enabled=True,                 announcement_message='test', comment='mycomment')
>>> AdminDomain(name=mydomain)
Parameters:
  • name (str) – name of domain

  • announcement_enabled (bool) – Enable or disable display of announcement message

  • announcement_message (str) – Announcement message to be displayed before the login window

  • contact_email (str) – contact email

  • contact_number (str) – contact phone number

  • category_filter_system (bool) – Flag to know if we need to show system elements. By default, true.

  • show_not_categorized (bool) – Flag to know if we need to show not categorized. By default, true.

  • user_alert_check (list) – The list of User alert checks.

  • comment (str) – optional comment

Raises:

CreateElementFailed – failed creating element with reason

Returns:

instance with meta

Return type:

AdminDomain

get_active_alerts(full=True)[source]

Available for all SMC API Versions but only for SMC Version above 7.1 (7.1 included)

Return active alerts for the requested domain

:optional param full ( default value is true ). When set to false, juste retrieve the log

key of each entry ( timestamp, component id, event id ).

Returns:

list of alert monitoring entries : session_monitoring.SessionMonitoringResult

Return type:

SerializedIterable(Route)

property show_not_categorized

Flag to know if we need to show not categorized. :rtype: bool

property user_alert_check

The list of User alert checks. :rtype: list(UserAlertCheck)

License

License

Module representing read-only licenses in SMC

class smc.administration.license.License(**data)[source]

Valid attributes (read-only) are:

Variables:
  • binding – master license binding serial number

  • binding_state – state of license, unassigned, bound, etc

  • bindings – which node is the license bound to

  • customer_name – customer name, if any

  • enabled_feature_packs – additional feature licenses

  • expiration_date – when license expires

  • features – features enabled on this license

  • granted_date – when license date began

  • license_id – license ID (unique for each license)

  • license_version – max version for this license

  • maintenance_contract_expires_date – date/time support ends

  • management_server_binding – management server binding POS

  • proof_of_license – proof of license key

  • type – type of license (SECNODE, Mgmt, etc)

class smc.administration.license.Licenses(licenses)[source]

List of all available licenses for this Management Server.

Scheduled Tasks

New in version 0.5.7: Requires SMC version >= 6.3.2

Scheduled tasks are administrative processes that can run either immediately after being defined, or scheduled to run on a regular basis. Scheduled tasks in the SMC are defined under Administration->Tasks->Definition.

Some tasks are read-only, meaning they are system elements and cannot be modified or copied and can therefore only be scheduled (these task related classes will not have a create method). Other tasks can be created and custom settings can be defined. Check the documentation for each task to determine the capabilities.

All tasks inherit the ScheduledTaskMixin which provides a start method and access to a TaskSchedule instance through the task_schedule property. The associated TaskSchedule defines whether to run the task ongoing and details specifying when the task should be run and how often.

An example follows that shows how to use a refresh policy task. Other tasks use the same API syntax.

Finding existing tasks for a specific task type:

for task in RefreshPolicyTask.objects.all():
    print(task, task.task_schedule)

Review an existing task and it’s task schedule:

task = RefreshPolicyTask(name='mytask')
for schedule in task.task_schedule:
    print(schedule.activation_date, schedule.activated)

Create a refresh policy refresh task:

task = RefreshPolicyTask.create(
    name='mytask',
    engines=[Engine('engine1'), Engine('engine2')],
    comment='some comment')

A created task can always be run at any time without having to set a schedule for the task by calling start on the task:

task = RefreshPolicyTask('mytask')
task.start()

A task can also be scheduled for a future time. Adding a scheduled run to the task requires that we first obtain the task and add the schedule to it. This can be done when creating the task, or the retrieved after:

task = RefreshPolicyTask.create(
    name='mytask',
    engines=[Engine('engine1'), Engine('engine2')],
    comment='refresh policy on specified engines')

task.add_schedule(
    name='refresh_policy_on_saturday',
    activation_date=1512325716000,  # 12/04/2017 00:00:00
    day_period='weekly',
    day_mask=128,
    comment='tun this task weekly')

You can also specify tasks that run on a regular interval, such as monthly:

task = RefreshPolicyTask(name='mytask')
task.add_schedule(
    name='run_monthly',
    activation_date=1512367200000, # Start 12/4/2017 at 00:00:00
    day_period='monthly')

Repeat a task for a period of time, then disable task on specified date:

task = DeleteLogTask.create(
    name='Delete SMC Server logs',
    servers='all',
    time_range='last_full_month',
    all_logs=True)

task.add_schedule(
    name='Run for 6 months',
    activation_date=1512367200000, # Start 12/04/2017
    day_period='monthly',
    repeat_until_date=1528088400000, # End 06/04/2018
    comment='purge log task')

Note

You can use the helper method smc.base.util.datetime_to_ms() for obtaining millisecond times for scheduled tasks.

class smc.administration.scheduled_tasks.ArchiveLogTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

An archive log task defines a way to archive log data from the SMC. When defining the task, you specify which servers to archive (typically management AND log server/s), and which log types to archive.

Note

Log tasks currently support pre-defined time ranges such as ‘yesterday’, ‘last_week’, etc. If creating custom time ranges for tasks, use the SMC.

classmethod create(name, servers=None, time_range='yesterday', filter_for_export=None, filter_for_delete=None, delete_source_data=False, all_logs=False, server_directory_lst=None, is_local_location=False, comment=None, **kwargs)[source]

Create a new archive log task. Provide True to all_logs to archive all log types. Otherwise provide kwargs to specify each log by type of interest.

Parameters:
  • name (str) – name for this task

  • servers (list(ManagementServer or LogServer)) – servers to back up. Servers must be instances of management servers or log servers. If no value is provided, all servers are backed up.

  • time_range (str) – specify a time range for the archive. Valid options are ‘yesterday’, ‘last_full_week_sun_sat’, ‘last_full_week_mon_sun’, ‘last_full_month’ (default ‘yesterday’)

  • filter_for_export (FilterExpression) – The Filter expression for the archive/export task to be able to filter logs to consider. (default: FilterExpression(‘Match All’)

  • filter_for_delete (FilterExpression) – The Filter expression for the archive/delete task to be able to filter logs for deletion. (default: FilterExpression(‘Match None’)

  • delete_source_data (bool) – Flag to know if after the archive operation, logs need to be deleted.

  • all_logs (bool) – if True, all log types will be archived. If this is True, kwargs are ignored (default: False)

  • server_directory_lst (list) – Server directories used to retrieve logs. see server_directory() for keyword arguments and default values.

  • is_local_location (bool) – Flag to know if the archive/export file will be stored on the log server or locally.

  • kwargs – see log_target_types() for keyword arguments and default values.

Raises:
Returns:

the task

Return type:

ArchiveLogTask

class smc.administration.scheduled_tasks.DeleteLogTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

A delete log task defines a way to purge log data from the SMC. When defining the task, you specify which servers to delete from (typically management AND log server/s), and which log types to delete.

Note

Log tasks currently support pre-defined time ranges such as ‘yesterday’, ‘last_week’, etc. If creating custom time ranges for tasks, use the SMC.

classmethod create(name, servers=None, time_range='yesterday', all_logs=False, filter_for_delete=None, comment=None, **kwargs)[source]

Create a new delete log task. Provide True to all_logs to delete all log types. Otherwise provide kwargs to specify each log by type of interest.

Parameters:
  • name (str) – name for this task

  • servers (list(ManagementServer or LogServer)) – servers to back up. Servers must be instances of management servers or log servers. If no value is provided, all servers are backed up.

  • time_range (str) – specify a time range for the deletion. Valid options are ‘yesterday’, ‘last_full_week_sun_sat’, ‘last_full_week_mon_sun’, ‘last_full_month’ (default ‘yesterday’)

  • filter_for_delete (FilterExpression) – optional filter for deleting. (default: FilterExpression(‘Match All’)

  • all_logs (bool) – if True, all log types will be deleted. If this is True, kwargs are ignored (default: False)

  • kwargs – see log_target_types() for keyword arguments and default values.

Raises:
Returns:

the task

Return type:

DeleteLogTask

class smc.administration.scheduled_tasks.DeleteOldRunTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

A read-only task to delete the task history from already run tasks. This is generally a recommended task to run on a monthly basis to purge the old task data.

class smc.administration.scheduled_tasks.DeleteOldSnapshotsTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

A read-only management server task to delete snapshots since the last scheduled run. For example, if this task is configured to run once per month, snapshots older than 1 month will be deleted.

class smc.administration.scheduled_tasks.DisableUnusedAdminTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

A read-only task to disable any administrator account that has not been used within the time set in the Administrator password policy.

class smc.administration.scheduled_tasks.ExportLogTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

An export log task defines a way to export log data from the SMC. When defining the task, you specify which servers to export from (typically management AND log server/s), and which log types to export.

Note

Log tasks currently support pre-defined time ranges such as ‘yesterday’, ‘last_week’, etc. If creating custom time ranges for tasks, use the SMC.

classmethod create(name, servers=None, time_range='yesterday', file_name=None, file_format='xml', is_local_location=True, filter_for_export=None, all_logs=False, overwrite_file_flag='overwrite', server_directory_lst=None, comment=None, **kwargs)[source]

Create a new export log task. Provide True to all_logs to export all log types. Otherwise provide kwargs to specify each log by type of interest.

Parameters:
  • name (str) – name for this task

  • servers (list(ManagementServer or LogServer)) – servers to back up. Servers must be instances of management servers or log servers. If no value is provided, all servers are backed up.

  • time_range (str) – specify a time range for the export. Valid options are ‘yesterday’, ‘last_full_week_sun_sat’, ‘last_full_week_mon_sun’, ‘last_full_month’ (default ‘yesterday’)

  • file_name (str) – name of the file to export

  • file_format (str) –

    format of the file to export options are:

    *csv* export in CSV format. *xml* export in XML format. *zip* export in ZIP format. *cef* export in CEF format. *leef* export in LEEF format. *esm* export in ESM format. *snoop* export IPS recordings as SNOOP. *pcap* export IPS recordings as PCAP.

  • filter_for_export (FilterExpression) – The Filter expression for the archive/export task to be able to filter logs to consider. (default: FilterExpression(‘Match All’)

  • all_logs (bool) – if True, all log types will be deleted. If this is True, kwargs are ignored (default: False)

  • server_directory_lst (list) – see server_directory() for keyword arguments and default values.

  • is_local_location (bool) – Flag to know if the archive/export file will be stored on the log server or locally.

  • overwrite_file_flag (str) – The overwrite options: *append*: append option. *overwrite*: overwrite option. *use_number_in_file_name* create an unique file with number as name. *fail_task*: fail the task.

  • kwargs – see log_target_types() for keyword arguments and default values.

Raises:
Returns:

the task

Return type:

ExportLogTask

class smc.administration.scheduled_tasks.FetchCertificateRevocationTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

A read-only management server task to download updated certificate revocation lists.

class smc.administration.scheduled_tasks.RefreshMasterEnginePolicyTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

Refresh a Master Engine and virtual policy task.

Note

This task is only relevant for Master Engines types.

classmethod create(name, master_engines, comment=None, **kwargs)[source]

Create a refresh task for master engines.

Parameters:
  • name (str) – name of task

  • master_engines (list(MasterEngine)) – list of master engines for this task

  • comment (str) – optional comment

  • kwargs – to support new attributes like preserve_connections, snapshot_creation.

Raises:

CreateElementFailed – failed to create the task, i.e. no valid engines provided

Returns:

the task

Return type:

RefreshMasterEnginePolicyTask

class smc.administration.scheduled_tasks.RefreshPolicyTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

A scheduled task associated with refreshing policy on engine/s. A refresh will push an existing policy that is already mapped to the engine/s. Use UploadPolicyTask to create a task that will assign a policy to an engine/s and upload.

Note

Any engine can force a policy refresh on the engine node directly by calling engine.refresh(), or from the engines assigned policy by calling policy.refresh(engine) also.

classmethod create(name, engines, comment=None, validate_policy=True, **kwargs)[source]

Create a refresh policy task associated with specific engines. A policy refresh task does not require a policy be specified. The policy used in the refresh will be the policy already assigned to the engine.

Parameters:
  • name (str) – name of this task

  • engines (list(Engine)) – list of Engines for the task

  • comment (str) – optional comment

  • validate_policy (bool) – validate the policy before upload. If set to true, validation kwargs can also be provided if customization is required, otherwise default validation settings are used.

  • kwargs – see policy_validation_settings() for keyword arguments and default values.

Raises:
Returns:

the task

Return type:

RefreshPolicyTask

class smc.administration.scheduled_tasks.RemoteUpgradeTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

A Remote Upgrade task will Upgrade Firewall to a specified version. If an engine specified

classmethod create(name, engines, package, comment=None, **kwargs)[source]

Create an upload policy task associated with specific engines. A policy reassigns any policies that might be assigned to a specified engine.

Parameters:
  • name (str) – name of this task

  • engines (list(Engine)) – list of Engines for the task

  • package (str) – Package to assign to the engine/s

  • comment (str) – optional comment

Raises:
Returns:

the task

Return type:

RemoteUpgradeTask

class smc.administration.scheduled_tasks.RenewGatewayCertificatesTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

A read-only management server task that renews certificates on internal gateways which have automatic certificate renewal enabled.

class smc.administration.scheduled_tasks.RenewInternalCATask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

A read-only management server task that renews certificate authorities used in system communications and send alerts about expiring certificate authorities.

class smc.administration.scheduled_tasks.RenewInternalCertificatesTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

A read-only management server task that renews certificates used in systems communications and send alerts about expiring certificates.

class smc.administration.scheduled_tasks.SGInfoTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

An SGInfo task is used for obtaining support data from the engine/s.

Note

An sginfo can be executed directly on an engine node by calling the node.sginfo() method directly.

Variables:
  • include_core_files (bool) – whether to include core files in output

  • include_slapcat_output (bool) – include slapcat in output

Warning

For an sginfo to be readable, the engine must not have the ‘encrypt_configuration’ field enabled on the engine or the data will be unreadable.

classmethod create(name, engines, include_core_files=False, include_slapcat_output=False, comment=None)[source]

Create an sginfo task.

Parameters:
  • name (str) – name of task

  • engines (list(Engine)) – list of engines to apply the sginfo task

  • include_core_files (bool) – include core files in the sginfo backup (default: False)

  • include_slapcat_output (bool) – include output from a slapcat command in output (default: False)

Raises:
Returns:

the task

Return type:

SGInfoTask

class smc.administration.scheduled_tasks.ScheduledTaskMixin[source]

Bases: object

Actions common to all scheduled tasks.

add_schedule(name, activation_date, day_period='one_time', final_action='ALERT_FAILURE', activated=True, minute_period='one_time', day_mask=None, repeat_until_date=None, comment=None)[source]

Add a schedule to an existing task.

Parameters:
  • name (str) – name for this schedule

  • activation_date (int) – when to start this task. Activation date should be a UTC time represented in milliseconds.

  • day_period (str) – when this task should be run. Valid options: ‘one_time’, ‘daily’, ‘weekly’, ‘monthly’, ‘yearly’. If ‘daily’ is selected, you can also provide a value for ‘minute_period’. (default: ‘one_time’)

  • minute_period (str) – only required if day_period is set to ‘daily’. Valid options: ‘each_quarter’ (15 min), ‘each_half’ (30 minutes), or ‘hourly’, ‘one_time’ (default: ‘one_time’)

  • day_mask (int) – If the task day_period=weekly, then specify the day or days for repeating. Day masks are: sun=1, mon=2, tue=4, wed=8, thu=16, fri=32, sat=64. To repeat for instance every Monday, Wednesday and Friday, the value must be 2 + 8 + 32 = 42

  • final_action (str) – what type of action to perform after the scheduled task runs. Options are: ‘ALERT_FAILURE’, ‘ALERT’, or ‘NO_ACTION’ (default: ALERT_FAILURE)

  • activated (bool) – whether to activate the schedule (default: True)

  • repeat_until_date (str) – if this is anything but a one time task run, you can specify the date when this task should end. The format is the same as the activation_date param.

  • comment (str) – optional comment

Raises:

ActionCommandFailed – failed adding schedule

Returns:

None

property resources

Resources associated with this task. Depending on the task, this may be engines, policies, servers, etc.

Returns:

list of Elements

Return type:

list

start()[source]

Start the scheduled task now. Task can then be tracked by using common Task methods.

Raises:

ActionCommandFailed – failed starting task

Returns:

return as a generic Task

Return type:

Task

property task_schedule

Return any task schedules associated with this scheduled task.

Raises:

ActionCommandFailed – failure to retrieve task schedule

Returns:

list of task schedules

Return type:

TaskSchedule

class smc.administration.scheduled_tasks.ServerBackupTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

A task that will back up the Management Server/s, Log Server/s and optionally the Log Server data.

Variables:

log_data_must_be_saved (bool) – whether to back up logs

classmethod create(name, servers, backup_log_data=False, encrypt_password=None, comment=None, path=None, script=None)[source]

Create a new server backup task. This task provides the ability to backup individual or all management and log servers under SMC management.

Parameters:
  • name (str) – name of task

  • servers (list(ManagementServer or LogServer)) – servers to back up. Servers must be instances of management servers or log servers. If no value is provided all servers are backed up.

  • backup_log_data (bool) – Should the log files be backed up. This field is only relevant if a Log Server is backed up.

  • encrypt_password (str) – Provide an encrypt password if you want this backup to be encrypted.

  • comment (str) – optional comment

  • path – The path to store the backup

  • script – Script to execute after backup has been generated

Raises:
Returns:

the task

Return type:

ServerBackupTask

class smc.administration.scheduled_tasks.SystemSnapsotTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

A read-only task that will make a snapshot of all system elements after a updating a dynamic package on SMC.

class smc.administration.scheduled_tasks.TaskSchedule(**meta)[source]

Bases: SubElement

A task schedule is associated with a given task type that defines when the scheduled task should run.

Variables:
  • day_period (str) – how often to run the task

  • final_action (str) – what to do when the task is complete

  • minute_period (str) – if day_period is set to hourly, when to run within the hour.

activate()[source]

If a task is suspended, this will re-activate the task. Usually it’s best to check for activated before running this:

task = RefreshPolicyTask('mytask')
for scheduler in task.task_schedule:
    if scheduler.activated:
        scheduler.suspend()
    else:
        scheduler.activate()
property activated

Whether this schedule is active for this task.

Return type:

bool

property activation_date

Return the UTC time when the task is set to first run. The activation date is returned as a python datetime object.

Returns:

datetime object in format ‘%Y-%m-%d %H:%M:%S.%f’

Return type:

datetime.datetime

suspend()[source]

Suspend this scheduled task.

Raises:

ActionCommandFailed – failed to suspend, already suspended. Call activate on this task to reactivate.

Returns:

None

class smc.administration.scheduled_tasks.TrafficCaptureInterfaceSettings(data)[source]

Bases: NestedDict

classmethod create(node_ref=None, pint_ref=None, filter=None)[source]
Parameters:
  • node_ref (Node) – Individual engine node on which traffic is being captured. Required.

  • pint_ref (PhysicalInterface) – Physical Interface Link on which traffic is being captured. Required.

  • filter (str) – IP Address for filtering. By default, no ip address filtering.

Returns:

TrafficCaptureInterfaceSettings

classmethod create_interface_setting_for_all_node(engine, pint_ref=None, filter=None)[source]
This method is used to create interface settings for all nodes of the engine with

the same filter for the given interface.

Parameters:
  • engine (Engine) – Engine on which traffic is being captured. Required.

  • pint_ref (PhysicalInterface) – Physical Interface Link on which traffic is being captured. Required.

  • filter (str) – IP Address for filtering. By default, no ip address filtering.

Returns:

list(TrafficCaptureInterfaceSettings)

class smc.administration.scheduled_tasks.TrafficCaptureTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

classmethod create(name, interface_settings=None, max_file_size_in_mb=500, capture_headers_only=False, description=None, duration_in_sec=3600, sg_info_option=False, destination_file=None, comment=None)[source]

This creates the Traffic Capture task element. It captures traffic on specific engine’s physical interface with some parameters given below. :param str name: name of the traffic capture task. :param list(TrafficCaptureInterfaceSettings) interface_settings: The traffic capture

interface settings to capture traffic.

Parameters:
  • max_file_size_in_mb (int) – The Maximum size of file the Traffic to be captured in MB.

  • capture_headers_only (bool) – Decide whether to capture only header or not. By default: False

  • description (str) – The Description about traffic capture task.

  • duration_in_sec (int) – The duration in second traffic capture task will run.

  • sg_info_option (int) – This flag will decide to include sginfo. By default: False.

  • destination_file (str) – The destination file path of traffic capture file to store.

  • comment (str) – optional comment.

@return:

class smc.administration.scheduled_tasks.UploadPolicyTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

An upload policy task will assign a specified policy to an engine or group of engines and upload. If an engine specified has an existing policy assigned, the engine will be reassigned the specified policy. If the intent is to create a policy task to push an existing assigned policy, use RefreshPolicyTask instead.

Note

Policy upload on an engine can be done from the engine node itself by calling engine.upload(‘policy_name’) or from a policy directly by policy.upload(‘engine_name’).

classmethod create(name, engines, policy, comment=None, validate_policy=False, **kwargs)[source]

Create an upload policy task associated with specific engines. A policy reassigns any policies that might be assigned to a specified engine.

Parameters:
  • name (str) – name of this task

  • engines (list(Engine)) – list of Engines for the task

  • policy (Policy) – Policy to assign to the engine/s

  • comment (str) – optional comment

  • validate_policy (bool) – validate the policy before upload. If set to true, validation kwargs can also be provided if customization is required, otherwise default validation settings are used.

  • kwargs – see policy_validation_settings() for keyword arguments and default values.

Raises:
Returns:

the task

Return type:

UploadPolicyTask

class smc.administration.scheduled_tasks.ValidatePolicyTask(name=None, **meta)[source]

Bases: ScheduledTaskMixin, Element

Run a policy validation task. This does not perform a policy push. This may be useful if you want to validate any pending changes before a future policy push.

Variables:

policy (Element) – The policy associated with this task

classmethod create(name, engines, policy=None, comment=None, **kwargs)[source]

Create a new validate policy task. If a policy is not specified, the engines existing policy will be validated. Override default validation settings as kwargs.

Parameters:
  • name (str) – name of task

  • engines (list(Engine)) – list of engines to validate

  • policy (Policy) – policy to validate. Uses the engines assigned policy if none specified.

  • kwargs – see policy_validation_settings() for keyword arguments and default values.

Raises:
Returns:

the task

Return type:

ValidatePolicyTask

smc.administration.scheduled_tasks.log_target_types(all_logs=False, **kwargs)[source]

Log targets for log tasks. A log target defines the log types that will be affected by the operation. For example, when creating a DeleteLogTask, you can specify which log types are deleted.

Parameters:
  • for_alert_event_log (bool) – alert events traces (default: False)

  • for_alert_log (bool) – alerts (default: False)

  • for_fw_log (bool) – NGFW Engine logs (default: False)

  • for_ips_log (bool) – IPS logs (default: False)

  • for_ips_recording (bool) – any IPS pcaps (default: False)

  • for_l2fw_log (bool) – layer 2 Engine logs (default: False)

  • for_third_party_log (bool) – any 3rd party logs (default: False)

Returns:

dict of log targets

smc.administration.scheduled_tasks.policy_validation_settings(**kwargs)[source]

Set policy validation settings. This is used when policy based tasks are created and validate_policy is set to True. The following kwargs can be overridden in the create constructor.

Parameters:
  • configuration_validation_for_alert_chain (bool) – default False

  • duplicate_rule_check_settings (bool) – default False

  • empty_rule_check_settings (bool) – default True

  • emtpy_rule_check_settings_for_alert (bool) – default False

  • general_check_settings (bool) – default True

  • nat_modification_check_settings (bool) – default True

  • non_supported_feature (bool) – default True

  • routing_modification_check (bool) – default False

  • unreachable_rule_check_settings (bool) – default False

  • vpn_validation_check_settings (bool) – default True

Returns:

dict of validation settings

smc.administration.scheduled_tasks.server_directories_settings(srv_directories)[source]

Server directories used to retrieve logs.. This is needed for export or archive logs tasks.

Parameters:

server_directories (list) – list of server_directory

Returns:

dict of server_directories settings

smc.administration.scheduled_tasks.server_directory(**kwargs)[source]

create a server directory dict. This is used for export/archive logs tasks. The following kwargs can be overridden in the create constructor.

Parameters:

archive_mask (bool) – The bit mask of selected archive directories, -1 for all. default -1

:param bool only_archive:Indicates whether only the active directory is excluded. :param LogServer / Server server: The server used for log retrieving. :return: dict of server_directory

Reports

New in version 0.6.0: Requires SMC version >= 6.3

Reports generated from the SMC. Provides an interface to running existing report designs and exporting their contents.

Example usage:

>>> from smc.administration.reports import ReportDesign, ReportTemplate, Report

List all available report templates:

>>> list(ReportTemplate.objects.all())
[ReportTemplate(name=Firewall Weekly Summary),
 ReportTemplate(name=Firewall Daily Summary from Specific Firewall),
 ReportTemplate(name=Firewall Multi-Link Usage)
 ...

Create a report design using an existing report template:

>>> template = ReportTemplate('Firewall Weekly Summary')
>>> template.create_design('myfirewallreport')
ReportDesign(name=myfirewallreport)

Generate a report based on an existing or created report design:

>>> list(ReportDesign.objects.all())
[ReportDesign(name=Application and Web Security), ReportDesign(name=myfirewallreport)]
...
>>> design = ReportDesign('Application and Web Security')
>>> poller = design.generate(wait_for_finish=True)
>>> while not poller.done():
...   poller.wait(3)
...
>>> poller.task.resource
>>> Report(name=Application and Web Security #1515295820751)
...
>>> design.report_files
[Report(name=Application and Web Security #1515295820751),
 Report(name=Application and Web Security #1515360776422)]
>>> report = Report('Application and Web Security #1515360776422')
>>> print(report.creation_time)
2018-01-07 15:32:56.422000
>>> report.export_pdf(filename='/foo/bar/a.pdf')
class smc.administration.reports.Report(name=None, **meta)[source]

Bases: Element

Report represent a report that has been generated and that is currently stored on the SMC. These reports can be exported in multiple formats.

property creation_time

When this report was generated. Using local time.

Return type:

datetime.datetime

export_pdf(filename)[source]

Export the report in PDF format. Specify a path for which to save the file, including the trailing filename.

Parameters:

filename (str) – path including filename

Returns:

None

export_text(filename=None)[source]

Export in text format. Optionally provide a filename to save to.

Parameters:

filename (str) – path including filename (optional)

Returns:

None

property period_begin

Period when this report was specified to start.

Return type:

datetime.datetime

property period_end

Period when this report was specified to end.

Return type:

datetime.datetime

class smc.administration.reports.ReportDesign(name=None, **meta)[source]

Bases: Element

A ReportDesign defines a report available in the SMC. This class provides access to generating these reports and exporting into a format supported by the SMC. Example of generating a report, and providing a callback once the report is complete which exports the report:

>>> def export_my_report(task):
...   if task.resource:
...     report = task.resource[0]
...     print("My report reference: %s" % report)
...     report.export_pdf('/Users/foo/myfile.pdf')
...
>>>
>>> report = ReportDesign('Application and Web Security')
>>> poller = report.generate(wait_for_finish=True)
>>> poller.add_done_callback(export_my_report)
>>> while not poller.done():
...   poller.wait(3)
...
My report reference: Report(name=Application and Web Security #1515375369483)
generate(start_time=None, end_time=None, launch_time=None, overriding_duration=None, use_elasticsearch=False, senders=None, wait_for_finish=False, timeout=5, **kw)[source]

Generate the report and optionally wait for results. You can optionally add filters to the report by providing the senders argument as a list of type Element:

report = ReportDesign('Firewall Weekly Summary')
begin = datetime_to_ms(datetime.strptime("2018-02-03T00:00:00", "%Y-%m-%dT%H:%M:%S"))
end = datetime_to_ms(datetime.strptime("2018-02-04T00:00:00", "%Y-%m-%dT%H:%M:%S"))
report.generate(start_time=begin, end_time=end, senders=[Engine('vm')])
Parameters:
  • start_time (int) – milliseconds time defining start time for report (legacy)

  • end_time (int) – milliseconds time defining end time for report(legacy)

:param long launch_time : End of timerange in milliseconds (new) :param int overriding_duration: period duration in seconds (new) :param bool use_elasticsearch: if true will use elasticsearch storage :param senders: filter targets to use when generating report :type senders: list(Element) :param bool wait_for_finish: enable polling for results :param int timeout: timeout between polling :raises TaskRunFailed: refresh failed, possibly locked policy :rtype: TaskOperationPoller

property report_files

Retrieve all reports that are currently available on the SMC.

Return type:

list(Report)

class smc.administration.reports.ReportOperation(name=None, **meta)[source]

Bases: Element

A report operation is a way to launch a task to generate reports.

classmethod create(launch_time=None, overriding_duration=None, report_design=None, report_per_sender=None, use_elasticsearch=False, export_in_txt=False, export_in_pdf=False, export_in_html=False, stored=False, email=None)[source]

Create a report design based on an existing template :param int launch_time: report launch time in seconds :param int overriding_duration: period duration in seconds (new) :param ReportDesign report_design: report design to base report operation on :param bool report_per_sender: if true to activate report per sender :param bool use_elasticsearch: if true will use elasticsearch storage :param bool export_in_txt: if true will generate txt :param bool export_in_pdf: if true will generate pdf :param bool export_in_html: if true will generate html :param bool stored: if true will be stored :param str email: email address :param str name: Name of new report operation :raises CreateElementFailed: cannot create element :return: Report operation

class smc.administration.reports.ReportTemplate(name=None, **meta)[source]

Bases: Element

A report template represents an existing template in the SMC. Templates can be retrieved through the normal collections:

>>> list(ReportTemplate.objects.all())
[ReportTemplate(name=Firewall Weekly Summary),
 ReportTemplate(name=Firewall Daily Summary from Specific Firewall),
 ReportTemplate(name=Firewall Multi-Link Usage)
 ...

Once a report template of interest is identified, you can create a ReportDesign using that template:

>>> template = ReportTemplate('Firewall Weekly Summary')
>>> template.create_design('myfirewallreport')
ReportDesign(name=myfirewallreport)
create_design(name)[source]

Create a report design based on an existing template.

Parameters:

name (str) – Name of new report design

Raises:

CreateElementFailed – failed to create template

Return type:

ReportDesign

System

Module that controls aspects of the System itself, such as updating dynamic packages, updating engines, applying global block lists, etc.

To load the configuration for system, do:

>>> from smc.administration.system import System
>>> system = System()
>>> system.smc_version
'6.2.0 [10318]'
>>> system.last_activated_package
'881'
>>> for pkg in system.update_package():
...   print(pkg)
...
UpdatePackage(name=Update Package 889)
UpdatePackage(name=Update Package 888)
UpdatePackage(name=Update Package 887)
class smc.administration.system.AdminDomain(name=None, **meta)[source]

Administrative domain element. Domains are used to provide object based segmentation within SMC. If domains are in use, you can log in directly to a domain to modify contents within that domain.

Find all available domains:

>>> list(AdminDomain.objects.all())
[AdminDomain(name=Shared Domain)]
>>> admindomain_obj = AdminDomain(name=mydomain)
>>> admindomain_obj.announcement_enabled
    True
>>> admindomain_obj.announcement_message
    test
>>> admindomain_obj.update(announcement_enabled=False)
>>> admindomain_obj.announcement_enabled
    False

Note

Admin Domains require and SMC license.

property announcement_enabled

Display flag of announcement message :rtype: bool

property announcement_message

Announcement message to be displayed before the login window. :rtype: str

property category_filter_system

Flag to know if we need to show system elements :@rtype: bool

property contact_number

Contact Number :rtype: str

classmethod create(name, announcement_enabled=False, announcement_message=None, contact_email=None, contact_number=None, category_filter_system=True, show_not_categorized=True, user_alert_check=[], comment=None)[source]

Create a new Admin Domain element for SMC objects.

Example:

>>> admindomain_obj=AdminDomain.create(name='mydomain',announcement_enabled=True,                 announcement_message='test', comment='mycomment')
>>> AdminDomain(name=mydomain)
Parameters:
  • name (str) – name of domain

  • announcement_enabled (bool) – Enable or disable display of announcement message

  • announcement_message (str) – Announcement message to be displayed before the login window

  • contact_email (str) – contact email

  • contact_number (str) – contact phone number

  • category_filter_system (bool) – Flag to know if we need to show system elements. By default, true.

  • show_not_categorized (bool) – Flag to know if we need to show not categorized. By default, true.

  • user_alert_check (list) – The list of User alert checks.

  • comment (str) – optional comment

Raises:

CreateElementFailed – failed creating element with reason

Returns:

instance with meta

Return type:

AdminDomain

get_active_alerts(full=True)[source]

Available for all SMC API Versions but only for SMC Version above 7.1 (7.1 included)

Return active alerts for the requested domain

:optional param full ( default value is true ). When set to false, juste retrieve the log

key of each entry ( timestamp, component id, event id ).

Returns:

list of alert monitoring entries : session_monitoring.SessionMonitoringResult

Return type:

SerializedIterable(Route)

property show_not_categorized

Flag to know if we need to show not categorized. :rtype: bool

property user_alert_check

The list of User alert checks. :rtype: list(UserAlertCheck)

class smc.administration.system.System[source]

System level operations such as SMC version, time, update packages, and updating engines

active_alerts_ack_all()[source]

Acknowledge all active alerts in the SMC. Only valid for SMC version >= 6.2.

Raises:

ActionCommandFailed – Failure during acknowledge with reason

Returns:

None

bind_license(element_href, license_id=None, **kwargs)[source]

Bind license on element.

When license_id is not set then automatic bind is done based on element type and license available.

Example:

system = System() system.bind_license(LogServer.objects.first()) # bind automatically license system.bind_license(MgtServer.objects.first(), “123456787”) # bind license based on id

blacklist(src, dst, duration=3600, **kw)[source]

Add blacklist to all defined engines. Use the cidr netmask at the end of src and dst, such as: 1.1.1.1/32, etc.

Parameters:
  • src – source of the entry

  • dst – destination of blacklist entry

Raises:

ActionCommandFailed – blacklist apply failed with reason

Returns:

None

See also

smc.core.engine.Engine.blacklist. Applying a blacklist at the system level will be a global blacklist entry versus an engine specific entry.

Note

If more advanced blacklist is required using source/destination ports and protocols (udp/tcp), use kw to provide these arguments. See smc.elements.other.prepare_blacklist() for more details.

Note

This method requires SMC version < 7.0

since this version, “blacklist” is renamed “block_list”

block_list(src, dst, duration=3600, **kw)[source]

Add block_list to all defined engines. Use the cidr netmask at the end of src and dst, such as: 1.1.1.1/32, etc.

Parameters:
  • src – source of the entry

  • dst – destination of block list entry

Raises:

ActionCommandFailed – block list apply failed with reason

Returns:

None

See also

smc.core.engine.Engine.block_list. Applying a blacklist at the system level will be a global blacklist entry versus an engine specific entry.

Note

If more advanced blacklist is required using source/destination ports and protocols (udp/tcp), use kw to provide these arguments. See smc.elements.other.prepare_blacklist() for more details.

Note

This method requires SMC version >= 7.0

block_list_bulk(block_list)[source]

Add block_list entries to all defined engines in bulk. For block_list to work, you must also create a rule with action “Apply Blocklist”. First create your block_list entries using smc.elements.other.Blocklist then provide the block_list to this method.

:param Blocklist block_list : pre-configured block_list entries

Note

This method requires SMC version >= 7.0

clean_invalid_filters()[source]

Remove all invalid filters when there are not referenced.

Raises:

ActionCommandFailed – failed removing invalid filters

Returns:

None

delete_license(license_id)[source]

Delete a license based on license id.

empty_trash_bin()[source]

Empty system level trash bin

Raises:

ActionCommandFailed – failed removing trash

Returns:

None

engine_upgrade()[source]

List all engine upgrade packages available

To find specific upgrades available from the returned collection, use convenience methods:

system = System()
upgrades = system.engine_upgrade()
upgrades.get_contains('6.2')
upgrades.get_all_contains('6.2')
Parameters:

engine_version – Version of engine to retrieve

Raises:

ActionCommandFailed – failure to retrieve resource

Return type:

SubElementCollection(EngineUpgrade)

engine_upgrade_import(import_engine_upgrade_file, force_import=False)[source]

Import upgrade package into SMC. Specify the fully qualified path to the upgrade package file.

Parameters:
  • import_engine_upgrade_file (str) – system level path to upgrade package file

  • force_import (boolean) – force import when certificate that signed

the zip file has expired. :return: list imported EngineUpgrade

export_elements(filename='export_elements.zip', typeof='all', timeout=5, max_tries=36, exclude_trashed=None)[source]

Export elements from SMC.

Valid types are: all (All Elements)|nw (Network Elements)|ips (IPS Elements)| sv (Services)|rb (Security Policies)|al (Alerts)| vpn (VPN Elements)

Parameters:
  • type – type of element

  • filename – Name of file for export

Raises:

TaskRunFailed – failure during export with reason

Return type:

DownloadTask

export_ldif_elements(filename='export_ldif_elements.zip', timeout=5, max_tries=36)[source]

Export internal LDAP elements in LDIF format from SMC.

Parameters:

filename – Name of file for export

Raises:

TaskRunFailed – failure during export with reason

Return type:

DownloadTask

find_system_element(element_type, system_key)[source]

Search an element from its system key and its type

:param element_type is the element type :param system_key is the system key of the element :raises ElementNotFound if the system element cannot be found

import_elements(import_file)[source]

Import elements into SMC. Specify the fully qualified path to the import file.

Parameters:

import_file (str) – system level path to file

Raises:

ActionCommandFailed

Returns:

None

import_ldif_elements(filename)[source]

Import LDIF elements into SMC. Specify the fully qualified path to the import ldif file.

Parameters:

filename (str) – LDIF file containing internal LDAP entries

Raises:

ActionCommandFailed

Returns:

None

import_new_certificate_authority_certificate(certificate)[source]

Create new SMC CA from certificate.

property last_activated_package

Return the last activated package by id

Raises:

ActionCommandFailed – failure to retrieve resource

license_check_for_new()[source]

Launch the check and download of licenses on the Management Server. This task can be long so call returns immediately.

Raises:

ActionCommandFailed – failure to retrieve resource

license_details()[source]

This represents the license details for the SMC. This will include information with regards to the POL/POS, features, type, etc

Raises:

ActionCommandFailed – failure to retrieve resource

Returns:

dictionary of key/values

license_fetch(proof_of_serial)[source]

Request a license download for the specified POS (proof of serial).

Parameters:

proof_of_serial (str) – proof of serial number of license to fetch

Raises:

ActionCommandFailed – failure to retrieve resource

license_install(license_file)[source]

Install a new license.

Parameters:

license_file (str) – fully qualified path to the license jar file.

Raises:

ActionCommandFailed

Returns:

None

property licenses

List of all engine related licenses This will provide details related to whether the license is bound, granted date, expiration date, etc.

>>> for license in system.licenses:
...    if license.bound_to.startswith('Management'):
...        print(license.proof_of_license)
abcd-efgh-ijkl-mnop
Raises:

ActionCommandFailed – failure to retrieve resource

Return type:

list(Licenses)

massive_delete(elements_list)[source]

Massive delete of several elements elements_list: List of element as object to delete

Example:

host_1 = Host(“My host 1”) host_2 = Host(“My host 2”) host_3 = Host(“My host 3”) system = System() system.massive_delete([host_1, host_2, host_3])

property massive_license_bind

Bind licenses on all unlicensed nodes

property mgt_integration_configuration

Retrieve the management API configuration for 3rd party integration devices.

Raises:

ActionCommandFailed – failure to retrieve resource

references_by_element(element_href)[source]

Return all references to element specified.

Parameters:

element_href (str) – element reference

Returns:

list of references where element is used

Return type:

list(dict)

smc_certificate_authority()[source]

Show all Certificate Authorities on SMC. :rtype: SubElementCollection(CertificateAuthority).

property smc_time

Return the SMC time as datetime object in UTC

:rtype datetime

property smc_version

Return the SMC version

system_properties()[source]

List all global system properties available.

To find specific system property available from the returned collection, use convenience methods:

system = System() system_properties = system.system_properties() system_properties.get_contains(‘enable_pci’)

Return type:

SubElementCollection(SystemProperty)

system_property(system_key)[source]

Retrieve the global system property from its system key (unique id). Otherwise BaseException.

system = System() system_property = system.system_property(system_key=8)

Return type:

SystemProperty

unlicensed_components()[source]

Return list of unlicensed element (if any)

upcoming_event()[source]

Allows to retrieve the upcoming events.

Returns:

UpcomingEvents

upcoming_event_ignore_settings()[source]

Allows to retrieve the upcoming event ignore settings.

Returns:

UpcomingEventIgnoreSettings

upcoming_event_policy()[source]

Allows to retrieve the upcoming events.

Returns:

UpcomingEventPolicy

update_package()[source]

Show all update packages on SMC.

To find specific updates available from the returned collection, use convenience methods:

system = System()
updates = system.update_package()
updates.get_contains('1027')
Raises:

ActionCommandFailed – failure to retrieve resource

Return type:

SubElementCollection(UpdatePackage)

update_package_import(import_update_package_file)[source]

Import update package into SMC. Specify the fully qualified path to the update package file.

Parameters:

import_update_package_file (str) – system level path to update package file

Returns:

list imported UpdatePackage

update_system_property(system_key, new_value)[source]

Update the global system property from its system key (unique id) with the specified value (str). If the system property does not exist a BaseException is thrown.

system = System() system.update_system_property(system_key=8, value=”0”)

update_upcoming_event_ignore_settings(situations_to_ignore)[source]

Allows to change the upcoming event ignore settings for the current administrator. As a note, all upcoming events linked to the situation will be filtered.

Parameters:

situations_to_ignore (list) – list of Situations to ignore

:return None

update_upcoming_event_policy(upcoming_event_policy)[source]

Allows to change the upcoming event policy. As a note, only super users are able to perform such operation.

Parameters:

upcoming_event_policy – UpcomingEventsPolicy to update

:return None

visible_security_group_mapping(filter=None)[source]

Return all security groups assigned to VSS container types. This is only available on SMC >= 6.5.

Parameters:

filter (str) – filter for searching by name

Raises:
Returns:

dict

visible_virtual_engine_mapping(filter=None)[source]

Mappings for master engines and virtual engines

Parameters:

filter (str) – filter to search by engine name

Raises:

ActionCommandFailed – failure to retrieve resource

Returns:

list of dict items related to master engines and virtual engine mappings

Tasks

Tasks will be fired when executing specific actions such as a policy upload, refresh, or making backups.

This module provides that ability to access task specific attributes and optionally poll for status of an operation.

An example of using a task poller when uploading an engine policy (use wait_for_finish=True):

engine = Engine('myfirewall')
poller = engine.upload(policy=fwpolicy, wait_for_finish=True)
while not poller.done():
    poller.wait(5)
    print("Task Progress {}%".format(poller.task.progress))
print(poller.last_message())
class smc.administration.tasks.DownloadTask(filename, task, timeout=5, max_tries=36, **kw)[source]

Bases: TaskOperationPoller

A download task handles tasks that have files associated, for example exporting an element to a specified file.

class smc.administration.tasks.Task(task)[source]

Bases: SubElement

Task representation. This is generic and the format is used for any calls to SMC that return an asynchronous follower link to check the status of the task.

Parameters:
  • last_message (str) – Last message received on this task

  • in_progress (bool) – Whether the task is in progress or finished

  • success (bool) – Whether the task succeeded or not

  • follower (str) – Fully qualified path to the follower link to track this task.

abort()[source]

Abort existing task.

Raises:

ActionCommandFailed – aborting task failed with reason

Returns:

None

download_only(filename, timeout=5, max_tries=36)[source]

This does not start task only return a Download Task. :rtype: DownloadTask(TaskOperationPoller)

property end_time

Task end time in UTC datetime format

Return type:

datetime

get_result()[source]

Get result of task. :rtype SMCResult.

get_task_poller(**kw)[source]

return a TaskOperationPoller for the Task.

Return type:

TaskOperationPoller

property last_message

the last message returned by the task

Return type:

string

property progress

Percentage of completion

Return type:

int

property resource

The resource/s associated with this task

Return type:

list(Element)

property result_url

Link to result (this task)

Return type:

str

property start_time

Task start time in UTC datetime format

Return type:

datetime

property success

the task has succeed

Return type:

boolean

update_status()[source]

Gets the current status of this task and returns a new task object.

Raises:

TaskRunFailed – fail to update task status

smc.administration.tasks.TaskHistory()[source]

Task history retrieves a list of tasks in an event queue.

Returns:

list of task events

Return type:

list(TaskProgress)

class smc.administration.tasks.TaskOperationPoller(task, timeout=5, max_tries=36, wait_for_finish=False)[source]

Bases: object

Task Operation Poller provides a way to poll the SMC for the status of the task operation. This is returned by functions that return a task. Typically these will be operations like refreshing policy, uploading policy, etc.

add_done_callback(callback)[source]

Add a callback to run after the task completes. The callable must take 1 argument which will be the completed Task.

Parameters:

callback – a callable that takes a single argument which will be the completed Task.

done()[source]

Is the task done yet

Return type:

bool

last_message(timeout=5)[source]

Wait a specified amount of time and return the last message from the task

Return type:

str

result(timeout=None)[source]

Return the current Task after waiting for timeout

Return type:

Task

stop()[source]

Stop the running task

property task

Access to task

Return type:

Task

wait(timeout=None)[source]

Blocking wait for task status.

class smc.administration.tasks.TaskProgress(name=None, **meta)[source]

Bases: Element

Task Progress represents a task event queue. These tasks may be completed or still running. The task event queue events can be retrieved by calling TaskHistory().

property task

Return the task associated with this event

Return type:

Task

Upcoming Event

Module representing read-only upcoming events in SMC

class smc.administration.upcoming_event.UpcomingEvent(data)[source]

Bases: object

Represents an upcoming event: - the date when the event will occur - the situation of the event - the impacted element - the possible resources an SMC event which will occur soon like certificate expiration, license expiration, scheduled task failure, …

property event_date

The upcoming event date: either the date when the event will occur or the upcoming event creation date.

Return type:

int

property impacted_element

The direct impacted element for this upcoming event.

Return type:

Element

property impacted_resources

The optional impacted resources for this upcoming event.

Return type:

list(Element)

property info

Possible more info for the upcoming event.

Return type:

str

property situation

The upcoming event situation which describes the context of the event.

Return type:

Situation

class smc.administration.upcoming_event.UpcomingEventIgnoreSettings(data)[source]

Bases: object

Represents the upcoming event ignore settings for the current administrator. List of inspection situation uri with possible resource uris. Note: all upcoming events linked to the situation uri will be filtered.

property entries

The list of inspection situation to filter.

Return type:

List(Situation)

class smc.administration.upcoming_event.UpcomingEvents(upcoming_events)[source]

Bases: object

List of all upcoming events for this Management Server.

class smc.administration.upcoming_event.UpcomingEventsPolicy(upcoming_event_policy)[source]

Bases: object

Represents the upcoming event policy. List of inspection situation uri with its threshold in days. Note: to be able to update it, you need to be superuser.

class smc.administration.upcoming_event.UpcomingEventsPolicyEntry(data)[source]

Bases: object

Represents an entry for the upcoming event policy: inspection policy uri with its threshold in days.

property enabled

Flag to determinate if this situation must be considered as upcoming event. This flag will be global for the whole SMC.

property situation

The linked upcoming situation.

Return type:

Situation

property threshold_in_days

The global threshold in days for the upcoming event. If the situation is confirmed, the event will be raised during this amount of time.

Updates

Functionality related to updating dynamic update packages and engine upgrades

class smc.administration.updates.PackageMixin[source]

Manages downloads and activations of update packages and software upgrades

activate(resource=None, force_upgrade=False, timeout=3, wait_for_finish=False)[source]

Activate this package on the SMC

Parameters:

resource (list) – node href’s to activate on. Resource is only required for software upgrades

:param query parameter ‘force_upgrade’ flag to know if we need to force

the upgrade (for instance trusted certificate has expired)

Parameters:

timeout (int) – timeout between queries

Raises:

TaskRunFailed – failure during activation (downloading, etc)

Return type:

TaskOperationPoller

download(timeout=5, wait_for_finish=False)[source]

Download Package or Engine Update

Parameters:

timeout (int) – timeout between queries

Raises:

TaskRunFailed – failure during task status

Return type:

TaskOperationPoller

property release_notes

HTTP location of the release notes

Engine Upgrade

class smc.administration.updates.EngineUpgrade(**meta)[source]

Bases: PackageMixin, SubElement

Engine Upgrade package management

For example, to check engine upgrades and find a specific one, then download for installation:

system = System()
upgrades = system.engine_upgrade()
package = upgrades.get_contains('6.2')

poller = package.download(wait_for_finish=True)
while not poller.done():
    print(poller.result(3))
print("Finished download: %s" % poller.result())
package.activate()
property platform

Platform for this engine upgrade

property release_date

Release date for this engine upgrade

property version

Engine upgrade version

Dynamic Update

class smc.administration.updates.UpdatePackage(**meta)[source]

Bases: PackageMixin, SubElement

Container for managing update packages on SMC

Download and activate a package:

system = System()
packages = system.update_package()
dynup = packages.get_contains('1007')

poller = dynup.download(wait_for_finish=True)
while not poller.done():
    print(poller.result(3))
print("Finished download: %s" % poller.result())
package.activate()
property activation_date

Date this update was activated, if any

Return type:

str

property package_id

ID of the package. These will increment as new versions are released.

Return type:

str

property release_date

Date of release

Return type:

str

property state

State of this package as string. Valid states are available, imported, active. If the package is available, you can execute a download. If the package is imported, you can activate.

Return type:

str

SD-WAN

Other Elements

VPN Elements are used in conjunction with Policy or Route Based VPN configurations. VPN elements consist of external gateway and VPN site settings that identify 3rd party gateways to be used as a VPN termination endpoint.

There are several ways to create an external gateway configuration. A step by step process which first creates a network element to be used in a VPN site, then creates the ExternalGatway, an ExternalEndpoint for the gateway, and inserts the VPN site into the configuration:

Network.create(name='mynetwork', ipv4_network='172.18.1.0/24')
gw = ExternalGateway.create(name='mygw')
gw.external_endpoint.create(name='myendpoint', address='10.10.10.10')
gw.vpn_site.create(name='mysite', site_element=[Network('mynetwork')])

You can also use the convenience method update_or_create on the ExternalGateway to fully provision in a single step. Note that the ExternalEndpoint and VPNSite also have an update_or_create method to limit the update to those respective configurations (SMC version 6.4.x):

>>> from smc.elements.network import Network
>>> from smc.vpn.elements import ExternalGateway
>>> network = Network.get_or_create(name='network-172.18.1.0/24', ipv4_network='172.18.1.0/24')
>>>
>>> g = ExternalGateway.update_or_create(name='newgw',
    external_endpoint=[
        {'name': 'endpoint1', 'address': '1.1.1.1', 'enabled': True},
        {'name': 'endpoint2', 'address': '2.2.2.2', 'enabled': True}],
    vpn_site=[{'name': 'sitea', 'site_element':[network]}])
>>> g
ExternalGateway(name=newgw)
>>> for endpoint in g.external_endpoint:
...   endpoint
...
ExternalEndpoint(name=endpoint1 (1.1.1.1))
ExternalEndpoint(name=endpoint2 (2.2.2.2))
>>> for site in g.vpn_site:
...   site, site.site_element
...
(VPNSite(name=sitea), [Network(name=network-172.18.1.0/24)])

In SMC version >= 6.5, you can also provide the connection_type_ref parameter when defining the external gateway:

.. note:: When calling `update_or_create` from the ExternalGateway, providing the
    parameters for external_endpoints and vpn_site is optional.

LinkUsageProfile

class smc.vpn.elements.LinkUsageProfile(name=None, **meta)[source]

Bases: Element

classmethod create(name, default_link_balancing_preference=0, link_usage_exception=None)[source]

Create a LinkUsageProfile. :param str name: name of Link usage profile :param int default_link_balancing_preference: The link balancing preference from 0 equal balancing to 4 best link :param list link_usage_exception: list of link_usage_exception :raises CreateElementFailed: failed to create element with reason :raises ElementNotFound: specified element reference was not found :rtype: LinkUsageProfile

default link balancing preference 0 to 4 equal balancing to best link

List of exceptions

Profiles

VPNProfile

class smc.vpn.elements.VPNProfile(name=None, **meta)[source]

Bases: Element

A VPN Profile is used to specify cryptography and other Policy VPN specific features. Every PolicyVPN requires a VPNProfile. The system will provide common profiles labeled as System Element that can be used without modification.

property capabilities

Capabilities are all boolean values that specify features or cryptography features to enable or disable on this VPN profile. To update or change these values, you can use the built in update with a key of ‘capabilities’ and dict value of attributes, i.e:

vpn = VPNProfile('mySecureVPN')
pprint(vpn.capabilities) # <-- show all options
vpn.update(capabilities={'sha2_for_ipsec': True, 'sha2_for_ike': True})
Return type:

dict

classmethod create(name, capabilities=None, cn_authentication_for_mobile_vpn=False, disable_anti_replay=False, disable_path_discovery=False, hybrid_authentication_for_mobile_vpn=False, keep_alive=False, preshared_key_for_mobile_vpn=False, sa_life_time=86400, sa_to_any_network_allowed=False, trust_all_cas=True, trusted_certificate_authority=[], tunnel_life_time_kbytes=0, tunnel_life_time_seconds=28800, comment=None, **kw)[source]

Create a VPN Profile. There are a variety of kwargs that can be and also retrieved about a VPN Profile. Keyword parameters are specified below. To access a valid keyword, use the standard dot notation.

To validate supported keyword attributes for a VPN Profile, consult the native SMC API docs for your version of SMC. You can also optionally print the element contents after retrieving the element and use update to modify the element.

For example:

vpn = VPNProfile.create(name='mySecureVPN', comment='test comment')
pprint(vars(vpn.data))

Then once identifying the attribute, update the relevant top level attribute values:

vpn.update(sa_life_time=128000, tunnel_life_time_seconds=57600)
Parameters:
  • name (str) – Name of profile

  • capabilities (dict) – Capabilities are all boolean values that specify features or cryptography features to enable or disable on this VPN profile. To update or change these values, you can use the built in update with a key of ‘capabilities’ and dict value of attributes

  • cn_authentication_for_mobile_vpn (bool) – Indicates whether CN authentification is allowed or not, for a client using a certificate authentication.

  • disable_anti_replay (bool) – IPSEC_DISABLE_ANTI_REPLAY flag value

  • disable_path_discovery (bool) – NO_PATH_MTU_DISCOVERY flag value.

  • hybrid_authentication_for_mobile_vpn (bool) – Indicates whether Hybrid authentification is allowed or not, for a client using a certificate authentication.

  • keep_alive (bool) – Keep-alive option

  • preshared_key_for_mobile_vpn (bool) – Indicates whether preshared key authentification is allowed or not,together with a client certificate authentication.,

  • sa_life_time (int) – IKE Lifetime in seconds

  • sa_to_any_network_allowed (bool) – IPSEC_SA_To_ANY flag value.

  • trust_all_cas (bool) – Whether to trust all certificate authorities or not

  • trusted_certificate_authority (list) – List of trusted certificate authorities for this profile (if the trust all CAs attribute has been set to false)

  • tunnel_life_time_kbytes (int) – IPsec Lifetime in KBytes.

  • tunnel_life_time_seconds (int) – IPsec Lifetime in seconds.

  • comment (str) – optional comment

Raises:

CreateElementFailed – failed creating element with reason

Return type:

VPNProfile

Elements

Elements used for various configuration areas within SMC. Element types are made up of network, service groups and other.

Network

Module representing network elements used within the SMC

Alias

class smc.elements.network.Alias(name=None, **meta)[source]

Bases: Element

Aliases are adaptive objects that represent a single element having different values based on the engine applied on. There are many default aliases in SMC and new ones can also be created.

Finding aliases can be achieved by using collections or loading directly if you know the alias name:

>>> from smc.elements.network import Alias
>>> list(Alias.objects.all())
[Alias(name=$$ Interface ID 46.net), Alias(name=$$ Interface ID 45.net), etc]

Resolve an alias to a specific engine:

>>> alias = Alias('$$ Interface ID 0.ip')
>>> alias.resolve('myfirewall')
[u'10.10.0.1']

Create an alias and assign values specific to an engine:

>>> alias = Alias.update_or_create(
    name='fooalias', engine=Layer3Firewall('vm'), translation_values=[Host('foo')])
>>> alias
Alias(name=fooalias)
classmethod create(name, comment=None, default_values=None, alias_values=None)[source]

Create an alias.

Parameters:
  • name (str) – name of alias

  • comment (str) – comment for this alias

  • default_values (list(Element)) – the default translated values

  • alias_values (dict) – the dedicated translated values for specified engines {Engine1: [Element1, Element2], Engine2: [Element3]}

Raises:

CreateElementFailed – create failed with reason

Return type:

Alias

full_resolve(engine)[source]

Fully resolve this Alias to a specific value (both translated_element and resolved_value). Specify the engine by name to find it’s value.

alias = Alias('$$ Interface ID 0.ip')
alias.full_resolve('smcpython-fw')
Parameters:

engine (str) – name of engine to resolve value

Raises:

ElementNotFound – if alias not found on engine

Returns:

alias resolving values:

{“resolved_value”: [resolved type:str..],

“translated_element”: [translated type:Element..]}

Return type:

{resolved_value:list str, translated_element: list Element}

resolve(engine)[source]

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')
Parameters:

engine (str) – name of engine to resolve value

Raises:

ElementNotFound – if alias not found on engine

Returns:

alias resolving values

Return type:

list

classmethod update_or_create(name, engine=None, translation_values=None, with_status=False, default_values=None, alias_values=None)[source]

Update or create an Alias and it’s mappings.

Parameters:
  • name (str) – name of alias

  • engine (Engine) – engine to modify alias translation values

  • translation_values (list(str,Element)) – translation values as elements. Can be None if you want to unset any existing values

  • with_status (bool) – 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

  • default_values (list(Element)) – the default translated values

  • alias_values (dict) – the dedicated translated values for specified engines {Engine1: [Element1, Element2], Engine2: [Element3]}

Raises:
Return type:

Element

AddressRange

class smc.elements.network.AddressRange(name=None, **meta)[source]

Bases: Element

Class representing a IpRange object used in access rules

Create an address range element:

IpRange.create('myrange', '1.1.1.1-1.1.1.5')

Available attributes:

Variables:

ip_range (str) – IP range for element. In format: ‘10.10.10.1-10.10.10.10’

classmethod create(name, ip_range, comment=None)[source]

Create an AddressRange element

Parameters:
  • name (str) – Name of element

  • iprange (str) – iprange of element

  • comment (str) – comment (optional)

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

AddressRange

DomainName

class smc.elements.network.DomainName(name=None, **meta)[source]

Bases: Element

Represents a domain name used as FQDN in policy Use this object to reference a DNS resolvable FQDN or partial domain name to be used in policy.

Create a domain based network element:

DomainName.create('mydomain.net')
classmethod create(name, domain_name_entry=None, comment=None)[source]

Create domain name element

Parameters:
  • name (str) – name of domain, i.e. example.net, www.example.net

  • domain_name_entry (list(str)) – The additional domain names.

  • comment (str) – Optional comment.

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

DomainName

property domain_name_entry

The additional domain names. :rtype: list(str)

Expression

class smc.elements.network.Expression(name=None, **meta)[source]

Bases: Element

Expressions are used to build boolean like objects used in policy. For example, if you wanted to create an expression that negates a specific set of network elements to use in a “NOT” rule, an expression would be the element type.

For example, adding a rule that negates (network A or network B):

sub_expression = Expression.build_sub_expression(
                    name='mytestexporession',
                    ne_ref=['http://172.18.1.150:8082/6.0/elements/host/3999',
                            'http://172.18.1.150:8082/6.0/elements/host/4325'],
                    operator='union')

Expression.create(name='apiexpression',
                  ne_ref=[],
                  sub_expression=sub_expression)

Note

The sub-expression creates the json for the expression (network A or network B) and is then used as an parameter to create.

static build_sub_expression(name, ne_ref=None, operator='union')[source]

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.

Parameters:
  • name (str) – name of sub-expression

  • ne_ref (list) – network elements references

  • operator (str) – exclusion (negation), union, intersection (default: union)

Returns:

JSON of subexpression. Use in create() constructor

classmethod create(name, ne_ref=None, operator='exclusion', sub_expression=None, comment=None)[source]

Create the expression

Parameters:
  • name (str) – name of expression

  • ne_ref (list) – network element references for expression

  • operator (str) – ‘exclusion’ (negation), ‘union’, ‘intersection’ (default: exclusion)

  • sub_expression (dict) – sub expression used

  • comment (str) – optional comment

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

Expression

Host

class smc.elements.network.Host(name=None, **meta)[source]

Bases: Element, IPv6Node

Class representing a Host object used in access rules

Create a host element with ipv4:

Host.create(name='myhost', address='1.1.1.1',
            secondary=['1.1.1.2'],
            comment='some comment for my host')

Create a host element with ipv6 and secondary ipv4 address:

Host.create(name='mixedhost',
            ipv6_address='2001:cdba::3257:9652',
            secondary=['1.1.1.1'])

Available attributes:

Variables:
  • address (str) – IPv4 address for this element

  • ipv6_address (str) – IPv6 address for this host element

  • secondary (list) – secondary IP addresses for this host

  • third_party_monitoring (ThirdPartyMonitoring) – The optional Third Party Monitoring configuration.

  • tools_profile_ref (DeviceToolsProfile) – Allows you to add commands to the element’s right-click menu. Not Required.

classmethod create(name, address=None, ipv6_address=None, secondary=None, third_party_monitoring=None, tools_profile_ref=None, comment=None)[source]

Create the host element

Parameters:
  • name (str) – Name of element

  • address (str) – ipv4 address of host object (optional if ipv6)

  • ipv6_address (str) – ipv6 address (optional if ipv4)

  • secondary (list) – secondary ip addresses (optional)

  • third_party_monitoring (ThirdPartyMonitoring) – The optional Third Party Monitoring configuration.

  • tools_profile_ref (DeviceToolsProfile) – Allows you to add commands to the element’s right-click menu. Not Required.

  • comment (str) – comment (optional)

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

Host

Note

Either ipv4 or ipv6 address is required

IPList

class smc.elements.network.IPList(name=None, **meta)[source]

Bases: Element

IPList represent a custom list of IP addresses, networks or ip ranges (IPv4 or IPv6). These are used in source/destination fields of a rule for policy enforcement.

Note

IPList requires SMC API version >= 6.1

Create an empty IPList:

IPList.create(name='mylist')

Create an IPList with initial content:

IPList.create(name='mylist', iplist=['1.1.1.1','1.1.1.2', '1.2.3.4'])

Example of downloading the IPList in text format:

>>> iplist = list(IPList.objects.filter('mylist'))
>>> print(iplist)
[IPList(name=mylist)]
>>> iplist[0].download(filename='iplist.txt', as_type='txt')

Example of uploading an IPList as a zip file:

>>> iplist = list(IPList.objects.filter('mylist'))
>>> print(iplist)
[IPList(name=mylist)]
iplist[0].upload(filename='/path/to/iplist.zip')

Upload an IPList using json format:

>>> iplist = IPList('mylist')
>>> iplist.upload(json={'ip': ['4.4.4.4']}, as_type='json')
classmethod create(name, iplist=None, comment=None)[source]

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.

Parameters:
  • name (str) – name of ip list

  • iplist (list) – list of ipaddress

  • comment (str) – optional comment

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

IPList

download(filename=None, as_type='zip')[source]

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.

Parameters:
  • filename (str) – Name of file to save to (required for zip)

  • as_type (str) – type of format to download in: txt,json,zip (default: zip)

Raises:

IOError – problem writing to destination filename

Returns:

None

property iplist

Return a list representation of this IPList. This is not a recommended function if the list is extremely large. In that case use the download function in zip format.

Raises:

FetchElementFailed – Reason for retrieval failure

Return type:

list

classmethod update_or_create(append_lists=True, with_status=False, **kwargs)[source]

Update or create an IPList.

Parameters:
  • append_lists (bool) – append to existing IP List

  • kwargs (dict) – provide at minimum the name attribute and optionally match the create constructor values

Raises:

FetchElementFailed – Reason for retrieval failure

upload(filename=None, json=None, as_type='zip')[source]

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’.

Parameters:
  • filename (str) – required for zip/txt uploads

  • json (str) – required for json uploads

  • as_type (str) – type of format to upload in: txt|json|zip (default)

Raises:
Returns:

None

Network

class smc.elements.network.Network(name=None, **meta)[source]

Bases: Element

Class representing a Network object used in access rules Network format should be CIDR based. It is recommended that when creating the network element, you use a naming convention that includes the network cidr in the name, such as ‘network-1.1.1.0/24’. This will simplify searches later and workaround the restriction that searches with ‘/’ and ‘-’ only match on the name field and not an actual attribute value.

Create an ipv4 network element:

Network.create('mynetwork', '2.2.2.0/24')

Create an ipv6 network element:

Network.create(name='mixednetwork', ipv6_network='fc00::/7')

Available attributes:

Variables:
  • ipv4_network (str) – IPv4 network, in format: 10.10.10.0/24

  • ipv6_network (str) – IPv6 network

classmethod create(name, ipv4_network=None, ipv6_network=None, broadcast=True, location_ref=None, comment=None)[source]

Create the network element

Parameters:
  • name (str) – Name of element

  • ipv4_network (str) – network cidr (optional if ipv6)

  • ipv6_network (str) – network cidr (optional if ipv4)

  • broadcast (bool) – Includes the broadcast address and the network address in the definition. This option is only used in the Source and Destination cells in rules. In other uses, the broadcast and network addresses are always included in the definition regardless of this option.

  • location_ref (Location) – Location of the network.

  • comment (str) – comment (optional)

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

Network

Note

Either an ipv4_network or ipv6_network must be specified

Router

class smc.elements.network.Router(name=None, **meta)[source]

Bases: Element, IPv6Node

Class representing a Router object used in access rules

Create a router element with ipv4 address:

Router.create('myrouter', '1.2.3.4', comment='my router comment')

Create a router element with ipv6 address:

Router.create(name='mixedhost',
              ipv6_address='2001:cdba::3257:9652')

Available attributes:

Variables:
  • address (str) – IPv4 address for this router

  • ipv6_address (str) – IPv6 address for this router

  • secondary (list) – list of additional IP’s for this router

  • third_party_monitoring (ThirdPartyMonitoring) – The optional Third Party Monitoring configuration.

  • tools_profile_ref (DeviceToolsProfile) – Allows you to add commands to the element’s right-click menu. Not Required.

classmethod create(name, address=None, ipv6_address=None, secondary=None, third_party_monitoring=None, tools_profile_ref=None, comment=None)[source]

Create the router element

Parameters:
  • name (str) – Name of element

  • address (str) – ip address of host object (optional if ipv6)

  • ipv6_address (str) – ipv6 address (optional if ipv4)

  • secondary (list) – secondary ip address (optional)

  • third_party_monitoring (ThirdPartyMonitoring) – The optional Third Party Monitoring configuration.

  • tools_profile_ref (DeviceToolsProfile) – Allows you to add commands to the element’s right-click menu. Not Required.

  • comment (str) – comment (optional)

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

Router

Note

either ipv4 or ipv6 address is required

URLListApplication

class smc.elements.network.URLListApplication(name=None, **meta)[source]

Bases: Element

URL List Application represents a list of URL’s (typically by domain) that allow for easy grouping for performing whitelist and blacklisting

Creating a URL List:

URLListApplication.create(
    name='whitelist',
    url_entry=['www.google.com', 'www.cnn.com'])

Note

URLListApplication requires SMC API version >= 6.1

Available attributes:

Variables:

url_entry (list) – URL entries as strings

add_application_port(application_ports)[source]

Add application_ports to this url list application.

Parameters:

application_ports (list(ApplicationPort)) – application ports to add

Raises:

UpdateElementFailed – failed updating the url list application

Returns:

None

property application_port

A collection of ApplicationPort

Return type:

list(ApplicationPort)

classmethod create(name, url_entry, application_ports=None, comment=None)[source]

Create the custom URL list

Parameters:
  • name (str) – name of url list

  • url_entry (list) – list of url’s

  • application_ports (list) – list of ApplicationPort

  • comment (str) – optional comment

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

URLListApplication

property url_entry

URL list :rtype: list(str)

Zone

class smc.elements.network.Zone(name=None, **meta)[source]

Bases: Element

Class representing a zone used on physical interfaces and used in access control policy rules, typically in source and destination fields. Zones can be applied on multiple interfaces which would allow logical grouping in policy.

Create a zone:

Zone.create('myzone')
classmethod create(name, comment=None)[source]

Create the zone element

Parameters:
  • zone (str) – name of zone

  • comment (str) – optional comment

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

Zone

Services

Module providing service configuration and creation.

Some services may be generic services while others might provide more in depth functionality using protocol agents. A protocol agent provides layer 7 configuration capabilities specific to the protocol it defines. If a given service inherits the ProtocolAgentMixin, this service type is eligible to have a protocol agent attached.

class smc.elements.service.ProtocolAgentMixin[source]

ProtocolAgentMixin is used by services that allow a protocol agent.

property protocol_agent

Protocol Agent for this service

Returns:

Return the protocol agent or None if this service does not reference a protocol agent

Return type:

ProtocolAgent

property protocol_agent_values

Protocol agent values are protocol specific settings configurable on a service when a protocol agent is assigned to that service. This property will return an iterable that represents each protocol specific parameter and it’s value.

Return type:

BaseIterable(ProtocolAgentValues)

update_protocol_agent(protocol_agent)[source]

Update this service to use the specified protocol agent. After adding the protocol agent to the service you must call update on the element to commit.

Parameters:

protocol_agent (str,ProtocolAgent) – protocol agent element or href

Returns:

None

EthernetService

class smc.elements.service.EthernetService(name=None, **meta)[source]

Bases: Element

Represents an ethernet based service in SMC Ethernet service only supports adding Ethernet II frame type.

The value1 field should be the ethernet2 ethertype hex code which will be converted to decimal format.

Create an ethernet rule representing the presence of an IEEE 802.1Q tag:

>>> EthernetService.create(name='8021q frame', value1='0x8100')
EthernetService(name=8021q frame)

Note

Ethernet Services are only available as of SMC version 6.1.2

classmethod create(name, frame_type='eth2', value1=None, value2=None, protocol_agent_ref=None, comment=None)[source]

Create an ethernet service

Parameters:
  • name (str) – name of service

  • frame_type (str) – ethernet frame type, eth2

  • value1 (str) – hex code representing ethertype field

  • value2 (str) – Following the frame_type value: For llc: the DSAP (destination service access point) address that the traffic uses. For snap: the type that the traffic uses.

  • protocol_agent_ref (ProtocolAgent) – The possible Protocol linked to this service.

  • comment (str) – optional comment

Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

EthernetService

property protocol_agent_ref

The possible Protocol linked to this service. :rtype: ProtocolAgent

RPCService

class smc.elements.service.RPCService(name=None, **meta)[source]

Bases: Element

Represents an RPC service element

classmethod create(name, program_number=None, transport=None, rpc_version=None, comment=None)[source]

This represents a SUN-RPC service. :param str name: name of rpc service. :param str program_number: The programe number. Not Required. :param str transport: The transport type:

tcp: Allows the RPC message when transported over TCP. udp: Allows the RPC message when transported over UDP. both: Allows the RPC message when transported over TCP and UDP.

Parameters:
  • rpc_version (str) – The remote program version number. If you do not enter a program version, the element matches traffic of any version.

  • comment (str) – optional comment.

:rtype RPCService.

property program_number

The programe number. :rtype str

property rpc_version

The remote program version number :rtype str

property transport

The transport type. :rtype str

ICMPService

class smc.elements.service.ICMPService(name=None, **meta)[source]

Bases: Element, ICMPServiceMixin

Represents an ICMP Service in SMC Use the RFC icmp type and code fields to set values. ICMP type is required, icmp code is optional but will make the service more specific if type codes exist.

Create an ICMP service using type 3, code 7 (Dest. Unreachable):

>>> ICMPService.create(name='api-icmp', icmp_type=3, icmp_code=7)
ICMPService(name=api-icmp)

Available attributes:

Variables:
  • icmp_type (int) – icmp type field

  • icmp_code (int) – icmp type code

classmethod create(name, icmp_type, icmp_code=None, comment=None)[source]

Create the ICMP service element

Parameters:
  • name (str) – name of service

  • icmp_type (int) – icmp type field

  • icmp_code (int) – icmp type code

  • comment (str) – optional comment.

Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

ICMPService

ICMPIPv6Service

class smc.elements.service.ICMPIPv6Service(name=None, **meta)[source]

Bases: Element, ICMPServiceMixin

Represents an ICMPv6 Service type in SMC Set the icmp type field at minimum. At time of writing the icmp code fields were all 0.

Create an ICMPv6 service for Neighbor Advertisement Message:

>>> ICMPIPv6Service.create('api-Neighbor Advertisement Message', icmp_type=4, icmp_code=8)
ICMPIPv6Service(name=api-Neighbor Advertisement Message)

Available attributes:

Variables:
  • icmp_type (int) – ipv6 icmp type field

  • icmp_code (int) – icmpv6 type code

classmethod create(name, icmp_type, icmp_code=None, comment=None)[source]

Create the ICMPIPv6 service element

Parameters:
  • name (str) – name of service

  • icmp_type (int) – ipv6 icmp type field

  • icmp_code (int) – icmp type code

  • comment (str) – optional comment.

Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

ICMPIPv6Service

IPService

class smc.elements.service.IPService(name=None, **meta)[source]

Bases: ProtocolAgentMixin, Element

Represents an IP-Proto service in SMC IP Service is represented by a protocol number. This will display in the SMC under Services -> IP-Proto. It may also show up in Services -> With Protocol if the protocol is tied to a Protocol Agent.

Create an IP Service for protocol 93 (AX.25):

>>> IPService.create('ipservice', 93)
IPService(name=ipservice)

Available attributes:

Variables:

protocol_number (str) – IP protocol number for this service

classmethod create(name, protocol_number, protocol_agent=None, comment=None)[source]

Create the IP Service

Parameters:
  • name (str) – name of ip-service

  • protocol_number (int) – ip proto number for this service

  • protocol_agent (str,ProtocolAgent) – optional protocol agent for this service

  • comment (str) – optional comment

Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

IPService

property protocol_number

Protocol number for this IP Service

Return type:

int

TCPService

class smc.elements.service.TCPService(name=None, **meta)[source]

Bases: ProtocolAgentMixin, Element

Represents a TCP based service in SMC TCP Service can use a range of ports or single port. If using single port, set only min_dst_port. If using range, set both min_dst_port and max_dst_port.

Create a TCP Service for port 5000:

>>> TCPService.create('tcpservice', 5000, comment='my service')
TCPService(name=tcpservice)

Available attributes:

Variables:
  • min_dst_port (int) – starting destination port for this service. If the service is a single port service, use only this field

  • max_dst_port (int) – used in conjunction with min_dst_port for creating a port range service.

classmethod create(name, min_dst_port, max_dst_port=None, min_src_port=None, max_src_port=None, protocol_agent=None, comment=None)[source]

Create the TCP service

Parameters:
  • name (str) – name of tcp service

  • min_dst_port (int) – minimum destination port value

  • max_dst_port (int) – maximum destination port value

  • min_src_port (int) – minimum source port value

  • max_src_port (int) – maximum source port value

  • protocol_agent (str,ProtocolAgent) – optional protocol agent for this service

  • comment (str) – optional comment for service

Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

TCPService

UDPService

class smc.elements.service.UDPService(name=None, **meta)[source]

Bases: ProtocolAgentMixin, Element

UDP Services can use a range of ports or single port. If using single port, set only min_dst_port. If using range, set both min_dst_port and max_dst_port.

Create a UDP Service for port range 5000-5005:

>>> UDPService.create('udpservice', 5000, 5005)
UDPService(name=udpservice)

Available attributes:

Variables:
  • min_dst_port (int) – starting destination port for this service. If the service is a single port service, use only this field

  • max_dst_port (int) – used in conjunction with min_dst_port for creating a port range service

classmethod create(name, min_dst_port, max_dst_port=None, min_src_port=None, max_src_port=None, protocol_agent=None, comment=None)[source]

Create the UDP Service

Parameters:
  • name (str) – name of udp service

  • min_dst_port (int) – minimum destination port value

  • max_dst_port (int) – maximum destination port value

  • min_src_port (int) – minimum source port value

  • max_src_port (int) – maximum source port value

  • protocol_agent (str,ProtocolAgent) – optional protocol agent for this service

  • comment (str) – optional comment

Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

UDPService

URLCategory

class smc.elements.service.URLCategory(name=None, **meta)[source]

Bases: Element

Represents a URL Category for policy. URL Categories are read only. To make whitelist or blacklists, use smc.elements.network.IPList.

With Protocol

New in version 0.6.2: Requires SMC version >= 6.4.3

Protocols define elements within the SMC that are specified to Protocol Agents. Protocol Agents can be attached to specific services by type. If a service inherits the ProtocolAgentMixin, the service type is eligible to add a protocol agent.

An example of attaching a protocol agent to a generic TCP Service, in this case used as a custom HTTP service:

>>> TCPService.create(name='testservice', min_dst_port=8080,
        protocol_agent=ProtocolAgent('HTTP'), comment='foo')
TCPService(name=testservice)

You can optionally also add a protocol agent to an existing service if the service is already created:

>>> from smc.elements.protocols import ProtocolAgent
>>> service.update_protocol_agent(ProtocolAgent('HTTP'))
>>> service.update()
...
>>> service.protocol_agent
ProtocolAgent(name=HTTP)

To make modifications on an existing Protocol Agent assigned to a service, you can iterate the protocol agent values to see the available parameter settings then call update on the same collection.

For example, to set the above service to redirect to a Proxy Server (CIS redirect), you can use this logic.

First view the available protocol agent parameters:

>>> service = TCPService('testservice')
>>> service.protocol_agent
ProtocolAgent(name=HTTP)
...
>>> for parameter in service.protocol_agent_values:
...    parameter
...
BooleanValue(name=http_enforce_safe_search,description=Enforce SafeSearch,value=0)
ProxyServiceValue(name=redir_cis,description=Redirect to Proxy Server,proxy_server=None)
StringValue(name=http_server_stream_by_user_agent,
description=Optimized server stream fingerprinting,value=Yes)
StringValue(name=http_url_logging,description=Logging of accessed URLs,value=Yes)

The parameters returned all inherit from a base class template ProtocolParameterValue. Each returned parameter is generated dynamically based on the type of input expected for the given parameter/field type.

Note

The description field of the parameter matches what you would see in the SMC under the Protocol Parameters tab of a service using a ProtocolAgent. The name field is the internal name that you would use to reference the setting when calling protocol_agent_values.update.

We want to add the CIS (ProxyServer) redirect, so update is done on the ‘redir_cis’ (name) field:

>>> from smc.elements.servers import ProxyServer
>>> service.protocol_agent_values.update(name='redir_cis', proxy_server=ProxyServer('generic5'))
True

The update was successful, and we can now validate the parameter repr shows an assigned proxy:

>>> for parameter in service.protocol_agent_values:
...   parameter
...
BooleanValue(name=http_enforce_safe_search,description=Enforce SafeSearch,value=0)
             ProxyServiceValue(name=redir_cis,description=Redirect to Proxy Server,
proxy_server=ProxyServer(name=generic5))
StringValue(name=http_server_stream_by_user_agent,
            description=Optimized server stream fingerprinting,value=Yes)
StringValue(name=http_url_logging,description=Logging of accessed URLs,value=Yes)

Lastly, to commit this change to SMC, you must still call update on the service element:

service.update()

You can unset a ProxyServer by setting the proxy_server field to None and updating:

service.update_protocol_agent(None)
service.update()
class smc.elements.protocols.ProtocolAgent(name=None, **meta)[source]

Bases: Element

Protocol Agents ensure that related connections for a service are properly grouped and evaluated by the engine, as well as assisting the engine with content filtering or network address translation tasks.

class smc.elements.protocols.ProtocolAgentMixin[source]

Bases: object

ProtocolAgentMixin is used by services that allow a protocol agent.

property protocol_agent

Protocol Agent for this service

Returns:

Return the protocol agent or None if this service does not reference a protocol agent

Return type:

ProtocolAgent

property protocol_agent_values

Protocol agent values are protocol specific settings configurable on a service when a protocol agent is assigned to that service. This property will return an iterable that represents each protocol specific parameter and it’s value.

Return type:

BaseIterable(ProtocolAgentValues)

update_protocol_agent(protocol_agent)[source]

Update this service to use the specified protocol agent. After adding the protocol agent to the service you must call update on the element to commit.

Parameters:

protocol_agent (str,ProtocolAgent) – protocol agent element or href

Returns:

None

class smc.elements.protocols.ProtocolAgentValues(protocol_agent, values)[source]

Bases: BaseIterable

Protocol Agent Values define settings that can be set for specific protocols when a protocol agent is referenced in a service.

This is a collection of parameters that are relevant based on the protocol agent type. This is called from the service itself when a service has a protocol agent attached. An example of iterating a given service with an HTTP protocol agent attached:

>>> from smc.elements.service import TCPService
>>> service = TCPService('mynewservice')
>>> service.protocol_agent
ProtocolAgent(name=HTTP)
>>> for parameter in service.protocol_agent_values:
...   parameter
...
BooleanValue(name=http_enforce_safe_search,description=Enforce SafeSearch,value=0)
ProxyServiceValue(name=redir_cis,description=Redirect to Proxy Server,proxy_server=None)
StringValue(name=http_server_stream_by_user_agent,
description=Optimized server stream fingerprinting,value=Yes)
StringValue(name=http_url_logging,description=Logging of accessed URLs,value=Yes)

Each protocol agent parameter has a name value and description. The name is an internal name representation but the description is the value you would see within the SMC for the given field.

Each parameter class is dynamically generated based on the class template ProtocolParameterValue. The class name indicates the type of parameter value that is expected for the given field.

Return type:

ProtocolParameterValue

get(parameter_name)[source]

Get the parameter by it’s name. This is a convenience for fetching. For example, fetch the proxy server (redir_cis) parameter from a HTTP or HTTPS protocol agent:

pv = newservice.protocol_agent_values.get('redir_cis')
Returns:

Return the parameter value if it exists, otherwise None

Return type:

ProtocolParameterValue

update(name, **kwargs)[source]

Update protocol agent parameters based on the parameter name. Provide the relevant keyword pairs based on the parameter type. When update is called, a boolean is returned indicating whether the field was successfully updated or not. You should check the return value and call update on the service to commit to SMC.

Example of updating a TCP Service using the HTTPS Protocol Agent to set an HTTPS Inspection Exception:

>>> service = TCPService('httpsservice')
>>> service.protocol_agent
ProtocolAgent(name=HTTPS)
>>> for parameter in service.protocol_agent_values:
...   parameter
...
ProxyServiceValue(name=redir_cis,
                  description=Redirect connections to Proxy Server,proxy_server=None)
BooleanValue(name=http_enforce_safe_search,description=Enforce SafeSearch,value=0)
StringValue(name=http_server_stream_by_user_agent,
           description=Optimized server stream fingerprinting,value=Yes)
StringValue(name=http_url_logging,description=Logging of accessed URLs,value=Yes)
TlsInspectionPolicyValue(name=tls_policy,
                         description=HTTPS Inspection Exceptions,tls_policy=None)
StringValue(name=tls_inspection,description=HTTPS decryption and inspection,value=No)
...
>>> service.protocol_agent_values.
                update(name='tls_policy',
                       tls_policy=HTTPSInspectionExceptions('myexceptions'))
True
Parameters:
  • name (str) – The name of the parameter to update

  • kwargs (dict) – The keyword args to perform the update

Raises:
  • ElementNotFound – Can be thrown when an element reference was passed but the element does not exist

  • MissingDependency – A dependency was missing preventing the update. This can happen when adding a ProxyServer for a protocol that isn’t enabled

class smc.elements.protocols.ProtocolParameterValue[source]

Bases: object

A ProtocolParameterValue defines a protocol agent parameter setting when a protocol agent is assigned to a service. There are multiple protocol parameter types and each protocol agent will have specific parameters depending on functionality.

Read only attributes are:

Variables:
  • protocol_agent (ProtocolAgent) – The protocol agent for this parameter value

  • protocol_agent_values (dict) – The protocol agent values for this setting

  • description (str) – The read-only description of this setting, used in SMC

  • type (str) – The value type that this parameter is expected, i.e. string, integer, etc

Mutable attributes are:

Variables:

value (str) – The mutable value for this particular setting

property description

Description of this protocol parameter. The description is what will be displayed on the service properties under the Protocol Parameters tab when a Protocol Agent is assigned to a service

Return type:

str

property name

Name of this protocol setting

Return type:

str

property type

The type of this parameter. Can be string value, integer value, etc. The type is returned as a string representation.

Return type:

str

property value

The value for this given protocol parameter. The return type is defined by the type of parameter

Returns:

value based on type of parameter. Will return None if this parameter does not support the value key for this parameter

class smc.elements.protocols.ProxyServiceValue[source]

Bases: ProtocolParameterValue

This represents a protocol parameter specific to setting a redirect to proxy setting on a service with a protocol agent.

Mutable attributes are:

Variables:

proxy_server (str) – The mutable value for this particular setting. Represents the ProxyServer element

property proxy_server

The ProxyServer element referenced in this protocol parameter, if any.

Returns:

The proxy server element or None if one is not assigned

Return type:

ProxyServer

class smc.elements.protocols.TlsInspectionPolicyValue[source]

Bases: ProtocolParameterValue

This represents HTTPS Inspection Exceptions that would be a parameter for a HTTPS Protocol Agent service.

Mutable attributes are:

Variables:

tls_policy (str) – The mutable value for this particular setting. Represents the HTTPS Inspection Exceptions element

property tls_policy

The HTTPSInspectionExceptions element referenced in this protocol agent parameter. Will be None if one is not assigned.

Returns:

The https inspection exceptions element or None if not assigned

Return type:

HTTPSInspectionExceptions

Groups

Groups that are used for element types, such as TCPServiceGroup, Group (generic), etc. All group types inherit from GroupMixin which allow for modifications of existing groups and their members.

class smc.elements.group.GroupMixin[source]

Methods associated with handling modification of Group objects for existing elements

empty_members()[source]

Empty members from group

Returns:

None

property members

Return members in raw href format. If you want to obtain a resolved list of elements as instance of Element, call ~obtain_members.

Return type:

list

obtain_members()[source]

Obtain all group members from this group

Returns:

group members as elements

Return type:

list(Element)

update_members(members, append_lists=False, remove_members=False, **kwargs)[source]

Update group members with member list. Set append=True to append to existing members, or append=False to overwrite.

Parameters:
  • members (list[str, Element]) – new members for group by href or Element

  • append_lists (bool) – whether to append

  • remove_members (bool) – remove members from the group

Returns:

bool was modified or not

classmethod update_or_create(append_lists=True, with_status=False, remove_members=False, **kwargs)[source]

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.

Parameters:
  • append_lists (bool) – add to existing members, if any

  • remove_members (bool) – remove specified members instead of appending or overwriting

  • kwargs (dict) – keyword arguments to satisfy the create constructor if the group needs to be created.

Raises:

CreateElementFailed – could not create element with reason

Returns:

element instance by type

Return type:

Element

ICMPServiceGroup

class smc.elements.group.ICMPServiceGroup(name=None, **meta)[source]

Bases: GroupMixin, Element

IP Service Group Used for storing IP Services or IP Service Groups

Available attributes:

Variables:

element (list) – list of elements by href. Call ~obtain_members to retrieved the resolved list of elements.

classmethod create(name, members=None, comment=None)[source]

Create the IP Service group element

Parameters:
  • name (str) – name of service group

  • element (list) – IP services or IP service groups by href

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

ICMPServiceGroup

IPServiceGroup

class smc.elements.group.IPServiceGroup(name=None, **meta)[source]

Bases: GroupMixin, Element

IP Service Group Used for storing IP Services or IP Service Groups

Available attributes:

Variables:

element (list) – list of elements by href. Call ~obtain_members to retrieved the resolved list of elements.

classmethod create(name, members=None, comment=None)[source]

Create the IP Service group element

Parameters:
  • name (str) – name of service group

  • element (list) – IP services or IP service groups by href

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

IPServiceGroup

RpcServiceGroup

class smc.elements.group.RpcServiceGroup(name=None, **meta)[source]

Bases: GroupMixin, Element

This represents a SUN-RPC Service Group, it groups a list of SUN-RPC Services.

classmethod create(name, members=None, comment=None)[source]

Create the SUN-RPC Service Group element.

Parameters:
  • name (str) – name of rpc service group

  • members (list(str,Element)) – The elements that are included in the Service Group.

  • comment (str) – optional comment.

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

RpcServiceGroup

Group

class smc.elements.group.Group(name=None, **meta)[source]

Bases: GroupMixin, Element

Class representing a Group object used in access rules Groups can hold other network element types as well as other groups.

Create a group element:

Group.create('mygroup') #no members

Group with members:

Group.create('mygroup', [Host('kali'), Network('mynetwork')])

Available attributes:

Variables:

element (list) – list of elements by href. Call ~obtain_members to retrieve the resolved list of elements.

classmethod create(name, members=None, comment=None, is_monitored=False)[source]

Create the group

Parameters:
  • name (str) – Name of element

  • members (str,Element) – group members by element names

  • comment (str) – optional comment

  • is_monitored (bool) – optional option Enable or not monitoring of the group. Default: False

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

Group

ServiceGroup

class smc.elements.group.ServiceGroup(name=None, **meta)[source]

Bases: GroupMixin, Element

Represents a service group in SMC. Used for grouping objects by service. Services can be “mixed” TCP/UDP/ICMP/ IPService, Protocol or other Service Groups. Element is an href to the location of the resource.

Create a TCP and UDP Service and add to ServiceGroup:

tcp1 = TCPService.create('api-tcp1', 5000)
udp1 = UDPService.create('api-udp1', 5001)
ServiceGroup.create('servicegroup', element=[tcp1, udp1])

Available attributes:

Variables:

element (list) – list of elements by href. Call ~obtain_members to retrieved the resolved list of elements.

classmethod create(name, members=None, comment=None)[source]

Create the TCP/UDP Service group element

Parameters:
  • name (str) – name of service group

  • members (list(str,Element)) – elements to add by href or Element

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

ServiceGroup

TCPServiceGroup

class smc.elements.group.TCPServiceGroup(name=None, **meta)[source]

Bases: GroupMixin, Element

Represents a TCP Service group

Create TCP Services and add to TCPServiceGroup:

tcp1 = TCPService.create('api-tcp1', 5000)
tcp2 = TCPService.create('api-tcp2', 5001)
ServiceGroup.create('servicegroup', element=[tcp1, tcp2])

Available attributes:

Variables:

element (list) – list of elements by href. Call ~obtain_members to retrieved the resolved list of elements.

classmethod create(name, members=None, comment=None)[source]

Create the TCP Service group

Parameters:
  • name (str) – name of tcp service group

  • element (list(str,Element)) – tcp services by element or href

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

TCPServiceGroup

UDPServiceGroup

class smc.elements.group.UDPServiceGroup(name=None, **meta)[source]

Bases: GroupMixin, Element

UDP Service Group Used for storing UDP Services or UDP Service Groups.

Create two UDP Services and add to UDP service group:

udp1 = UDPService.create('udp-svc1', 5000)
udp2 = UDPService.create('udp-svc2', 5001)
UDPServiceGroup.create('udpsvcgroup', element=[udp1, udp2])

Available attributes:

Variables:

element (list) – list of elements by href. Call ~obtain_members to retrieved the resolved list of elements.

classmethod create(name, members=None, comment=None)[source]

Create the UDP Service group

Parameters:
  • name (str) – name of service group

  • element (list) – UDP services or service group by reference

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

UDPServiceGroup

URLCategoryGroup

class smc.elements.group.URLCategoryGroup(name=None, **meta)[source]

Bases: Element

EthernetServiceGroup

class smc.elements.group.EthernetServiceGroup(name=None, **meta)[source]

Bases: GroupMixin, Element

This represents an Ethernet Service Group, it groups a list of Ethernet Services.

Create EthernetService and add to EthernetServiceGroup:

es1 = EthernetService.create('EthernetService1', frame_type="eth2",
                                          protocol_agent_ref=protocol, value1='1',
                                          value2='2', comment=COMMENT)
es2 = EthernetService.create('EthernetService2', frame_type="eth2",
                                          protocol_agent_ref=protocol, value1='1',
                                          value2='2', comment=COMMENT)
EthernetServiceGroup.create('ethernetservicegroup', element=[es1, es2])
classmethod create(name, members=None, comment=None)[source]

Create the Ethernet Service Group

Parameters:
  • name (str) – name of ethernet service group.

  • members (list(EthernetService)) – The elements that are included in the EthernetServiceGroup.

  • comment (str) – Optional comment.

Raises:

CreateElementFailed – element creation failed with reason.

Returns:

instance with meta

Return type:

EthernetServiceGroup

Servers

Module that represents server based configurations

class smc.elements.servers.AuthenticationServerMixin(name=None, **meta)[source]

This mixin class provide interface to a TACACS+/RADIUS Authentication Server.

classmethod create(name, address=None, ipv6_address=None, clear_text=False, location_ref=None, provided_method=None, retries=2, timeout=10, secondary=None, shared_secret=None, port=49, third_party_monitoring=None, tools_profile_ref=None, comment=None)[source]
Parameters:
  • name (str) – Name of the TacacsServer/RadiusServer.

  • address (str) – Single valid IPv4 address. Required.

  • ipv6_address (str) – Single valid IPv6 address

  • clear_text (bool) – Select Accepted by Firewall if you want the Firewall to accept unencrypted replies from the TACACS+ authentication server. Not Required.

  • location_ref (Location) – The location of TacacsServer/RadiusServer.

  • provided_method (list(AuthenticationMethod)) – Specify provided Authentication methods. Not Required.

  • retries (int) – Specify the number of times Firewalls try to connect to the RADIUS or TACACS+ authentication server if the connection fails. Required.

  • timeout (int) – Specify the time (in seconds) that Firewalls wait for the RADIUS or TACACS+ authentication server to reply. Not Required.

  • secondary (list(str)) – If the device has additional IP addresses, you can enter them here instead of creating additional elements for the other IP addresses. The secondary IP addresses are valid in policies and in routing and antispoofing. You can add several IPv4 and IPv6 addresses (one by one)

  • shared_secret (str) – Specify the Shared Secret that you have defined for RADIUS clients on the Active Directory server.

  • port (int) – Specify the port number if the server communicates on a port other than the default port. The predefined Firewall Template allows the engines to connect to the default port. If you change to a custom port, you must add a new IPv4 Access Rule to allow the traffic. Not Required.

  • third_party_monitoring (ThirdPartyMonitoring) – The optional Third Party Monitoring configuration.

  • tools_profile_ref (tools_profile) – Allows you to add commands to the element’s right-click menu. Not Required.

  • comment (str) – optional comment.

property port

Specify the port number if the server communicates on a port other than the default port. :rtype int

property provided_method

Provided Authentication methods. :rtype list(AuthenticationMethod)

property shared_secret

Shared secrete text :rtype str

property timeout
Specify the time (in seconds) that Firewalls wait for the TACACS+/RADIUS authentication

server to reply

:rtype Time out value

class smc.elements.servers.ContactAddressMixin[source]

Mixin class to provide an interface to contact addresses on the management and log server. Contact addresses on servers can contain multiple IP’s for a single location.

add_contact_address(contact_address, location)[source]

Add a contact address to the Log Server:

server = LogServer('LogServer 172.18.1.25')
server.add_contact_address('44.44.44.4', 'ARmoteLocation')
Parameters:
  • contact_address (str) – IP address used as contact address

  • location (str) – Name of location to use, will be created if it doesn’t exist

Raises:

ModificationFailed – failed adding contact address

Returns:

None

property contact_addresses

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'])
Return type:

MultiContactAddress

remove_contact_address(location)[source]

Remove contact address by name of location. You can obtain all contact addresses by calling contact_addresses().

Parameters:

location (str) – str name of location, will be created if it doesn’t exist

Raises:

ModificationFailed – failed removing contact address

Returns:

None

class smc.elements.servers.DataContext(name=None, **meta)[source]

This represents the Data Context.

class smc.elements.servers.ManagementLogServerMixin[source]
add_netflow_collector(netflow_collectors)[source]

Add netflow collector/s to this log server.

Parameters:

netflow_collectors (list(netflow_collectors)) – netflow_collector/s to add to log server

Raises:

UpdateElementFailed – failed updating log server

Returns:

None

property elasticsearch_authentication_settings

Elasticsearch authentication settings.

property es_tls_settings

Elasticsearch TLS Settings. :rtype: TlsSettings

property external_pki_certificate_settings

Get the certificate info of this component when working with External PKI. :rtype: PkiCertificateSettings

property forwarding_tls_settings

Log Forwarding TLS Settings. :rtype: TlsSettings

property log_disk_space_handling_mode

Mode chosen to handle extra logs when disk runs out of space. :rtype: str

property netflow_collector

A collection of NetflowCollector

Return type:

list(NetflowCollector)DomainController

pki_certificate_info()[source]

Get the certificate info of this component when working with External PKI. This can return None if the component does not directly have a certificate.

Return type:

PkiCertificateInfo

pki_certificate_settings()[source]

Get the certificate info of this component when working with External PKI.

Return type:

PkiCertificateSettings

pki_delete_certificate_request()[source]

Delete the certificate request if any is defined for this component.

pki_export_certificate_request(filename=None)[source]

Export the certificate request for the component when working with an External PKI. This can return None if the component does not have a certificate request.

Raises:

CertificateExportError – error exporting certificate

Return type:

str or None

pki_import_certificate(certificate)[source]

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.

Parameters:

certificate (str) – fully qualified path or string

Raises:
Returns:

None

pki_renew_certificate()[source]

Start renewal process on component when using external PKI mode. It generates new private key and prepare a new certificate request.

remove_netflow_collector(netflow_collector)[source]

Remove a netflow collector from this log server.

Parameters:

netflow_collector (NetflowCollector) – element to remove

Returns:

remove element if it exists and return bool

Return type:

bool

property uiid

Installation ID (aka UUID). :rtype: str

class smc.elements.servers.MultiContactAddress(**meta)[source]

A MultiContactAddress is a location and contact address pair which can have multiple addresses. Server elements such as Management and Log Server can have configured locations with multiple addresses per location.

Use this server reference to create, add or remove contact addresses from servers:

mgt_server = ManagementServer.objects.first()
mgt_server.contact_addresses.update_or_create(
    location='mylocation', addresses=['1.1.1.1', '1.1.1.2'])

Or remove by location:

mgt_server.contact_addresses.delete('mylocation')
delete(location_name)[source]

Remove a given location by location name. This operation is performed only if the given location is valid, and if so, update is called automatically.

Parameters:

location (str) – location name or location ref

Raises:

UpdateElementFailed – failed to update element with reason

Return type:

bool

get(location_name)[source]

Get a contact address by location name

Parameters:

location_name (str) – name of location

Returns:

return contact address element or None

Return type:

ContactAddress

update_or_create(location, contact_addresses, with_status=False, overwrite_existing=False, **kw)[source]

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).

Parameters:
  • contact_addresses (list(str)) – list of contact addresses for the specified location

  • location (str) – location to place the contact address in

  • overwrite_existing (bool) – if you want to replace existing location to address mappings set this to True. Otherwise if the location exists, only new addresses are appended

  • with_status (bool) – 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

Return type:

MultiContactAddress

class smc.elements.servers.NetflowCollector(data_context, host, netflow_collector_port, netflow_collector_service, netflow_collector_version, filter=None, tls_profile=None, tlsIdentity=None, kafka_topic=None)[source]

Represents a Netflow collector. This is a sub part of Log Server entity. Log Servers can be configured to forward log data to external hosts. You can define which type of log data you want to forward and in which format. You can also use Filters to specify in detail which log data is forwarded.

property data_context

The type of log data that is forwarded. :rtype: DataContext

property filter

An optional local filter that defines which log data is forwarded. The local filter is only applied to the log data that matches the Log Forwarding rule. :rtype: FilterExpression

property host

The Host element that represents the target host to which the log data is forwarded. :rtype: Host

property kafka_topic

Kafka Topic: used only in the case forwarding logs through KAFKA. :rtype str

property netflow_collector_port

The Port that is used for log forwarding. The default port used by IPFIX/NetFlow data collectors is 2055.<br/> <b>Note!</b> If you have to define an Access rule that allows traffic to the target host, make sure that the Port you select is also used as the Port in the Access rule. :rtype: int

property netflow_collector_service

The network protocol for forwarding the log data (udp/tcp/tcp_with_tls).<br/> <b>Note!</b> If you have to define an Access rule that allows traffic to the target host, make sure that the Service you specify is also used as the Service in the Access rule. :rtype: str

property netflow_collector_version

The format for forwarding the log data: <ul> <li><i>cef</i>: Logs are forwarded in CEF format.</li> <li><i>csv</i>: Logs are forwarded in CSV format.</li> <li><i>leef</i>: Logs are forwarded in LEEF format.</li> <li><i>netflow_v11</i>: Logs are forwarded in NetFlow format.

The supported version is NetFlow v16.</li>

<li><i>ipfix</i>: Logs are forwarded in IPFIX (NetFlow v16) format.</li> <li><i>xml</i>: Logs are forwarded in XML format.</li> <li><i>esm</i>: Logs are forwarded in McAfee ESM format.</li> </ul> <b> Only csv, xml and esm are supported for Audit Forwarding from Mgt Server</b> :rtype: str

property tlsIdentity

Field/value pair used to insure server identity when connecting to Sys Log server using TLS Optional If not provided, server identity is not checked This is ignored if service is not tcp_with_tls

Return type:

property tls_profile

TLS information required to establish TLS connection to SysLog servers Mandatory when service is “tcp_with_tls” :rtype: TlSProfile

class smc.elements.servers.TlsSettings(data)[source]
classmethod create(use_internal_credentials=None, tls_credentials=None)[source]

TLS credentials used for Elasticsearch/Log Forwarding If useInternalCredentials is set to FALSE, this attribute will be read. If this field is set to null, no authentication will be requested. :param bool use_internal_credentials: Indicate if we need to use the server’s internal TLS

credentials for Elasticsearch/Log Forwarding TRUE if we want to use internal credentials FALSE if we want to use the tlsServerCredentials attribute.

Parameters:

tls_credentials (TLSServerCredential) – TLS credentials used for Elasticsearch/Log Forwarding If useInternalCredentials is set to FALSE, this attribute will be read. If this field is set to null, no authentication will be requested.

class smc.elements.servers.WebApp(data)[source]

Represents a Web Application parameter.

classmethod create(enabled=False, eca_enabled=False, listening_address=None, log_access=False, port=8083, server_credentials_ref=None, session_timeout=300, ssl_session_id=False, tls_cipher_suites=None, standalone_enabled=False, web_app_identifier=None, host_name=None)[source]
Parameters:
  • enabled (bool) – If the Web Application is enabled or not.

  • eca_enabled (bool) – Indicates if ECA Rollout evaluation is enabled in SMC Download pages (SMC Downloads has to be enabled )

  • listening_address (str) – The Web Application listening address, null if listening on all addresses.

  • log_access (bool) – Indicates whether access to this Web Application are logged.

  • port (int) – The port on which the Web Application listens for connections.

  • server_credentials_ref (TLSServerCredential) – TLS Credentials of server.

  • session_timeout (int) – Session Timeout for Webswing.

  • ssl_session_id (bool) – Indicates whether session ID must be used with SSL.

  • tls_cipher_suites (TLSCryptographySuite) – TLS Cipher suite.

  • standalone_enabled (bool) – Indicates if Standalone client bundles download are enabled in SMC Download pages (SMC Downloads has to be enabled )

  • web_app_identifier (str) – The Web Application Identifier.

  • host_name (str) – The Web Application host name, null if none.

LogServer

class smc.elements.servers.LogServer(name=None, **meta)[source]

Bases: ContactAddressMixin, Element, ManagementLogServerMixin

Log Server elements are used to receive log data from the security engines Most settings on Log Server generally do not need to be changed, however it may be useful to set a contact address location and IP mapping if the Log Server needs to be reachable from an engine across NAT

It’s easiest to get the log server reference through a collection:

>>> LogServer.objects.first()
LogServer(name=LogServer 172.18.1.150)
property backup_log_server

Several backup Log Servers. :rtype list(LogServer)

property channel_port

Log Server’s TCP Port Number. :rtype int

classmethod create(name, address=None, ipv6_address=None, location_ref=None, external_pki_certificate_settings=None, uiid='N/A', tools_profile_ref=None, secondary=None, es_tls_settings=None, elasticsearch_authentication_settings=None, forwarding_tls_settings=None, netflow_collector=None, log_disk_space_handling_mode=None, backup_log_server=None, channel_port=3020, inactive=False, comment=None)[source]

Log Server elements are used to receive log data from the security engines Most settings on Log Server generally do not need to be changed, however it may be useful to set a contact address location and IP mapping if the Log Server needs to be reachable from an engine across NAT :param str name: Name of the Log Server. :param str address: Single valid IPv4 address. Required. :param str ipv6_address: IPv6 address. :param Location location_ref: Location of the server. :param PkiCertificateSettings external_pki_certificate_settings: Certificate Settings for

External PKI mode.

Parameters:
  • uiid (str) – Mgt Server Installation ID (aka UUID).

  • tools_profile_ref (tools_profile) – Allows you to add commands to the element’s right-click menu.

  • secondary (list(str)) – If the device has additional IP addresses, you can enter them here instead of creating additional elements for the other IP addresses. The secondary IP addresses are valid in policies and in routing and antispoofing. You can add several IPv4 and IPv6 addresses (one by one)

  • es_tls_settings (TlsSettings) – Elasticsearch TLS Settings. Not null when we decide to override the ES Tls Settings in the Log Server or Management Server.

  • elasticsearch_authentication_settings (dict) –

    if we want to override defined authentication setting of Elasticsearch Server (> 7.1) dict : method: None, basic, api_key, certificate

    api_key : api_key certificate : es_tls_settings aside basic : login, password

  • forwarding_tls_settings (TlsSettings) – Log Forwarding TLS Settings. Should be NULL if no Log Forwarding has been defined for this Log Server. Not required

  • netflow_collector (list(NetflowCollector)) – Log Servers can be configured to forward log data to external hosts. You can define which type of log data you want to forward and in which format. You can also use Filters to specify in detail which log data is forwarded.

  • log_disk_space_handling_mode (str) – Mode chosen to handle extra logs when disk runs out of space.

  • backup_log_server (list(LogServer)) – You can specify several backup Log Servers. The same Log Server can simultaneously be the main Log Server for some components and a backup Log Server for components that primarily use another Log Server. You can also set Log Servers to be backup Log Servers for each other so that whenever one goes down, the other Log Server is used. If Domain elements have been configured, a Log Server and its backup Log Server(s) must belong to the same Domain. Caution: If the log volumes are very high, make sure that the backup Log Server can handle the traffic load in fail-over situations.

  • channel_port (int) – Log Server’s TCP Port Number. We recommend using default port 3020 if possible. To use a non-standard port, manually add Access rules to allow communications using the new port from the NGFW Engines to the Log Server.

  • inactive (bool) – Is excluded from Log Browsing, Reporting and Statistics.

  • comment (str) – optional comment.

property inactive

Is excluded from Log Browsing, Reporting and Statistics. :rtype bool

update(*exception, **kwargs)[source]

Update the existing element and clear the instance cache. Removing the cache will ensure subsequent calls requiring element attributes will force a new fetch to obtain the latest copy.

Calling update() with no args will assume the element has already been modified directly and the data cache will be used to update. You can also override the following attributes: href, etag, json and params. If json is sent, it is expected to the be a complete payload to satisfy the update.

For kwargs, if attribute values are a list, you can pass ‘append_lists=True’ to add to an existing list, otherwise overwrite the existing (default: overwrite)

See also

To see different ways to utilize this method for updating, see: Update.

Parameters:
  • exception – pass a custom exception to throw if failure

  • kwargs – optional kwargs to update request data to server.

Raises:
Returns:

href of the element modified

Return type:

str

ManagementServer

class smc.elements.servers.ManagementServer(name=None, **meta)[source]

Bases: ContactAddressMixin, Element, ManagementLogServerMixin

Management Server configuration. Most configuration settings are better set through the SMC, such as HA, however this object can be used to do simple tasks such as add a contact addresses to the Management Server when a security engine needs to communicate over NAT.

It’s easiest to get the management server reference through a collection:

>>> ManagementServer.objects.first()
ManagementServer(name=Management Server)
property alert_server_ref

Specify the Log Server to which you want the Mgt Server to send its logs :rtype: LogServer

classmethod create(name, address=None, ipv6_address=None, alert_server=None, location_ref=None, web_app=None, announcement_enabled=False, announcement_message=None, external_pki_certificate_settings=None, uiid=None, tools_profile_ref=None, secondary=None, updates_check_enabled=False, license_update_enabled=False, updates_proxy_enabled=False, updates_proxy_address=None, updates_proxy_port=82, updates_proxy_authentication_enabled=False, updates_proxy_username=None, updates_proxy_password=None, db_replication=False, tls_profile=None, tls_credentials=None, es_tls_settings=None, elasticsearch_authentication_settings=None, forwarding_tls_settings=None, netflow_collector=None, mgt_integration_container=None, smtp_server_ref=None, sender_address=None, sender_name=None, snmp_gateways=None, script_path=None, sms_http_channel=None, sms_smtp_channel=None, sms_script_channel=None, radius_method='eap-md5', tacacs_method='mschap', comment=None)[source]

This represents a Management Server. A system component that stores all information about the configurations of all NGFW Engines,and other components in the Stonesoft Management Center, monitors their state, and provides access for Management Clients when administrators want to change the configurations or command the engines. The most important component in the system. :param str name: Name of the Management Server. :param str address: Single valid IPv4 address. Required. :param str ipv6_address: IPv6 address. :param LogServer alert_server: Specify the Log Server to which you want the Management

Server to send its logs. Required.

Parameters:
  • location_ref (Location) – Location of the server.

  • web_app (list(WebApp)) – Mgt Server can be configured to define several Web Applications like webclient, webswing.

  • announcement_enabled (bool) – Is announcement enabled for Mgt Server:Announcements in the Mgt Server element are shown for all users that connect to that Mgt Server. Not Required.

  • announcement_message (str) – The announcement message for Mgt Server.

  • external_pki_certificate_settings (PkiCertificateSettings) – Certificate Settings for External PKI mode.

  • uiid (str) – Mgt Server Installation ID (aka UUID).

  • tools_profile_ref (tools_profile) – Allows you to add commands to the element’s right-click menu.

  • secondary (list(str)) – If the device has additional IP addresses, you can enter them here instead of creating additional elements for the other IP addresses. The secondary IP addresses are valid in policies and in routing and antispoofing. You can add several IPv4 and IPv6 addresses (one by one)

  • updates_check_enabled (bool) – Are you notified of new dynamic updates?

  • license_update_enabled (bool) – Select Generate and Install New Licenses Automatically to automatically regenerate and install the licenses required for upgrading system components to a major new release.

  • updates_proxy_enabled (bool) – If the connection from the Management Server to the Internet servers requires a proxy server, select Use Proxy Server for HTTPS Connection.

  • updates_proxy_address – If the connection from the Management Server to the Internet servers requires a proxy server, select an FQDN as proxy address.

  • updates_proxy_port (int) – If the connection from the Management Server to the Internet servers requires a proxy server, select a port as proxy port.

  • updates_proxy_authentication_enabled (bool) – If the connection from the Management Server to the Internet servers requires a proxy server with authentication.

  • updates_proxy_username (str) – If the connection from the Management Server to the Internet servers requires a proxy server with authentication, select an users’s name.

  • updates_proxy_password (str) – If the connection from the Management Server to the Internet servers requires a proxy server with authentication, select an users’s password

  • db_replication (bool) – Disable automatic database replication.

  • tls_profile (TLSProfile) – Select the TLS Profile to be used for admin login with Client Certificate authentication.

  • tls_credentials (TLSServerCredential) – Select the Credentials to be used for admin login with Client Certificate authentication.

  • es_tls_settings (TlsSettings) – Elasticsearch TLS Settings. Not null when we decide to override the ES Tls Settings in the Log Server or Management Server.

  • elasticsearch_authentication_settings (dict) –

    if we want to override defined authentication setting of Elasticsearch Server (> 7.1) dict : method: None, basic, api_key, certificate

    api_key : api_key certificate : es_tls_settings aside basic : login, password

  • forwarding_tls_settings (TlsSettings) – Log Forwarding TLS Settings. Should be NULL if no Log Forwarding has been defined for this Log Server. Not required

  • netflow_collector (list(NetflowCollector)) – Log Servers can be configured to forward log data to external hosts. You can define which type of log data you want to forward and in which format. You can also use Filters to specify in detail which log data is forwarded.

  • mgt_integration_container (list) – Mgt Server can be configured to define several Management Integration instances.

  • smtp_server_ref (SmtpServer) – The SMTP Server used for sending emails.

  • sender_address (str) – The sender email address.

  • sender_name (str) – The sender name.

  • snmp_gateways (str) – The SNMP gateway.

  • script_path (str) – The custom alert script path.

  • sms_http_channel (list) – The SMS HTTP channels.

  • sms_smtp_channel (list) – The SMS SMTP channels.

  • sms_script_channel (list) – The SMS Script channels.

  • radius_method (str) – Radius Method used in authentication when using Radius Server for authenticating administrators. One of the following values: “pap”,”chap”, “mschap”, “mschap2”, “eap-md5” Default is eap-md5.

:param str tacacs_method:Tacacs Method used in authentication when using Tacas Server for

authenticating administrators.One of the following values: “ascii”,”pap”,”chap”,”mschap” Default is mschap.

Parameters:

comment (str) – optional comment.

property db_replication

Disable automatic database replication? :rtype: bool

property license_update_enabled
Select Generate and Install New Licenses Automatically to automatically regenerate and

install the licenses required for upgrading system components to a major new release.

Return type:

bool

property mgt_integration_container

Several Management Integration instances. :rtype: list

restart_web_access()[source]

Restart Web Access on Mgt Server. :raises SMCOperationFailure: failed to restart SMC Web Access :return: None

property script_path

The custom alert script path. :rtype: str

property sender_address

The sender email address. :rtype: str

property sender_name

The sender name. :rtype: str

property sms_http_channel

The SMS HTTP channels. :rtype: list

property sms_script_channel

The SMS Script channels. :rtype: list

property sms_smtp_channel

The SMS SMTP channels. :rtype: list

property smtp_server_ref

The SMTP Server used for sending emails. :rtype: SmtpServer

property snmp_gateways

The SNMP gateway. :rtype: str

property tls_credentials

Credentials to be used for admin login with Client Certificate authentication. :rtype: TLSServerCredential

property tls_profile

TLS Profile to be used for admin login with Client Certificate authentication. :rtype: TLSProfile.

update(*exception, **kwargs)[source]

Update the existing element and clear the instance cache. Removing the cache will ensure subsequent calls requiring element attributes will force a new fetch to obtain the latest copy.

Calling update() with no args will assume the element has already been modified directly and the data cache will be used to update. You can also override the following attributes: href, etag, json and params. If json is sent, it is expected to the be a complete payload to satisfy the update.

For kwargs, if attribute values are a list, you can pass ‘append_lists=True’ to add to an existing list, otherwise overwrite the existing (default: overwrite)

See also

To see different ways to utilize this method for updating, see: Update.

Parameters:
  • exception – pass a custom exception to throw if failure

  • kwargs – optional kwargs to update request data to server.

Raises:
Returns:

href of the element modified

Return type:

str

property updates_check_enabled

Are you notified of new dynamic updates? :rtype: bool

property updates_proxy_address

FQDN as proxy address :rtype: str

property updates_proxy_authentication_enabled
If the connection from the Management Server to the Internet servers requires a proxy server

with authentication.

Return type:

bool

property updates_proxy_enabled
If the connection from the Management Server to the Internet servers requires a proxy server

, select Use Proxy Server for HTTPS Connection.

Return type:

bool

property updates_proxy_password

Proxy server authentication password. :rtype: str

property updates_proxy_port

Proxy server port. :rtype: int

property updates_proxy_username

Proxy server authentication username. :rtype: str

property web_app

Represents a Web Application parameter. :rtype: list(WebApp):

DNSServer

class smc.elements.servers.DNSServer(name=None, **meta)[source]

There are some cases in which you must define an External DNS Server element.

  • For dynamic DNS (DDNS) updates with a Multi-Link configuration.

  • If you want to use a DNS server for resolving malware signature mirrors.

  • If you want to use a DNS server for resolving domain names and URL filtering categorization services on Firewalls, IPS engines, and Layer 2 Firewalls.

You can also optionally use External DNS Server elements to specify the DNS servers to which the firewall forwards DNS requests when you configure DNS relay.

Variables:
  • time_to_live (int) – how long a DNS entry can be cached

  • update_interval (int) – how often DNS entries can be updated

classmethod create(name, address, time_to_live=20, update_interval=10, secondary=None, comment=None)[source]

Create a DNS Server element.

Parameters:
  • name (str) – Name of DNS Server

  • address (str) – IP address for DNS Server element

  • time_to_live (int) – Defines how long a DNS entry can be cached before querying the DNS server again (default: 20)

  • update_interval (int) – Defines how often the DNS entries can be updated to the DNS server if the link status changes constantly (default: 10)

  • secondary (list) – a secondary set of IP address for this element

Raises:

CreateElementFailed – Failed to create with reason

Return type:

DNSServer

HttpProxy

class smc.elements.servers.HttpProxy(name=None, **meta)[source]

An HTTP Proxy based element. Used in various areas of the configuration such as engine properties to define proxies for File Reputation, etc.

property address

Single valid IPv4 address. :rtype str

classmethod create(name, address, proxy_port=8080, username=None, password=None, secondary=None, third_party_monitoring=None, tools_profile_ref=None, comment=None)[source]

Create a new HTTP Proxy service. Proxy must define at least one primary address but can optionally also define a list of secondary addresses.

Parameters:
  • name (str) – Name of the proxy element

  • address (str) – Primary address for proxy

  • proxy_port (int) – proxy port (default: 8080)

  • username (str) – optional username for authentication (default: None)

  • password (str) – password for username if defined (default: None)

  • secondary (list) – secondary list of proxy server addresses

  • third_party_monitoring (ThirdPartyMonitoring) – The optional Third Party Monitoring configuration.

  • tools_profile_ref (DeviceToolsProfile) – Allows you to add commands to the element’s right-click menu. Not Required.

  • comment (str) – optional comment

Raises:

CreateElementFailed – Failed to create the proxy element

Return type:

HttpProxy

property http_proxy_port

Listening proxy port. :rtype int

property http_proxy_username

Username for authentication. :rtype str

ProxyServer

class smc.elements.servers.ProxyServer(name=None, **meta)[source]

Bases: ContactAddressMixin, Element, MultiContactServer

A ProxyServer element is used in the firewall policy to provide the ability to send HTTP, HTTPS, FTP or SMTP traffic to a next hop proxy. There are two types of next hop proxies, ‘Generic’ and ‘Forcepoint AP Web”.

Example of creating a configuration for a Forcepoint AP-Web proxy redirect:

server = ProxyServer.update_or_create(name='myproxy',
    address='1.1.1.1', proxy_service='forcepoint_ap-web_cloud',
    fp_proxy_key='mypassword', fp_proxy_key_id=3, fp_proxy_user_id=1234,
    inspected_service=[{'service_type': 'HTTP', 'port': '80'}])

Create a Generic Proxy forward service:

server = ProxyServer.update_or_create(name='generic', address='1.1.1.1,1.1.1.2',
    inspected_service=[{'service_type': 'HTTP', 'port': 80},
                       {'service_type': 'HTTPS', 'port': 8080}])

Inspected services take a list of keys service_type and port. Service type key values are ‘HTTP’, ‘HTTPS’, ‘FTP’ and ‘SMTP’. Port value is the port for the respective protocol.

Parameters:

http_proxy (str) – type of proxy configuration, either generic or forcepoint_ap-web_cloud

property add_x_forwarded_for

Add X-Forwarded-For header when using the Generic Proxy forwarding method (default: False) :rtype: bool

property balancing_mode
How to balance traffic, valid options are ha (first available server), src, dst, srcdst

(default: ha)

Return type:

str

classmethod create(name, address, secondary=None, ipv6_address=None, balancing_mode='ha', proxy_service='generic', location=None, add_x_forwarded_for=False, trust_host_header=False, inspected_service=None, third_party_monitoring=None, tools_profile_ref=None, comment=None, **kw)[source]

Create a Proxy Server element

Parameters:
  • name (str) – name of proxy server element

  • address (str) – address of element. Can be a single FQDN or comma separated list of IP addresses

  • secondary (list) – List of secondary IP addresses

  • ipv6_address (str) – Single valid IPv6 address.

  • balancing_mode (str) – how to balance traffic, valid options are ha (first available server), src, dst, srcdst (default: ha)

  • proxy_service (str) – which proxy service to use for next hop, options are generic or forcepoint_ap-web_cloud

  • location (Location) – location for this proxy server

  • add_x_forwarded_for (bool) – add X-Forwarded-For header when using the Generic Proxy forwarding method (default: False)

  • trust_host_header (bool) – trust the host header when using the Generic Proxy forwarding method (default: False)

  • inspected_service (dict) – inspection services dict. Valid keys are service_type and port. Service type valid values are HTTP, HTTPS, FTP or SMTP and are case sensitive

  • third_party_monitoring (ThirdPartyMonitoring) – The optional Third Party Monitoring configuration.

  • tools_profile_ref (DeviceToolsProfile) – Allows you to add commands to the element’s right-click menu. Not Required.

  • comment (str) – optional comment

  • 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

property fp_proxy_key

Password of Customer ID used in HTTP/HTTPS properties. :rtype: str

property fp_proxy_key_id

Key ID in case of Web-Gateway choice :rtype: int

property fp_proxy_user_id

Customer ID used in HTTP/HTTPS properties. :rtype: str

property inspected_services

The specified services for inspection. An inspected service is a reference to a protocol that can be forwarded for inspection, such as HTTP, HTTPS, FTP and SMTP.

Return type:

list(InspectedService)

property ip_address
List of IP Addresses to be used in addition to the ‘address’ field to allow using multiple

IP Addresses for the element.

Return type:

list(str)

property proxy_service

The proxy service for this proxy server configuration

Return type:

str

property trust_host_header

Trust the host header when using the Generic Proxy forwarding method (default: False) :rtype: bool

classmethod update_or_create(with_status=False, **kwargs)[source]

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 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
Parameters:
  • filter_key (dict) – filter key represents the data attribute and value to use to find the element. If none is provided, the name field will be used.

  • kwargs – keyword arguments mapping to the elements create method.

  • with_status (bool) – 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:
Returns:

element instance by type

Return type:

Element

DHCPServer

class smc.elements.servers.DHCPServer(name=None, **meta)[source]

Bases: Element

A DHCP Server based element. Used in various areas to define External DHCP Server.

classmethod create(name, address, ipv6_address=None, location=None, comment=None)[source]

Create a DHCP Server element.

Parameters:
  • name (str) – Name of DHCP Server

  • address (str) – IP address for DHCP Server element

  • ipv6_address (str) – IPv6 addres fir DHCP Server

  • location (str) – Specifies the location for the server if there is a NAT device between the server and other SMC components.

  • comment (str) – Comment for DHCP Server element

Raises:

CreateElementFailed – Failed to create with reason

Return type:

DHCPServer

WebPortalServer

class smc.elements.servers.WebPortalServer(name=None, **meta)[source]

Bases: Element, MultiContactServer

This represents a Web Portal Server. A component of the Management Center responsible for browsing logs, Policy Snapshots and reports from a Web Browser.

property alert_server

Specify the Log Server to which you want the Web Portal Server to send its logs rtype LogServer

classmethod create(name, address=None, ipv6_address=None, alert_server=None, location_ref=None, web_app=None, announcement_enabled=False, announcement_message=None, external_pki_certificate_settings=None, uiid=None, tools_profile_ref=None, secondary=None, comment=None)[source]
This represents a Web Portal Server. A component of the Management Center responsible for

browsing logs, Policy Snapshots and reports from a Web Browser.

Parameters:
  • name (str) – Name of the Web Portal Server.

  • address (str) – Single valid IPv4 address. Required.

  • ipv6_address (str) – IPv6 address.

  • alert_server (LogServer) – Specify the Log Server to which you want the Web Portal Server to send its logs. Required.

  • location_ref (Location) – Location of the server.

  • web_app (list(WebApp)) – Web Portal Server can be configured to define several Web

Application like webclient, webswing. :param bool announcement_enabled: Is announcement enabled for WebPortal Server:Announcements

in the Web Portal Server element are shown for all users that connect to that Web Portal Server.Not Required.

Parameters:
  • announcement_message (str) – The announcement message for WebPortal users.

  • external_pki_certificate_settings (PkiCertificateSettings) – Certificate Settings for External PKI mode.

  • uiid (str) – Web Portal Server Installation ID (aka UUID).

  • tools_profile_ref (tools_profile) – Allows you to add commands to the element’s right-click menu.

  • secondary (list(str)) – If the device has additional IP addresses, you can enter them here instead of creating additional elements for the other IP addresses. The secondary IP addresses are valid in policies and in routing and antispoofing. You can add several IPv4 and IPv6 addresses (one by one)

  • comment (str) – optional comment.

property external_pki_certificate_settings

Certificate Settings for External PKI mode. return PkiCertificateSettings

property web_app

Represents a Web Application parameter. :rtype list(WebApp):

EpoServer

class smc.elements.servers.EpoServer(name=None, **meta)[source]

Bases: Element, ContactAddressMixin, IPv6Node

This represents an ePO server: A Network Element that represents an ePO instance of server.

classmethod create(name, address=None, ipv6_address=None, epo_password=None, epo_login=None, epo_port=8444, location_ref=None, secondary=None, third_party_monitoring=None, tools_profile_ref=None, comment=None)[source]

This represents an ePO server: A Network Element that represents an ePO instance of server. :param str name: Name of the EpoServer. :param str address: Single valid IPv4 address. Required. :param str ipv6_address: Single valid IPv6 address. :param str epo_password: The ePO password Must be entered in clear. If filled with stars,the

field won’t be updated. Required.

Parameters:
  • epo_login (str) – The ePO login user name.

  • epo_port (int) – The ePO port.

  • location_ref (Location) – The location of EpoServer.

  • secondary (list(str)) – If the device has additional IP addresses, you can enter them here instead of creating additional elements for the other IP addresses. The secondary IP addresses are valid in policies and in routing and antispoofing. You can add several IPv4 and IPv6 addresses (one by one)

  • third_party_monitoring (ThirdPartyMonitoring) – The optional Third Party Monitoring configuration.

  • tools_profile_ref (DeviceToolsProfile) – Allows you to add commands to the element’s right-click menu. Not Required.

  • comment (str) – optional comment.

property epo_login

The ePO login user name. :rtype: str

property epo_port

The ePO port. :rtype: int

LDAPServer

ActiveDirectoryServer

SmtpServer

class smc.elements.servers.SmtpServer(name=None, **meta)[source]

Bases: Element, ContactAddressMixin, MultiContactServer

This represents a Simple Mail Transfer Protocol (SMTP) server. Server used to process

notifications by e-mails.

classmethod create(name, address=None, ipv6_address=None, port=25, email_sender_address=None, email_sender_name=None, location_ref=None, secondary=None, third_party_monitoring=None, tools_profile_ref=None, comment=None)[source]

This represents a Simple Mail Transfer Protocol (SMTP) server. Server used to process notifications by e-mails. :param str name: Name of the SmtpServer. :param str address: Single valid IPv4 address. Required. :param str ipv6_address: Single valid IPv6 address. :param int port: The port on which the SMTP server is listening. default port 25.Required :param str email_sender_address: E-mail address to be used in the From field of the e-mail.

This default value can be overridden in the properties of the element where the SMTP Server is used.Not Required.

Parameters:
  • email_sender_name (str) – Name to be used in the From field of the e-mail. This default value can be overridden in the properties of the element where the SMTP Server is used. Not Required.

  • location_ref (Location) – The location of SmtpServer.

  • secondary (list(str)) – If the device has additional IP addresses, you can enter them here instead of creating additional elements for the other IP addresses. The secondary IP addresses are valid in policies and in routing and antispoofing. You can add several IPv4 and IPv6 addresses (one by one)

  • third_party_monitoring (ThirdPartyMonitoring) – The optional Third Party Monitoring configuration.

  • tools_profile_ref (DeviceToolsProfile) – Allows you to add commands to the element’s right-click menu. Not Required.

  • comment (str) – optional comment.

property email_sender_address

E-mail address to be used in the From field of the e-mail. :rtype str

property email_sender_name

Name to be used in the From field of the e-mail. :rtype str

property port

The port on which the SMTP server is listening. :rtype int

IcapServer

class smc.elements.servers.IcapServer(name=None, **meta)[source]

Bases: Element, MultiContactServer

This represents an ICAP server: A Network Element that represents an ICAP instance of server.

classmethod create(name, address=None, ipv6_address=None, icap_include_xhdrs=False, icap_path=None, icap_port=1344, icap_secure=False, icap_xhdr_clientip=None, icap_xhdr_serverip=None, icap_xhdr_username=None, tls_profile_ref=None, location_ref=None, secondary=None, third_party_monitoring=None, tools_profile_ref=None, comment=None)[source]
Parameters:
  • name (str) – Name of the IcapServer.

  • address (str) – Single valid IPv4 address. Required.

  • ipv6_address (str) – Single valid IPv6 address.

:param bool icap_include_xhdrs:Include X-Headers or not. :param str icap_path: The path to the service. Not Required. Defaults to “reqmod”. :param int icap_port: The port on which the ICAP server is listening.Defaults to 1344, or

11344 for Secure

Parameters:
  • icap_secure (bool) – Secure ICAP Enabled. Not Required.

  • icap_xhdr_clientip (str) – X-Header Client IP. Not Required. Defaults to “X-Client-IP”

  • icap_xhdr_serverip (str) – X-Header Server IP. Not Required. Defaults to “X-Server-IP”

  • icap_xhdr_username (str) – X-Header Username. Not Required. Defaults to “X-Authenticated-User”

  • tls_profile_ref (TLSProfile) – Represents a TLS Profile Contains common parameters for establishing TLS based connections.

  • location_ref (Location) – The location of TacacsServer/RadiusServer.

  • secondary (list(str)) – If the device has additional IP addresses, you can enter them here instead of creating additional elements for the other IP addresses. The secondary IP addresses are valid in policies and in routing and antispoofing. You can add several IPv4 and IPv6 addresses (one by one)

  • third_party_monitoring (ThirdPartyMonitoring) – The optional Third Party Monitoring configuration.

  • tools_profile_ref (DeviceToolsProfile) – Allows you to add commands to the element’s right-click menu. Not Required.

  • comment (str) – optional comment.

property icap_include_xhdrs

Include X-Headers or not. :rtype bool

property icap_path

The path to the service. Not Required. Defaults to “reqmod”.

property icap_port

The port on which the ICAP server is listening. :rtype int

property icap_secure

Secure ICAP Enabled. :rtype bool

property icap_xhdr_clientip

X-Header Client IP. :rtype str

property icap_xhdr_serverip

X-Header Server IP. :rtype str

property icap_xhdr_username

X-Header Username. :rtype str

property tls_profile_ref

Represents a TLS Profile Contains common parameters for establishing TLS based connections. :rtype TLSProfile

RadiusServer

class smc.elements.servers.RadiusServer(name=None, **meta)[source]

Bases: AuthenticationServerMixin, ContactAddressMixin

This represents a RADIUS Server. It is an Authentication server using RADIUS authentication method. It can be used as authentication method for Administrators. An external authentication server can be any server that supports either the RADIUS or the TACACS+ protocol, including Microsoft Active Directory servers. External authentication servers are integrated with the help of Active Directory Server, RADIUS Authentication Server, TACACS+ Authentication Server, and Authentication Method elements. The RADIUS Authentication Server Server elements define the settings necessary for connecting to an external authentication server. The Authentication Method elements define an authentication method, and can include several RADIUS Authentication Servers or TACACS+ Authentication Servers that support the method and can be used as backups to each other.

TacacsServer

class smc.elements.servers.TacacsServer(name=None, **meta)[source]

Bases: AuthenticationServerMixin, ContactAddressMixin

This represents a TACACS Server.An external authentication server can be any server that supports either the RADIUS or the TACACS+ protocol, including Microsoft Active Directory servers External authentication servers are integrated with the help of Active Directory Server, RADIUS Authentication Server, TACACS+ Authentication Server, and Authentication Method elements. The RADIUS Authentication Server and TACACS+ Authentication Server elements define the settings necessary for connecting to an external authentication server. The Authentication Method elements define an authentication method, and can include several RADIUS Authentication Servers or TACACS+ Authentication Servers that support the method and can be used as backups to each other.

property clear_text
Select Accepted by Firewall if you want the Firewall to accept unencrypted replies from the

TACACS+ authentication server.

:rtype bool

NTPServer

class smc.elements.servers.NTPServer(name=None, **meta)[source]

Bases: Element, IPv6Node

This represents an NTP server: A Network Element that represents an NTP instance of server.

classmethod create(name, address, ipv6_address=None, ntp_host_name=None, ntp_auth_key_type='none', ntp_auth_key_id=None, ntp_auth_key=None, secondary=None, third_party_monitoring=None, tools_profile_ref=None, comment=None)[source]

Create NTP server

Parameters:
  • name (str) – name for the Element

  • address (str) – The NTP address (Required)

  • ipv6_address (str) – Single valid IPv6 address.

  • ntp_host_name (str) – NTP server name to use

:param str ntp_auth_key_type:The NTP Authentication Key Type (Required) possible values are (none, md5, sha1, sha256) :param str ntp_auth_key_id:The NTP Authentication Key ID (Not Required) value between 1 - 65534 :param str ntp_auth_key:The NTP Authentication Key (Not Required) :param list secondary: secondary ip address (optional) :param ThirdPartyMonitoring third_party_monitoring: The optional Third Party Monitoring

configuration.

Parameters:
  • tools_profile_ref (DeviceToolsProfile) – Allows you to add commands to the element’s right-click menu. Not Required.

  • comment (str) – comment for the element

Raises:

CreateElementFailed – Failed to create with reason

Return type:

NTPServer

property ntp_auth_key

The NTP Authentication Key (Not Required)

property ntp_auth_key_id

The NTP Authentication Key ID (Not Required) value between 1 - 65534

property ntp_auth_key_type

The NTP Authentication Key Type (Required) Possible values are: - none - md5 - sha1 - sha256

property ntp_host_name

The NTP Host Name (Not Required)

ElasticsearchCluster

class smc.elements.servers.ElasticsearchCluster(name=None, **meta)[source]

Bases: ContactAddressMixin, Element

An ElasticsearchCluster server type element.

property addresses
The list of hostnames / IP addresses (at least one) used to establish connection to the

Elasticsearch Cluster.

Return type:

list(str)

property authentication_settings

Elasticsearch authentication settings.

classmethod create(name, addresses, port=9200, es_retention_period=30, es_shard_number=0, es_replica_number=0, enable_cluster_sniffer=False, location=None, comment=None, tls_profile=None, es_tls_settings=None, authentication_settings=None)[source]

Create a Elasticsearch Cluster Server element.

Parameters:
  • name (str) – Name of Elasticsearch Cluster

  • addresses (list,str) – str comma-separated list or list of one or more FQDNs or IP addresses

  • port (int) – Default port is 9200

  • es_retention_period (int) – How much time logs will be kept

30days default :param int es_shard_number: Auto by default, number of shards :param int es_replica_number : number of ES replicas :param bool enable_cluster_sniffer : Enable cluster sniffer (False default) :param str location: Specifies the location for the server if there is a NAT device between the server and other SMC components. :param str comment: Comment for Elasticsearch cluster Server element :param str tls_profile: tls profile name to use :param TlsSettings es_tls_settings: Elasticsearch TLS Settings. :param dict authentication_settings: method: str can be none, basic, api_key or certificate for basic

login : elasticsearch user login password : elasticsearch user password

for api_key:

api_key: elasticsearch api key for user

Raises:

CreateElementFailed – Failed to create with reason

Return type:

ElasticsearchCluster

property es_enable_cluster_sniffer

Enabling the cluster sniffer. Default: false. :rtype: bool

property es_retention_period

Retention period (in days) for logs in Elasticsearch cluster. :rtype: int

property es_shard_number
The number of shards for the fwlogsandalerts indices, a strictly positive number, or auto

(default value).

Return type:

int

property es_tls_settings

Elasticsearch TLS Settings. :rtype: TlsSettings

property port

The port on which connection is established on Elasticsearch Cluster nodes. :rtype: int

update(*exception, **kwargs)[source]

Update the existing element and clear the instance cache. Removing the cache will ensure subsequent calls requiring element attributes will force a new fetch to obtain the latest copy.

Calling update() with no args will assume the element has already been modified directly and the data cache will be used to update. You can also override the following attributes: href, etag, json and params. If json is sent, it is expected to the be a complete payload to satisfy the update.

For kwargs, if attribute values are a list, you can pass ‘append_lists=True’ to add to an existing list, otherwise overwrite the existing (default: overwrite)

See also

To see different ways to utilize this method for updating, see: Update.

Parameters:
  • exception – pass a custom exception to throw if failure

  • kwargs – optional kwargs to update request data to server.

Raises:
Returns:

href of the element modified

Return type:

str

Other

Other element types that treated more like generics, or that can be applied in different areas within the SMC. They will not independently be created as standalone objects and will be more generic container classes that define the required json when used by API functions or methods. For example, blocklist can be applied to an engine directly or system wide. This class will define the format when calling blocklist functions.

class smc.elements.other.Blacklist[source]

Blacklist provides a simple container to add multiple blacklist entries. Pass an instance of this to smc.core.engine.blacklist_bulk to upload to the engine.

Note

This method requires SMC version < 7.0

since this version, “blacklist” is renamed “block_list”

add_entry(src, dst, duration=3600, src_port1=None, src_port2=None, src_proto='predefined_tcp', dst_port1=None, dst_port2=None, dst_proto='predefined_tcp')[source]

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.

Parameters:
  • src – source address, with cidr, i.e. 10.10.10.10/32 or ‘any’

  • dst – destination address with cidr, i.e. 1.1.1.1/32 or ‘any’

  • duration (int) – 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')
Parameters:
  • src_port1 (int) – start source port to limit blacklist

  • src_port2 (int) – end source port to limit blacklist

  • src_proto (str) – source protocol. Either ‘predefined_tcp’ or ‘predefined_udp’. (default: ‘predefined_tcp’)

  • dst_port1 (int) – start dst port to limit blacklist

  • dst_port2 (int) – end dst port to limit blacklist

  • dst_proto (str) – 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.

class smc.elements.other.Blocklist[source]

Blocklist provides a simple container to add multiple block_list entries. Pass an instance of this to smc.core.engine.block_list_bulk to upload to the engine.

Note

This method requires SMC version >= 7.0

add_entry(src, dst, duration=3600, src_port1=None, src_port2=None, src_proto='predefined_tcp', dst_port1=None, dst_port2=None, dst_proto='predefined_tcp')[source]

Create a blocklist entry.

A blocklist can be added directly from the engine node, or from the system context. If submitting from the system context, it becomes a global blocklist. This will return the properly formatted json to submit.

Parameters:
  • src – source address, with cidr, i.e. 10.10.10.10/32 or ‘any’

  • dst – destination address with cidr, i.e. 1.1.1.1/32 or ‘any’

  • duration (int) – length of time to blocklist

Both the system and engine context blocklist 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 blocklist using additional kw:

engine.block_list('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')
Parameters:
  • src_port1 (int) – start source port to limit blocklist

  • src_port2 (int) – end source port to limit blocklist

  • src_proto (str) – source protocol. Either ‘predefined_tcp’ or ‘predefined_udp’. (default: ‘predefined_tcp’)

  • dst_port1 (int) – start dst port to limit blocklist

  • dst_port2 (int) – end dst port to limit blocklist

  • dst_proto (str) – 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.

class smc.elements.other.Category(name=None, **meta)[source]

A Category is used by an element to group and categorize elements by some criteria. Once a category is created, it can be assigned to the element and used as a search filter when managing large numbers of elements. A category can be added to a category tag (or tags) to provide a higher level container/group for searching.

>>> from smc.elements.other import Category
>>> Category.create(name='footag', comment='test tag')
Category(name=footag)
Variables:

categories (list(CategoryTag)) – category tags for this category

add_category(tags)[source]

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.

Parameters:

tags (list(str)) – list of category tag names to add to this element

Raises:

ElementNotFound – Category tag element name not found

Returns:

None

add_category_tag(tags, append_lists=True)[source]

Add this category to a category tag (group). This provides drop down filters in the SMC by category tag.

Parameters:
  • tags (list(str)) – category tag by name

  • append_lists (bool) – append to existing tags or overwrite default: append)

Returns:

None

add_element(element)[source]

Element can be href or type smc.base.model.Element

>>> from smc.elements.other import Category
>>> category = Category('foo')
>>> category.add_element(Host('kali'))
Parameters:

element (str,Element) – element to add to tag

Raises:

ModificationFailed: failed adding element

Returns:

None

classmethod create(name, comment=None)[source]

Add a category element

Parameters:

name – name of location

Returns:

instance with meta

Return type:

Category

remove_element(element)[source]

Remove an element from this category tag. Find elements assigned by search_elements(). Element can be str href or type smc.base.model.Element.

>>> from smc.elements.other import Category
>>> from smc.elements.network import Host
>>> category.remove_element(Host('kali'))
Parameters:

element (str, Element) – element to remove

Raises:

ModificationFailed – cannot remove element

Returns:

None

search_elements()[source]

Find all elements assigned to this category tag. You can also find category tags assigned directly to an element also:

>>> host = Host('kali')
>>> host.categories
[Category(name=myelements), Category(name=foocategory)]
Returns:

smc.base.model.Element

Return type:

list

class smc.elements.other.CategoryTag(name=None, **meta)[source]

A Category Tag is a grouping of categories within SMC. Category Tags are used as filters (typically in the SMC) to change the view based on the tag.

Variables:
classmethod create(name, comment=None)[source]

Create a CategoryTag. A category tag represents a group of categories or a group of category tags (nested groups). These are used to provide filtering views within the SMC and organize elements by user defined criteria.

Parameters:
  • name (str) – name of category tag

  • comment (str) – optional comment

Raises:

CreateElementFailed – problem creating tag

Returns:

instance with meta

Return type:

CategoryTag

remove_category(categories)[source]

Remove a category from this Category Tag (group).

Parameters:

categories (list(str,Element)) – categories to remove

Returns:

None

class smc.elements.other.ContactAddress(data=None, **kwargs)[source]

A contact address is used by elements to provide an alternative IP or FQDN mapping based on a location

property addresses

List of addresses set as contact address

Return type:

list

property name

Location name for this contact address

Return type:

str

class smc.elements.other.FilterExpression(name=None, **meta)[source]

A filter expression defines either a system element filter or a user defined filter based on an expression. For example, a system level filter is ‘Match All’. For classes that allow filters as input, a filter expression can be used.

class smc.elements.other.Geolocation(name=None, **meta)[source]

Geolocation objects are mutable as of SMC version 6.6

New in version 0.7.0.

class smc.elements.other.HTTPSInspectionExceptions(name=None, **meta)[source]

The HTTPS Inspection Exceptions element is a list of domains that are excluded from decryption and inspection. HTTPS Inspection Exceptions are used in a custom HTTPS service to define a list of domains for which HTTPS traffic is not decrypted. The custom HTTPS service must be used in a rule, and only traffic that matches the rule is excluded from decryption and inspection.

Note

As of SMC 6.4.3, this is a read-only element

class smc.elements.other.Location(name=None, **meta)[source]

Locations are used by elements to identify when they are behind a NAT connection. For example, if you have an engine that connects to the SMC across the internet using a public address, a location will be the tag applied to the Management Server (with contact address) and on the engine to identify how to connect. In this case, the location will map to a contact address using a public IP.

Note

Locations require SMC API version >= 6.1

classmethod create(name, comment=None)[source]

Create a location element

Parameters:

name – name of location

Raises:

CreateElementFailed – failed creating element with reason

Returns:

instance with meta

Return type:

Location

property used_on

Return all NAT’d elements using this location.

Note

Available only in SMC version 6.2

Returns:

elements used by this location

Return type:

list

class smc.elements.other.LogicalInterface(name=None, **meta)[source]

Logical interface is used on either inline or capture interfaces. If an engine has both inline and capture interfaces (L2 Firewall or IPS role), then you must use a unique Logical Interface on the interface type.

Create a logical interface:

LogicalInterface.create('mylogical_interface')
classmethod create(name, comment=None)[source]

Create the logical interface

Parameters:
  • name (str) – name of logical interface

  • comment (str) – optional comment

Raises:

CreateElementFailed – failed creating element with reason

Returns:

instance with meta

Return type:

LogicalInterface

class smc.elements.other.MacAddress(name=None, **meta)[source]

Mac Address network element that can be used in L2 and IPS policy source and destination fields.

Creating a MacAddress:

>>> MacAddress.create(name='mymac', mac_address='22:22:22:22:22:22')
MacAddress(name=mymac)
classmethod create(name, mac_address, comment=None)[source]

Create the Mac Address

Parameters:
  • name (str) – name of mac address

  • mac_address (str) – mac address notation

  • comment (str) – optional comment

Raises:

CreateElementFailed – failed creating element with reason

Returns:

instance with meta

Return type:

MacAddress

class smc.elements.other.QueryDataFilter(name=None, **meta)[source]

A Query Data Filter is an Internal filter container. Created on the fly when adding filtering context in some components

class smc.elements.other.RuleValidityTime(name=None, **meta)[source]

This represents a Rule Validity Time.

class smc.elements.other.SituationTag(name=None, **meta)[source]

A situation tag is used to categorize situations based on some sort of user defined criteria such as Botnet, Attacks, etc. These can help with categorization of specific threat event types.

class smc.elements.other.UpdateServerProfile(name=None, **meta)[source]

This represents Update Server Profile (aka Update Service)

classmethod create(name, retry=0, timeout=0, urls=None, tls_profile_ref=None, comment=None)[source]

Create a UpdateServerProfile. A Update Server Profile represents a update service. These are used to provide server providing the updates within the SMC.

Parameters:
  • name (str) – name of category tag.

  • retry (int) – number of retries.

  • timeout (int) – connection timeout.

  • urls (list) – list of URL, at least one is mandatory.

  • tls_profile_ref (str) – TLS profile used to connect to the server(s).

  • comment (str) – optional comment.

Raises:

CreateElementFailed – problem creating tag.

Returns:

instance with meta.

Return type:

CategoryTag.

property ordered_url

The list of url used by update service. :rtype List(url)

property retry

number of retries

property timeout

It is connection timeout

property tls_profile

TLS profile used to connect to the server(s). :rtype TLSProfile

smc.elements.other.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')[source]

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.

Parameters:
  • src – source address, with cidr, i.e. 10.10.10.10/32 or ‘any’

  • dst – destination address with cidr, i.e. 1.1.1.1/32 or ‘any’

  • duration (int) – 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')
Parameters:
  • src_port1 (int) – start source port to limit blacklist

  • src_port2 (int) – end source port to limit blacklist

  • src_proto (str) – source protocol. Either ‘predefined_tcp’ or ‘predefined_udp’. (default: ‘predefined_tcp’)

  • dst_port1 (int) – start dst port to limit blacklist

  • dst_port2 (int) – end dst port to limit blacklist

  • dst_proto (str) – 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.

Note

This method requires SMC version < 7.0

smc.elements.other.prepare_block_list(src, dst, duration=3600, src_port1=None, src_port2=None, src_proto='predefined_tcp', dst_port1=None, dst_port2=None, dst_proto='predefined_tcp')[source]

Create a block_list entry.

A blocklist can be added directly from the engine node, or from the system context. If submitting from the system context, it becomes a global blocklist. This will return the properly formatted json to submit.

Parameters:
  • src – source address, with cidr, i.e. 10.10.10.10/32 or ‘any’

  • dst – destination address with cidr, i.e. 1.1.1.1/32 or ‘any’

  • duration (int) – length of time to blocklist

Both the system and engine context blocklist 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 blocklist using additional kw:

engine.block_list('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')
Parameters:
  • src_port1 (int) – start source port to limit blocklist

  • src_port2 (int) – end source port to limit blocklist

  • src_proto (str) – source protocol. Either ‘predefined_tcp’ or ‘predefined_udp’. (default: ‘predefined_tcp’)

  • dst_port1 (int) – start dst port to limit blocklist

  • dst_port2 (int) – end dst port to limit blocklist

  • dst_proto (str) – 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.

Note

This method requires SMC version >= 7.0

Blacklist

class smc.elements.other.Blacklist[source]

Blacklist provides a simple container to add multiple blacklist entries. Pass an instance of this to smc.core.engine.blacklist_bulk to upload to the engine.

Note

This method requires SMC version < 7.0

since this version, “blacklist” is renamed “block_list”

add_entry(src, dst, duration=3600, src_port1=None, src_port2=None, src_proto='predefined_tcp', dst_port1=None, dst_port2=None, dst_proto='predefined_tcp')[source]

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.

Parameters:
  • src – source address, with cidr, i.e. 10.10.10.10/32 or ‘any’

  • dst – destination address with cidr, i.e. 1.1.1.1/32 or ‘any’

  • duration (int) – 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')
Parameters:
  • src_port1 (int) – start source port to limit blacklist

  • src_port2 (int) – end source port to limit blacklist

  • src_proto (str) – source protocol. Either ‘predefined_tcp’ or ‘predefined_udp’. (default: ‘predefined_tcp’)

  • dst_port1 (int) – start dst port to limit blacklist

  • dst_port2 (int) – end dst port to limit blacklist

  • dst_proto (str) – 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.

Category

class smc.elements.other.Category(name=None, **meta)[source]

Bases: Element

A Category is used by an element to group and categorize elements by some criteria. Once a category is created, it can be assigned to the element and used as a search filter when managing large numbers of elements. A category can be added to a category tag (or tags) to provide a higher level container/group for searching.

>>> from smc.elements.other import Category
>>> Category.create(name='footag', comment='test tag')
Category(name=footag)
Variables:

categories (list(CategoryTag)) – category tags for this category

add_category(tags)[source]

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.

Parameters:

tags (list(str)) – list of category tag names to add to this element

Raises:

ElementNotFound – Category tag element name not found

Returns:

None

add_category_tag(tags, append_lists=True)[source]

Add this category to a category tag (group). This provides drop down filters in the SMC by category tag.

Parameters:
  • tags (list(str)) – category tag by name

  • append_lists (bool) – append to existing tags or overwrite default: append)

Returns:

None

add_element(element)[source]

Element can be href or type smc.base.model.Element

>>> from smc.elements.other import Category
>>> category = Category('foo')
>>> category.add_element(Host('kali'))
Parameters:

element (str,Element) – element to add to tag

Raises:

ModificationFailed: failed adding element

Returns:

None

classmethod create(name, comment=None)[source]

Add a category element

Parameters:

name – name of location

Returns:

instance with meta

Return type:

Category

remove_element(element)[source]

Remove an element from this category tag. Find elements assigned by search_elements(). Element can be str href or type smc.base.model.Element.

>>> from smc.elements.other import Category
>>> from smc.elements.network import Host
>>> category.remove_element(Host('kali'))
Parameters:

element (str, Element) – element to remove

Raises:

ModificationFailed – cannot remove element

Returns:

None

search_elements()[source]

Find all elements assigned to this category tag. You can also find category tags assigned directly to an element also:

>>> host = Host('kali')
>>> host.categories
[Category(name=myelements), Category(name=foocategory)]
Returns:

smc.base.model.Element

Return type:

list

CategoryTag

class smc.elements.other.CategoryTag(name=None, **meta)[source]

Bases: Element

A Category Tag is a grouping of categories within SMC. Category Tags are used as filters (typically in the SMC) to change the view based on the tag.

Variables:
classmethod create(name, comment=None)[source]

Create a CategoryTag. A category tag represents a group of categories or a group of category tags (nested groups). These are used to provide filtering views within the SMC and organize elements by user defined criteria.

Parameters:
  • name (str) – name of category tag

  • comment (str) – optional comment

Raises:

CreateElementFailed – problem creating tag

Returns:

instance with meta

Return type:

CategoryTag

remove_category(categories)[source]

Remove a category from this Category Tag (group).

Parameters:

categories (list(str,Element)) – categories to remove

Returns:

None

FilterExpression

class smc.elements.other.FilterExpression(name=None, **meta)[source]

Bases: Element

A filter expression defines either a system element filter or a user defined filter based on an expression. For example, a system level filter is ‘Match All’. For classes that allow filters as input, a filter expression can be used.

Location

class smc.elements.other.Location(name=None, **meta)[source]

Bases: Element

Locations are used by elements to identify when they are behind a NAT connection. For example, if you have an engine that connects to the SMC across the internet using a public address, a location will be the tag applied to the Management Server (with contact address) and on the engine to identify how to connect. In this case, the location will map to a contact address using a public IP.

Note

Locations require SMC API version >= 6.1

classmethod create(name, comment=None)[source]

Create a location element

Parameters:

name – name of location

Raises:

CreateElementFailed – failed creating element with reason

Returns:

instance with meta

Return type:

Location

property used_on

Return all NAT’d elements using this location.

Note

Available only in SMC version 6.2

Returns:

elements used by this location

Return type:

list

LogicalInterface

class smc.elements.other.LogicalInterface(name=None, **meta)[source]

Bases: Element

Logical interface is used on either inline or capture interfaces. If an engine has both inline and capture interfaces (L2 Firewall or IPS role), then you must use a unique Logical Interface on the interface type.

Create a logical interface:

LogicalInterface.create('mylogical_interface')
classmethod create(name, comment=None)[source]

Create the logical interface

Parameters:
  • name (str) – name of logical interface

  • comment (str) – optional comment

Raises:

CreateElementFailed – failed creating element with reason

Returns:

instance with meta

Return type:

LogicalInterface

MacAddress

class smc.elements.other.MacAddress(name=None, **meta)[source]

Bases: Element

Mac Address network element that can be used in L2 and IPS policy source and destination fields.

Creating a MacAddress:

>>> MacAddress.create(name='mymac', mac_address='22:22:22:22:22:22')
MacAddress(name=mymac)
classmethod create(name, mac_address, comment=None)[source]

Create the Mac Address

Parameters:
  • name (str) – name of mac address

  • mac_address (str) – mac address notation

  • comment (str) – optional comment

Raises:

CreateElementFailed – failed creating element with reason

Returns:

instance with meta

Return type:

MacAddress

HTTPSInspectionExceptions

class smc.elements.other.HTTPSInspectionExceptions(name=None, **meta)[source]

Bases: Element

The HTTPS Inspection Exceptions element is a list of domains that are excluded from decryption and inspection. HTTPS Inspection Exceptions are used in a custom HTTPS service to define a list of domains for which HTTPS traffic is not decrypted. The custom HTTPS service must be used in a rule, and only traffic that matches the rule is excluded from decryption and inspection.

Note

As of SMC 6.4.3, this is a read-only element

Sidewinder Elements

Module providing sidewinder element creation.

The different sidewinder elements in this module that can be configured are SSM Logging Profiles, SSH Profiles, SSH Known Hosts, and SSH Known Hosts Lists.

class smc.elements.ssm.DeviceToolsProfile(name=None, **meta)[source]
class smc.elements.ssm.LoggingProfile(name=None, **meta)[source]
class smc.elements.ssm.ProbingProfile(name=None, **meta)[source]
class smc.elements.ssm.SSHKnownHosts(name=None, **meta)[source]

Class representing a SSH Known Host object used in SSH Known Hosts Lists

Create a SSH Knwown Host element with ipv4 and with ssh-rsa:

SSHKnownHosts.create(name='ipv4_rsa_known_host',
            sshkey_type='ssh-rsa',
            host_key='<ssh_host_rsa_key.pub output>',
            ipaddress='1.1.1.1', port=22000,
            comment='some comment for my known host')

Create a SSH Knwown Host element with ipv6 and with ecdsa-sha2-nistp256:

Host.create(name='ipv6_ecdsa_known_host',
            ssh_type='ecdsa-sha2-nistp256',
            host_key='<ssh_host_ecdsa_key.pub output>',
            ipv6_address='2001:cdba::3257:9652')

Available attributes:

Variables:
  • ipaddress (str) – IPv4 address for this element

  • ipv6_address (str) – IPv6 address for this element

  • sshkey_type (str) – ssh key type (i.e. ssh-rsa, ecdsa-sha2-nistp256)

  • host_key (str) – public host key of host

  • port (int) – port number for this element

classmethod create(name, host_key, sshkey_type, ipaddress=None, ipv6_address=None, port=22, comment=None)[source]

Create the SSH Known Host

Parameters:
  • name (str) – name of ssh known host

  • host_key (str) – string of public host key of known host

  • sshkey_type (str) – ssh key type of the known host public key

  • ipaddress (str) – IPv4 address of known host

  • ipv6_ipaddress (str) – IPv6 address of known host

  • port (int) – port number of the ssh known host element

  • comment (str) – comment (optional)

Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

SSHKnownHosts

Note

Either an ipaddress or ipv6_address must be specified

class smc.elements.ssm.SSHKnownHostsLists(name=None, **meta)[source]

Class representing a SSH Known Hosts List object used in the Sidewinder Proxy Add-On on the engine

Create a SSH Knwown Hosts List element and add a created Known Host to it:

known_host = SSHKnownHosts.create(name='ipv4_rsa_known_host',
                        sshkey_type='ssh-rsa',
                        host_key='<ssh_host_rsa_key.pub output>',
                        ipaddress='1.1.1.1', port=22000,
                        comment='some comment for my known host')

SSHKnownHostsLists.create(name='myknownhostslist',
            known_host=[known_host.href],
            comment='some comment for my known host list')

Available attributes:

Variables:

known_host (list) – href of known host for this element

classmethod create(name, known_host=[], comment=None)[source]

Create the SSH Known Host List

Parameters:
  • name (str) – name of ssh known host list

  • known_host (list) – href of ssh known hosts to add to the list

  • comment (str) – comment (optional)

Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

SSHKnownHostsLists

class smc.elements.ssm.SSHProfile(name=None, **meta)[source]

Class representing a SSH Profile object used in SSM SSH Proxy services

Create a SSH Profile element with ciphers, kex, and macs:

SSHProfile.create(name='mysshprofile',
            cipher='aes256-ctr,aes128-ctr,aes192-ctr,aes128-cbc',
            kex='ecdh-sha2-nistp256,diffie-hellman-group14-sha1',
            mac='hmac-sha2-256,hmac-sha2-512,hmac-md5-etm@openssh.com',
            comment='some comment for my ssh profile')

Available attributes:

Variables:
  • cipher (str) – cipher algorithms set for this element

  • kex (str) – key exchange algorithms set for this element

  • mac (str) – mac algorithms set for this element

Note

Each algorithm type must have an algorithm set

classmethod create(name, cipher, kex, mac, comment=None)[source]

Create the SSH Profile

Parameters:
  • name (str) – name of ssh profile

  • cipher (str) – string of cipher algorithms (comma separated)

  • kex (str) – string of key exchange algorithms (comma separated)

  • mac (str) – string of mac algorithms (comma separated)

  • comment (str) – comment (optional)

Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

SSHProfile

Note

No algorithm type can be empty

class smc.elements.ssm.SSMLoggingProfile(name=None, **meta)[source]

SSHProfile

class smc.elements.ssm.SSHProfile(name=None, **meta)[source]

Bases: Element

Class representing a SSH Profile object used in SSM SSH Proxy services

Create a SSH Profile element with ciphers, kex, and macs:

SSHProfile.create(name='mysshprofile',
            cipher='aes256-ctr,aes128-ctr,aes192-ctr,aes128-cbc',
            kex='ecdh-sha2-nistp256,diffie-hellman-group14-sha1',
            mac='hmac-sha2-256,hmac-sha2-512,hmac-md5-etm@openssh.com',
            comment='some comment for my ssh profile')

Available attributes:

Variables:
  • cipher (str) – cipher algorithms set for this element

  • kex (str) – key exchange algorithms set for this element

  • mac (str) – mac algorithms set for this element

Note

Each algorithm type must have an algorithm set

classmethod create(name, cipher, kex, mac, comment=None)[source]

Create the SSH Profile

Parameters:
  • name (str) – name of ssh profile

  • cipher (str) – string of cipher algorithms (comma separated)

  • kex (str) – string of key exchange algorithms (comma separated)

  • mac (str) – string of mac algorithms (comma separated)

  • comment (str) – comment (optional)

Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

SSHProfile

Note

No algorithm type can be empty

SSHKnownHosts

class smc.elements.ssm.SSHKnownHosts(name=None, **meta)[source]

Bases: Element

Class representing a SSH Known Host object used in SSH Known Hosts Lists

Create a SSH Knwown Host element with ipv4 and with ssh-rsa:

SSHKnownHosts.create(name='ipv4_rsa_known_host',
            sshkey_type='ssh-rsa',
            host_key='<ssh_host_rsa_key.pub output>',
            ipaddress='1.1.1.1', port=22000,
            comment='some comment for my known host')

Create a SSH Knwown Host element with ipv6 and with ecdsa-sha2-nistp256:

Host.create(name='ipv6_ecdsa_known_host',
            ssh_type='ecdsa-sha2-nistp256',
            host_key='<ssh_host_ecdsa_key.pub output>',
            ipv6_address='2001:cdba::3257:9652')

Available attributes:

Variables:
  • ipaddress (str) – IPv4 address for this element

  • ipv6_address (str) – IPv6 address for this element

  • sshkey_type (str) – ssh key type (i.e. ssh-rsa, ecdsa-sha2-nistp256)

  • host_key (str) – public host key of host

  • port (int) – port number for this element

classmethod create(name, host_key, sshkey_type, ipaddress=None, ipv6_address=None, port=22, comment=None)[source]

Create the SSH Known Host

Parameters:
  • name (str) – name of ssh known host

  • host_key (str) – string of public host key of known host

  • sshkey_type (str) – ssh key type of the known host public key

  • ipaddress (str) – IPv4 address of known host

  • ipv6_ipaddress (str) – IPv6 address of known host

  • port (int) – port number of the ssh known host element

  • comment (str) – comment (optional)

Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

SSHKnownHosts

Note

Either an ipaddress or ipv6_address must be specified

SSHKnownHostsLists

class smc.elements.ssm.SSHKnownHostsLists(name=None, **meta)[source]

Bases: Element

Class representing a SSH Known Hosts List object used in the Sidewinder Proxy Add-On on the engine

Create a SSH Knwown Hosts List element and add a created Known Host to it:

known_host = SSHKnownHosts.create(name='ipv4_rsa_known_host',
                        sshkey_type='ssh-rsa',
                        host_key='<ssh_host_rsa_key.pub output>',
                        ipaddress='1.1.1.1', port=22000,
                        comment='some comment for my known host')

SSHKnownHostsLists.create(name='myknownhostslist',
            known_host=[known_host.href],
            comment='some comment for my known host list')

Available attributes:

Variables:

known_host (list) – href of known host for this element

classmethod create(name, known_host=[], comment=None)[source]

Create the SSH Known Host List

Parameters:
  • name (str) – name of ssh known host list

  • known_host (list) – href of ssh known hosts to add to the list

  • comment (str) – comment (optional)

Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

SSHKnownHostsLists

Situations

Module that represents inspection and correlated situations.

New in version 0.6.3: Requires SMC version >= 6.5

Situations can be either inspection related or correlated. Both types can be searched to obtain collections.

Every situation has an associated ‘context’ which identifies properties of the situation and how matching or correlation is performed.

A situation context group is a top level structure that encapsulates similar individual inspection contexts. You can retrieve these as follows:

>>> from smc.elements.situations import SituationContextGroup
>>> for group in SituationContextGroup.objects.all():
...   group
...
SituationContextGroup(name=DoS Detection)
SituationContextGroup(name=FINGER)
SituationContextGroup(name=SMTP Deprecated)
SituationContextGroup(name=PPTP)
SituationContextGroup(name=IPv6)
SituationContextGroup(name=NETBIOS)
SituationContextGroup(name=SIP)
SituationContextGroup(name=SNMP)

You can optionally retrieve situation context groups directly, and iterate the inspection contexts (sub_elements), which might be additional situation context groups or inspection contexts:

>>> group = SituationContextGroup('DoS Detection')
>>> group.sub_elements
[InspectionSituationContext(name=TCP synflood detection (SYN-ACK timeout based detection)),
 InspectionSituationContext(name=TCP synflood detection (SYN-timeout method)),
 InspectionSituationContext(name=Non-ratebased DoS attacks),
 InspectionSituationContext(name=TCP DoS events),
 InspectionSituationContext(name=UDP DoS events),
                            InspectionSituationContext(name=UDP DoS detected)]

If you are interested in inspection contexts directly (i.e. groups are ‘flattened’ out), you can retrieve these as follows:

>>> from smc.elements.situations import InspectionSituationContext
>>> for context in InspectionSituationContext.objects.all():
...   context
...
InspectionSituationContext(name=Context for DNS_POLICY_NOTIFY_FAIL)
InspectionSituationContext(name=Context for FTP AUTH success)
InspectionSituationContext(name=TCP PPTP Server Stream)
InspectionSituationContext(name=Context for SMTP_INCONSISTENT_REPLIES)
InspectionSituationContext(name=Context for TCP Option Too Short)
InspectionSituationContext(name=RIFF File Stream)
InspectionSituationContext(name=Context for IP Total Length Error)
...

You can optionally retrieve an inspection situation context directly. Most situation contexts are system level elements and will be read only, but you can fetch them to view configurations if necessary.

Every situation context will have at least one situation parameter, which is the parameter / value pair used to match the on inspection situations which are categorized by the situation context. For example, in the case of detecting a text file stream, a single regular expression type situation parameter is used:

>>> context = InspectionSituationContext('Text File Stream')
>>> for parameter in context.situation_parameters:
...   parameter
...
SituationParameter(name=Regular Expression)

Inspection Situations are the individual events that are either predefined or system defined that identify specific events to inspect for. All inspection situations have an inspection context (see above), and can also be customized or be duplicated.

Creating an inspection situation is a two step process. You must first create the situation with a specified context, then add the necessary parameter values.

An example of creating a new situation that uses a regular expression pattern to match within a Text File Stream:

>>> from smc.elements.situations import InspectionSituation
>>> from smc.elements.situations import InspectionSituationContext
>>>
>>> situation = InspectionSituation.create(name='foosituation',
                situation_context=InspectionSituationContext('Text File Stream'),
                severity='high')
>>> situation
InspectionSituation(name=foosituation)
>>> situation.create_regular_expression(r'(?x)\n.*ActiveXObject \x28 \x22 WScript\.'                                            'Shell(?[s_file_text_script -> sid()])\n')
>>>
class smc.elements.situations.CorrelationSituation(name=None, **meta)[source]

Bases: Situation

Correlation Situations are used by NGFW Engines and Log Servers to conduct further analysis of detected events. Correlation Situations do not handle traffic directly. Instead they analyze the events generated by matches to Situations found in traffic. Correlation Situations use Event Binding elements to define the log events that bind together different types of events in traffic.

class smc.elements.situations.CorrelationSituationContext(name=None, **meta)[source]

Bases: SituationContext

Correlation Contexts define the patterns for matching groups of related events in traffic. Examples of correlation contexts are Count, Compress, Group, Match and Sequence. See SMC documentation for more details on each context type and meaning.

property situation_parameters

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.

Return type:

list(SituationParameter)

class smc.elements.situations.EcaOperatingSystemSituation(name=None, **meta)[source]

Bases: Situation

Used to configure ECA Endpoint setting

class smc.elements.situations.InspectionSituation(name=None, **meta)[source]

Bases: Situation

It is an element that identifies and describes detected events in the traffic or in the operation of the system. Situations contain the Context information, i.e., a pattern that the system is to look for in the inspected traffic.

classmethod create(name, situation_context, attacker=None, target=None, severity='information', situation_type=None, description=None, comment=None)[source]

Create an inspection situation.

Parameters:
  • name (str) – name of the situation

  • situation_context (InspectionSituationContext) – The situation context type used to define this situation. Identifies the proper parameter that identifies how the situation is defined (i.e. regex, etc).

  • attacker (str) – 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

  • target (str) – 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

  • severity (str) – severity for this situation. Valid values are critical, high, low, information

  • description (str) – optional description

  • comment (str) – optional comment

create_regular_expression(regexp)[source]

Create a regular expression for this inspection situation context. The inspection situation must be using an inspection context that supports regex.

Parameters:

regexp (str) – regular expression string

Raises:

CreateElementFailed – failed to modify the situation

property vulnerability_references

If this inspection situation has associated CVE, OSVDB, BID, etc references, this will return those reference IDs

Return type:

list(str)

class smc.elements.situations.InspectionSituationContext(name=None, **meta)[source]

Bases: SituationContext

Represents groups of situation contexts that can be characterized by a common technique used for identifying the situation. Contexts also typically have in common the type of situation they apply to, i.e. File Text Stream would be an inspection context, and encapsulates inspection situations such as ActiveX in text file stream detection, etc.

class smc.elements.situations.Situation(name=None, **meta)[source]

Bases: Element

Situation defines a common interface for inspection and correlated situations.

property attacker

How the Attacker is determined when the Situation matches. This information is used for blacklisting and in log entries and may be None

Return type:

str or None

property description

The description for this situation

Return type:

str

property parameter_values

Parameter values for this inspection situation. This correlate to the the situation_context.

Return type:

list(SituationParameterValue)

property severity

The severity of this inspection situation, critical, high, low, information

Return type:

int

property target

How the Target is determined when the Situation matches. This information is used for blacklisting and in log entries and may be None

Return type:

str or None

class smc.elements.situations.SituationContext(name=None, **meta)[source]

Bases: Element

A situation context can be used by an inspection situation or by a correlated situation. The context defines the situation parameters used to define a pattern match and how that match is made.

Variables:
  • name (str) – name of this situation context

  • comment (str) – comment for the context

property description

Description for this context

Return type:

str

property situation_parameters

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.

Return type:

list(SituationParameter)

class smc.elements.situations.SituationContextGroup(name=None, **meta)[source]

Bases: Element

A situation context group is simply a top level group for organizing individual situation contexts. This is a top level element that can be retrieved directly:

>>> from smc.elements.situations import SituationContextGroup
>>> for group in SituationContextGroup.objects.all():
...   group
...
SituationContextGroup(name=DoS Detection)
SituationContextGroup(name=FINGER)
SituationContextGroup(name=SMTP Deprecated)
SituationContextGroup(name=PPTP)
SituationContextGroup(name=IPv6)
SituationContextGroup(name=NETBIOS)
SituationContextGroup(name=SIP)
SituationContextGroup(name=SNMP)
...
Variables:

sub_elements (list(InspectionContext, InspectionContextGroup)) – the members of this inspection context group

class smc.elements.situations.SituationParameter(**meta)[source]

Bases: SubElement

A situation parameter defines the parameter type used to define the inspection situation context. For example, Regular Expression would be a situation parameter.

property display_name

The display name as shown in the SMC

Return type:

str

property order

The order placement for this parameter. This is only relevant when there are multiple parameters in an inspection context definition.

Return type:

int

property type

The type of this situation parameter in textual format. For example, integer, regexp, etc.

Return type:

str

class smc.elements.situations.SituationParameterValue(**meta)[source]

Bases: SubElement

The situation parameter value is associated with a situation parameter and as the name implies, provides the value payload for the given parameter.

class smc.elements.situations.SubTLSMatchSituation(name=None, **meta)[source]

Bases: Situation

Used by TLSMatchSituation

classmethod create(name, context)[source]

Create the sub tls match situation Used by TLSMatchSituation

Parameters:
  • name (str) – name of sub tls match

  • context (str) – context for sub tls match

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

SubTLSMatchSituation

class smc.elements.situations.TLSMatchSituation(name=None, **meta)[source]

Bases: Situation

TLS Match elements define matching criteria for the use of the TLS protocol in traffic, and allow you to prevent the specified traffic from being decrypted. TLS Matches that deny decrypting are applied globally, even if the TLS Match elements are not used in the policy. However, TLS Match elements that are used in specific Access rules can override globally-applied TLS matches.

classmethod create(name, matching_domains=None, match_certificate_validation='succeed_tls_validation', validation_failed_matches=None, deny_decrypting=False, comment=None)[source]

Create TLS Match

Parameters:
  • name (str) –

  • matching_domains (list) – list of domain url’s

  • match_certificate_validation (str) – possible values:

  • “succeed_tls_validation” to be used with matching_domains parameter

  • “no_validation”

  • “validation_failed” to be used with validation_failed_matches parameter

Parameters:

validation_failed_matches (list) – possible values:

  • “match_self_signed_certificates”

  • “match_non_trusted_CAs”

  • “match_expired_certificates”

  • “match_invalid_certificates”

Parameters:
  • deny_decrypting (bool) – deny decrypting default=False

  • comment (str) – optional comment

Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

TLSMatchSituation

class smc.elements.situations.TLSMatchSituationContext(name=None, **meta)[source]

Bases: SituationContext

Used by TLSMatchSituation

Profiles

Profiles are generic container settings that are used in other areas of the SMC configuration. Each profile should document it’s usage and how it is referenced.

DNSRelayProfile

Profiles are templates used in other parts of the system to provide default functionality for specific feature sets. For example, to enable DNS Relay on an engine you must specify a DNSRelayProfile to use which defines the common settings (or sub-settings) for that feature.

A DNS Relay Profile allows multiple DNS related mappings that can be configured. Example usage:

>>> from smc.elements.profiles import DNSRelayProfile
>>> profile = DNSRelayProfile('mynewprofile')

Note

If the DNSRelayProfile does not exist, it will automatically be created when a DNS relay rule is added to the DNSRelayProfile instance.

Add a fixed domain answer rule:

>>> profile.fixed_domain_answer.add([('microsoft3.com', 'foo.com'), ('microsoft4.com',)])
>>> profile.fixed_domain_answer.all()
[{u'domain_name': u'microsoft3.com', u'translated_domain_name': u'foo.com'},
{u'domain_name': u'microsoft4.com'}]

Translate hostnames (not fqdn) to a specific IP address:

>>> profile.hostname_mapping.add([('hostname1,hostname2', '1.1.1.12')])
>>> profile.hostname_mapping.all()
[{u'hostnames': u'hostname1,hostname2', u'ipaddress': u'1.1.1.12'}]

Translate an IP address to another:

>>> profile.dns_answer_translation.add([('12.12.12.12', '172.18.1.20')])
>>> profile.dns_answer_translation.all()
[{u'translated_ipaddress': u'172.18.1.20', u'original_ipaddress': u'12.12.12.12'}]

Specify a DNS server to handle specific domains:

>>> profile.domain_specific_dns_server.add([('myfoo.com', '172.18.1.20')])
>>> profile.domain_specific_dns_server.all()
[{u'dns_server_addresses': u'172.18.1.20', u'domain_name': u'myfoo.com'}]
class smc.elements.profiles.DNSAnswerTranslation(profile)[source]

Bases: DNSRule

Map IPv4 addresses resolved by external DNS servers to IPv4 addresses in the internal network.

add(answers)[source]

Takes an IPv4 address and translates to a specified IPv4 value. Provide a list of two-tuple with the first entry providing the original address and second entry specifying the translated address:

profile = DNSRelayProfile('dnsrules')
profile.dns_answer_translation.add([('12.12.12.12', '172.18.1.20')])
Parameters:

answers (tuple[str, str]) – (original_ipaddress, translated_ipaddress)

Raises:

UpdateElementFailed – failure to add to SMC

Returns:

None

class smc.elements.profiles.DNSRelayProfile(name=None, **meta)[source]

Bases: Element

DNS Relay Settings specify a profile to handle how the engine will interpret DNS queries. The engine can act as a DNS relay, rewrite DNS queries or redirect domains to the specified DNS servers.

property dns_answer_translation

Add a DNS answer translation

Return type:

DNSAnswerTranslation

property domain_specific_dns_server

Add domain to DNS server mapping

Return type:

DomainSpecificDNSServer

property fixed_domain_answer

Add a fixed domain answer entry.

Return type:

FixedDomainAnswer

property hostname_mapping

Add a hostname to IP mapping

Return type:

HostnameMapping

class smc.elements.profiles.DNSRule(profile)[source]

Bases: object

DNSRule is the parent class for all DNS relay rules.

all()[source]

Return all entries

Return type:

list(dict)

class smc.elements.profiles.DomainSpecificDNSServer(profile)[source]

Bases: DNSRule

Forward DNS requests to different DNS servers based on the requested domain.

add(answers)[source]

Relay specific domains to a specified DNS server. Provide a list of two-tuple with first entry the domain name to relay for. The second entry is the DNS server that should handle the query:

profile = DNSRelayProfile('dnsrules')
profile.domain_specific_dns_server.add([('myfoo.com', '172.18.1.20')])
Parameters:

answers (tuple[str, str]) – (domain_name, dns_server_addresses), dns server addresses can be a comma separated string

Raises:

UpdateElementFailed – failure to add to SMC

Returns:

None

class smc.elements.profiles.FixedDomainAnswer(profile)[source]

Bases: DNSRule

Direct requests for specific domains to IPv4 addresses, IPv6 addresses, fully qualified domain names (FQDNs), or empty DNS replies

add(answers)[source]

Add a fixed domain answer. This should be a list of two-tuples, the first entry is the domain name, and the second is the translated domain value:

profile = DNSRelayProfile('dnsrules')
profile.fixed_domain_answer.add([
    ('microsoft.com', 'foo.com'), ('microsoft2.com',)])
Parameters:

answers (tuple[str, str]) – (domain_name, translated_domain_name)

Raises:

UpdateElementFailed – failure to add to SMC

Returns:

None

Note

translated_domain_name can be none, which will cause the NGFW to return NXDomain for the specified domain.

class smc.elements.profiles.HostnameMapping(profile)[source]

Bases: DNSRule

Statically map host names, aliases for host names, and unqualified names (a host name without the domain suffix) to IPv4 or IPv6 addresses

add(answers)[source]

Map specific hostname to specified IP address. Provide a list of two-tuples. The first entry is the hostname/s to translate (you can provide multiple comma separated values). The second entry should be the IP address to map the hostnames to:

profile = DNSRelayProfile('dnsrules')
profile.hostname_mapping.add([('hostname1,hostname2', '1.1.1.1')])
Parameters:

answers (tuple[str, str]) – (hostnames, ipaddress), hostnames can be a comma separated list.

Raises:

UpdateElementFailed – failure to add to SMC

Returns:

None

SNMPAgent

class smc.elements.profiles.SNMPAgent(name=None, **meta)[source]

Bases: Element

Minimal implementation of SNMPAgent

LLDPProfile

class smc.core.lldp.LLDPProfile(name=None, **meta)[source]

Bases: Element

LLDP Profile represents a set of attributes used for configuring LLDP(Link Layer Discovery Protocol). LLDP information is advertised by devices at a fixed interval in the form of LLDP data units represented by TLV structures.

property chassis_id

TLV field: Chassis ID. The MAC address of the first Ethernet port (Always enabled)

classmethod create(name, transmit_delay, hold_time_multiplier, system_name, system_description, system_capabilities, management_address, comment=None)[source]

Create a LLDPProfile. :param str name: name of TLS Profile :param int transmit_delay: The transmit delay determines the delay between any two consecutive LLDP advertisement frames. :param int hold_time_multiplier: Represents the multiplier to apply to the advertisement interval. :param bool system_name: The system name that the SNMP Agent uses :param bool system_description: The system description that the SNMP Agent uses :param bool system_capabilities: Capability bit-map. Depends on the interface type :param bool management_address: Management Address IP addresses of the control interfaces :param str comment: optional comment :raises CreateElementFailed: failed to create element with reason :raises ElementNotFound: specified element reference was not found :rtype: TLSProfile

property hold_time_multiplier

Represents the multiplier to apply to the advertisement interval. The product of the advertisement interval and the hold time multiplier gives cache life time for the learned LLDP information, after which it is discarded.

property management_address

TLV Field: Management Address IP addresses of the control interfaces

property port_description

TLV field: Port Description. The description that the SNMP Agent uses for the interface (Always enabled)

property port_id

TLV field: Port ID. The name that the SNMP Agent uses for the interface (Always enabled)

property system_capabilities

TLV field: System Capabilities. Capability bit-map. Depends on the interface type

property system_description

TLV field: System Description. The system description that the SNMP Agent uses

property system_name

TLV field: System Name. The system name that the SNMP Agent uses

property time_to_live

TLV field: Time to Live. Automatically calculated based on transmit delay and hold time multiplier (Always enabled)

property transmit_delay

The transmit delay determines the delay between any two consecutive LLDP advertisement frames.

Engine

class smc.core.engine.Engine(name=None, **meta)[source]

Bases: Element

An engine is the top level representation of a firewall, IPS or virtualized software.

Engine can be referenced directly and will be loaded when attributes are accessed:

>>> from smc.core.engine import Engine
>>> engine = Engine('testfw')
>>> print(engine.href)
http://1.1.1.1:8082/6.1/elements/single_fw/39550

Generically search for engines of all types:

>>> list(Engine.objects.all())
[Layer3Firewall(name=i-06145fc6c59a04335 (us-east-2a)), FirewallCluster(name=sg_vm),
Layer3VirtualEngine(name=ve-5), MasterEngine(name=master-eng)]

Or only search for specific engine types:

>>> from smc.core.engines import Layer3Firewall
>>> list(Layer3Firewall.objects.all())
[Layer3Firewall(name=i-06145fc6c59a04335 (us-east-2a))]

Engine types are defined in smc.core.engines.

add_interface(interface, **kw)[source]

Add interface is a lower level option to adding interfaces directly to the engine. The interface is expected to be an instance of Layer3PhysicalInterface, Layer2PhysicalInterface, TunnelInterface, or ClusterInterface. The engines instance cache is flushed after this call is made to provide an updated cache after modification.

See also

smc.core.engine.interface.update_or_create

Parameters:

interface (PhysicalInterface,TunnelInterface) – instance of pre-created interface

Returns:

None

Add link_usage_exception_rules/s to this engine.

Parameters:

link_usage_exception_rules (list(link_usage_exception_rules)) – link_usage_exception_rules/s to add to engine

Raises:

UpdateElementFailed – failed updating engine

Returns:

None

add_route(gateway=None, network=None, payload=None)[source]

Add a route to engine. Specify gateway and network. If this is the default gateway, use a network address of 0.0.0.0/0.

Parameters:
  • gateway (str) – gateway of an existing interface

  • network (str) – network address in cidr format

  • payload (href) –

    the payload to add route with href of element Example:

    {“gateway_ip”: X.Y.Z.Z, “network_ip”: A.B.C.D} OR {“gateway_ref”: href, “network_ref”: href}

Raises:

EngineCommandFailed – invalid route, possibly no network

Returns:

None

property adsl_interface

Get only adsl interfaces for this engine node.

Raises:

UnsupportedInterfaceType – adsl interfaces are only supported on layer 3 engines

Returns:

list of dict entries with href,name,type, or None

alias_resolving()[source]

Alias definitions with resolved values as defined on this engine. Aliases can be used in rules to simplify multiple object creation

fw = Engine('myfirewall')
for alias in fw.alias_resolving():
    print(alias, alias.resolved_value)
...
(Alias(name=$$ Interface ID 0.ip), [u'10.10.0.1'])
(Alias(name=$$ Interface ID 0.net), [u'10.10.0.0/24'])
(Alias(name=$$ Interface ID 1.ip), [u'10.10.10.1'])
Returns:

generator of aliases

Return type:

Alias

property all_vpns

Engine level all VPN gateway information. Example:

>>> list_of_all_internal_gateways=engine.all_vpns
>>> first_vpn_instance= list_of_all_internal_gateways[0]
>>> first_vpn_instance.name
Raises:

UnsupportedEngineFeature – internal gateway is only supported on layer 3 engine types.

Returns:

list of engine internal gateways

Return type:

List of All VPN Gateway Configuration

property antispoofing

Antispoofing interface information. By default is based on routing but can be modified.

for entry in engine.antispoofing.all():
    print(entry)
Returns:

top level antispoofing node

Return type:

Antispoofing

property antivirus

AntiVirus engine settings. Note that for virtual engines the AV settings are configured on the Master Engine. Get current status:

engine.antivirus.status
Raises:

UnsupportedEngineFeature – Invalid engine type for AV

Return type:

AntiVirus

property automatic_rules_settings

Represents the container for all automatic rules settings for a cluster. Example of using automatic rules settings:

>>> engine = Engine("testme")
>>> automatic_rules_settings=engine.automatic_rules_settings
>>> update_automatic_rules_settings(allow_auth_traffic=False, allow_no_nat=False)
>>> engine.update()
>>> engine.automatic_rules_settings.allow_auth_traffic
    False
>>> engine.automatic_rules_settings.allow_listening_interfaces_to_dns_relay_port
    True
Return type:

AutomaticRulesSettings

blacklist(src, dst, duration=3600, **kw)[source]

Add blacklist entry to engine node by name. For blacklist to work, you must also create a rule with action “Apply Blacklist”.

Parameters:
  • src – source address, with cidr, i.e. 10.10.10.10/32 or ‘any’

  • dst – destination address with cidr, i.e. 1.1.1.1/32 or ‘any’

  • duration (int) – how long to blacklist in seconds

Raises:

EngineCommandFailed – blacklist failed during apply

Returns:

None

Note

This method requires SMC version >= 6.4 and SMC version <7.0

since this version, “blacklist” is renamed “block_list”

blacklist_bulk(block_list)[source]

Add block list entries to the engine node in bulk. For block list to work, you must also create a rule with action “Apply Block List”. First create your block_list entries using smc.elements.other.Blacklist then provide the block list to this method.

:param Blacklist block_list : pre-configured block list entries

Note

This method requires SMC version >= 6.4 and SMC version <7.0

since this version, “blacklist” is renamed “block_list”

blacklist_flush()[source]

Flush entire blacklist for engine

Raises:

EngineCommandFailed – flushing blacklist failed with reason

Returns:

None

Note

This method requires SMC version < 7.0

since this version, “blacklist” is renamed “block_list”

blacklist_show(**kw)[source]

New in version 0.5.6: Requires pip install smc-python-monitoring

Blacklist show requires that you install the smc-python-monitoring package. To obtain Blacklist entries from the engine you need to use this extension to plumb the websocket to the session. If you need more granular controls over the blacklist such as filtering by source and destination address, use the smc-python-monitoring package directly. Blacklist entries that are returned from this generator have a delete() method that can be called to simplify removing entries. A simple query would look like:

for bl_entry in engine.blacklist_show():
    print(bl_entry)
Parameters:

kw – keyword arguments passed to blacklist query. Common setting is to pass max_recv=20, which specifies how many “receive” batches will be retrieved from the SMC for the query. At most, 200 results can be returned in a single query. If max_recv=5, then 1000 results can be returned if they exist. If less than 1000 events are available, the call will be blocking until 5 receives has been reached.

Returns:

generator of results

Return type:

smc_monitoring.monitors.blacklist.BlacklistEntry

Note

This method requires SMC version < 7.0

since this version, “blacklist” is renamed “block_list”

block_list(src, dst, duration=3600, **kw)[source]

Add block_list entry to engine node by name. For block_list to work, you must also create a rule with action “Apply Blocklist”.

Parameters:
  • src – source address, with cidr, i.e. 10.10.10.10/32 or ‘any’

  • dst – destination address with cidr, i.e. 1.1.1.1/32 or ‘any’

  • duration (int) – how long to block list in seconds

Raises:

EngineCommandFailed – block list failed during apply

Returns:

None

Note

This method requires SMC version >= 7.0

block_list_bulk(block_list)[source]

Add block_list entries to the engine node in bulk. For block_list to work, you must also create a rule with action “Apply Blocklist”. First create your block_list entries using smc.elements.other.Blocklist then provide the block_list to this method.

:param Blocklist block_list : pre-configured block_list entries

Note

This method requires SMC version >= 7.0

block_list_flush()[source]

Flush entire block list for engine

Raises:

EngineCommandFailed – flushing block list failed with reason

Returns:

None

Note

This method requires SMC version >= 7.0

block_list_show(**kw)[source]

New in version 0.5.6: Requires pip install smc-python-monitoring

Block list show requires that you install the smc-python-monitoring package. To obtain Blocklist entries from the engine you need to use this extension to plumb the websocket to the session. If you need more granular controls over the block_list such as filtering by source and destination address, use the smc-python-monitoring package directly. Blocklist entries that are returned from this generator have a delete() method that can be called to simplify removing entries. A simple query would look like:

for bl_entry in engine.block_list_show():
    print(bl_entry)
Parameters:

kw – keyword arguments passed to block list query. Common setting is to pass max_recv=20, which specifies how many “receive” batches will be retrieved from the SMC for the query. At most, 200 results can be returned in a single query. If max_recv=5, then 1000 results can be returned if they exist. If less than 1000 events are available, the call will be blocking until 5 receives has been reached.

Returns:

generator of results

Return type:

smc_monitoring.monitors.blocklist.BlocklistEntry

property client_inspection

Client TLS Inspection settings manage certificates assigned to the engine for TLS client decryption (outbound). In order to enable either, you must first assign certificates to the engine. Example of adding ClientInspection to an engine:

>>> engine = Engine('myfirewall')
>>> tls = ClientInspection('client.test.local')
>>> engine.client_inspection.enable(tls)
>>> engine.update()
Return type:

ClientInspection

property connection_timeout

This is definition of timeout by protocol or by TCP connection state. You can define general timeouts for removing idle connections from the state table, including non-TCP communications that are handled like connections. The timeout prevents wasting engine resources on storing information about abandoned connections. Timeouts are a normal way to clear traffic information with protocols that have no closing mechanism.Timeouts do not affect active connections. The connections are kept in the state table as long as the interval of packets within a connection is shorter than the timeouts set. Example of using idle time out settings:

>>> engine = Engine("testme")
>>> connection_timeout=engine.connection_timeout
>>> connection_timeout.add('tcp_syn_seen',120)
>>> engine.connection_timeout.data
    {'connection_timeout': [{'protocol': 'tcp', 'timeout': 1800}, {'protocol': 'udp',
    'timeout': 50}, {'protocol': 'icmp', 'timeout': 5}, {'protocol': 'other', 'timeout':
     180}, {'protocol': 'tcp_syn_seen', 'timeout': 120}]}
>>> engine.update()
>>> engine.connection_timeout.data
>>> connection_timeout.remove('tcp_syn_seen')
    {'connection_timeout': [{'protocol': 'tcp', 'timeout': 1800}, {'protocol': 'udp',
    'timeout': 50}, {'protocol': 'icmp', 'timeout': 5}, {'protocol': 'other', 'timeout':
     180}]}
Return type:

IdleTimeout

property contact_addresses

Contact addresses are NAT addresses that are assigned to interfaces. These are used when a component needs to communicate with another component through a NAT’d connection. For example, if a firewall is known by a pubic address but the interface uses a private address, you would assign the public address as a contact address for that interface.

Note

Contact addresses are only supported with SMC >= 6.2.

Obtain all eligible interfaces for contact addressess:

>>> engine = Engine('dingo')
>>> for ca in engine.contact_addresses:
...   ca
...
ContactAddressNode(interface_id=11, interface_ip=10.10.10.20)
ContactAddressNode(interface_id=120, interface_ip=120.120.120.100)
ContactAddressNode(interface_id=0, interface_ip=1.1.1.1)
ContactAddressNode(interface_id=12, interface_ip=3.3.3.3)
ContactAddressNode(interface_id=12, interface_ip=17.17.17.17)

This is set to a private method because the logic doesn’t make sense with respects to how this is configured under the SMC.

Return type:

ContactAddressCollection(ContactAddressNode)

create_internal_gateway(name, antivirus=None, auto_certificate=None, auto_site_content=None, dhcp_relay=None, end_point=None, firewall=None, gateway_profile=None, ssl_vpn_portal_setting=None, ssl_vpn_proxy=None, ssl_vpn_tunneling=None, trust_all_cas=None, trusted_certificate_authorities=None, vpn_client_mode=None, **kwargs)[source]

Create internal gateway Example of creating internal gateway:

>>> engine.create_internal_gateway("test")
Parameters:
  • name (str) – Name of the internal gateway

  • antivirus (str) – Antivirus

  • auto_certificate (str) – Automated RSA Certificate Management

  • auto_site_content (str) – Indicates whether the site content is automatically generated from the routing view.

  • dhcp_relay (str) – DHCP Relay.

  • end_point (str) – List of end-points.

  • firewall (str) – Firewall

  • gateway_profile (str) – Gateway Profile

  • ssl_vpn_portal_setting (str) – SSL VPN Settings for the Portal.

  • ssl_vpn_proxy (str) – vpn proxy

  • ssl_vpn_tunneling (str) – SSL VPN Settings for the VPN Client.

  • trust_all_cas (str) – Indicates if the EndPoint trust all VPN Certificate Authorities.

  • trusted_certificate_authorities (str) – List of trusted VPN Certificate Authorities. Valid only if the EndPoint does not trust all VPN CAs.

  • vpn_client_mode (str) – VPN Client Mode accepted values given below: *no *ipsec *ssl *both

Raises:

UnsupportedEngineFeature – internal gateway is only supported on layer 3 engine types

Returns:

None

Return type:

None

property default_nat

Configure default nat on the engine. Default NAT provides automatic NAT without the requirement to add specific NAT rules. This is a more common configuration for outbound traffic. Inbound traffic will still require specific NAT rules for redirection.

Return type:

DefaultNAT

delete_user_authentication_certificate()[source]

Delete the certificate if any is defined for this component.

delete_user_authentication_certificate_request()[source]

Delete the certificate request if any is defined for this component.

property discard_quic_if_cant_inspect

Discard or allow QUIC if inspection is impossible

Return type:

bool

property dns

Current DNS entries for the engine. Add and remove DNS entries. This resource is iterable and yields instances of smc.core.addon.DNSEntry. Example of adding entries:

>>> from smc.elements.servers import DNSServer
>>> server = DNSServer.create(name='mydnsserver', address='10.0.0.1')
>>> engine.dns.add(['8.8.8.8', server])
>>> engine.update()
'http://172.18.1.151:8082/6.4/elements/single_fw/948'
>>> list(engine.dns)
[DNSEntry(rank=0,value=8.8.8.8,ne_ref=None),
 DNSEntry(rank=1,value=None,ne_ref=DNSServer(name=mydnsserver))]
Return type:

RankedDNSAddress

property dns_relay

Enable, disable or get status for the DNS Relay Service on this engine. You must still separately configure the smc.elements.profiles.DNSRelayProfile that the engine references.

Raises:

UnsupportedEngineFeature – unsupported feature on this engine type.

Return type:

DNSRelay

property dynamic_routing

Dynamic Routing entry point. Access BGP, OSPF configurations

Raises:

UnsupportedEngineFeature – Only supported on layer 3 engines

Return type:

DynamicRouting

property endpoint_integration

Endpoint Integration status on engine. Note that for master engines the endpoint integrations settings are configured on Virtual Engines. Get current status:

engine.endpoint_integration.status
Raises:

UnsupportedEngineFeature – Invalid engine type for file rep

Return type:

EndpointIntegration

export_user_authentication_certificate(filename=None)[source]

Export the certificate if any is defined for this component.

export_user_authentication_certificate_request(filename=None)[source]

Export the certificate request if any is defined for this component.

property file_reputation

File reputation status on engine. Note that for virtual engines the AV settings are configured on the Master Engine. Get current status:

engine.file_reputation.status
Raises:

UnsupportedEngineFeature – Invalid engine type for file rep

Return type:

FileReputation

generate_and_sign_user_authentication_certificate()[source]

Generate and internally sign User Authentication certificate.

generate_snapshot(filename='snapshot.zip')[source]

Generate and retrieve a policy snapshot from the engine This is blocking as file is downloaded

Parameters:

filename (str) – name of file to save file to, including directory path

Raises:

EngineCommandFailed – snapshot failed, possibly invalid filename specified

Returns:

None

generate_user_authentication_certificate_request()[source]

Export the certificate request for the node when working external CA. This can return None if the engine type does not have a certificate request.

Raises:

CertificateExportError – error exporting certificate

Return type:

str or None

property geolocation

Return the geolocation for the given engine. This attribute requires at least SMC version >= 6.5.x. If no geolocation is assigned or the SMC is not a correct version this will return None. If setting a new geolocation, call update() after modification.

Example:

>>> from smc.elements.other import Geolocation
>>> engine = Engine('azure')

>>> geo = Geolocation.create(name='MyGeo', latitude='44.97997', longitude='-93.26384')
>>> geo
Geolocation(name=MyGeo)
>>> engine.geolocation = geo
>>> engine.update()
>>> engine.geolocation
Geolocation(name=MyGeo)
Parameters:

value (Geolocation) – Geolocation to assign engine. Can be str href or type Geolocation element.

Return type:

Geolocation or None

get_session_monitoring(sesmon_type, full=True)[source]

Available for all SMC API Versions but only for SMC Version above 7.1 (7.1 included)

Return session monitoring for the requested session monitoring type for the engine Find all routes for engine resource:

:param sesmon_type requested session monitoring type. Possible value are defined

in session_monitoring.EngineSessionMonitoringType

:optional param full ( default value is true ). When set to false, juste retrieve

the log key of each entry ( timestamp, component id, event id ).

:raises EngineCommandFailed : session monitoring result cannot be retrieved :return: list of session monitoring entries : session_monitoring.SessionMonitoringResult :rtype: SerializedIterable(Route)

Example:

from smc.core.session_monitoring import EngineSessionMonitoringType engine.get_session_monitoring(EngineSessionMonitoringType.CONNECTION)

property granted_permissions

Retrieve the access control list permissions for this engine instance.

>>> from smc.core.engine import Engine
>>> engine = Engine('myfirewall')
>>> for x in engine.permissions.granted_permissions:
...   print(x)
...
AccessControlList(name=ALL Elements)
AccessControlList(name=ALL Firewalls)
Raises:

UnsupportedEngineFeature – requires SMC version >= 6.1

Returns:

access control list permissions

Return type:

list(AccessControlList)

property installed_policy

Return the name of the policy installed on this engine. If no policy, None will be returned.

Return type:

str or None

property interface

Get all interfaces, including non-physical interfaces such as tunnel or capture interfaces. These are returned as Interface objects and can be used to load specific interfaces to modify, etc.

for interfaces in engine.interface:
    ......
Return type:

InterfaceCollection

See smc.core.interfaces.Interface for more info

property interface_options

Interface options specify settings related to setting primary/ backup management, outgoing, and primary/backup heartbeat interfaces. For example, set primary management interface (this unsets it from the currently assigned interface):

engine.interface_options.set_primary_mgt(10)

Obtain the primary management interface:

print(engine.interface_options.primary_mgt)
Return type:

InterfaceOptions

property internal_gateway

Engine level VPN gateway information. This is a link from the engine to VPN level settings like VPN Client, Enabling/disabling an interface, adding VPN sites, etc. Example of adding a new VPN site to the engine’s site list with associated networks:

>>> network = Network.get_or_create(name='mynetwork', ipv4_network='1.1.1.0/24')
Network(name=mynetwork)
>>> engine.internal_gateway.vpn_site.create(name='mynewsite', site_element=[network])
VPNSite(name=mynewsite)
Raises:

UnsupportedEngineFeature – internal gateway is only supported on layer 3 engine types.

Returns:

this engines internal gateway

Return type:

InternalGateway

property known_host_lists

Configure SSH known host lists on the engine. Can only be set if Sidewinder Proxy is enabled.

Raises:

MissingRequiredInput – requires sidewinder proxy to be enabled

Return type:

KnownHostLists

property l2fw_settings

Layer 2 Firewall Settings make it possible for a layer 3 firewall to run specified interfaces in layer 2 mode. This requires that a layer 2 interface policy is assigned to the engine and that inline_l2fw interfaces are created.

Raises:

UnsupportedEngineFeature – requires layer 3 engine

Return type:

Layer2Settings

property lbfilter_useports

Load Balancing Filter use ports :raises UnsupportedEngineFeature: Invalid engine type :rtype: bool

property lbfilters

Load balancing filter list :raises UnsupportedEngineFeature: Invalid engine type :rtype: list LBFilter

ldap_replication(enable)[source]

Enable or disable LDAP replication

Raises:

EngineCommandFailed – the LDAP replication is already enabled or disabled

Parameters:

enable (boolean) – True enable the LDAP replication False disable it

A collection of link_usage_exception_rules

Return type:

list(LinkUsageExceptionRules)

Represent link usage profile :param value: Link usage profile to assign engine. Can be str href, or LinkUsageProfile element. :raises UpdateElementFailed: failure to update element :return: LinkUsageProfile element or None

property lldp_profile

It represents a set of attributes used for configuring LLDP(Link Layer Discovery Protocol). LLDP information is advertised by devices at a fixed interval in the form of LLDP data units represented by TLV structures.

Parameters:

value – LLDP Profile to assign engine. Can be str href, or LLDPProfile element.

Raises:

UpdateElementFailed – failure to update element

Returns:

LLDPProfile element or None

property local_log_storage

Local Log Storage Settings for not virtual engines. Example of using local log storage settings:

>>> engine = Engine("testme")
>>> local_log_storage=engine.local_log_storage
>>> local_log_storage.local_log_storage_activated
    True
>>> local_log_storage.lls_max_time
    10
>>> local_log_storage.update(lls=20_max_time)
>>> engine.update()
>>> local_log_storage=engine.local_log_storage
>>> local_log_storage.lls_max_time
    20

:rtype LocalLogStorageSettings

property location

The location for this engine. May be None if no specific location has been assigned.

Parameters:

value – location to assign engine. Can be name, str href, or Location element. If name, it will be automatically created if a Location with the same name doesn’t exist.

Raises:

UpdateElementFailed – failure to update element

Returns:

Location element or None

property log_moderation

This is the definition of Log Compression for the engine or for an interface. You can also configure Log Compression to save resources on the engine. By default, each generated Antispoofing and Discard log entry is logged separately and displayed as a separate entry in the Logs view. Log Compression allows you to define the maximum number of separately logged entries.When the defined limit is reached, a single Antispoofing log entry or Discard log entry is logged. The single entry contains information on the total number of the generated Antispoofing log entries or Discard log entries. After this, logging returns to normal and all the generated entries are once more logged and displayed separately. Example of using log moderation settings:

>>> engine = Engine("testme")
>>> log_moderation_obj=engine.log_moderation
>>> log_moderation_obj.get(1)["rate"]
    100
>>> log_moderation_obj.get(1)["burst"]
    1000
>>> log_moderation_obj.add(rate=200,burst=1100,log_event=2)
>>> engine.update(log_spooling_policy='discard')
>>> log_moderation_obj=engine.log_moderation
>>> log_moderation_obj.get(2)["rate"]
    200
>>> log_moderation_obj.get(2)["burst"]
    1100

:rtype LogModeration

property log_server

Log server for this engine.

Returns:

The specified log server

Return type:

LogServer

property loopback_interface

Retrieve any loopback interfaces for this engine. Loopback interfaces are only supported on layer 3 firewall types.

Retrieve all loopback addresses:

for loopback in engine.loopback_interface:
    print(loopback)
Raises:

UnsupportedInterfaceType – supported on layer 3 engine only

Return type:

LoopbackCollection

property modem_interface

Get only modem interfaces for this engine node.

Raises:

UnsupportedInterfaceType: modem interfaces are only supported on layer 3 engines

Returns:

list of dict entries with href,name,type, or None

property nodes

Return a list of child nodes of this engine. This can be used to iterate to obtain access to node level operations

>>> print(list(engine.nodes))
[Node(name=myfirewall node 1)]
>>> engine.nodes.get(0)
Node(name=myfirewall node 1)
Returns:

nodes for this engine

Return type:

SubElementCollection(Node)

property ntp_settings

NTP settings definition for the engine :rtype: NTPSettings

property pending_changes

Pending changes provides insight into changes on an engine that are pending approval or disapproval. Feature requires SMC >= v6.2.

Raises:

UnsupportedEngineFeature – SMC version >= 6.2 is required to support pending changes

Return type:

PendingChanges

property permissions

Retrieve the permissions for this engine instance. :rtype: GrantedElementPermissions

Note

This method has changed in fp-NGFW-SMC-python >= 1.0.24 so need to make your script compatible with this change.” .. seealso:: smc.administration.access_rights.GrantedElementPermissions.

property physical_interface

Returns a PhysicalInterface. This property can be used to add physical interfaces to the engine. For example:

engine.physical_interface.add_inline_interface(....)
engine.physical_interface.add_layer3_interface(....)
Raises:

UnsupportedInterfaceType – engine doesn’t support this type

Return type:

PhysicalInterfaceCollection

property policy_route

Configure policy based routes on the engine.

engine.policy_route.create(
    source='172.18.2.0/24', destination='192.168.3.0/24',
    gateway_ip='172.18.2.1')
Return type:

PolicyRoute

query_route(source_ref=None, destination_ref=None, source_ip=None, destination_ip=None)[source]

Allows querying a route for the specific supported engine Options: A. Using Query Parameters:

source_ip: the IP Address A.B.C.D corresponding to the source query ip address. destination_ip: the IP Address A.B.C.D corresponding to the destination query ip address

  1. Using payload to be able to specify source network element uri

    and/or destination network element uri.

Find route for source to destination using ip address
>>> engine = Engine('Plano')
>>> engine.query_route(source_ip='0.0.0.0', destination_ip= '0.0.0.0')
[Routing(name=Interface 1,level=None,type=routing), Routing(name=net-172.31.14.0/24,
level=None,type=routing), Routing(name=AT&T Plano Router,level=None,type=routing),
 Routing(name=Any network,level=None,type=routing)]
Find the route using query route with ref
>>> list_of_routing = list(Host.objects.all())
>>> host1 = list_of_routing[0]
>>> host2 = list_of_routing[1]
>>> engine.query_route(source_ref=host1.href, destination_ref=host2.href)
Parameters:
  • source_ref (str) – specify source network element uri

  • destination_ref (str) – destination network element uri

  • source_ip (str) – source ip address

  • destination_ip (str) – destination ip address

Return list(Routing):

the result pages containing the result routing.

refresh(timeout=3, wait_for_finish=False, preserve_connections=True, generate_snapshot=True, **kw)[source]

Refresh existing policy on specified device. This is an asynchronous call that will return a ‘follower’ link that can be queried to determine the status of the task.

poller = engine.refresh(wait_for_finish=True)
while not poller.done():
    poller.wait(5)
    print('Percentage complete {}%'.format(poller.task.progress))
Parameters:
  • timeout (int) – timeout between queries

  • wait_for_finish (bool) – poll the task waiting for status

  • preserve_connections (bool) – flag to preserve connections (True by default)

  • generate_snapshot (bool) – flag to generate snapshot (True by default)

Raises:

TaskRunFailed – refresh failed, possibly locked policy

Return type:

TaskOperationPoller

remove_alternative_policies()[source]

Remove all alternative policies on engine.

Remove a link_usage_exception_rules from this engine.

Parameters:

link_usage_exception_rules (link_usage_exception_rules) – element to remove

Returns:

remove element if it exists and return bool

Return type:

bool

rename(name)[source]

Rename the firewall engine, nodes, and internal gateway (VPN gw)

Returns:

None

property routing

Find all routing nodes within engine:

for routing in engine.routing.all():
    for routes in routing:
        ...

Or just retrieve a routing configuration for a single interface:

interface = engine.routing.get(0)
Returns:

top level routing node

Return type:

Routing

property routing_monitoring

Return route table for the engine, including gateway, networks and type of route (dynamic, static). Calling this can take a few seconds to retrieve routes from the engine.

Find all routes for engine resource:

>>> engine = Engine('sg_vm')
>>> for route in engine.routing_monitoring:
...   route
...
Route(route_network=u'0.0.0.0', route_netmask=0, route_gateway=u'10.0.0.1',
      route_type=u'Static', dst_if=1, src_if=-1)
...
Raises:

EngineCommandFailed – routes cannot be retrieved

Returns:

list of route elements

Return type:

SerializedIterable(Route)

property sandbox

Configure sandbox settings on the engine. Get current status:

engine.sandbox.status
Raises:

UnsupportedEngineFeature – not supported on virtual engine

Return type:

Sandbox

property sidewinder_proxy

Configure Sidewinder Proxy settings on this engine. Sidewinder proxy is supported on layer 3 engines and require SMC and engine version >= 6.1. Get current status:

engine.sidewinder_proxy.status
Raises:

UnsupportedEngineFeature – requires layer 3 engine

Return type:

SidewinderProxy

property snapshots

References to policy based snapshots for this engine, including the date the snapshot was made

Raises:

EngineCommandFailed – failure downloading, or IOError

Return type:

SubElementCollection(Snapshot)

property snmp

SNMP engine settings. SNMP is supported on all engine types, however can be enabled only on NDI interfaces (interfaces that have assigned addresses).

Return type:

SNMP

property switch_physical_interface

Get only switch physical interfaces for this engine node. This is an iterable property:

for interface in engine.switch_physical_interface:
    ...

Or you can fetch a switch port interface/module directly by using the generic interface property:

engine.interface.get('SWP_0')

Or through this property directly:

engine.switch_physical_interface.get('SWP_0')
Raises:

UnsupportedInterfaceType – switch interfaces are only supported on specific firewall models

Returns:

list of dict entries with href,name,type, or None

property tls_inspection

TLS Inspection settings manage certificates assigned to the engine for TLS server decryption (inbound) and TLS client decryption (outbound). In order to enable either, you must first assign certificates to the engine. Example of adding TLSServerCredentials to an engine:

>>> engine = Engine('myfirewall')
>>> tls = TLSServerCredential('server2.test.local')
>>> engine.tls_inspection.add_tls_credential([tls])
>>> engine.tls_inspection.server_credentials
[TLSServerCredential(name=server2.test.local)]
Return type:

TLSInspection

property tunnel_interface

Get only tunnel interfaces for this engine node.

Raises:

UnsupportedInterfaceType – supported on layer 3 engine only

Return type:

TunnelInterfaceCollection

upload(policy=None, timeout=5, wait_for_finish=False, preserve_connections=True, generate_snapshot=True, **kw)[source]

Upload policy to engine. This is used when a new policy is required for an engine, or this is the first time a policy is pushed to an engine. If an engine already has a policy and the intent is to re-push, then use refresh() instead. The policy argument can use a wildcard * to specify in the event a full name is not known:

engine = Engine('myfw')
task = engine.upload('Amazon*', wait_for_finish=True)
for message in task.wait():
    print(message)
Parameters:
  • policy (str) – name of policy to upload to engine; if None, current policy

  • wait_for_finish (bool) – poll the task waiting for status

  • timeout (int) – timeout between queries

  • preserve_connections (bool) – flag to preserve connections (True by default)

  • generate_snapshot (bool) – flag to generate snapshot (True by default)

Raises:

TaskRunFailed – upload failed with reason

Return type:

TaskOperationPoller

upload_alternative_slot(alternative_slot=None, policy=None, timeout=5, wait_for_finish=False, generate_snapshot=True, **kw)[source]

Upload policy to engine alternative slot. This is used when multiple policies are required for an engine. If an engine already has a policy and the intent is to re-push, then use refresh() instead. The policy argument can use a wildcard * to specify in the event a full name is not known:

engine = Engine('myfw')
task = engine.upload_alternative_slot(1, 'Amazon*', wait_for_finish=True)
for message in task.wait():
    print(message)
Parameters:
  • alternative_slot (int) – Slot of policy to upload to engine(1 to 3)

  • policy (str) – name of policy to upload to engine; if None, current policy

  • wait_for_finish (bool) – poll the task waiting for status

  • timeout (int) – timeout between queries

  • generate_snapshot (bool) – flag to generate snapshot (True by default)

Raises:

TaskRunFailed – upload failed with reason

Return type:

TaskOperationPoller

property url_filtering

Configure URL Filtering settings on the engine. Get current status:

engine.url_filtering.status
Raises:

UnsupportedEngineFeature – not supported on virtual engines

Return type:

UrlFiltering

user_authentication_import_certificate(certificate)[source]

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.

Parameters:

certificate (str) – fully qualified path or string

Raises:
property version

Version of this engine. Can be none if the engine has not been initialized yet.

Return type:

str or None

property virtual_physical_interface

Master Engine virtual instance only

A virtual physical interface is for a master engine virtual instance. This interface type is just a subset of a normal physical interface but for virtual engines. This interface only sets Auth_Request and Outgoing on the interface.

To view all interfaces for a virtual engine:

for intf in engine.virtual_physical_interface:
    print(intf)
Raises:

UnsupportedInterfaceType – supported on virtual engines only

Return type:

VirtualPhysicalInterfaceCollection

property virtual_resource

Available on a Master Engine only.

To get all virtual resources call:

engine.virtual_resource.all()
Raises:

UnsupportedEngineFeature – master engine only

Return type:

CreateCollection(VirtualResource)

property vpn

VPN configuration for the engine.

Raises:

UnsupportedEngineFeature: VPN is only supported on layer 3 engines.

Return type:

VPN

property vpn_broker_interface

Get only vpn broker interfaces for this engine node.

Raises:

UnsupportedInterfaceType – supported on layer 3 engine only

Return type:

VPNBrokerInterfaceCollection

property vpn_endpoint

A VPN endpoint is an address assigned to a layer 3 interface that can be enabled to turn on VPN capabilities. As an interface may have multiple IP addresses assigned, the endpoints are returned based on the address. Endpoints are properties of the engines Internal Gateway.

Raises:

UnsupportedEngineFeature – only supported on layer 3 engines

Return type:

SubElementCollection(InternalEndpoint)

property vpn_mappings

New in version 0.6.0: Requires SMC version >= 6.3.4

VPN policy mappings (by name) for this engine. This is a shortcut method to determine which VPN policies are used by the firewall.

Raises:

UnsupportedEngineFeature – requires a layer 3 firewall and SMC version >= 6.3.4.

Return type:

VPNMappingCollection(VPNMapping)

property wireless_interface

Get only wireless interfaces for this engine node.

Raises:

UnsupportedInterfaceType – wireless interfaces are only supported on layer 3 engines

Returns:

list of dict entries with href,name,type, or None

class smc.core.engine.HAForSingleEngine(data=None)[source]

Bases: object

High availability configuration on the single engine. Access through an engine reference:

engine.ha_settings.ha_backup_unit
engine.ha_settings.set_ha_backup_unit(pos='1234567890-1234567890')
engine.ha_settings.disable_ha_backup_unit()

engine.ha_settings.connection_sync_mode
engine.ha_settings.set_connection_sync(ha_connection_sync_interface=0,
                                       connection_sync_group=connection_sync_group_name)
engine.ha_settings.disable_connection_sync()

When making changes to the HA configuration, any methods called that change the configuration also require that engine.update() is called once changes are complete. This way you can make multiple changes without refreshing the engine cache.

Variables:

connection_sync_group (ConnectionSynchronizationGroup) – ConnectionSynchronizationGroup

reference for this engine. Applicable when HA mode is connection_sync.

property connection_sync_mode

Get connection synchronization for external high availability mode for this engine

Returns:

str or None

disable_connection_sync()[source]

Disable connection synchronization for external high availability on this engine.

Returns:

None

disable_ha_backup_unit()[source]

Disable HA backup unit mode on this engine.

Returns:

None

property ha_backup_unit_mode

Get high availability backup unit mode for this engine

Returns:

str or None

property pos

proof of serial for hugh availability. Applicable when HA backup unit mode is enabled.

Return type:

str or None

set_connection_sync(connection_sync_group, ha_connection_sync_interface)[source]

Enable connection synchronization for external high availability on this engine. Disable high availability backup unit.

Parameters:
  • connection_sync_group (str,ConnectionSynchronizationGroup) – ConnectionSynchronizationGroup element or str href

  • ha_connection_sync_interface (str) – ID of the interface for unicast state

synchronization :raises ElementNotFound: ConnectionSynchronizationGroup not found :return: None

set_ha_backup_unit(pos=None)[source]

Enable high availability backup unit on this engine. Disable connection synchronization for external high availability.

Parameters:

pos (str) – proof of serial for pairing

Returns:

None

property sync_interface

ID of the interface for unicast state Applicable when HA mode is connection_sync.

Return type:

int or None

class smc.core.engine.IdleTimeout(engine)[source]

Bases: NestedDict

This is definition of timeout by protocol or by TCP connection state. You can define general timeouts for removing idle connections from the state table, including non-TCP communications that are handled like connections. The timeout prevents wasting engine resources on storing information about abandoned connections. Timeouts are a normal way to clear traffic information with protocols that have no closing mechanism.Timeouts do not affect active connections. The connections are kept in the state table as long as the interval of packets within a connection is shorter than the timeouts set.

add(name, timeout=None)[source]

Add a timeout setting for the new protocol. :param str name: name of the protocol. :param int timeout: timeout value.

remove(name)[source]

Remove the timeout setting for specific protocols on the engine. :param str name: namr of the protocol to be removed.

class smc.core.engine.LBFilter(action, ip_descriptor, replace_ip, nodeid, ignore_other=False, nat_enforce=False, use_ipsec=False, use_ports=False)[source]

Bases: NestedDict

This represents the Load Balancing Filter.

property action

Action for the filter. possible values are: none, replace, node, select_none, replace_offset :rtype: str

property ignore_other

Tell that other entries might not be concerned.

Return type:

bool

property ip_descriptor

Represents the IPNetwork or the IPAddressRange

Return type:

str

property nat_enforce

Tells NAT to enforce translated packet headers to the same hash value to the matching packet.

Return type:

bool

property replace_ip

Address in case of replace action.

Return type:

str

property use_ipsec

Tells the engine that this entry has to be handled with special care because part of VPN

Return type:

bool

property use_ports

Defines whether to use port numbers when calculating the hash value for the packet.

Return type:

bool

class smc.core.engine.LinkUsageExceptionRules(destinations=None, services=None, sources=None, isp_link_ref=None, comment=None)[source]

Bases: NestedDict

property comment

comment. :rtype: str

isp_link :rtype: isp_link

class smc.core.engine.LocalLogStorageSettings(engine)[source]

Bases: NestedDict

Local Log Storage Settings for not virtual engines.

property lls_guaranteed_free_percent

Minimum amount of spool space that must be left available for other uses in percentage

property lls_guaranteed_free_size_in_mb

Minimum amount of spool space that must be left available for other uses in MegaBytes

property lls_max_time

The maximum amount of hours before the stored logs are deleted.

property local_log_storage_activated

Activate the Local Log Storage feature. At least one of the Guaranteed free disk partition values must be set up.

class smc.core.engine.VPN(engine, internal_gateway=None)[source]

Bases: object

VPN is the top level interface to all engine based VPN settings. To enable IPSEC, SSL or SSL VPN on the engine, enable on the endpoint.

add_site(name, site_elements=None)[source]

Add a VPN site with site elements to this engine. VPN sites identify the sites with protected networks to be included in the VPN. Add a network and new VPN site:

>>> net = Network.get_or_create(name='wireless', ipv4_network='192.168.5.0/24')
>>> engine.vpn.add_site(name='wireless', site_elements=[net])
VPNSite(name=wireless)
>>> list(engine.vpn.sites)
[VPNSite(name=dingo - Primary Site), VPNSite(name=wireless)]
Parameters:
  • name (str) – name for VPN site

  • site_elements (list(str,Element)) – network elements for VPN site

Raises:
Return type:

VPNSite

Note

Update is immediate for this operation.

property gateway_certificate

A Gateway Certificate is used by the engine for securing communications such as VPN. You can also check the expiration, view the signing CA and renew the certificate from this element.

Returns:

GatewayCertificate

Return type:

list

property gateway_certificate_request

A Gateway Certificate request is a gateway certificate that need to be signed internally or externally using external CA

Returns:

GatewayCertificateRequest

Return type:

list

property gateway_profile

Gateway Profile for this VPN. This is only a valid setting on layer 3 firewalls.

Return type:

GatewayProfile

property gateway_settings

A gateway settings profile defines VPN specific settings related to timers such as negotiation retries (min, max) and mobike settings. Gateway settings are only present on layer 3 FW types.

Return type:

GatewaySettings

Note

This can return None on layer 3 firewalls if VPN is not enabled.

generate_certificate(common_name, organization='Forcepoint', public_key_algorithm='rsa', signature_algorithm='rsa_sha_512', key_length=2048, signing_ca=None, certificate=None)[source]

Generate an internal gateway certificate used for VPN on this engine. Certificate request should be an instance of VPNCertificate.

Param:

str common_name: common name for certificate

Param:

str organization: organization for certificate

Parameters:
  • public_key_algorithm (str) – public key type to use. Valid values rsa, dsa, ecdsa.

  • signature_algorithm (str) – signature algorithm. Valid values dsa_sha_1, dsa_sha_224, dsa_sha_256, rsa_md5, rsa_sha_1, rsa_sha_256, rsa_sha_384, rsa_sha_512, ecdsa_sha_1, ecdsa_sha_256, ecdsa_sha_384, ecdsa_sha_512. (Default: rsa_sha_512)

  • key_length (int) – length of key. Key length depends on the key type. For example, RSA keys can be 1024, 2048, 3072, 4096. See SMC documentation for more details.

  • signing_ca (str,VPNCertificateCA) – by default will use the internal RSA CA

:param str, certificate : used directly call another _create_from_cert :raises CertificateError: error generating certificate :return: GatewayCertificate

property internal_endpoint

Internal endpoints to enable VPN for the engine.

Return type:

SubElementCollection(InternalEndpoint)

property loopback_endpoint

Internal Loopback endpoints to enable VPN for the engine.

Return type:

SubElementCollection(InternalEndpoint)

remove()[source]

Rename the internal gateway.

Parameters:

name (str) – new name for internal gateway

Returns:

None

rename(name)[source]

Rename the internal gateway.

Parameters:

name (str) – new name for internal gateway

Returns:

None

property sites

VPN sites configured for this engine. Using sub element methods simplify fetching sites of interest:

engine = Engine('sg_vm')
mysite = engine.vpn.sites.get_contains('inter')
print(mysite)
Return type:

CreateCollection(VPNSite)

property vpn_client

VPN Client settings for this engine.

Alias for internal_gateway.

Return type:

InternalGateway

class smc.core.engine.VPNMapping(gateway_ref, vpn_ref, gateway_nodes_usage)[source]

Bases: VPNMapping

A VPN Mapping represents Policy Based VPNs associated with this engine. This simplifies finding references where an engine is used within a VPN without iterating through existing VPNs to find the engine.

property internal_gateway

Return the engines internal gateway as element

Return type:

InternalGateway

property is_central_gateway

Is this engine a central gateway in the VPN policy

Return type:

bool

property is_mobile_gateway

Is the engine specified as a mobile gateway in the Policy VPN configuration

Return type:

bool

property is_satellite_gateway

Is this engine a satellite gateway in the VPN policy

Return type:

bool

property vpn

The VPN policy for this engine mapping

Return type:

PolicyVPN

class smc.core.engine.VPNMappingCollection(vpns)[source]

Bases: BaseIterable

AddOn

Engine feature add on functionality such as default NAT, Antivirus, File Reputation, etc. These are common settings that are located under the SMC AddOn or General properties.

Property features will have a common interface allowing you to enable, disable and check status from the engine reference. When property features are modified, they are done so against a local copy of the server intsance. To commit the change, you must call .update() on the engine instance.

For example, to view status of antivirus, given a specific engine:

engine.antivirus.status

Then enable or disable:

engine.antivirus.enable()
engine.antivirus.disable()
engine.update()
..note:: Engine property settings require that you call engine.update() after

making / queuing your changes.

AntiVirus

class smc.core.addon.AntiVirus(engine)[source]

Antivirus settings for the engine. In order to use AV, you must also have DNS server addresses configured on the engine.

Enable AV, use a proxy for updates and adjust update schedule:

engine.antivirus.enable()
engine.antivirus.update_frequency('daily')
engine.antivirus.update_day('tu')
engine.antivirus.log_level('transient')
engine.antivirus.http_proxy('10.0.0.1', proxy_port=8080, user='foo', password='password')
engine.update()
Variables:
  • antivirus_enabled (bool) – is antivirus enabled

  • antivirus_http_proxy (str) – http proxy settings

  • antivirus_http_proxy_enabled (bool) – is http proxy enabled

  • antivirus_proxy_port (int) – http proxy port

  • antivirus_proxy_user (str) – http proxy user

  • antivirus_update (str) – how often to update

  • antivirus_update_day (str) – if update set to weekly, which day to update

  • antivirus_update_time (int) – time to update av signatures

  • virus_log_level (str) – antivirus logging level

Note

You must call engine.update() to commit any changes.

disable()[source]

Disable antivirus on the engine

enable()[source]

Enable antivirus on the engine

http_proxy(proxy, proxy_port, user=None, password=None)[source]

New in version 0.5.7: Requires SMC and engine version >= 6.4

Set http proxy settings for Antivirus updates.

Parameters:
  • proxy (str) – proxy IP address

  • proxy_port (str,int) – proxy port

  • user (str) – optional user for authentication

log_level(level)[source]

Set the log level for antivirus alerting.

Parameters:

log_level (str) – none,transient,stored,essential,alert

property status

Status of AV on this engine

Return type:

bool

update_day(day)[source]

Update the day when updates should occur.

Parameters:

day (str) – only used if ‘weekly’ is specified. Which day or week to perform update. Valid options: mo, tu, we, th, fr, sa, su.

update_frequency(when)[source]

Set the update frequency. By default this is daily.

Parameters:

antivirus_update (str) – how often to check for updates. Valid options are: ‘never’,’1hour’, ‘startup’, ‘daily’, ‘weekly’

FileReputation

class smc.core.addon.FileReputation(engine)[source]

Configure the engine to use File Reputation capabilities.

Enable file reputation and specify outbound http proxies for queries:

engine.file_reputation.enable(http_proxy=[HttpProxy('myproxy')])
engine.update()
Variables:

file_reputation_context (str) – file reputation context, either gti_cloud_only or disabled

Note

You must call engine.update() to commit any changes.

disable()[source]

Disable any file reputation on the engine.

enable(http_proxy=None)[source]

Enable GTI reputation on the engine. If proxy servers are needed, provide a list of proxy elements.

Parameters:

http_proxy (list(str,HttpProxy)) – list of proxies for GTI connections

property http_proxy

Return any HTTP Proxies that are configured for File Reputation.

Returns:

list of http proxy instances

Return type:

list(HttpProxy)

property status

Return the status of File Reputation on this engine.

Return type:

bool

SidewinderProxy

class smc.core.addon.SidewinderProxy(engine)[source]

Sidewinder status on this engine. Sidewinder proxy can only be enabled on specific engine types and also requires SMC and engine version >= 6.1.

Enable Sidewinder proxy:

engine.sidewinder_proxy.enable()

Note

You must call engine.update() to commit any changes.

disable()[source]

Disable Sidewinder proxy on the engine

enable()[source]

Enable Sidewinder proxy on the engine

property status

Status of Sidewinder proxy on this engine

Return type:

bool

UrlFiltering

class smc.core.addon.UrlFiltering(engine)[source]

Enable URL Filtering on the engine.

Enable Url Filtering with next hop proxies:

engine.url_filtering.enable(http_proxy=[HttpProxy('myproxy')])
engine.update()

Disable Url Filtering:

engine.url_filtering.disable()
engine.update()

Note

You must call engine.update() to commit any changes.

disable()[source]

Disable URL Filtering on the engine

enable(http_proxy=None)[source]

Enable URL Filtering on the engine. If proxy servers are needed, provide a list of HTTPProxy elements.

Parameters:

http_proxy (list(str,HttpProxy)) – list of proxies for GTI connections

property http_proxy

Return any HTTP Proxies that are configured for Url Filtering.

Returns:

list of http proxy instances

Return type:

list(HttpProxy)

property status

Return the status of URL Filtering on the engine

Return type:

bool

ZTNAConnector

class smc.core.addon.ZTNAConnector(engine)[source]

Enable ZTNA Connector on the engine.

engine.ztna_connector.enable(bgkey=”xxx:yyy:zzz”, datacenter=”ddd”) engine.update()

Disable ZTNA Connector:

engine.ztna_connector.disable() engine.update()

Note

You must call engine.update() to commit any changes.

property auto_update

get ztna auto_update or None

property bgkey

get ztna installation key or None

property datacenter

get ztna datacenter or None

disable()[source]

Disable ZTNA Connector on the engine.

enable(bgkey, datacenter, auto_update)[source]

Enable ZTNA Connector on the engine.

Parameters:
  • bgkey (str) – connector installer key

  • datacenter (str) – datacenter accessed via this connector

  • auto_update (bool) – install automatically the latest version

property status

Return the status (enabled/disabled) of ZTNA Connector on the engine

Return type:

bool

ClientInspection

class smc.core.addon.ClientInspection(engine)[source]
property ca_for_signing

Return the Client Protection Certificate Authority assigned to this engine. The CA is used to provide decryption services to outbound client connections.

Return type:

ClientProtectionCA or None if not defined

disable()[source]

Disable client decryption.

Returns:

None

enable(ca_for_signing, tls_trusted_ca_tags=None, tls_trusted_cas=None)[source]

Enable client decryption. Provide a valid client protection CA that the engine will use to decrypt.

Parameters:
  • ca_for_signing – tls_signing_certificate_authority

  • tls_trusted_ca_tags – optional trusted_ca_tag array

  • tls_trusted_cas – optional tls_certificate_authority array

Returns:

None

property status

Whether client based decryption is enabled or disabled.

Return type:

bool

property tls_trusted_ca_tags

Return the TLS trusted CA tags.

Return type:

TrustedCATag array or [] if not defined

property tls_trusted_cas

Return the TLS trusted CAs.

Return type:

TLSCertificateAuthority array or [] if not defined

Sandbox

class smc.core.addon.Sandbox(engine)[source]

Engine based sandbox settings. Sandbox can be configured for local (on prem) or cloud based sandbox. To create file filtering policies that use sandbox, you must first enable it and provide license keys on the engine.

Enable cloud sandbox on the engine, specifying a proxy for outbound connections:

engine.sandbox.enable(
    license_key='123',
    license_token='456',
    http_proxy=[HttpProxy('myproxy')])

Note

You must call engine.update() to commit any changes.

disable()[source]

Disable the sandbox on this engine.

enable(license_key, license_token, sandbox_type='cloud_sandbox', service='Automatic', http_proxy=None, sandbox_data_center='Automatic')[source]

Enable sandbox on this engine. Provide a valid license key and license token obtained from your engine licensing. Requires SMC version >= 6.3.

Note

Cloud sandbox is a feature that requires an engine license.

Parameters:
  • license_key (str) – license key for specific engine

  • license_token (str) – license token for specific engine

  • sandbox_type (str) – ‘local_sandbox’, ‘cloud_sandbox’, ‘forcepoint_sandbox’ or ‘atd’

  • service (str,SandboxService) – a sandbox service element from SMC. The service defines which location the engine is in and which data centers to use. The default is to use the ‘US Data Centers’ profile if undefined.

  • sandbox_data_center (str,SandboxDataCenter) – sandbox data center to use if the service specified does not exist. Requires SMC >= 6.4.3

Returns:

None

property http_proxy

Return any HTTP Proxies that are configured for Sandbox.

Returns:

list of http proxy instances

Return type:

list(HttpProxy)

property status

Status of sandbox on this engine

Return type:

bool

TLSInspection

class smc.core.addon.TLSInspection(engine)[source]

TLS Inspection settings control settings for doing inbound TLS decryption and outbound client TLS decryption. This provides an interface to manage TLSServerCredentials and TLSClientCredentials assigned to the engine.

Note

You must call engine.update() to commit any changes.

add_tls_credential(credentials)[source]

Add a list of TLSServerCredential to this engine. TLSServerCredentials can be in element form or can also be the href for the element.

Parameters:

credentials (list(str,TLSServerCredential)) – list of pre-created TLSServerCredentials

Returns:

None

remove_tls_credential(credentials)[source]

Remove a list of TLSServerCredentials on this engine.

Parameters:

credentials (list(str,TLSServerCredential)) – list of credentials to remove from the engine

Returns:

None

property server_credentials

Return a list of assigned (if any) TLSServerCredentials assigned to this engine.

Return type:

list(TLSServerCredential)

Dynamic Routing

Represents classes responsible for configuring dynamic routing protocols

OSPF

For more information on creating OSPF elements and enabling on a layer 3 engine:

See also

smc.routing.ospf

BGP

For more information on creating BGP elements and enabling on a layer 3 engine:

See also

smc.routing.bgp

General

DefaultNAT

class smc.core.general.DefaultNAT(engine)[source]

Default NAT on the engine is used to automatically create NAT configurations based on internal routing. This simplifies the need to create specific NAT rules, primarily for outbound traffic.

Note

You must call engine.update() to commit any changes.

disable()[source]

Disable default NAT on this engine

enable()[source]

Enable default NAT on this engine

property status

Status of default nat on the engine.

Return type:

bool

RankedDNSAddress

class smc.core.general.RankedDNSAddress(entries)[source]

A RankedDNSAddress represents a list of DNS entries used as a ranked list to provide an ordered way to perform DNS queries. DNS entries can be added as raw IP addresses, or as elements of type smc.elements.network.Host, smc.elements.servers.DNSServer or a dynamic_interface_alias (or combination of all). This is an iterable class yielding namedtuples of type DNSEntry.

Normal access is done through an engine reference:

>>> list(engine.dns)
[DNSEntry(rank=0,value=8.8.8.8,ne_ref=None),
 DNSEntry(rank=1,value=None,ne_ref=DNSServer(name=mydnsserver))]

>>> engine.dns.append(['8.8.8.8', '9.9.9.9'])
>>> engine.dns.prepend(['1.1.1.1'])
>>> engine.dns.remove(['8.8.8.8', DNSServer('mydnsserver')])

Note

You must call engine.update() to commit any changes.

append(values)[source]

Add DNS entries to the engine at the end of the existing list (if any). A DNS entry can be either a raw IP Address, or an element of type smc.elements.network.Host or smc.elements.servers.DNSServer.

Parameters:

values (list) – list of IP addresses, Host and/or DNSServer elements.

Returns:

None

Note

If the DNS entry added already exists, it will not be added. It’s not a valid configuration to enter the same DNS IP multiple times. This is also true if the element is assigned the same address as a raw IP address already defined.

prepend(values)[source]

Prepend DNS entries to the engine at the beginning of the existing list (if any). A DNS entry can be either a raw IP Address, or an element of type smc.elements.network.Host or smc.elements.servers.DNSServer.

Parameters:

values (list) – list of IP addresses, Host and/or DNSServer elements.

Returns:

None

remove(values)[source]

Remove DNS entries from this ranked DNS list. A DNS entry can be either a raw IP Address, or an element of type smc.elements.network.Host or smc.elements.servers.DNSServer.

Parameters:

values (list) – list of IP addresses, Host and/or DNSServer elements.

Returns:

None

class smc.core.general.DNSEntry(rank, value=None, ne_ref=None)[source]

DNSEntry represents a single DNS entry within an engine DNSAddress list.

Variables:
  • value (str) – IP address value of this entry (None if type Element is used)

  • rank (int) – order rank for the entry

  • ne_ref (str) – network element href of entry. Use element property to resolve to type Element.

  • element (Element) – If the DNS entry is an element type, this property will returned a resolved version of the ne_ref field.

DNS Relay

class smc.core.general.DNSRelay(engine)[source]

DNS Relay allows the engine to provide DNS caching or specific host, IP and domain replies to clients. It can also be used to sinkhole specific DNS requests.

disable()[source]

Disable DNS Relay on this engine

Returns:

None

enable(interface_id, dns_relay_profile=None)[source]

Enable the DNS Relay service on this engine.

Parameters:
  • interface_id (int) – interface id to enable relay

  • dns_relay_profile (str,DNSRelayProfile) – DNSRelayProfile element or str href

Raises:
Returns:

None

property status

Status of DNS Relay on this engine.

Return type:

bool

SNMP

class smc.core.general.SNMP(engine)[source]

SNMP configuration details for applying SNMP on an engine. SNMP requires at minimum an assigned SNMPAgent configuration which defines the SNMP specific settings (version, community string, etc). You can also define specific interfaces to enable SNMP on. By default, if no addresses are specified, SNMP will be defined on all interfaces.

property agent

The SNMP agent profile used for this engine.

Return type:

SNMPAgent

disable()[source]

Disable SNMP on this engine. You must call update on the engine for this to take effect.

Returns:

None

enable(snmp_agent, snmp_location=None, snmp_interface=None, snmp_engine_id=None)[source]

Enable SNMP on the engine. Specify a list of interfaces by ID to enable only on those interfaces. Only interfaces that have NDI’s are supported.

Example of adding SNMP on a port group interface:

engine = Engine('azure')
engine.snmp.enable(SNMPAgent('myagent'), snmp_interface=['SWP_0.1'])
engine.update()
Parameters:
  • snmp_agent (str,Element) – the SNMP agent reference for this engine

  • snmp_location (str) – the SNMP location identifier for the engine

  • snmp_interface (list) – list of interface IDs to enable SNMP

  • snmp_engine_id (str) – Specify snmp engine id. If None the it will be automatic.

Raises:
property interface

Return a list of physical interfaces that the SNMP agent is bound to.

Return type:

list(PhysicalInterface)

property location

Return the SNMP location string

Return type:

str

property status

Status of SNMP on this engine

Return type:

bool

update_configuration(**kwargs)[source]

Update the SNMP configuration using any kwargs supported in the enable constructor. Return whether a change was made. You must call update on the engine to commit any changes.

Parameters:

kwargs (dict) – keyword arguments supported by enable constructor

Return type:

bool

Layer2Settings

class smc.core.general.Layer2Settings(engine)[source]

Layer 2 Settings are only applicable on Layer 3 Firewall engines that want to run specific interfaces in layer 2 mode. This requires that a Layer 2 Interface Policy is applied to the engine. You can also set connection tracking and bypass on overload settings for these interfaces as well.

Set policy for the engine:

engine.l2fw_settings.enable(InterfacePolicy('mylayer2'))
Variables:
  • bypass_overload_traffic (bool) – whether to bypass traffic on overload

  • tracking_mode (str) – connection tracking mode

Note

You must call engine.update() to commit any changes.

Warning

This feature requires SMC and engine version >= 6.3

bypass_on_overload(value)[source]

Set the l2fw settings to bypass on overload.

Parameters:

value (bool) – boolean to indicate bypass setting

Returns:

None

connection_tracking(mode)[source]

Set the connection tracking mode for these layer 2 settings.

Parameters:

mode (str) – normal, strict, loose

Returns:

None

disable()[source]

Disable the layer 2 interface policy

enable(policy)[source]

Set a layer 2 interface policy.

Parameters:

policy (str,Element) – an InterfacePolicy or str href

Raises:
Returns:

None

property policy

Return the InterfacePolicy for this layer 3 firewall.

Return type:

InterfacePolicy

NTPSettings

class smc.core.general.NTPSettings(engine=None)[source]

This represents the definition of NTP settings.

classmethod create(ntp_enable, ntp_servers)[source]

Create a new defintiion of NTPSettings :param bool ntp_enable: is NTP enabled :param list(NTPServer) ntp_servers: define one or more NTP Servers.

property ntp_enable

Is NTP enabled? (required)

Return type:

bool

property ntp_servers

Define one or more NTP Servers.

Return type:

list(NTPServer)

VPN

Provisioning a firewall for VPN consists of the following steps:

  • Enable VPN an interface (InternalEndpoint)

  • Optionally add VPN sites with protected networks

Note

By default Forcepoint NGFW Engine’s provide a capability that allows the protected VPN networks to be identified based on the routing table.

It is still possible to override this setting and add your own custom VPN sites as needed.

Once the firewall has VPN enabled, you must also assign the NGFW Engine to a specified Policy VPN as a central or satellite gateway.

The entry point for enabling the VPN on an engine is under the engine resource smc.core.engine.Engine.vpn.

Enabling IPSEC on an interface is done by accessing the engine resource and finding the correct InternalEndpoint for which to enable the VPN. Internal Endpoints are not exactly interface maps, instead they identify all addresses on a given firewall capable for running VPN. It is possible for a single interface to have more than one internal endpoint if the interface has multiple IP addresses assigned.

>>> from smc.core.engine import Engine
>>> engine = Engine('myfirewall')
>>> for ie in engine.vpn.internal_endpoint:
...   ie
...
InternalEndpoint(name=6.6.6.6)
InternalEndpoint(name=10.10.0.1)
InternalEndpoint(name=11.11.11.11)
InternalEndpoint(name=4.4.4.4)
InternalEndpoint(name=10.10.10.1)

Notice that internal endpoints are referenced by their IP address and not their interface. The interface is available as an attribute on the endpoint to make it easier to find the correct interface:

>>> for ie in engine.vpn.internal_endpoint:
...   print(ie, ie.interface_id)
...
(InternalEndpoint(name=6.6.6.6), u'6')
(InternalEndpoint(name=10.10.0.1), u'0')
(InternalEndpoint(name=11.11.11.11), u'11')
(InternalEndpoint(name=4.4.4.4), u'2.200')
(InternalEndpoint(name=10.10.10.1), u'1')

If I want to enable VPN on interface 0, you can obtain the right endpoint and enable:

>>> for ie in engine.vpn.internal_endpoint:
...   if ie.interface_id == '0':
...     ie.ipsec_vpn = True

Note

Once you’ve enabled the interface for VPN, you must also call engine.update() to commit the change.

The second step (optional) is to add VPN sites to the firewall. VPN Sites define a group of protected networks that can be applied to the VPN.

For example, add a new VPN site called wireless with a new network element that we’ll create beforehand.

>>> net = Network.get_or_create(name='wireless', ipv4_network='192.168.5.0/24')
>>> engine.vpn.add_site(name='wireless', site_elements=[net])
VPNSite(name=wireless)
>>> list(engine.vpn.sites)
[VPNSite(name=dingo - Primary Site), VPNSite(name=wireless)]

Once the engine is enabled for VPN, see smc.vpn.policy.PolicyVPN for information on how to create a PolicyVPN and add engines.

InternalEndpoint

class smc.core.engine.InternalEndpoint(**meta)[source]

Bases: SubElement

An Internal Endpoint is an interface mapping that enables VPN on the associated interface. This also defines what type of VPN to enable such as IPSEC, SSL VPN, or SSL VPN Portal.

To see all available internal endpoint (VPN gateways) on a particular engine, use an engine reference:

>>> engine = Engine('sg_vm')
>>> for e in engine.vpn.internal_endpoint:
...   print(e)
...
InternalEndpoint(name=10.0.0.254)
InternalEndpoint(name=172.18.1.254)

You can also retrieve an internal endpoint directly and operate on it, for example, enabling it as a VPN endpoint:

engine = Engine('sg_vm')
my_interface = engine.vpn.internal_endpoint.get_exact('10.0.0.254')
my_interface.update(enabled=True)

Multiple attributes can be updated by calling update:

my_interface.update(enabled=True,ipsec_vpn=True,force_nat_t=True,ssl_vpn_portal=False,ssl_vpn_tunnel=False)

Available attributes:

Variables:
  • enabled (bool) – enable this interface as a VPN endpoint (default: False)

  • nat_t (bool) – enable NAT-T (default: False)

  • force_nat_t (bool) – force NAT-T (default: False)

  • ssl_vpn_portal (bool) – enable SSL VPN portal on the interface (default: False)

  • ssl_vpn_tunnel (bool) – enable SSL VPN tunnel on the interface (default: False)

  • ipsec_vpn (bool) – enable IPSEC VPN on the interface (default: False)

  • udp_encapsulation (bool) – Allow UDP encapsulation (default: False)

  • balancing_mode (str) – VPN load balancing mode. Valid options are: ‘standby’, ‘aggregate’, ‘active’ (default: ‘active’)

property interface_id

Interface ID for this VPN endpoint

Returns:

str interface id

property name

Get the name from deducted name

property physical_interface

Physical interface for this endpoint.

Return type:

PhysicalInterface

InternalGateway

class smc.core.engine.InternalGateway(**meta)[source]

Bases: SubElement

InternalGateway represents the VPN Client configuration endpoint on the NGFW. Settings under Internal Gateway reflect client settings such as requiring antivirus, windows firewall and setting the VPN client mode.

View settings through an engine reference:

>>> engine = Engine('dingo')
>>> vpn = engine.vpn
>>> vpn.name
u'dingo Primary'
>>> vpn.vpn_client.firewall
False
>>> vpn.vpn_client.antivirus
False
>>> vpn.vpn_client.vpn_client_mode
u'ipsec'

Introduced all_vpns property to get list all vpn instances, Each vpn instance associated only one internal gateway to make code backward compatible.

>>> list_of_all_internal_gateways=engine.all_vpns
>>> first_vpn_instance= list_of_all_internal_gateways[0]
>>> first_vpn_instance.name
u'dingo Primary'
>>> first_vpn_instance.vpn_client.firewall
False
>>> first_vpn_instance.vpn_client.antivirus
False
>>> first_vpn_instance.vpn_client.vpn_client_mode
u'ipsec'

Enable client AV and windows FW:

engine.vpn.vpn_client.update(
    firewall=True, antivirus=True)
Variables:
  • firewall (bool) – require windows firewall

  • antivirus (bool) – require client antivirus

  • vpn_client_mode (str) –

property internal_endpoint

Internal endpoints to enable VPN for the engine.

Return type:

SubElementCollection(InternalEndpoint)

remove()[source]

Remove Internal Gateway from this engine.

Interfaces

Represents classes responsible for configuring interfaces on engines

InterfaceCollections

Changed in version 0.7.0.

Collections classes for interfaces provide searching and methods to simplify creation based on interface types.

You can iterate any interface type by specifying the type:

>>> for interface in engine.tunnel_interface:
...   interface
...
TunnelInterface(name=Tunnel Interface 1008)
TunnelInterface(name=Tunnel Interface 1003)
TunnelInterface(name=Tunnel Interface 1000)

Or iterate all interfaces which will also return their types:

>>> for interface in engine.interface:
...   interface
...
Layer3PhysicalInterface(name=Interface 3)
TunnelInterface(name=Tunnel Interface 1000)
Layer3PhysicalInterface(name=Interface 61)
Layer3PhysicalInterface(name=Interface 56)
Layer3PhysicalInterface(name=Interface 15)
Layer2PhysicalInterface(name=Interface 7 (Capture))
ModemInterfaceDynamic(name=Modem 0)
TunnelInterface(name=Tunnel Interface 1030)
SwitchPhysicalInterface(name=Switch 0)
...

Accessing interface methods for creating interfaces can also be done in multiple ways. The simplest is to use an engine reference to use this collection. The engine reference specifies the type of interface and indicates how it will be created for the engine.

For example, creating an interface on a virtual engine:

engine.virtual_physical_interface.add_layer3_interface(
    interface_id=1,
    address='14.14.14.119',
    network_value='14.14.14.0/24',
    comment='my comment',
    zone_ref='myzone')

The helper methods use the interface API to create the interface that is then submitted to the engine. You can optionally create the interface manually using the API which provides more customization capabilities.

Example of creating a VirtualPhysicalInterface for a virtual engine manually:

payload = {'comment': 'comment on this interface',
           'interfaces': [{'nodes': [{'address': '13.13.13.13',
                                      'network_value': '13.13.13.0/24'}]}]}

vinterface = VirtualPhysicalInterface(interface_id=1, **payload)

Pass this to update_or_create in the event that you want to potentially modify an existing interface should the same interface ID exist:

engine.virtual_physical_interface.update_or_create(vinterface)

Or create a new interface (this will fail if the interface exists):

engine.add_interface(vinterface)

Collections also provide a simple helper when you want to provide a pre-configured interface and apply an update_or_create logic. In the update or create case, if the interface exists any fields that have changed will be updated. If the interface does not exist it is created. Provide with_status to obtain the interface and status of the operation. The update or create will return a tuple of (Interface, modified, created), where created and modified are booleans indicating the operations performed:

>>> from smc.core.engine import Engine
>>> from smc.core.interfaces import Layer3PhysicalInterface
>>> engine = Engine('myfw')
>>> interface = engine.interface.get(0)
>>> interface
Layer3PhysicalInterface(name=Interface 0)
>>> interface.addresses
[(u'11.11.11.11', u'11.11.11.0/24', u'0')]
>>> myinterface = Layer3PhysicalInterface(interface_id=0,
interfaces=[{'nodes': [{'address': '66.66.66.66', 'network_value': '66.66.66.0/24'}]}],
            comment='changed today')
...
>>> interface, modified, created = engine.physical_interface.update_or_create(myinterface)
>>> interface
Layer3PhysicalInterface(name=Interface 0)
>>> modified
True
>>> created
False
>>> interface.addresses
[(u'66.66.66.66', u'66.66.66.0/24', u'0')]
>>> interface.comment
u'changed today'
class smc.core.collection.InterfaceCollection(engine, rel='interfaces')[source]

Bases: BaseIterable

An interface collection provides top level search capabilities to iterate or get interfaces of the specified type. This also delegates all ‘add’ methods of an interface to the interface type specified. Collections are returned from an engine reference and not called directly.

For example, you can use this to obtain all interfaces of a given type from an engine:

>>> for interface in engine.interface.all():
...   print(interface.name, interface.addresses)
('Tunnel Interface 2001', [('169.254.9.22', '169.254.9.20/30', '2001')])
('Tunnel Interface 2000', [('169.254.11.6', '169.254.11.4/30', '2000')])
('Interface 2', [('192.168.1.252', '192.168.1.0/24', '2')])
('Interface 1', [('10.0.0.254', '10.0.0.0/24', '1')])
('Interface 0', [('172.18.1.254', '172.18.1.0/24', '0')])

Or only physical interface types:

for interface in engine.physical_interfaces:
    print(interface)

Get switch interfaces and associated port groups:

for interface in engine.switch_physical_interface:
    print(interface, interface.port_groups)

Get a specific interface directly:

engine.interface.get(10)

Switch interface direct fetching must include the ‘SWP_’ prefix as well. To get switch interface 0:

engine.interface.get('SWP_0')

You can also get port groups directly similar to fetching VLANs:

engine.switch_physical_interface.get('SWP_0.1')

Or use collection helpers to create interfaces:

engine.physical_interface.add(2)
engine.physical_interface.add_layer3_interface(....)
...

Note

This can raise UnsupportedInterfaceType for unsupported engine types based on the interface context.

add_layer3_vlan_interface(*args, **kwargs)[source]

Add a Layer 3 VLAN interface. Optionally specify an address and network if assigning an IP to the VLAN. This method will also assign an IP address to an existing VLAN, or add an additional address to an existing VLAN. This method may commonly be used on a Master Engine to create VLANs for virtual firewall engines.

Example of creating a VLAN and passing kwargs to define a DHCP server service on the VLAN interface:

engine = Engine('engine1')
engine.physical_interface.add_layer3_vlan_interface(interface_id=20, vlan_id=20,
    address='20.20.20.20', network_value='20.20.20.0/24', comment='foocomment',
    dhcp_server_on_interface={
        'default_gateway': '20.20.20.1',
        'default_lease_time': 7200,
        'dhcp_address_range': '20.20.20.101-20.20.20.120',
        'dhcp_range_per_node': [],
        'primary_dns_server': '8.8.8.8'})
Parameters:
  • interface_id (str,int) – interface identifier

  • vlan_id (int) – vlan identifier

  • address (str) – optional IP address to assign to VLAN

  • network_value (str) – network cidr if address is specified. In format: 10.10.10.0/24.

  • zone_ref (str) – zone to use, by name, href, or Zone

  • comment (str) – optional comment for VLAN level of interface

  • virtual_mapping (int) – virtual engine mapping id See smc.core.engine.VirtualResource.vfw_id

  • virtual_resource_name (str) – name of virtual resource See smc.core.engine.VirtualResource.name

  • kw (dict) – keyword arguments are passed to top level of VLAN interface, not the base level physical interface. This is useful if you want to pass in a configuration that enables the DHCP server on a VLAN for example.

Raises:

EngineCommandFailed – failure creating interface

Returns:

None

get(interface_id)[source]

Get the interface by id, if known. The interface is retrieved from the top level Physical or Tunnel Interface. If the interface is an inline interface, you can specify only one of the two inline pairs and the same interface will be returned.

If interface type is unknown, use engine.interface for retrieving:

>>> engine = Engine('sg_vm')
>>> intf = engine.interface.get(0)
>>> print(intf, intf.addresses)
(PhysicalInterface(name=Interface 0), [('172.18.1.254', '172.18.1.0/24', '0')])

Get an inline interface:

>>> intf = engine.interface.get('2-3')

Note

For the inline interface example, you could also just specify ‘2’ or ‘3’ and the fetch will return the pair.

Parameters:

interface_id (str,int) – interface ID to retrieve

Raises:

InterfaceNotFound – invalid interface specified

Returns:

interface object by type (Physical, Tunnel, VlanInterface)

update_or_create(interface)[source]

Collections class update or create method that can be used as a shortcut to updating or creating an interface. The interface must first be defined and provided as the argument. The interface method must have an update_interface method which resolves differences and adds as necessary.

Parameters:

interface (Interface) – an instance of an interface type, either PhysicalInterface, TunnelInterface or SwitchPhysicalInterface

Raises:
Return type:

tuple

Returns:

A tuple with (Interface, modified, created), where created and modified are booleans indicating the operations performed

class smc.core.collection.LoopbackCollection(engine)[source]

Bases: BaseIterable

An loopback collection provides top level search capabilities to iterate or get loopback interfaces from a given engine.

All loopback interfaces can be fetched from the engine:

>>> engine = Engine('dingo')
>>> for lb in engine.loopback_interface:
...   lb
...
LoopbackInterface(address=172.20.1.1, nodeid=1, rank=1)
LoopbackInterface(address=172.31.1.1, nodeid=1, rank=2)

Or directly from the nodes:

>>> for node in engine.nodes:
...   for lb in node.loopback_interface:
...     lb
...
LoopbackInterface(address=172.20.1.1, nodeid=1, rank=1)
LoopbackInterface(address=172.31.1.1, nodeid=1, rank=2)
get(address)[source]

Get a loopback address by it’s address. Find all loopback addresses by iterating at either the node level or the engine:

loopback = engine.loopback_interface.get('127.0.0.10')
Parameters:

address (str) – ip address of loopback

Raises:

InterfaceNotFound – invalid interface specified

Return type:

LoopbackInterface

class smc.core.collection.PhysicalInterfaceCollection(engine)[source]

Bases: InterfaceCollection

PhysicalInterface Collection provides an interface to retrieving existing interfaces and helper methods to shortcut the creation of an interface.

add(*args, **kwargs)[source]

Add single physical interface with interface_id. Use other methods to fully add an interface configuration based on engine type. Virtual mapping and resource are only used in Virtual Engines.

Parameters:
  • interface_id (str,int) – interface identifier

  • virtual_mapping (int) – virtual firewall id mapping See smc.core.engine.VirtualResource.vfw_id

  • virtual_resource_name (str) – virtual resource name See smc.core.engine.VirtualResource.name

  • lldp_mode (str) – disabled, receive_only, send_and_receive, send_only

Raises:

EngineCommandFailed – failure creating interface

Returns:

None

add_capture_interface(interface_id, logical_interface_ref, inspect_unspecified_vlans=True, zone_ref=None, comment=None)[source]

Add a capture interface. Capture interfaces are supported on Layer 2 engine and IPS engines.

..note:: Capture interface are supported on Layer 3 engine/clusters for NGFW engines

version >= 6.3 and SMC >= 6.3.

Parameters:
  • interface_id (str,int) – interface identifier

  • logical_interface_ref (str) – logical interface name, href or LogicalInterface. If None, ‘default_eth’ logical interface will be used.

  • zone_ref (str) – zone reference, can be name, href or Zone

Raises:

EngineCommandFailed – failure creating interface

Returns:

None

See smc.core.sub_interfaces.CaptureInterface for more information

add_cluster_interface_on_master_engine(interface_id, macaddress, nodes, zone_ref=None, vlan_id=None, comment=None)[source]

Add a cluster address specific to a master engine. Master engine clusters will not use “CVI” interfaces like normal layer 3 clusters, instead each node has a unique address and share a common macaddress. Adding multiple addresses to an interface is not supported with this method.

Parameters:
  • interface_id (str,int) – interface id to use

  • macaddress (str) – mac address to use on interface

  • nodes (list) – interface node list

  • is_mgmt (bool) – is this a management interface

  • zone_ref – zone to use, by name, str href or Zone

  • vlan_id – optional VLAN id if this should be a VLAN interface

Raises:

EngineCommandFailed – failure creating interface

Returns:

None

add_dhcp_interface(interface_id, dynamic_index, zone_ref=None, vlan_id=None, comment=None, pppoe_settings=None, ipv6=False, **kw)[source]

Add a DHCP interface on a single engine :param int interface_id: interface id :param int vlan_id: vlan id :param int dynamic_index: index number for dhcp interface (IPv4/IPv6) :param bool primary_mgt: whether to make this primary mgt :param str zone_ref: zone reference, can be name, href or Zone :param bool ipv6: to set IPv6 dynamic interface mode :param dict pppoe_settings: set pppoe settings with a dict

pppoe_dict = {“pppoe_password”: “password”, “pppoe_servicename”: “sn”, “pppoe_username”: “name”}

Parameters:

comment (str) – comment

Raises:

EngineCommandFailed – failure creating interface

Returns:

None

See DHCPInterface for more information

add_inline_interface(interface_id, second_interface_id, logical_interface_ref=None, vlan_id=None, second_vlan_id=None, zone_ref=None, second_zone_ref=None, failure_mode='normal', comment=None, **kw)[source]

Add an inline interface pair. This method is only for IPS or L2FW engine types.

Parameters:
  • interface_id (str) – interface id of first interface

  • second_interface_id (str) – second interface pair id

  • logical_interface_ref (str, href) – logical interface by href or name

  • vlan_id (str) – vlan ID for first interface in pair

  • second_vlan_id (str) – vlan ID for second interface in pair

  • zone_ref (str, href) – zone reference by name or href for first interface

  • second_zone_ref (str, href) – zone reference by nae or href for second interface

  • failure_mode (str) – normal or bypass

  • comment (str) – optional comment

Raises:

EngineCommandFailed – failure creating interface

Returns:

None

add_inline_ips_interface(interface_id, second_interface_id, logical_interface_ref=None, vlan_id=None, failure_mode='normal', zone_ref=None, second_zone_ref=None, comment=None)[source]

New in version 0.5.6: Using an inline interface on a layer 3 engine requires SMC and engine version >= 6.3.

An inline IPS interface is a new interface type for Layer 3 NGFW engines version >=6.3. Traffic passing an Inline IPS interface will have a access rule default action of Allow. Inline IPS interfaces are bypass capable. When using bypass interfaces and NGFW is powered off, in an offline state or overloaded, traffic is allowed through without inspection regardless of the access rules.

If the interface does not exist and a VLAN id is specified, the logical interface and zones will be applied to the top level physical interface. If adding VLANs to an existing inline ips pair, the logical and zones will be applied to the VLAN.

Parameters:
  • interface_id (str) – first interface in the interface pair

  • second_interface_id (str) – second interface in the interface pair

  • logical_interface_ref (str) – logical interface name, href or LogicalInterface. If None, ‘default_eth’ logical interface will be used.

  • vlan_id (str) – optional VLAN id for first interface pair

  • failure_mode (str) – ‘normal’ or ‘bypass’ (default: normal). Bypass mode requires fail open interfaces.

  • zone_ref – zone for first interface in pair, can be name, str href or Zone

  • second_zone_ref – zone for second interface in pair, can be name, str href or Zone

  • comment (str) – comment for this interface

Raises:

EngineCommandFailed – failure creating interface

Returns:

None

Note

Only a single VLAN is supported on this inline pair type

add_inline_l2fw_interface(interface_id, second_interface_id, logical_interface_ref=None, vlan_id=None, zone_ref=None, second_zone_ref=None, comment=None)[source]

New in version 0.5.6: Requires NGFW engine >=6.3 and layer 3 engine or cluster

An inline L2 engine interface is a new interface type for Layer 3 NGFW engines version >=6.3. Traffic passing an Inline Layer 2 Firewall interface will have a default action in access rules of Discard. Layer 2 Firewall interfaces are not bypass capable, so when NGFW is powered off, in an offline state or overloaded, traffic is blocked on this interface.

If the interface does not exist and a VLAN id is specified, the logical interface and zones will be applied to the top level physical interface. If adding VLANs to an existing inline ips pair, the logical and zones will be applied to the VLAN.

Parameters:
  • interface_id (str) – interface id; ‘1-2’, ‘3-4’, etc

  • logical_interface_ref (str) – logical interface name, href or LogicalInterface. If None, ‘default_eth’ logical interface will be used.

  • vlan_id (str) – optional VLAN id for first interface pair

  • vlan_id2 (str) – optional VLAN id for second interface pair

  • zone_ref_intf1 – zone for first interface in pair, can be name, str href or Zone

  • zone_ref_intf2 – zone for second interface in pair, can be name, str href or Zone

Raises:

EngineCommandFailed – failure creating interface

Returns:

None

Note

Only a single VLAN is supported on this inline pair type

add_layer3_cluster_interface(interface_id, cluster_virtual=None, network_value=None, macaddress=None, nodes=None, cvi_mode='packetdispatch', zone_ref=None, comment=None, lldp_mode=None, **kw)[source]

Add cluster virtual interface. A “CVI” interface is used as a VIP address for clustered engines. Providing ‘nodes’ will create the node specific interfaces. You can also add a cluster address with only a CVI, or only NDI’s.

Add CVI only:

engine.physical_interface.add_cluster_virtual_interface(
    interface_id=30,
    cluster_virtual='30.30.30.1',
    network_value='30.30.30.0/24',
    macaddress='02:02:02:02:02:06')

Add NDI’s only:

engine.physical_interface.add_cluster_virtual_interface(
    interface_id=30,
    nodes=nodes)

Add CVI and NDI’s:

engine.physical_interface.add_cluster_virtual_interface(
    cluster_virtual='5.5.5.1',
    network_value='5.5.5.0/24',
    macaddress='02:03:03:03:03:03',
    nodes=[{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1},
           {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2}])

Changed in version 0.6.1: Renamed from add_cluster_virtual_interface

Parameters:
  • interface_id (str,int) – physical interface identifier

  • cluster_virtual (str) – CVI address (VIP) for this interface

  • network_value (str) – network value for VIP; format: 10.10.10.0/24

  • macaddress (str) – mandatory mac address if cluster_virtual and cluster_mask provided

  • nodes (list) – list of dictionary items identifying cluster nodes

  • cvi_mode (str) – packetdispatch is recommended setting

  • zone_ref (str) – zone reference, can be name, href or Zone

  • lldp_mode (str) – disabled, receive_only, send_and_receive, send_only

  • kw – key word arguments are valid NodeInterface sub-interface settings passed in during create time. For example, ‘backup_mgt=True’ to enable this interface as the management backup.

Raises:

EngineCommandFailed – failure creating interface

Returns:

None

add_layer3_interface(interface_id, address, network_value, zone_ref=None, comment=None, lldp_mode=None, **kw)[source]

Add a layer 3 interface on a non-clustered engine. For Layer 2 engine and IPS engines, this interface type represents a layer 3 routed (node dedicated) interface. For clusters, use the cluster related methods such as add_layer3_cluster_interface()

Parameters:
  • interface_id (str,int) – interface identifier

  • address (str) – ip address

  • network_value (str) – network/cidr (12.12.12.0/24)

  • zone_ref (str) – zone reference, can be name, href or Zone

  • lldp_mode (str) – disabled, receive_only, send_and_receive, send_only

  • comment (str) – optional comment

  • kw – keyword arguments are passed to the sub-interface during create time. If it is a single engine, the sub-interface type is smc.core.sub_interfaces.SingleNodeInterface. For all other engines, the type is smc.core.sub_interfaces.NodeInterface For example, pass ‘backup_mgt=True’ to enable this interface as the management backup.

Raises:

EngineCommandFailed – failure creating interface

Returns:

None

Note

If an existing ip address exists on the interface and zone_ref is provided, this value will overwrite any previous zone definition.

add_layer3_shared_virtual_interface(interface_id, mac_address_prefix, vlan_id=None, virtual_resource_settings=None, zone_ref=None, comment=None, **kw)[source]

New in version 0.7.0: Requires SMC >= 6.6.0

Add a single layer 3 physical interface on a Master NGFW Engine that can be shared by up to 250 Virtual Firewalls. In addition, VLAN interfaces under the physical interface can be shared.

A shared interface can have individual VLANs with single virtual resources but this interface type can provide communication without requiring an external switch (access rules and routing are still required to allow access).

If a VLAN id is not provided, then this interface will be shared by the specified virtual resource settings.

Virtual resource settings should be a list in the following format:

[{'qos_limit': -1,
  'virtual_mapping': '0',
  'virtual_resource_name': 've-1'}]

The qos_limit defines the throughput limit for the given virtual resource (-1 is no limit) in Mbps. The virtual_mapping defines the interface ID that will be seen within the VirtualFirewall. The resource name maps to the VirtualResource and should already exist.

Parameters:
  • interface_id – the interface ID for the shared interface

  • mac_address_prefix (str) – a unique unicast MAC address prefix (the first five octets of a MAC address) that identifies the interface and groups the Virtual Firewalls that use this interface

  • vlan_id (str) – optional VLAN id if specifying shared VLANs

  • virtual_resource_settings (list) – list of virtual resources by name to add to shared interface

  • zone_ref (str) – zone reference, can be name, href or Zone

  • comment (str) – optional comment

add_layer3_vlan_cluster_interface(interface_id, vlan_id, nodes=None, cluster_virtual=None, network_value=None, macaddress=None, cvi_mode='packetdispatch', zone_ref=None, comment=None, **kw)[source]

Add IP addresses to VLANs on a firewall cluster. The minimum params required are interface_id and vlan_id. To create a VLAN interface with a CVI, specify cluster_virtual, cluster_mask and macaddress.

To create a VLAN with only NDI, specify nodes parameter.

Nodes data structure is expected to be in this format:

nodes=[{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1},
       {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2}]
Parameters:
  • interface_id (str,int) – interface id to assign VLAN.

  • vlan_id (str,int) – vlan identifier

  • nodes (list) – optional addresses for node interfaces (NDI’s). For a cluster, each node will require an address specified using the nodes format.

  • cluster_virtual (str) – cluster virtual ip address (optional). If specified, cluster_mask parameter is required

  • network_value (str) – Specifies the network address, i.e. if cluster virtual is 1.1.1.1, cluster mask could be 1.1.1.0/24.

  • macaddress (str) – (optional) if used will provide the mapping from node interfaces to participate in load balancing.

  • cvi_mode (str) – cvi mode for cluster interface (default: packetdispatch)

  • zone_ref – zone to assign, can be name, str href or Zone

  • kw (dict) – keyword arguments are passed to top level of VLAN interface, not the base level physical interface. This is useful if you want to pass in a configuration that enables the DHCP server on a VLAN for example.

Raises:

EngineCommandFailed – failure creating interface

Returns:

None

Note

If the interface_id specified already exists, it is still possible to add additional VLANs and interface addresses.

class smc.core.collection.SwitchInterfaceCollection(engine)[source]

Bases: InterfaceCollection

SwitchInterfaceCollection provides an interface to retrieving existing interfaces and helper methods to shortcut the creation of a switch. Note that switch interfaces are only supported on specific engine types and require that the top level switch is created and port groups are created (although you can use one single port group for the entire switch configuration.

Get specific switch interfaces assigned on the given engine:

for interface in engine.switch_physical_interface:
    print(interface, interface.port_groups_interface)

You can also retrieve a switch directly by referencing it using the switch interface id. Switch interfaces will always have a name starting with ‘SWP_’. For example, SWP_0 specifies physical switch port 0:

engine.switch_physical_interface.get('SWP_0')

You can also get port_group_interfaces directly:

engine.switch_physical_interface.get('SWP_0.1')

Or iterate through the port_group_interface collection:

interface = engine.switch_physical_interface.get('SWP_0')
for port_group in interface.port_group_interface:
    ...
add_port_group_interface(interface_id, port_group_id, interface_ports, interfaces=None, zone_ref=None)[source]

Add a port group to an existing switch physical interface. If the switch port should have an address assigned, use the following format:

engine.switch_physical_interface.add_port_group_interface('SWP_1', 1, [1],
        interfaces=[{'nodes': [{'address': '12.12.12.12',
                                'network_value': '12.12.12.0/24',
                                'nodeid': 1}]}])

To create a generic switch port group without IP addresses assigned with port group ID 1 and using physical port numbers 2,3,4,5:

engine.switch_physical_interface.add_port_group_interface('SWP_1', 1, [2,3,4,5])

Note

If the port group ID exists, this method will modify the existing port group with the specified settings

Parameters:
  • interface_id (str) – The top level switch, naming convention should be SWP_0, SWP_1, etc. ( Since API 6.8: SWI_0, SWI_1..)

  • port_group_id (int) – Port group number encapsulating switch port/s

  • interface_ports (list) – list of interface ports to add to this port group. If the port group.

  • interfaces (list) – list of interface node definitions if the switch port should have IP address/es assigned

  • zone_ref (str) – zone reference, can be name, href or Zone, will be created if it doesn’t exist

Raises:

InterfaceNotFound – invalid switch interface_id specified

Returns:

None

add_switch_interface(interface_id, appliance_switch_module='110', comment=None, **kwargs)[source]

In case of Switch Physical/Port Group interfaces, the interface ID must be prefixed by ‘SWP_’. For example, for switch ID 1 and Port Group ID 1.2 you must enter ‘SWP_1’ for the switch and SWP_1.2 for the Port Group. Since API 6.8 prefix is ‘SWI_’

Parameters:
  • interface_id (str) – Name of the interface, must be prefixed with ‘SWP_’

  • appliance_switch_module (str) – appliance switch module which specifies the hardware module (default: ‘110’)

  • comment (str) – optional comment

  • kwargs (dict) – optional kwargs conforming to the port group dict format if port groups need to be created

Raises:

EngineCommandFailed – failure during creation

Returns:

None

class smc.core.collection.TunnelInterfaceCollection(engine)[source]

Bases: InterfaceCollection

TunnelInterface Collection provides an interface to retrieving existing interfaces and helper methods to shortcut the creation of an interface.

add_cluster_virtual_interface(interface_id, cluster_virtual=None, network_value=None, nodes=None, zone_ref=None, comment=None, **kw)[source]

Add a tunnel interface on a clustered engine. For tunnel interfaces on a cluster, you can specify a CVI only, NDI interfaces, or both. This interface type is only supported on layer 3 firewall engines.

Add a tunnel CVI and NDI:

engine.tunnel_interface.add_cluster_virtual_interface(
    interface_id_id=3000,
    cluster_virtual='4.4.4.1',
    network_value='4.4.4.0/24',
    nodes=nodes)

Add tunnel NDI's only:

engine.tunnel_interface.add_cluster_virtual_interface(
    interface_id=3000,
    nodes=nodes)

Add tunnel CVI only:

engine.tunnel_interface.add_cluster_virtual_interface(
    interface_id=3000,
    cluster_virtual='31.31.31.31',
    network_value='31.31.31.0/24',
    zone_ref='myzone')
Parameters:
  • interface_id (str,int) – tunnel identifier (akin to interface_id)

  • cluster_virtual (str) – CVI ipaddress (optional)

  • network_value (str) – CVI network; required if cluster_virtual set

  • nodes (list) – nodes for clustered engine with address,network_value,nodeid

  • zone_ref (str) – zone reference, can be name, href or Zone

  • comment (str) – optional comment

Raises:

EngineCommandFailed – failure during creation

Returns:

None

add_layer3_interface(interface_id, address=None, network_value=None, zone_ref=None, comment=None, **kw)[source]

Creates a tunnel interface with sub-type single_node_interface. This is to be used for single layer 3 firewall instances.

Note

If no address or network_value is provided, an unconfigured tunnel interface will be created

Parameters:
  • interface_id (str,int) – the tunnel id for the interface, used as nicid also

  • address (str) – ip address of interface

  • network_value (str) – network cidr for interface; format: 1.1.1.0/24

  • zone_ref (str) – zone reference for interface can be name, href or Zone

  • comment (str) – optional comment

Raises:

EngineCommandFailed – failure during creation

Returns:

None

class smc.core.collection.VPNBrokerInterfaceCollection(engine)[source]

Bases: InterfaceCollection

VPNBrokerInterfaceCollection Collection provides an interface to retrieving existing interfaces and helper methods to shortcut the creation of an interface.

add_cluster_virtual_interface(interface_id, cluster_virtual=None, vpn_broker_domain_ref=None, mac_address_postfix=None, shared_secret=None, network_value=None, nodes=None, zone_ref=None, comment=None, retrieve_routes=None, adjust_antispoofing=None, **kw)[source]

Add a VPN Broker interface on a clustered engine. For VPN Broker interfaces on a cluster, you can specify a CVI only, NDI interfaces, or both. This interface type is only supported on layer 3 firewall engines.

Add a VPN Broker CVI and NDI:

engine.vpn_broker_interface.add_cluster_virtual_interface(
    interface_id_id=3000,
    cluster_virtual='4.4.4.1',
    network_value='4.4.4.0/24',
    nodes=nodes)

Add VPN Broker NDI's only:

engine.vpn_broker_interface.add_cluster_virtual_interface(
    interface_id=3000,
    nodes=nodes)

Add VPN Broker CVI only:

engine.vpn_broker_interface.add_cluster_virtual_interface(
    interface_id=3000,
    cluster_virtual='31.31.31.31',
    network_value='31.31.31.0/24',
    zone_ref='myzone')
add_layer3_interface(interface_id, address=None, network_value=None, zone_ref=None, comment=None, vpn_broker_domain_ref=None, mac_address_postfix=None, retrieve_routes=None, adjust_antispoofing=None, shared_secret=None, **kw)[source]

Creates a vpn broker interface with sub-type single_node_interface. This is to be used for single layer 3 firewall instances.

class smc.core.collection.VirtualPhysicalInterfaceCollection(engine)[source]

Bases: InterfaceCollection

PhysicalInterface Collection provides an interface to retrieving existing interfaces and helper methods to shortcut the creation of an interface.

add_layer3_interface(interface_id, address, network_value, zone_ref=None, comment=None, **kw)[source]

Add a layer 3 interface on a virtual engine.

Parameters:
  • interface_id (str,int) – interface identifier

  • address (str) – ip address

  • network_value (str) – network/cidr (12.12.12.0/24)

  • zone_ref (str) – zone reference, can be name, href or Zone

  • kw – keyword arguments are passed are any value attribute values of type smc.core.sub_interfaces.NodeInterface

Raises:

EngineCommandFailed – failure creating interface

Returns:

None

Note

If an existing ip address exists on the interface and zone_ref is provided, this value will overwrite any previous zone definition.

add_tunnel_interface(interface_id, address, network_value, zone_ref=None, comment=None)[source]

Creates a tunnel interface for a virtual engine.

Parameters:
  • interface_id (str,int) – the tunnel id for the interface, used as nicid also

  • address (str) – ip address of interface

  • network_value (str) – network cidr for interface; format: 1.1.1.0/24

  • zone_ref (str) – zone reference for interface can be name, href or Zone

Raises:

EngineCommandFailed – failure during creation

Returns:

None

Interface module encapsulates interface types for security engines. All interface have a ‘top level’ such as Physical or Tunnel Interface. These top level interfaces have certain common settings that can be modified such as assigning a zone.

IP addresses, netmask, management settings, VLANs, etc are part of an interfaces ‘sub’ interface. Sub interfaces can be retrieved from an engine reference and call to sub_interfaces()

The interface hierarchy resembles:

    Interface
        |
Physical/Tunnel Interface
        |
        | - VlanInterface (is a PhysicalInterface)
        |      /
    Sub Interfaces (SingleNodeInterface, NodeInterface, InlineInterface, etc)
        |
    Attributes (address, network_value, vlan_id, etc)

Sub interfaces are documented in smc.core.sub_interfaces.

VLANs are properties of specific interfaces and can also be retrieved by first getting the top level interface, and calling

to view or modify specific aspects of a VLAN, such as addresses, etc.

class smc.core.interfaces.Interface(**meta)[source]

Interface settings common to all interface types.

add_ip_address(cvi=None, sni=None, nodes=None)[source]

Add an ip address(ipv4/ipv6) to tunnel interface :param SingleNodeInterface sni: The single node interface. :param ClusterVirtualInterface cvi: The cluster virtual interface instance. :param list(NodeInterface) nodes: List of Node Interface instance.

property addresses

Return 3-tuple with (address, network, nicid)

Returns:

address related information of interface as 3-tuple list

Return type:

list

property all_interfaces

Access to all assigned sub-interfaces on this interface. A sub interface is the node level where IP addresses are assigned, or a inline interface is defined, VLANs, etc. Example usage:

>>> engine = Engine('dingo')
>>> itf = engine.interface.get(0)
>>> assigned = itf.all_interfaces
>>> list(assigned)
[SingleNodeInterface(address=1.1.1.1)]
>>> assigned.get(address='1.1.1.1')
SingleNodeInterface(address=1.1.1.1)
>>> itf = engine.interface.get(52)
>>> assigned = itf.all_interfaces
>>> list(assigned)
[Layer3PhysicalInterfaceVlan(name=VLAN 52.52),
 Layer3PhysicalInterfaceVlan(name=VLAN 52.53)]
>>> vlan = assigned.get(vlan_id='52')
>>> vlan.addresses
[(u'52.52.52.52', u'52.52.52.0/24', u'52.52')]
Return type:

BaseIterable(AllInterfaces)

change_interface_id(interface_id)[source]

Change the interface ID for this interface. This can be used on any interface type. If the interface is an Inline interface, you must provide the interface_id in format ‘1-2’ to define both interfaces in the pair. The change is committed after calling this method.

itf = engine.interface.get(0)
itf.change_interface_id(10)

Or inline interface pair 10-11:

itf = engine.interface.get(10)
itf.change_interface_id('20-21')
Parameters:

interface_id (str,int) – new interface ID. Format can be single value for non-inline interfaces or ‘1-2’ format for inline.

Raises:

UpdateElementFailed – changing the interface failed with reason

Returns:

None

property comment

Optional interface comment

Returns:

str or None

property contact_addresses

Configure an interface contact address for this interface. Note that an interface may have multiple IP addresses assigned so you may need to iterate through contact addresses. Example usage:

>>> itf = engine.interface.get(0)
>>> itf.contact_addresses
[ContactAddressNode(interface_id=0, interface_ip=1.1.1.10),
 ContactAddressNode(interface_id=0, interface_ip=1.1.1.25)]
>>> for ca in itf.contact_addresses:
...   print("IP: %s, addresses: %s" % (ca.interface_ip, list(ca)))
...
IP: 1.1.1.10, addresses: []
IP: 1.1.1.25, addresses: [InterfaceContactAddress(address=172.18.1.20,
                          location=Default)]

>>> for ca in itf.contact_addresses:
...   if ca.interface_ip == '1.1.1.10':
...     ca.add_contact_address('10.5.5.5', location='remote')
Returns:

list of interface contact addresses

Return type:

ContactAddressNode

delete()[source]

Override delete in parent class, this will also delete the routing configuration referencing this interface.

engine = Engine('vm')
interface = engine.interface.get(2)
interface.delete()
delete_invalid_route()[source]

Delete any invalid routes for this interface. An invalid route is a left over when an interface is changed to a different network.

Returns:

None

get_boolean(name)[source]

Get the boolean value for attribute specified from the sub interface/s.

property has_interfaces

Does the interface have interface have any sub interface types assigned. For example, a physical interface with no IP addresses would return False.

Returns:

Does this interface have actual types assigned

Return type:

bool

property has_vlan

Does the interface have VLANs

Returns:

Whether VLANs are configured

Return type:

bool

property interface_id

The Interface ID automatically maps to a physical network port of the same number during the initial configuration of the engine, but the mapping can be changed as necessary. Call change_interface_id() to change inline, VLAN, cluster and single interface ID’s.

Note

It is not possible to change an interface ID from a VlanInterface. You must call on the parent PhysicalInterface.

Parameters:

value (str) – interface_id

Return type:

str

property interfaces

Access to assigned sub-interfaces on this interface. A sub interface is the node level where IP addresses are assigned, or a layer 2 interface is defined.

>>> itf = engine.interface.get(20)
>>> assigned = itf.interfaces
>>> list(assigned)
[SingleNodeInterface(address=20.20.20.20), SingleNodeInterface(address=21.21.21.21)]
>>> assigned.get(address='20.20.20.20')
SingleNodeInterface(address=20.20.20.20)
Return type:

BaseIterable(SubInterfaceCollection)

property log_moderation

This is the definition of Log Compression for the engine or for an interface. You can also configure Log Compression to save resources on the engine. By default, each generated Antispoofing and Discard log entry is logged separately and displayed as a separate entry in the Logs view. Log Compression allows you to define the maximum number of separately logged entries.When the defined limit is reached, a single Antispoofing log entry or Discard log entry is logged. The single entry contains information on the total number of the generated Antispoofing log entries or Discard log entries. After this, logging returns to normal and all the generated entries are once more logged and displayed separately. Example of using log moderation settings:

>>> engine = Engine("testme")
>>> interface = engine.interface.get(1)
>>> log_moderation_obj = interface.log_moderation
>>> log_moderation_obj.get(1)["rate"]
    100
>>> log_moderation_obj.get(1)["burst"]
    1000
>>> log_moderation_obj.add(rate=200,burst=1100,log_event=2)
>>> interface.update()
>>> engine = Engine("testme")
>>> interface = engine.interface.get(1)
>>> log_moderation_obj=interface.log_moderation
>>> log_moderation_obj.get(2)["rate"]
    200
>>> log_moderation_obj.get(2)["burst"]
    1100

:rtype LogModeration

property name

Read only name tag

property port_group_interface

The associated port group interfaces for this switch physical interface.

Return type:

PortGroupInterfaceCollection(PortGroupInterface)

reset_interface()[source]

Reset the interface by removing all assigned addresses and VLANs. This will not delete the interface itself, only the sub interfaces that may have addresses assigned. This will not affect inline or capture interfaces. Note that if this interface is used as a primary control, auth request or outgoing interface, the update will fail. You should move that functionality to another interface before calling this. See also:: smc.core.engine.interface_options.

Raises:

UpdateElementFailed – failed to update the interfaces. This is usually caused when the interface is assigned as a control, outgoing, or auth_request interface.

Returns:

None

sub_interfaces()[source]

Flatten out all top level interfaces and only return sub interfaces. It is recommended to use all_interfaces(), interfaces() or vlan_interfaces() which return collections with helper methods to get sub interfaces based on index or attribute value pairs.

Return type:

list(SubInterface)

update(*args, **kw)[source]

Update/save this interface information back to SMC. When interface changes are made, especially to sub interfaces, call update on the top level interface.

Example of changing the IP address of an interface:

>>> engine = Engine('sg_vm')
>>> interface = engine.physical_interface.get(1)
>>> interface.zone_ref = zone_helper('mynewzone')
>>> interface.update()
Raises:

UpdateElementFailed – failure to save changes

Returns:

Interface

update_interface(other_interface, ignore_mgmt=True)[source]

Update an existing interface by comparing values between two interfaces. If a VLAN interface is defined in the other interface and it doesn’t exist on the existing interface, it will be created.

Parameters:
  • Interface (other_interface) – an instance of an interface where values in this interface will be used to as the template to determine changes. This only has to provide attributes that need to change (or not).

  • ignore_mgmt (bool) – ignore resetting management fields. These are generally better set after creation using engine.interface_options

Raises:

UpdateElementFailed – Failed to update the element

Returns:

(Interface, modified, created)

Return type:

tuple

Note

Interfaces with multiple IP addresses are ignored

property vlan_interface

Access VLAN interfaces for this interface, if any. Example usage:

>>> itf = engine.interface.get(52)
>>> assigned = itf.vlan_interface
>>> list(assigned)
[Layer3PhysicalInterfaceVlan(name=VLAN 52.52),
 Layer3PhysicalInterfaceVlan(name=VLAN 52.53)]
>>> vlan = assigned.get(vlan_id='52')
>>> vlan.addresses
[(u'52.52.52.52', u'52.52.52.0/24', u'52.52')]
>>> assigned.get(address='12.12.12.13')
SingleNodeInterface(address=12.12.12.13, vlan_id=1)
>>> assigned.get(vlan_id='1')
SingleNodeInterface(address=12.12.12.12, vlan_id=1)
>>> assigned.get(vlan_id='2')
SingleNodeInterface(address=36.35.35.37, vlan_id=2)
Return type:

BaseIterable(VlanInterface)

property zone

Return the Zone for this interface, otherwise None

Returns:

Zone or None

property zone_ref

Zone for this physical interface.

Parameters:

value (str) – href of zone, set to None to remove existing zone

Return type:

str

InterfaceOptions

class smc.core.interfaces.InterfaceOptions(engine)[source]

Interface Options allow you to define settings related to the roles of the firewall interfaces:

  • Which IP addresses are used as the primary and backup Control IP address

  • Which interfaces are used as the primary and backup heartbeat interface

  • The default IP address for outgoing traffic

You can optionally change which interface is used for each of these purposes, and define a backup Control IP address and backup Heartbeat Interface. If calling the set methods, using a value of None will unset the option.

Note

Setting an interface option will commit the change immediately.

property auth_request

Return the interface for authentication requests. Can be either a PhysicalInterface or LoopbackInterface

Returns:

interface id

Return type:

str

property backup_heartbeat

Obtain the interface specified as the backup heartbeat interface. This may return None if a backup has not been specified or this is not a cluster.

Returns:

interface id

Return type:

str

property backup_mgt

Obtain the interface specified as the backup management interface. This can return None if no backup has been defined

Returns:

interface id

Return type:

str

property outgoing

Obtain the interface specified as the “Default IP address for outgoing traffic”. This will always return a value.

Returns:

interface id

Return type:

str

property primary_heartbeat

Obtain the interface specified as the primary heartbeat interface. This will return None if this is not a clustered engine.

Returns:

interface id

Return type:

str

property primary_mgt

Obtain the interface specified as the primary management interface. This will always return a value as you must have at least one physical interface specified for management.

Returns:

interface id

Return type:

str

set_auth_request(interface_id, address=None)[source]

Set the authentication request field for the specified engine.

set_backup_heartbeat(interface_id)[source]

Set this interface as the backup heartbeat interface. Clusters and Master NGFW Engines only.

Parameters:

interface_id (str,int) – interface as backup

Raises:
Returns:

None

set_backup_mgt(interface_id)[source]

Set this interface as a backup management interface.

Backup management interfaces cannot be placed on an interface with only a CVI (requires node interface/s). To ‘unset’ the specified interface address, set interface id to None

engine.interface_options.set_backup_mgt(2)

Set backup on interface 1, VLAN 201:

engine.interface_options.set_backup_mgt('1.201')

Remove management backup from engine:

engine.interface_options.set_backup_mgt(None)
Parameters:

interface_id (str,int) – interface identifier to make the backup management server.

Raises:
Returns:

None

set_outgoing(interface_id)[source]

Specifies the IP address that the engine uses to initiate connections (such as for system communications and ping) through an interface that has no Node Dedicated IP Address. In clusters, you must select an interface that has an IP address defined for all nodes. Setting primary_mgt also sets the default outgoing address to the same interface.

Parameters:

interface_id (str,int) – interface to set outgoing

Raises:
Returns:

None

set_primary_heartbeat(interface_id)[source]

Set this interface as the primary heartbeat for this engine. This will ‘unset’ the current primary heartbeat and move to specified interface_id. Clusters and Master NGFW Engines only.

Parameters:

interface_id (str,int) – interface specified for primary mgmt

Raises:
Returns:

None

set_primary_mgt(interface_id, auth_request=None, address=None)[source]

Specifies the Primary Control IP address for Management Server contact. For single engine and cluster engines, this will enable ‘Outgoing’, ‘Auth Request’ and the ‘Primary Control’ interface. For clusters, the primary heartbeat will NOT follow this change and should be set separately using set_primary_heartbeat(). For virtual engines, only auth_request and outgoing will be set. For master engines, only primary control and outgoing will be set.

Primary management can be set on an interface with single IP’s, multiple IP’s or VLANs.

engine.interface_options.set_primary_mgt(1)

Set primary management on a VLAN interface:

engine.interface_options.set_primary_mgt('1.100')

Set primary management and different interface for auth_request:

engine.interface_options.set_primary_mgt(
    interface_id='1.100', auth_request=0)

Set on specific IP address of interface VLAN with multiple addresses:

engine.interface_options.set_primary_mgt(
    interface_id='3.100', address='50.50.50.1')
Parameters:
  • interface_id (str,int) – interface id to make management

  • address (str) – if the interface for management has more than one ip address, this specifies which IP to bind to.

  • auth_request (str,int) – if setting primary mgt on a cluster interface with no CVI, you must pick another interface to set the auth_request field to (default: None)

Raises:
Returns:

None

Note

Setting primary management on a cluster interface with no CVI requires you to set the interface for auth_request.

QoS

class smc.core.interfaces.QoS(interface)[source]

QoS can be placed on physical interfaces, physical VLAN interfaces and tunnel interfaces. It is possible to have multiple QoS policies defined if using VLANs on a physical interface as QoS can be attached directly at the interface level or VLAN level. You obtain the QoS reference after retrieving the interface:

itf = engine.interface.get(0)
itf.qos.full_qos(100000, QoSPolicy('testqos'))
itf.update()

Disable QoS:

itf = engine.interface.get(0)
itf.qos.disable()
itf.update()

On a tunnel interface:

itf = engine.interface.get(1000)
itf.qos.full_qos(100000, QoSPolicy('testqos'))
itf.update()

Or a VLAN:

itf = engine.interface.get('1.100')
itf.qos.full_qos(100000, QoSPolicy('testqos'))
itf.update()

Note

You must call update on the interface to commit the change

disable()[source]

Disable QoS on this interface

dscp_marking_and_throttling(qos_policy)[source]

Enable DSCP marking and throttling on the interface. This requires that you provide a QoS policy to which identifies DSCP tags and how to prioritize that traffic.

Parameters:

qos_policy (QoSPolicy) – the qos policy to apply to the interface

full_qos(qos_limit, qos_policy)[source]

Enable full QoS on the interface. Full QoS requires that you set a bandwidth limit (in Mbps) for the interface. You must also provide a QoS policy to which identifies the parameters for prioritizing traffic.

Parameters:
  • qos_limit (int) – max bandwidth in Mbps

  • qos_policy (QoSPolicy) – the qos policy to apply to the interface

property qos_limit

QoS Limit for this interface. The limit represents the number in bps. For example, 100000 represents 100Mbps.

Return type:

int

property qos_mode

QoS mode in string format

Return type:

str

property qos_policy

QoS Policy for this interface/vlan. A QoS policy will only be present if DSCP throttling or Full QoS is specified.

Return type:

QoSPolicy

statistics_only()[source]

Set interface to collect QoS statistics only. No enforcement is being done but visiblity will be provided in dashboards against applications tagged by QoS.

LoopbackInterface

class smc.core.sub_interfaces.LoopbackInterface(data, engine=None)[source]

Bases: NodeInterface

Loopback interface for a physical or virtual single firewall. To create a loopback interface, call from the engine node:

engine.loopback_interface.add_single(...)
add_node_loopback(addresses, **kwargs)[source]

Add a node loopback interface to this engine.

Parameters:

addresses (dict) – {nodeid: {‘address’:’127.0.0.1’, ‘ospf_area’:ospfArea}, …}

Raises:

UpdateElementFailed – failure to create loopback address

Returns:

None

add_single(address, rank=1, nodeid=1, ospf_area=None, **kwargs)[source]

Add a single loopback interface to this engine. This is used for single or virtual engines.

Parameters:
  • address (str) – ip address for loopback

  • nodeid (int) – nodeid to apply. Default to 1 for single engine

  • ospf_area (str, Element) – ospf area href or element

Raises:

UpdateElementFailed – failure to create loopback address

Returns:

None

delete()[source]

Delete a loopback interface from this engine. Changes to the engine configuration are done immediately.

A simple way to obtain an existing loopback is to iterate the loopbacks or to get by address:

lb = engine.loopback_interface.get('127.0.0.10')
lb.delete()

Warning

When deleting a loopback assigned to a node on a cluster all loopbacks with the same rank will also be removed.

Raises:

UpdateElementFailed – failure to delete loopback interface

Returns:

None

LoopbackClusterInterface

class smc.core.sub_interfaces.LoopbackClusterInterface(data, engine=None)[source]

Bases: ClusterVirtualInterface

This represents the CVI Loopback IP address. A CVI loopback IP address is used for loopback traffic that is sent to the whole cluster. It is shared by all the nodes in the cluster.

add_cvi_loopback(address, ospf_area=None, **kw)[source]

Add a loopback interface as a cluster virtual loopback. This enables the loopback to ‘float’ between cluster members. Changes are committed immediately.

Parameters:
  • address (str) – ip address for loopback

  • rank (int) – rank of this entry

  • ospf_area (str,Element) – optional ospf_area to add to loopback

Raises:

UpdateElementFailed – failure to save loopback address

Returns:

None

delete()[source]

Delete a loopback cluster virtual interface from this engine. Changes to the engine configuration are done immediately.

You can find cluster virtual loopbacks by iterating at the engine level:

for loopbacks in engine.loopback_interface:
    ...
Raises:

UpdateElementFailed – failure to delete loopback interface

Returns:

None

PhysicalInterface

class smc.core.interfaces.PhysicalInterface(engine=None, meta=None, **interface)[source]

Bases: Interface

Physical Interfaces on NGFW. This represents the following base configuration for the following interface types:

  • Single Node Interface

  • Node Interface

  • Capture Interface

  • Inline Interface

  • Cluster Virtual Interface

  • Virtual Physical Interface (used on Virtual Engines)

  • DHCP Interface

This should be used to add interfaces to an engine after it has been created. First get the engine context by loading the engine then get the engine property for physical interface:

engine = Engine('myfw')
engine.physical_interface.add_layer3_interface(.....)
engine.physical_interface.add(5) #single unconfigured physical interface
engine.physical_interface.add_inline_ips_interface('5-6', ....)
....

When making changes, the etag used should be the top level engine etag.

property aggregate_mode

LAGG configuration mode for this interface. Values are ‘ha’ or ‘lb’ (load balancing). This can return None if LAGG is not configured.

Returns:

aggregate mode set, if any

Return type:

str, None

property arp_entry

Return any manually configured ARP entries for this physical interface

Returns:

arp entries as dict

Return type:

list

change_vlan_id(original, new)[source]

Change VLAN ID for a single VLAN, cluster VLAN or inline interface. When changing a single or cluster engine vlan, you can specify the original VLAN and new VLAN as either single int or str value. If modifying an inline interface VLAN when the interface pair has two different VLAN identifiers per interface, use a str value in form: ‘10-11’ (original), and ‘20-21’ (new).

Single VLAN id:

>>> engine = Engine('singlefw')
>>> itf = engine.interface.get(1)
>>> itf.vlan_interfaces()
[PhysicalVlanInterface(vlan_id=11), PhysicalVlanInterface(vlan_id=10)]
>>> itf.change_vlan_id(11, 100)
>>> itf.vlan_interfaces()
[PhysicalVlanInterface(vlan_id=100), PhysicalVlanInterface(vlan_id=10)]

Inline interface with unique VLAN on each interface pair:

>>> itf = engine.interface.get(2)
>>> itf.vlan_interfaces()
[PhysicalVlanInterface(vlan_id=2-3)]
>>> itf.change_vlan_id('2-3', '20-30')
>>> itf.vlan_interfaces()
[PhysicalVlanInterface(vlan_id=20-30)]
Parameters:
  • original (str,int) – original VLAN to change.

  • new (str,int) – new VLAN identifier/s.

Raises:
Returns:

None

enable_aggregate_mode(mode, interfaces)[source]

Enable Aggregate (LAGG) mode on this interface. Possible LAGG types are ‘ha’ and ‘lb’ (load balancing). For HA, only one secondary interface ID is required. For load balancing mode, up to 7 additional are supported (8 max interfaces).

Parameters:
  • mode (str) – ‘lb’ or ‘ha’

  • interfaces (list(str,int)) – secondary interfaces for this LAGG

Raises:

UpdateElementFailed – failed adding aggregate

Returns:

None

property is_auth_request

Is this physical interface tagged as the interface for authentication requests

Return type:

bool

property is_backup_heartbeat

Is this physical interface tagged as the backup heartbeat interface for this cluster.

Returns:

is backup heartbeat

Return type:

bool

property is_backup_mgt

Is this physical interface tagged as the backup management interface for this cluster.

Returns:

is backup heartbeat

Return type:

bool

property is_outgoing

Is this the default interface IP used for outgoing for system communications.

Returns:

is dedicated outgoing IP interface

Return type:

bool

property is_primary_heartbeat

Is this physical interface tagged as the primary heartbeat interface for this cluster.

Returns:

is backup heartbeat

Return type:

bool

property is_primary_mgt

Is this physical interface tagged as the backup management interface for this cluster.

Returns:

is backup heartbeat

Return type:

bool

property lldp_mode

Represents the LLDP Mode configuration on an interface. Send is to advertise information about device itself. Receive is to receive information about the neighbouring devices. Disable is the default selection. Supported values are: disabled, receive_only, send_and_receive, send_only :rtype: str

property mtu

Set MTU on interface. Enter a value between 400-65535. The same MTU is automatically applied to any VLANs created under this physical interface

Parameters:

value (int) – MTU

Return type:

int

property multicast_ip

Enter a multicast address, that is, an IP address from the range 224.0.0.0-239.255.255.255. The address is used for automatically calculating a MAC address. Required only if multicastigmp cvi mode is selected as the cvi_mode.

Parameters:

value (str) – address

Return type:

str

property ndi_interfaces

Return a formatted dict list of NDI interfaces on this engine. This will ignore CVI or any inline or layer 2 interface types. This can be used to identify to indicate available IP addresses for a given interface which can be used to run services such as SNMP or DNS Relay.

Returns:

list of dict items [{‘address’:x, ‘nicid’:y}]

Return type:

list(dict)

property qos

The QoS settings for this physical interface

Return type:

QoS

property second_interface_id

Peer interfaces used in LAGG configuration.

Parameters:

value (str) – comma seperated nic id’s for LAGG peers

Return type:

str

static_arp_entry(ipaddress, macaddress, arp_type='static', netmask=32)[source]

Add an arp entry to this physical interface.

interface = engine.physical_interface.get(0)
interface.static_arp_entry(
    ipaddress='23.23.23.23',
    arp_type='static',
    macaddress='02:02:02:02:04:04')
interface.save()
Parameters:
  • ipaddress (str) – ip address for entry

  • macaddress (str) – macaddress for ip address

  • arp_type (str) – type of entry, ‘static’ or ‘proxy’ (default: static)

  • netmask (str,int) – netmask for entry (default: 32)

Returns:

None

property virtual_engine_vlan_ok

Whether to allow VLAN creation on the Virtual Engine. Only valid for master engine.

Parameters:

value (bool) – enable/disable

Return type:

bool

property virtual_mapping

The virtual mapping id. Required if Virtual Resource chosen. See smc.core.engine.VirtualResource.vfw_id

Parameters:

value (int) – vfw_id

Return type:

int

property virtual_resource_name

Virtual Resource name used on Master Engine to map a virtual engine. See smc.core.engine.VirtualResource.name

Parameters:

value (str) – virtual resource name

Return type:

str

Layer3PhysicalInterface

class smc.core.interfaces.Layer3PhysicalInterface(engine=None, meta=None, **interface)[source]

Bases: PhysicalInterface

Represents a routed layer 3 interface on an any engine type.

Example interface:

interface = {
    'comment': u'Regular interface',
    'interface_id': u'67',
    'interfaces': [{'nodes': [{'address': u'5.5.5.2',
                               'network_value': u'5.5.5.0/24',
                               'nodeid': 1},
                              {'address': u'5.5.5.3',
                               'network_value': u'5.5.5.0/24',
                               'nodeid': 1}]}],
     'zone_ref': 'foozone'}

Layer3 VLAN interface:

interface = {
    'comment': u'Interface with VLAN',
    'interface_id': u'67',
    'interfaces': [{'nodes': [{'address': u'5.5.5.2',
                               'network_value': u'5.5.5.0/24',
                               'nodeid': 1},
                              {'address': u'5.5.5.3',
                               'network_value': u'5.5.5.0/24',
                               'nodeid': 1}],
                    'vlan_id': 10}],
     'zone_ref': 'foozone'}

DHCP interface on a VLAN (use dynamic and specify dynamic_index):

interface = {
    'comment': u'Interface with VLAN',
    'interface_id': u'67',
    'interfaces': [{'nodes': [{'dynamic': True,
                               'dynamic_index': 2,
                               'nodeid': 1}],
                    'vlan_id': 10}],
     'zone_ref': 'foozone'}

When an interface is created, the first key level is applied to the “top” level physical interface. The interfaces list specifies the node and addressing information using the nodes parameter. If vlan_id is specified as a key/value in the interfaces dict, the list dict keys are applied to the nested physical interface VLAN.

Parameters:
  • interface_id (str) – id for interface

  • interface (str) – specifies the type of interface to create. The interface type defaults to ‘node_interface’ and applies to all engine types except a single engine. For single engine, specify single_node_interface

  • interfaces (list) – interface attributes, cluster_virtual, network_value, nodes, etc

  • nodes (dict) – nodes dict should contain keys address, network_value and nodeid. Overridden sub interface settings can also be set here

  • zone_ref (str) – zone reference, name or zone

  • comment (str) – comment for interface

Layer2PhysicalInterface

class smc.core.interfaces.Layer3PhysicalInterface(engine=None, meta=None, **interface)[source]

Bases: PhysicalInterface

Represents a routed layer 3 interface on an any engine type.

Example interface:

interface = {
    'comment': u'Regular interface',
    'interface_id': u'67',
    'interfaces': [{'nodes': [{'address': u'5.5.5.2',
                               'network_value': u'5.5.5.0/24',
                               'nodeid': 1},
                              {'address': u'5.5.5.3',
                               'network_value': u'5.5.5.0/24',
                               'nodeid': 1}]}],
     'zone_ref': 'foozone'}

Layer3 VLAN interface:

interface = {
    'comment': u'Interface with VLAN',
    'interface_id': u'67',
    'interfaces': [{'nodes': [{'address': u'5.5.5.2',
                               'network_value': u'5.5.5.0/24',
                               'nodeid': 1},
                              {'address': u'5.5.5.3',
                               'network_value': u'5.5.5.0/24',
                               'nodeid': 1}],
                    'vlan_id': 10}],
     'zone_ref': 'foozone'}

DHCP interface on a VLAN (use dynamic and specify dynamic_index):

interface = {
    'comment': u'Interface with VLAN',
    'interface_id': u'67',
    'interfaces': [{'nodes': [{'dynamic': True,
                               'dynamic_index': 2,
                               'nodeid': 1}],
                    'vlan_id': 10}],
     'zone_ref': 'foozone'}

When an interface is created, the first key level is applied to the “top” level physical interface. The interfaces list specifies the node and addressing information using the nodes parameter. If vlan_id is specified as a key/value in the interfaces dict, the list dict keys are applied to the nested physical interface VLAN.

Parameters:
  • interface_id (str) – id for interface

  • interface (str) – specifies the type of interface to create. The interface type defaults to ‘node_interface’ and applies to all engine types except a single engine. For single engine, specify single_node_interface

  • interfaces (list) – interface attributes, cluster_virtual, network_value, nodes, etc

  • nodes (dict) – nodes dict should contain keys address, network_value and nodeid. Overridden sub interface settings can also be set here

  • zone_ref (str) – zone reference, name or zone

  • comment (str) – comment for interface

ClusterPhysicalInterface

class smc.core.interfaces.ClusterPhysicalInterface(engine=None, meta=None, **interface)[source]

Bases: PhysicalInterface

A ClusterPhysicalInterface represents an interface on a cluster that is a physical interface type. A cluster interface can have a CVI, NDI’s, or CVI’s and NDI’s.

Example interface format, with CVI and 2 nodes:

 interface = {
     'interface_id': '23',
     'comment': 'my comment',
     'zone_ref': 'zone1',
     'cvi_mode': 'packetdispatch',
     'macaddress': '02:08:08:02:02:06',
     'interfaces': [{'cluster_virtual': '241.241.241.250',
                     'network_value': '241.241.241.0/24',
                     'nodes': [{'address': '241.241.241.2',
                                'network_value': '241.241.241.0/24', 'nodeid': 1},
                               {'address': '241.241.241.3',
                                'network_value': '241.241.241.0/24', 'nodeid': 2}]
                     }]}

Example interface with VLAN and CVI / NDI::

interface = {
    'interface_id': '24',
    'cvi_mode': 'packetdispatch',
    'macaddress': '02:02:08:08:08:06',
    'interfaces': [{'cluster_virtual': '242.242.242.250',
                    'network_value': '242.242.242.0/24',
                    'nodes': [{'address': '242.242.242.2',
                               'network_value': '242.242.242.0/24', 'nodeid': 1},
                              {'address': '242.242.242.3',
                               'network_value': '242.242.242.0/24', 'nodeid': 2}],
                    'vlan_id': 24,
                    'zone_ref': 'vlanzone',
                    'comment': 'comment on vlan'}],
    'zone_ref': zone_helper('myzone'),
    'comment': 'top level interface'}

When an interface is created, the first key level is applied to the “top” level physical interface. The interfaces list specifies the node and addressing information using the nodes parameter. If vlan_id is specified as a key/value in the interfaces dict, the list dict keys are applied to the nested physical interface VLAN.

Parameters:
  • interface_id (str) – id for interface

  • cvi_mode – cvi mode type (i.e. packetdispatch), required when using CVI

  • macaddress (str) – mac address for top level physical interface. Required if CVI set

  • interfaces (list) – interface attributes, cluster_virtual, network_value, nodes, etc

  • nodes (dict) – nodes dict should contain keys address, network_value and nodeid. Overridden sub interface settings can also be set here

  • zone_ref (str,href) – zone reference, name or zone. If zone does not exist it will be created

  • comment (str) – comment for interface

Note

Values for dict match the FirewallCluster.create constructor

property cvi_mode

HA Cluster mode.

Returns:

possible values: packetdispatch, unicast, multicast, multicastgmp

Return type:

str

property macaddress

MAC Address for cluster virtual interface. Not required for NDI only interfaces.

Parameters:

value (str) – macaddress

Return type:

str

VirtualPhysicalInterface

class smc.core.interfaces.VirtualPhysicalInterface(engine=None, meta=None, **interface)[source]

Bases: Layer3PhysicalInterface

This interface type is used by virtual engines and has subtle differences to a normal interface. For a VE in layer 3 firewall, it also specifies a Single Node Interface as the physical interface sub-type. When creating the VE, one of the interfaces must be designated as the source for Auth Requests and Outgoing.

SwitchPhysicalInterface

class smc.core.interfaces.SwitchPhysicalInterface(engine=None, meta=None, **interface)[source]

Bases: Interface

A switch physical interface is a new dedicated physical module supported on N110 appliances at the time of this document. Check the latest updated spec sheets to determine if your physical appliance currently supports this module

Represents a routed layer 3 interface on an any engine type.

Example interface:

{'interface_id': u'SWP_0.1',
 'interfaces': [{'nodes': [{'dynamic': True,
                            'dynamic_index': 2}]}],
 'switch_physical_interface_port': [{u'switch_physical_interface_port_comment': u'',
                                     u'switch_physical_interface_port_number': 0}],
 'zone_ref': u'External'},
{'interface_id': u'SWP_0.2',
 'interfaces': [{'nodes': [{'dynamic': True,
                            'dynamic_index': 3}]}],
 'switch_physical_interface_port': [{u'switch_physical_interface_port_comment': u'',
                                     u'switch_physical_interface_port_number': 1}],
 'zone_ref': u'External'},
{'interface_id': u'SWP_0.3',
 'interfaces': [{'nodes': [{'dynamic': True,
                            'dynamic_index': 4}]}],
 'switch_physical_interface_port': [{u'switch_physical_interface_port_comment': u'',
                                     u'switch_physical_interface_port_number': 3}],
 'zone_ref': u'External'},
{'interface_id': u'SWP_0.4',
 'switch_physical_interface_port': [{u'switch_physical_interface_port_comment': u'port 2',
                                     u'switch_physical_interface_port_number': 2},
                                    {u'switch_physical_interface_port_comment': u'',
                                     u'switch_physical_interface_port_number': 4},
                                    {u'switch_physical_interface_port_comment': u'',
                                     u'switch_physical_interface_port_number': 5},
                                    {u'switch_physical_interface_port_comment': u'',
                                     u'switch_physical_interface_port_number': 6}]}
Variables:

switch_physical_module (ApplianceSwitchModule) – appliance module type

property appliance_switch_module

Return the appliance module used for this switch physical interface.

Return type:

ApplianceSwitchModule

update_interface(other_interface, ignore_mgmt=True)[source]

Update a switch physical interface with another interface. You can provide only partial interface data, for example, if you have an existing port group and you want to add additional ports. Or if you want to change the zone assigned to a single port group. There is nothing that can be modified on the top level switch interface itself, only the nested port groups.

If the intent is to delete a port_group, retrieve the port group interface and call delete().

Parameters:

TunnelInterface

class smc.core.interfaces.TunnelInterface(engine=None, meta=None, **interface)[source]

Bases: Interface

This interface type represents a tunnel interface that is typically used for route based VPN traffic. Nested interface nodes can be SingleNodeInterface (for L3 NGFW), a NodeInterface (for cluster’s with only NDI’s) or ClusterVirtualInterface (CVI) for cluster VIP. Tunnel Interfaces are only available under layer 3 routed interfaces and do not support VLANs.

Example tunnel interface format on cluster:

cluster_tunnel_interface = {
    'comment': u'My Tunnel on cluster',
    'interface_id': u'1000',
    'interfaces': [{'cluster_virtual': u'77.77.77.70',
                    'network_value': u'77.77.77.0/24',
                    'nodes': [{'address': u'5.5.5.2',
                               'network_value': u'5.5.5.0/24',
                                'nodeid': 1},
                              {'address': u'5.5.5.3',
                               'network_value': u'5.5.5.0/24',
                               'nodeid': 2}]}],
     'zone_ref': 'foozone'}

Tunnel interface on single engine with multiple tunnel IPs:

single_fw_interface = {
    'comment': u'Tunnel with two addresses on single engine',
    'interface_id': u'1000',
    'interfaces': [{'nodes': [{'address': u'5.5.5.2',
                               'network_value': u'5.5.5.0/24',
                               'nodeid': 1},
                              {'address': u'5.5.5.3',
                               'network_value': u'5.5.5.0/24',
                               'nodeid': 1}]
                            }],
     'zone_ref': 'foozone'}
property qos

The QoS settings for this tunnel interface

Return type:

QoS

VPNBrokerInterface

class smc.core.interfaces.VPNBrokerInterface(engine=None, meta=None, **interface)[source]

Bases: Interface

This interface type represents a VPN broker interface. Not meant to be used directly: instead use:

engine.vpn_broker_interface.add_layer3_interface to create a VPNBrokerInterface

Usage:

itf ={‘nodes’: [{‘address’: u’10.88.0.12’,

‘network_value’: u’10.88.0.0/24’, ‘nodeid’: 1, “nicid”: “VPN_0”

}]}

my_interface = VPNBrokerInterface(

zone_ref=”Internal”, interface_id=”VPN_0”, comment=”testing vpn broker”, vpn_broker_domain_ref = brokdom.href, mac_address_postfix=”a3:b3:c3”, retrieve_routes=True, shared_secret=”blabla”, interfaces = [itf])

print(json.dumps(dict(my_interface.data)))

VlanInterface

class smc.core.interfaces.VlanInterface[source]

Bases: object

VlanInterface is a dynamic class generated by collections referencing interfaces with vlan interfaces. The inheriting class for a VlanInterface is dependent on the parent interface.

change_vlan_id(vlan_id)[source]

Change the VLAN id for this VLAN interface. If this is an inline interface, you can specify two interface values to create unique VLANs on both sides of the inline pair. Or provide a single to use the same VLAN id.

Parameters:

vlan_id (str) – string value for new VLAN id.

Raises:

UpdateElementFailed – failed to update the VLAN id

Returns:

None

delete()[source]

Delete this Vlan interface from the parent interface. This will also remove stale routes if the interface has networks associated with it.

Returns:

None

property qos

QoS on VLANs is only supported for Layer3PhysicalInterface types.

Return type:

QoS

property vlan_id

Vlan id for this vlan

Return type:

str

Sub-Interfaces

Module provides an interface to sub-interfaces on an engine. A ‘top level’ interface is linked from the engine and will be PhysicalInterface, TunnelInterface, etc. Within the top level interface, there are sub-interface configurations that identify the basic settings such as ip address, network, administrative settings etc. These are not called directly but used as a reference to the top level interface. All sub interfaces are type dict.

class smc.core.sub_interfaces.CaptureInterface(data)[source]

Capture Interface (SPAN) This is a single physical interface type that can be installed on either layer 2 or IPS engine roles. It enables the NGFW to capture traffic on the wire without actually blocking it (although blocking is possible).

Variables:
  • inspect_unspecified_vlans (boolean) – promiscuous SPAN on unspecified VLANs

  • (required) (str logical_interface_ref) – logical interface to use, by href

  • reset_interface_nicid (int) – if sending passive RST back, interface id to use

  • nicid (str,int) – nicid for this capture interface

class smc.core.sub_interfaces.ClusterVirtualInterface(data)[source]

These interfaces (CVI) are used on cluster devices and applied to layer 3 interfaces. They specify a ‘VIP’ (or shared IP) to be used for traffic load balancing or high availability. Each engine will still also have a ‘node’ interface for communication to/from the engine itself. The following getter/setter properties are available:

Variables:
  • address (str) – address of the CVI

  • auth_request (boolean) – interface for authentication requests (only 1)

  • network_value (str) – network address for interface, i.e. 1.1.1.0/24

  • nicid (int) – nic interface identifier

  • relayed_by_dhcp (boolean) – is the interface using DHCP

  • igmp_mode (str) – IGMP mode (upstream/downstream/None)

property vlan_id

VLAN ID for this interface, if any

Returns:

VLAN identifier

Return type:

str

class smc.core.sub_interfaces.InlineIPSInterface(data)[source]

An Inline IPS Interface is a new interface type introduced in SMC version 6.3. This interface type is the same as a normal IPS interface except that it is applied on a Layer 3 Firewall.

New in version 0.5.6: Requires SMC 6.3.

class smc.core.sub_interfaces.InlineInterface(data)[source]

This interface type is used on layer 2 or IPS related engines. It requires that you specify two interfaces to be part of the inline pair. These interfaces do not need to be sequential. It is also possible to add VLANs and zones to the inline interfaces. The logical interface reference needs to be unique for inline and capture interfaces when they are applied on the same engine.

Variables:
  • inspect_unspecified_vlans (boolean) – promiscuous SPAN on unspecified VLANs

  • (required) (str logical_interface_ref) – logical interface to use, by href

  • failure_mode (str) – normal or bypass

  • nicid (str) – interfaces for inline pair, for example, ‘4.50-5.55’, ‘5-6’

  • vlan_id (str) – vlan identifier for interface

  • (optional) (str zone_ref) – zone for second interface in pair

change_interface_id(newid)[source]

Change the inline interface ID. The current format is nicid=’1-2’, where ‘1’ is the top level interface ID (first), and ‘2’ is the second interface in the pair. Consider the existing nicid in case this is a VLAN.

Parameters:

newid (str) – string defining new pair, i.e. ‘3-4’

Returns:

None

change_vlan_id(vlan_id)[source]

Change a VLAN id for an inline interface.

Parameters:

vlan_id (str) – New VLAN id. Can be in format ‘1-2’ or a single numerical value. If in ‘1-2’ format, this specifies the vlan ID for the first inline interface and the rightmost for the second.

Returns:

None

property vlan_id

VLAN ID for this interface, if any

Returns:

VLAN identifier

Return type:

str

class smc.core.sub_interfaces.InlineL2FWInterface(data)[source]

An Inline L2FW Interface is a new interface type introduced in SMC version 6.3. This interface type is the a layer 2 engine interface on a layer 3 firewall. By default this interface type does not support bypass mode and will discard on overload.

New in version 0.5.6: Requires SMC 6.3.

class smc.core.sub_interfaces.LoopbackClusterInterface(data, engine=None)[source]

This represents the CVI Loopback IP address. A CVI loopback IP address is used for loopback traffic that is sent to the whole cluster. It is shared by all the nodes in the cluster.

add_cvi_loopback(address, ospf_area=None, **kw)[source]

Add a loopback interface as a cluster virtual loopback. This enables the loopback to ‘float’ between cluster members. Changes are committed immediately.

Parameters:
  • address (str) – ip address for loopback

  • rank (int) – rank of this entry

  • ospf_area (str,Element) – optional ospf_area to add to loopback

Raises:

UpdateElementFailed – failure to save loopback address

Returns:

None

delete()[source]

Delete a loopback cluster virtual interface from this engine. Changes to the engine configuration are done immediately.

You can find cluster virtual loopbacks by iterating at the engine level:

for loopbacks in engine.loopback_interface:
    ...
Raises:

UpdateElementFailed – failure to delete loopback interface

Returns:

None

class smc.core.sub_interfaces.LoopbackInterface(data, engine=None)[source]

Loopback interface for a physical or virtual single firewall. To create a loopback interface, call from the engine node:

engine.loopback_interface.add_single(...)
add_node_loopback(addresses, **kwargs)[source]

Add a node loopback interface to this engine.

Parameters:

addresses (dict) – {nodeid: {‘address’:’127.0.0.1’, ‘ospf_area’:ospfArea}, …}

Raises:

UpdateElementFailed – failure to create loopback address

Returns:

None

add_single(address, rank=1, nodeid=1, ospf_area=None, **kwargs)[source]

Add a single loopback interface to this engine. This is used for single or virtual engines.

Parameters:
  • address (str) – ip address for loopback

  • nodeid (int) – nodeid to apply. Default to 1 for single engine

  • ospf_area (str, Element) – ospf area href or element

Raises:

UpdateElementFailed – failure to create loopback address

Returns:

None

delete()[source]

Delete a loopback interface from this engine. Changes to the engine configuration are done immediately.

A simple way to obtain an existing loopback is to iterate the loopbacks or to get by address:

lb = engine.loopback_interface.get('127.0.0.10')
lb.delete()

Warning

When deleting a loopback assigned to a node on a cluster all loopbacks with the same rank will also be removed.

Raises:

UpdateElementFailed – failure to delete loopback interface

Returns:

None

class smc.core.sub_interfaces.NodeInterface(data)[source]

Node Interface Node dedicated interface (NDI) is used on specific engine types and represents an interface used for management (IPS and layer 2 engines), or as normal layer 3 interfaces such as on a layer 3 firewall cluster.

For Layer 2 Firewall/IPS these are used as individual interfaces. On clusters, these are used to define the node specific address for each node member, along with a cluster virtual interface.

Variables:
  • address (str) – ip address of this interface

  • network_value (str) – network for this interface, i.e. 1.1.1.0/24

  • nicid (str or int) – nic interface id

  • nodeid (int) – node identifier for interface (in a cluster, each node will be unique)

  • outgoing (boolean) –

    This option defines the IP address that the nodes use if they have to initiate connections (system communications, ping, etc.) through an interface that has no Node Dedicated IP Address. In Firewall Clusters, you must select an interface

    that has an IP address defined for all nodes.

  • primary_heartbeat (boolean) – Whether interface is the primary heartbeat interface for communications between the nodes. It is recommended that you use a Physical Interface, not a VLAN Interface. It is also recommended that you do not direct any other traffic through this interface.

  • primary_mgt (boolean) – Is it the Primary Control Interface for Management Server contact. There must be one and only one Primary Control Interface

  • auth_request (boolean) – whether to specify this interface as interface for authentication requests. Should be set on interface acting as management

  • auth_request_source (boolean) – If the authentication requests are sent to an external authentication server over VPN, select an interface with a Node Dedicated IP address that you want use for the authentication requests

  • reverse_connection (boolean) – Reverse connection enables engine to contact SMC versus other way around

  • vlan_id (str) – VLAN id for interface if assigned

  • backup_mgt (boolean) – Whether interface is a backup control interface that is used if the primary control interface is not available

  • backup_heartbeat (boolean) – Whether the interface is a backup heartbeat. It is not mandatory to configure a backup heartbeat interface.

  • dynamic (boolean) – Whether this is a DHCP interface

  • dynamic_index (int) – The dynamic index of the DHCP interface. The value is between 1 and 16. Only used when ‘dynamic’ is set to True.

  • igmp_mode (str) – IGMP mode (upstream/downstream/None)

  • vrrp (boolean) – Enable VRRP

  • vrrp_address (str) – IP address if VRRP is enabled

  • vrrp_id (int) – The VRRP ID. Required only for VRRP mode

  • vrrp_priority (int) – The VRRP Priority. Required only for VRRP mode

property vlan_id

VLAN ID for this interface, if any

Returns:

VLAN identifier

Return type:

str

class smc.core.sub_interfaces.SingleNodeInterface(data)[source]

This interface is used by single node Layer 3 Firewalls. This type of interface can be a management interface as well as a non-management routed interface.

Variables:
  • dynamic (bool) – is this interface a dynamic DHCP interface

  • dynamic_index (int) – dynamic interfaces index value

  • automatic_default_route (boolean) – Flag to know if the dynamic default route will be automatically created for this dynamic interface. Used in DHCP interfaces only

class smc.core.sub_interfaces.SubInterface(data)[source]
change_interface_id(interface_id)[source]

Generic change interface ID for VLAN interfaces that are not Inline Interfaces (non-VLAN sub interfaces do not have an interface_id field).

Parameters:

interface_id (str, int) – interface ID value

change_vlan_id(vlan_id)[source]

Change a VLAN id

Parameters:

vlan_id (str) – new vlan

class smc.core.sub_interfaces.SubInterfaceCollection(interface)[source]

A Sub Interface collection for non-VLAN interfaces.

InterfaceContactAddress

A ContactAddress is used by elements to provide an alternate address for communication between engine and management/log server. This is typically used when the SMC sits behind a NAT address and the SMC needs to contact the engine directly (this is a default behavior). In this case, you would add the public IP in front of the engine as a contact address to the engine interface.

Obtain all eligible interfaces for contact addressess:

>>> engine = Engine('dingo')
>>> for ca in engine.contact_addresses:
...   ca
...
ContactAddressNode(interface_id=11, interface_ip=10.10.10.20)
ContactAddressNode(interface_id=120, interface_ip=120.120.120.100)
ContactAddressNode(interface_id=0, interface_ip=1.1.1.1)
ContactAddressNode(interface_id=12, interface_ip=3.3.3.3)
ContactAddressNode(interface_id=12, interface_ip=17.17.17.17)

Retrieve a specific contact address interface for modification:

>>> ca = engine.contact_addresses.get(interface_id=12, interface_ip='3.3.3.3')
>>> ca
ContactAddressNode(interface_id=12, interface_ip=3.3.3.3)
>>> list(ca)
[InterfaceContactAddress(location=Default,address=4.4.4.4),
                         InterfaceContactAddress(location=Foo,address=3.4.5.6)]

Add a new contact address to the fetched interface:

>>> ca.add_contact_address('23.23.23.23', location='mynewlocation')
>>> list(ca)
[InterfaceContactAddress(location=Default,address=4.4.4.4),
                         InterfaceContactAddress(location=Foo,address=3.4.5.6),
                         InterfaceContactAddress(location=mynewlocation,address=23.23.23.23)]

Remove a contact address:

>>> ca.remove_contact_address('23.23.23.23')
>>> list(ca)
[InterfaceContactAddress(location=Default,address=4.4.4.4),
 InterfaceContactAddress(location=Foo,address=3.4.5.6)]

Note

Contact Addresses for servers (Management/Log Server) do not use this same object definition

class smc.core.contact_address.ContactAddressCollection(resource)[source]

Bases: SubElementCollection

A contact address collection provides all available interfaces that can be used to configure a contact address. An eligible interface is one that is a layer 3 interface with an address assigned (including VLANs):

for ca in engine.contact_addresses:
    ...

Note

All eligible interfaces are returned, regardless of whether a contact address is assigned or not.

get(interface_id, interface_ip=None)[source]

Get will return a list of interface references based on the specified interface id. Multiple references can be returned if a single interface has multiple IP addresses assigned.

Returns:

If interface_ip is provided, a single ContactAddressNode element is returned if found. Otherwise a list will be returned with all contact address nodes for the given interface_id.

class smc.core.contact_address.ContactAddressNode(**meta)[source]

Bases: SubElement

A mapping of contact address to interface. This is specific to assigning the contact address on the engine.

add_contact_address(contact_address, location='Default', dynamic=False)[source]

Add a contact address to this specified interface. A contact address is an alternative address which is typically applied when NAT is used between the NGFW and another component (such as management server). Adding a contact address operation is committed immediately.

Parameters:
  • contact_address (str) – IP address for this contact address.

  • location (str) – name of the location, the location will be added if it doesn’t exist

  • dynamic (bool) – flag to specify the dynamic FQDN contact address.

Raises:

EngineCommandFailed – invalid contact address

Returns:

ContactAddressNode

As example for dynamic FQDN:
add_contact_address(contract_address=”your.fqdn”,

location=Location(“SpecificLocation”), dynamic=True)

As example for dynamic:
update_or_create(contract_address=”dynamic”,

location=Location(“SpecificLocation”))

delete(location_name)[source]

Remove a given location by location name. This operation is performed only if the given location is valid, and if so, update is called automatically.

Parameters:

location (str) – location name or location ref

Raises:

UpdateElementFailed – failed to update element with reason

Return type:

bool

property interface_id

The interface ID for this contact address interface

Return type:

str

property interface_ip

The IP address for this contact address interface

Return type:

str

remove_contact_address(location)[source]

Remove a contact address from an interface by the location name. There is a one to one relationship between a contact address and

Parameters:

contact_address (str) – ip for contact address

Raises:

EngineCommandFailed – problem removing address

Returns:

status of delete as boolean

Return type:

bool

update_or_create(location, contact_address, dynamic=False, with_status=False, **kw)[source]

Update an existing contact address or create if the location does not exist.

Parameters:
  • location (str) – name of the location, the location will be added if it doesn’t exist

  • contact_address (str) – contact address IP. Can be the string ‘dynamic’ if this should be a dynamic contact address (i.e. on DHCP interface)

  • dynamic (bool) – flag to specify the dynamic FQDN contact address.

  • with_status (bool) – 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

Return type:

ContactAddressNode

As example for dynamic FQDN:
update_or_create(location=Location(“SpecificLocation”),

contract_address=”your.fqdn”, dynamic=True)

As example for dynamic:
update_or_create(location=Location(“SpecificLocation”),

contract_address=”dynamic”)

class smc.core.contact_address.InterfaceContactAddress(data=None, **kwargs)[source]

Bases: ContactAddress

An interface contact address is used on engine interfaces to provide an alternative location to address mapping. This is frequently used when the engine sits behind a NAT and you need a public NAT mapping, as might be the case with site to site VPN.

property addresses

List of addresses set as contact address

Return type:

list

Node

Node level actions for an engine. Once an engine is loaded, all methods and resources are available to that particular engine.

For example, to load an engine and run node level commands:

engine = Engine('myfw')
for node in engine.nodes:
    node.reboot()
    node.bind_license()
    node.go_online()
    node.go_offline()
    ...
    ...
class smc.core.node.MasterNode(**meta)[source]

Bases: Node

This represents an individual Master NGFW Engine node in the Security Management Client, representing a device that runs firewall software as part of a Master NGFW Engine.

class smc.core.node.Node(**meta)[source]

Bases: SubElement

Node settings to make each engine node controllable individually. Obtain a reference to a Node by loading an Engine resource. Engine will have a ‘has-a’ relationship with node and stored as the nodes attribute.

>>> for node in engine.nodes:
...   node
...
Node(name=fwcluster node 1)
Node(name=fwcluster node 2)
appliance_info()[source]

New in version 0.5.7: Requires SMC version >= 6.3

Retrieve appliance info for this engine.

Raises:

NodeCommandFailed – Appliance info not supported on this node

Return type:

ApplianceInfo

bind_license(license_item_id=None, **kwargs)[source]

Auto bind license, uses dynamic if POS is not found

Parameters:

license_item_id (str) – license id

Raises:

LicenseError – binding license failed, possibly no licenses

Returns:

None

cancel_unbind_license(**kwargs)[source]

Cancel unbind for license

Raises:

LicenseError – unbind failed with reason

Returns:

None

certificate_info()[source]

Get the certificate info of this node. This can return None if the engine type does not directly have a certificate, like a virtual engine where the master engine manages certificates.

Returns:

dict with links to cert info

change_ssh_pwd(pwd=None, comment=None)[source]

Executes a change SSH password operation on the specified node

Parameters:
  • pwd (str) – changed password value

  • comment (str) – optional comment for audit log

Raises:

NodeCommandFailed – cannot change ssh password

Returns:

None

debug(filter_enabled=False)[source]

View all debug settings for this node. This will return a debug object. View the debug object repr to identify settings to enable or disable and submit the object to set_debug() to enable settings.

Add filter_enabled=True argument to see only enabled settings

Parameters:

filter_enabled (bool) – returns all enabled diagnostics

Raises:

NodeCommandFailed – failure getting diagnostics

Return type:

Debug

See also

Debug for example usage

fetch_license(**kwargs)[source]

Fetch the node level license

Raises:

LicenseError – fetching license failure with reason

Returns:

None

go_offline(comment=None)[source]

Executes a Go-Offline operation on the specified node

Parameters:

comment (str) – optional comment to audit

Raises:

NodeCommandFailed – offline not available

Returns:

None

go_online(comment=None)[source]

Executes a Go-Online operation on the specified node typically done when the node has already been forced offline via go_offline()

Parameters:

comment (str) – (optional) comment to audit

Raises:

NodeCommandFailed – online not available

Returns:

None

go_standby(comment=None)[source]

Executes a Go-Standby operation on the specified node. To get the status of the current node/s, run status()

Parameters:

comment (str) – optional comment to audit

Raises:

NodeCommandFailed – engine cannot go standby

Returns:

None

property hardware_status

Obtain hardware statistics for various areas of this node.

See HardwareStatus for usage.

Raises:

NodeCommandFailed – failure to retrieve current status

Return type:

HardwareStatus

property health

Basic status for individual node. Specific information such as node name dynamic package version, configuration status, platform and version.

Return type:

ApplianceStatus

initial_contact(enable_ssh=True, time_zone=None, keyboard=None, install_on_server=None, filename=None, as_base64=False)[source]

Allows to save the initial contact for for the specified node

Parameters:
  • enable_ssh (bool) – flag to know if we allow the ssh daemon on the specified node

  • time_zone (str) – optional time zone to set on the specified node

  • keyboard (str) – optional keyboard to set on the specified node

  • install_on_server (bool) – optional flag to know if the generated configuration needs to be installed on SMC Install server (POS is needed)

  • filename (str) – filename to save initial_contact to

  • as_base64 (bool) – return the initial config in base 64 format. Useful for cloud based engine deployments as userdata

Raises:

NodeCommandFailed – IOError handling initial configuration data

Returns:

initial contact text information

Return type:

str

property interface_status

Obtain the interface status for this node. This will return an iterable that provides information about the existing interfaces. Retrieve a single interface status:

>>> node = engine.nodes[0]
>>> node
Node(name=ngf-1065)
>>> node.interface_status
<smc.core.node.InterfaceStatus object at 0x103b2f310>
>>> node.interface_status.get(0)
InterfaceStatus(aggregate_is_active=False, capability=u'Normal Interface',
    flow_control=u'AutoNeg: off Rx: off Tx: off',
    interface_id=0, mtu=1500, name=u'eth0_0', port=u'Copper',
    speed_duplex=u'1000 Mb/s / Full / Automatic', status=u'Up')

Or iterate and get all interfaces:

>>> for stat in node.interface_status:
...   stat
...
InterfaceStatus(aggregate_is_active=False, capability=u'Normal Interface', ...
...
Raises:

NodeCommandFailed – failure to retrieve current status

Return type:

InterfaceStatus

lock_offline(comment=None)[source]

Executes a Lock-Offline operation on the specified node Bring back online by running go_online().

Parameters:

comment (str) – comment for audit

Raises:

NodeCommandFailed – lock offline failed

Returns:

None

lock_online(comment=None)[source]

Executes a Lock-Online operation on the specified node

Parameters:

comment (str) – comment for audit

Raises:

NodeCommandFailed – cannot lock online

Returns:

None

property loopback_interface

Loopback interfaces for this node. This will return empty if the engine is not a layer 3 firewall type:

>>> engine = Engine('dingo')
>>> for node in engine.nodes:
...   for loopback in node.loopback_interface:
...     loopback
...
LoopbackInterface(address=172.20.1.1, nodeid=1, rank=1)
LoopbackInterface(address=172.31.1.1, nodeid=1, rank=2)
LoopbackInterface(address=2.2.2.2, nodeid=1, rank=3)
Return type:

list(LoopbackInterface)

property nodeid

ID of this node

pki_certificate_info()[source]

Get the certificate info of this component when working with External PKI. This can return None if the component does not directly have a certificate, like a virtual engine where the master engine manages certificates.

Raises:

UnsupportedEngineFeature – requires layer 3 engine

Return type:

PkiCertificateInfo

pki_certificate_settings()[source]

Get the certificate info of this node when working with External PKI. This can return None if the engine type does not directly have a certificate,

like a virtual engine where the master engine manages certificates.

Raises:

UnsupportedEngineFeature – requires engine version 6.10 and external PKI

installation :rtype: PkiCertificateSettings

pki_delete_certificate_request()[source]

Delete the certificate request if any is defined for this component.

pki_export_certificate_request(filename=None)[source]

Export the certificate request for the node when working with an External PKI. This can return None if the engine type does not have a certificate request.

Raises:

CertificateExportError – error exporting certificate

Return type:

str or None

pki_import_certificate(certificate)[source]

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.

Parameters:

certificate (str) – fully qualified path or string

Raises:
pki_renew_certificate()[source]

Start renewal process on component when using external PKI mode. It generates new private key and prepares a new certificate request.

power_off()[source]

New in version 0.5.6: Requires engine version >=6.3

Power off engine.

Raises:

NodeCommandFailed – online not available

Returns:

None

reboot(comment=None)[source]

Send reboot command to this node.

Parameters:

comment (str) – comment to audit

Raises:

NodeCommandFailed – reboot failed with reason

Returns:

None

rename(name)[source]

Rename this node

Parameters:

name (str) – new name for node

reset_to_factory()[source]

New in version 0.5.6: Requires engine version >=6.3

Reset the engine to factory defaults.

Raises:

NodeCommandFailed – online not available

Returns:

None

reset_user_db(comment=None)[source]

Executes a Send Reset LDAP User DB Request operation on this node.

Parameters:

comment (str) – comment to audit

Raises:

NodeCommandFailed – failure resetting db

Returns:

None

set_debug(debug)[source]

Set the debug settings for this node. This should be a modified Debug instance. This will take effect immediately on the specified node.

Parameters:

debug (Debug) – debug object with specified settings

Raises:

NodeCommandFailed – fail to communicate with node

Returns:

None

See also

Debug for example usage

sginfo(include_core_files=False, include_slapcat_output=False, filename='sginfo.gz')[source]

Get the SG Info of the specified node. Optionally provide a filename, otherwise default to ‘sginfo.gz’. Once you run gzip -d <filename>, the inner contents will be in .tar format.

Parameters:
  • include_core_files – flag to include or not core files

  • include_slapcat_output – flag to include or not slapcat output

Raises:

NodeCommandFailed – failed getting sginfo with reason

Returns:

string path of download location

Return type:

str

ssh(enable=True, comment=None)[source]

Enable or disable SSH

Parameters:
  • enable (bool) – enable or disable SSH daemon

  • comment (str) – optional comment for audit

Raises:

NodeCommandFailed – cannot enable SSH daemon

Returns:

None

status()[source]

Basic status for individual node. Specific information such as node name dynamic package version, configuration status, platform and version.

Return type:

ApplianceStatus

time_sync()[source]

Send a time sync command to this node.

Raises:

NodeCommandFailed – time sync not supported on node

Returns:

None

property type

Node type

unbind_license(**kwargs)[source]

Unbind a bound license on this node.

Raises:

LicenseError – failure with reason

Returns:

None

property version

Engine version. If the node is not yet initialized, this will return None.

Returns:

str or None

Appliance Info

class smc.core.node.ApplianceInfo(cloud_id, cloud_type, first_upload_time, hardware_version, initial_contact_time, product_name, initial_license_remaining_days, proof_of_serial, software_features, software_version)

Bases: tuple

Appliance specific information about the given engine node. Appliance info is specific to the engine itself and will provide additional details about the hardware model, applied license features, if the engine has made initial contact and when initial policy upload was made.

Retrieve appliance info engine nodes:

engine = Engine('dingo')
for node in engine.nodes:
    node.appliance_info()
Variables:
  • cloud_id (str) – N/A

  • cloud_type (str) – N/A

  • first_upload_time (long) – policy first upload time in ms

  • hardware_version (float) – hardware version of appliance

  • initial_contact_time (long) – when node contacted SMC, in ms

  • intial_license_remaining_days (int) – validity in days of current license

  • product_name (str) – name of hardware model

  • proof_of_serial (str) – proof of serial for this hardware

  • software_features (str) – feature string

  • software_version (str) – initial software version on base image

Appliance Status

class smc.core.node.ApplianceStatus(data)[source]

Bases: NestedDict

Appliance status attributes define specifics about the hardware platform itself, including version, dynamic package, current configuration status and installed policy. Retrieve appliance status for engine nodes:

for node in engine.nodes:
    node.health

Changed in version 1.0.1: added master_node since SMC version >= 6.10 API6.10, 6.9, 6.8

property configuration_status
Valid values:
  • Initial (no initial configuration file is yet generated)

  • Declared (initial configuration file is generated)

  • Configured (initial configuration is done with the engine)

  • Installed (policy is installed on the engine)

Returns:

str configuration_status: configuration status

property dyn_up
Returns:

str dyn_up: Dynamic update package version

property installed_policy
Returns:

str installed_policy: Installed policy by name

property master_node

The master engine node for a virtual engine

Returns:

MasterNode: the master node or None

property name
Returns:

str name: Name of engine

property platform
Returns:

str platform: Underlying platform, x86, etc

property state
Valid values:

INITIAL/READY/ERROR/SERVER_ERROR/NO_STATUS/TIMEOUT/ DELETED/DUMMY

Returns:

str state: state of the Node

property status

str status:

Valid values:

Not Monitored/Unknown/Online/Going Online/Locked Online/ Going Locked Online/Offline/Going Offline/Locked Offline/ Going Locked Offline/Standby/Going Standby/No Policy Installed

Returns:

property version
Returns:

str version: Version of software installed

ApplianceSwitchModule

class smc.core.hardware.ApplianceSwitchModule(name=None, **meta)[source]

Bases: Element

Read only class specifying hardware switch modules used in smaller appliance form factors. This is referenced when creating switch interfaces

Hardware Status

class smc.core.node.HardwareStatus(*args, **kwargs)[source]

Bases: SerializedIterable

Provides an interface to methods that simplify viewing hardware statuses on this node. Example of usage:

>>> engine = Engine('sg_vm')
>>> node = engine.nodes[0]
>>> node
Node(name=ngf-1065)
>>> node.hardware_status
HardwareStatus(Anti-Malware, File Systems, GTI Cloud, Sandbox, Logging subsystem,
               MLC Connection, Web Filtering)
>>> node.hardware_status.filesystem
HardwareCollection(File Systems, items: 5)
>>> for stats in node.hardware_status.filesystem:
...   stats
...
Status(label=u'Root', param=u'Partition Size', status=-1, sub_system=u'File Systems',
       value=u'600 MB')
Status(label=u'Data', param=u'Usage', status=-1, sub_system=u'File Systems',
       value=u'6.3%')
Status(label=u'Data', param=u'Size', status=-1, sub_system=u'File Systems',
       value=u'1937 MB')
Status(label=u'Spool', param=u'Usage', status=-1, sub_system=u'File Systems',
       value=u'4.9%')
Status(label=u'Spool', param=u'Size', status=-1, sub_system=u'File Systems',
       value=u'9729 MB')
Status(label=u'Tmp', param=u'Usage', status=-1, sub_system=u'File Systems',
       value=u'0.0%')
Status(label=u'Tmp', param=u'Size', status=-1, sub_system=u'File Systems',
       value=u'3941 MB')
Status(label=u'Swap', param=u'Usage', status=-1, sub_system=u'File Systems',
       value=u'0.0%')
Status(label=u'Swap', param=u'Size', status=-1, sub_system=u'File Systems',
       value=u'1887 MB')

Since SMC-API >= v6.7
('OK', Status(label='Swap', param='Size', sub_system='File Systems', value='494 MB'))
('WARNING', Status(label='Tmp', param='Usage', sub_system='File Systems', value='96.7%'))
('WARNING', Status(label='Tmp', param='Size', sub_system='File Systems', value='997 MB'))

>>> for stats in node.hardware_status.sandbox_subsystem:
...   stats
...
('WARNING', Status(label='Cloud connection', param='status', sub_system='Sandbox',
                   value='1'))
property cloud_sync

A collection of Connection Synchronisation related statuses

Return type:

Status

property filesystem

A collection of filesystem related statuses

Return type:

Status

property logging_subsystem

A collection of logging subsystem statuses

Return type:

Status

property sandbox_subsystem

A collection of sandbox subsystem statuses

Return type:

Status

property single_ip_ha

A collection of Single IP High Availability related statuses

Return type:

Status

Interface Status

class smc.core.node.InterfaceStatus(status)[source]

Bases: SerializedIterable

An iterable that provides a collections interface to interfaces and current status on the specified node.

Interface status fields:

Variables:
  • aggregate_is_active (bool) – Is link aggregation enabled on this interface

  • capability (str) – What type of interface this is, i.e. “Normal Interface”

  • flow_control (str) – Autonegotiation, etc

  • interface_id (int) – Physical interface id

  • mtu (int) – Max transmission unit

  • name (str) – Name of the interface, i.e. eth0_0, etc

  • port (str) – Type of physical port, i.e. Copper, Fiber

  • speed_duplex (str) – Negotiated speed on the interface

  • status (str) – Status of interface, Up, Down, etc.

get(interface_id)[source]

Get a specific interface by the interface id

Parameters:

interface_id (int) – interface ID

Return type:

InterfaceStatus

Debug

class smc.core.node.Debug(diag)[source]

Debug settings that can be enabled on the engine. To view available options, print the repr of this object. All diagnostic values can be set as an attribute of this class instance. Set the values to either True or False and submit this object back to the node to change settings. Setting changes are in effect immediately and does not require a policy push. Example usage:

>>> node = engine.nodes[0]
>>> node
Node(name=ngf-1065)
>>> debug = node.debug()
>>> debug
Debug(access_guardian=False, accounting=False, anti_malware=False, authentication=False,
    blacklisting=False, browser_based_user_authentication=False, cluster_daemon=False,
    cluster_protocol=False, connection_tracking=False, data_synchronization=False,
    dhcp_client=False, dhcp_relay=False, dhcp_service=False, dns_resolution=False,
    dynamic_routing=False, endpoint_integration=False, file_reputation=False,
    inspection=False, invalid=False, ipsec_vpn=False, licensing=False,
    load_balancing_filter=False, log_server=False, logging_system=False, management=False,
    mcafee_logon_collector=False, monitoring=False, multicast_routing=False, nat=False,
    netlink_incoming_ha=False, packet_filtering=False, protocol_agent=False,
    radius_forwarder=False, sandbox=False, server_pool_load_balancing=False, snmp=False,
    ssl_vpn=False, ssl_vpn_portal=False, ssl_vpn_session_manager=False,
    state_synchronisation=False, syslog=False, system_utilities=False, tester=False,
    user_agent=False, wireless_access_point=False)
    >>> debug.management=True
    >>> debug.sandbox=True
    >>> node.set_debug(debug)

Pending Changes

class smc.core.resource.ChangeRecord(approved_on=None, changed_on=None, element=None, element_name=None, event_type=None, modifier=None, approver=None)[source]

Bases: ChangeRecord

Change record details for any pending changes.

Parameters:
  • approved_on – approved on datetime, may be empty if not approved

  • change_on – changed on datetime

  • element – element affected

  • event_type – type of change, update, delete, etc.

  • modifier – account making the modification

  • element_name – name of the element (only present in SMC >= 6.5)

  • approver – name of who has done the change.

class smc.core.resource.PendingChanges(engine)[source]

Bases: SerializedIterable

Pending changes apply to the engine having changes that have not yet been committed. Retrieve from the engine level:

>>> for changes in engine.pending_changes.all():
...   print(changes, changes.resolve_element)
...
(ChangeRecord(approved_on=u'', changed_on=u'2017-07-12 15:24:40 (GMT)',
element=u'http://172.18.1.150:8082/6.2/elements/fw_cluster/116',
event_type=u'stonegate.object.update', modifier=u'admin'),
FirewallCluster(name=sg_vm))

Approve all changes:

>>> engine.pending_changes.approve_all()

Conversely, reject all pending changes:

>>> engine.pending_changes.disapprove_all()
Raises:

ActionCommandFailed – failure to retrieve pending changes

Return type:

ChangeRecord

approve_all()[source]

Approve all pending changes

Raises:

ActionCommandFailed – possible permissions issue

Returns:

None

disapprove_all()[source]

Disapprove all pending changes

Raises:

ActionCommandFailed – possible permissions issue

Returns:

None

Routing

Route module encapsulates functions related to static routing and related configurations on NGFW. When retrieving routing, it is done from the engine context.

For example, retrieve all routing for an engine in context:

>>> engine = Engine('sg_vm')
>>> for route_node in engine.routing:
...   print(route_node)
...
Routing(name=Interface 0,level=interface)
Routing(name=Interface 1,level=interface)
Routing(name=Interface 2,level=interface)
Routing(name=Tunnel Interface 2000,level=interface)
Routing(name=Tunnel Interface 2001,level=interface)

Routing nodes are nested, starting with the engine level. Routing node nesting is made up of ‘levels’ and can be represented as a tree:

engine (root)
    |
    --> interface
            |
            --> network
                    |
                    --> gateway
                            |
                            --> any

You can get a representation of the routing or antispoofing tree nodes by calling as_tree:

>>> print(engine.routing.as_tree())
Routing(name=myfw,level=engine_cluster)
--Routing(name=Interface 0,level=interface)
----Routing(name=network-1.1.1.0/24,level=network)
------Routing(name=mypeering,level=gateway)
------Routing(name=mynetlink,level=gateway)
--------Routing(name=router-1.1.1.1,level=any)
------Routing(name=mystatic,level=gateway)
--Routing(name=Interface 1,level=interface)
----Routing(name=network-10.10.10.0/24,level=network)
------Routing(name=anotherpeering,level=gateway)
--Routing(name=Tunnel Interface 1000,level=interface)
----Routing(name=network-2.2.2.0/24,level=network)
--Routing(name=Tunnel Interface 1001,level=interface)
--Routing(name=Interface 2,level=interface)
----Routing(name=Network (IPv4),level=network)
------Routing(name=dynamic_netlink-myfw-Interface 2,level=gateway)
--------Routing(name=Any network,level=any)

If nested routes exist, you can iterate a given node to get specific information:

>>> interface = engine.routing.get(1)
>>> for routes in interface:
...   print(routes)
...
Routing(name=network-10.0.0.0/24,level=network)
...
>>> for networks in interface:
...   networks
...   for gateways in networks:
...     print gateways, gateways.ip
...
Routing(name=network-172.18.1.0/24,level=network)
Routing(name=asus-wireless,level=gateway) 172.18.1.200

If BGP, OSPF or a Traffic Handler (netlink) need to be added to an interface that has multiple IP addresses assigned and you want to bind to only one, you can provide the network parameter to add_ methods. The network can be obtained for an interface:

>>> engine = Engine('sg_vm')
>>> interface0 = engine.routing.get(0)
>>> for network in interface0:
...   network, network.ip
...
(Routing(name=network-172.18.1.0/24,level=network), '172.18.1.0/24')

Then add using:

>>> engine = Engine('sg_vm')
>>> interface0 = engine.routing.get(0)
>>> interface0.add_traffic_handler(StaticNetlink('foo'), network='172.18.1.0/24')

Note

If the network keyword is omitted and the interface has multiple IP addresses assigned, this will bind OSPF, BGP or the Traffic Handler to all address assigned.

Adding a basic static route can be done from the engine directly if it is a simple source network to destination route:

engine.add_route(gateway='192.168.1.254/32', network='172.18.1.0/24')

The route gateway will be mapped to an interface with an address range in the 192.168.1.x network automatically.

For more complex static routes such as ones that may use group elements, use the routing node:

>>> engine = Engine('ve-1')
>>> interface0 = engine.routing.get(0)
>>> interface0.add_static_route(Router('tmprouter'), destination=[Group('routegroup')])

When a routing gateway is added to an IPv6 network, the gateway is validated before adding. For example, if you have a single interface that has both an IPv4 and IPv6 address assigned, a static route using a Router gateway with only an IPv4 address will only bind to the IPv4 network. In this case, you can optionally add both an IPv4 and IPv6 to the router element, or run this operation for each network respectively.

Note

When changing are made to a routing node, i.e. adding OSPF, BGP, Netlink’s, the configuration is updated immediately without calling .update()

class smc.core.route.RoutingTree(data=None, **meta)[source]

RoutingTree is the base class for both Routing and Antispoofing nodes. This provides a commmon API for operations that affect how routing table and antispoofing operate.

all()[source]

Return all routes for this engine.

Returns:

current route entries as Routing element

Return type:

list

as_tree(level=0)[source]

Display the routing tree representation in string format

Return type:

str

delete()[source]

Delete the element

Raises:

DeleteElementFailed – possible dependencies, record locked, etc

Returns:

None

property dynamic_nicid

NIC id for this dynamic interface

Returns:

nic identifier, if this is a DHCP interface

Return type:

str or None

get(interface_id)[source]

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)

Parameters:

interface_id (str,int) – interface identifier

Raises:

InterfaceNotFound – invalid interface for engine

Returns:

Routing element, or None if not found

Return type:

Routing

property ip

IP network / host for this route

Returns:

IP address of this routing level

Return type:

str

property level

Routing nodes have multiple ‘levels’ where routes can be nested. Most routes are placed at the interface level. This setting can mostly be ignored, but provides an informative view of how the route is nested.

Returns:

routing node level (interface,network,gateway,any)

Return type:

str

property name

Interface name / ID for routing level

Returns:

name of routing node

Return type:

str

property nicid

NIC id for this interface

Returns:

nic identifier

Return type:

str

property probe_ecmp

the ECMP for multi path routing.

Return type:

int

property probe_interval

the probe interval.

Return type:

int

property probe_ipaddress

the probe ipaddress, when the probe test is Ping.

Return type:

str

property probe_metric

the probe metric.

Return type:

int

property probe_retry_count

the probe retry counter.

Return type:

int

property probe_test

probe test for a route. possible values: ping, next_hop_reachability, not_enabled

Returns:

probe test value

Return type:

str

property related_element_type

New in version 0.6.0: Requires SMC version >= 6.4

Related element type defines the ‘type’ of element at this routing or antispoofing node level.

Return type:

str

update()[source]

Update the existing element and clear the instance cache. Removing the cache will ensure subsequent calls requiring element attributes will force a new fetch to obtain the latest copy.

Calling update() with no args will assume the element has already been modified directly and the data cache will be used to update. You can also override the following attributes: href, etag, json and params. If json is sent, it is expected to the be a complete payload to satisfy the update.

For kwargs, if attribute values are a list, you can pass ‘append_lists=True’ to add to an existing list, otherwise overwrite the existing (default: overwrite)

See also

To see different ways to utilize this method for updating, see: Update.

Parameters:
  • exception – pass a custom exception to throw if failure

  • kwargs – optional kwargs to update request data to server.

Raises:
Returns:

href of the element modified

Return type:

str

Routing

class smc.core.route.Routing(data=None, **meta)[source]

Bases: RoutingTree

Routing represents the Engine routing configuration and provides the ability to view and add features to routing nodes such as OSPF.

add_bgp_peering(bgp_peering, external_bgp_peer=None, network=None)[source]

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'))
Parameters:
  • bgp_peering (BGPPeering) – BGP Peer element

  • external_bgp_peer (ExternalBGPPeer,Engine) – peer element or href

  • network (str) – if network specified, only add OSPF to this network on interface

Raises:
Returns:

Status of whether the route table was updated

Return type:

bool

add_dynamic_gateway(networks)[source]

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')])
Parameters:

Network (list) – list of network elements to add to this DHCP gateway

Raises:
Returns:

Status of whether the route table was updated

Return type:

bool

add_ospf_area(ospf_area, ospf_interface_setting=None, network=None, communication_mode='not_forced', unicast_ref=None)[source]

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

Parameters:
  • ospf_area (OSPFArea) – OSPF area instance or href

  • ospf_interface_setting (OSPFInterfaceSetting) – used to override the OSPF settings for this interface (optional)

  • network (str) – if network specified, only add OSPF to this network on interface

  • communication_mode (str) – not_forced|point_to_point|passive|unicast

  • unicast_ref (Element) – Element used as unicast gw (required for unicast)

Raises:
Returns:

Status of whether the route table was updated

Return type:

bool

add_static_route(gateway, destination, network=None)[source]

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')])
Parameters:
  • gateway (Element) – gateway for this route (Router, Host)

  • destination (list(Host, Router, ..)) – destination network/s for this route.

Raises:
Returns:

Status of whether the route table was updated

Return type:

bool

add_traffic_handler(netlink, netlink_gw=None, network=None)[source]

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')
Parameters:
  • netlink (StaticNetlink,Multilink) – netlink element

  • netlink_gw (list(Element)) – list of elements that should be destinations for this netlink. Typically these may be of type host, router, group, server, network or engine.

  • network (str) – if network specified, only add OSPF to this network on interface

Raises:
Returns:

Status of whether the route table was updated

Return type:

bool

property bgp_peerings

BGP Peerings applied to a routing node. This can be called from the engine, interface or network level. Return is a tuple of (interface, network, bgp_peering). This simplifies viewing and removing BGP Peers from the routing table:

>>> for bgp in engine.routing.bgp_peerings:
...   bgp
...
(Routing(name=Interface 0,level=interface,type=physical_interface),
 Routing(name=network-1.1.1.0/24,level=network,type=network),
 Routing(name=mypeering,level=gateway,type=bgp_peering))
(Routing(name=Interface 1,level=interface,type=physical_interface),
 Routing(name=network-2.2.2.0/24,level=network,type=network),
 Routing(name=mypeering,level=gateway,type=bgp_peering))

See also

netlinks() and ospf_areas() for obtaining other routing element types

Return type:

tuple(Routing)

Netlinks applied to a routing node. This can be called from the engine, interface or network level. Return is a tuple of (interface, network, netlink). This simplifies viewing and removing Netlinks from the routing table:

>>> interface = engine.routing.get(1)
>>> for static_netlink in interface.netlinks:
...   interface, network, netlink = static_netlink
...   netlink
...   netlink.delete()
...
Routing(name=mylink,level=gateway,type=netlink)

See also

bgp_peerings() and ospf_areas() for obtaining other routing element types

Return type:

tuple(Routing)

property ospf_areas

OSPFv2 areas applied to a routing node. This can be called from the engine, interface or network level. Return is a tuple of (interface, network, bgp_peering). This simplifies viewing and removing BGP Peers from the routing table:

>>> for ospf in engine.routing.ospf_areas:
...   ospf
...
(Routing(name=Interface 0,level=interface,type=physical_interface),
 Routing(name=network-1.1.1.0/24,level=network,type=network),
 Routing(name=area10,level=gateway,type=ospfv2_area))

See also

bgp_peerings() and netlinks() for obtaining other routing element types

Return type:

tuple(Routing)

remove_route_gateway(element, network=None)[source]

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')
Parameters:
  • element (str,Element) – element to remove from this routing node

  • network (str) – if network specified, only add OSPF to this network on interface

Raises:
Returns:

Status of whether the entry was removed (i.e. or not found)

Return type:

bool

property routing_node_element

A routing node element will reference the element used to represent the node (i.e. router, host, network, netlink, bgp peering, etc). Although the routing node already resolves the element and provides the ip property to obtain the address/network, use this property to obtain access to modifying the element itself:

>>> interface0 = engine.routing.get(0)
>>> for networks in interface0:
...   for gateway in networks:
...     gateway.routing_node_element
...
Router(name=router-1.1.1.1)
StaticNetlink(name=mystatic)
BGPPeering(name=anotherpeering)
BGPPeering(name=mypeering)
>>>

Antispoofing

class smc.core.route.Antispoofing(data=None, **meta)[source]

Bases: RoutingTree

Anti-spoofing is configured by default based on interface networks directly attached. It is possible to override these settings by adding additional networks as valid source networks on a given interface.

Antispoofing is nested similar to routes. Iterate the antispoofing configuration:

for entry in engine.antispoofing.all():
    print(entry)
add(element)[source]

Add an entry to this antispoofing node level. Entry can be either href or network elements specified in smc.elements.network

if0 = engine.antispoofing.get(0)
if0.add(Network('foonet'))
Parameters:

element (Element) – entry to add, i.e. Network(‘mynetwork’), Host(..)

Raises:
Returns:

whether entry was added

Return type:

bool

property autogenerated

Was the entry auto generated by a route entry or added manually as an override

Return type:

bool

remove(element)[source]

Remove a specific user added element from the antispoofing tables of a given interface. This will not remove autogenerated or system level entries.

Parameters:

element (Element) – element to remove

Returns:

remove element if it exists and return bool

Return type:

bool

property validity

Enabled or disabled antispoofing entry

Returns:

validity of this entry (enable,disable,absolute)

Return type:

str

Route Table

class smc.core.route.Route(data)[source]

Active routes obtained from a running engine. Obtain routes from an engine reference:

>>> engine = Engine('sg_vm')
>>> for route in engine.routing_monitoring:
...    route
Variables:
  • route_network (str) – network for this route

  • route_netmask (int) – netmask for the route

  • route_gateway (str) – route gateway, may be None if it’s a local network only

  • route_type (str) – status of the route

  • dst_if (int) – destination interface index

  • src_if (int) – source interface index

Policy Routing

class smc.core.route.PolicyRoute(engine)[source]

An iterable providing an interface to policy based routing on the engine. You must call engine.udpate() after performing an add or delete:

>>> engine = Engine('myfw')
>>> engine.policy_route
PolicyRoute(items: 1)
>>> for rt in engine.policy_route:
...   rt
...
PolicyRoute(source=u'172.18.1.0/24', destination=u'172.18.1.0/24',
            gateway_ip=u'172.18.1.1', comment=None)
>>> engine.policy_route.create(source='172.18.2.0/24',
                               destination='192.168.3.0/24', gateway_ip='172.18.2.1')
>>> engine.update()
'http://172.18.1.151:8082/6.4/elements/single_fw/746'
>>> for rt in engine.policy_route:
...   rt
...
PolicyRoute(source=u'172.18.1.0/24', destination=u'172.18.1.0/24',
            gateway_ip=u'172.18.1.1', comment=None)
PolicyRoute(source=u'172.18.2.0/24', destination=u'192.168.3.0/24',
            gateway_ip=u'172.18.2.1', comment=None)
>>> engine.policy_route.delete(source='172.18.2.0/24')
>>> engine.update()
'http://172.18.1.151:8082/6.4/elements/single_fw/746'
>>> for rt in engine.policy_route:
...   rt
...
PolicyRoute(source=u'172.18.1.0/24', destination=u'172.18.1.0/24',
            gateway_ip=u'172.18.1.1', comment=None)
Variables:
  • source (str) – source network/cidr for the route

  • destination (str) – destination network/cidr for the route

  • gateway_ip (str) – gateway IP address, must be on source network

  • comment (str) – optional comment

create(source, destination, gateway_ip, comment=None)[source]

Add a new policy route to the engine.

Parameters:
  • source (str) – network address with /cidr

  • destination (str) – network address with /cidr

  • gateway (str) – IP address, must be on source network

  • comment (str) – optional comment

delete(**kw)[source]

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.

Parameters:

kw – use valid Route keyword values to delete by exact match

TunnelMonitoringGroup

Snapshot

class smc.core.resource.Snapshot(**meta)[source]

Bases: SubElement

Policy snapshots currently held on the SMC. You can retrieve all snapshots at the engine level and view details of each:

for snapshot in engine.snapshots:
    print(snapshot)

Snapshots can be generated manually, but also will be generated automatically when a policy is pushed:

engine.generate_snapshot(filename='mysnapshot.zip')

Snapshots can also be downloaded:

for snapshot in engine.snapshots:
    if snapshot.name == 'blah snapshot':
        snapshot.download()

Snapshot filename will be <snapshot_name>.zip if not specified.

compare_to_latest(filename=None)[source]

Download comparison between this snapshot and the current version of the configuration as HTML to filename

Parameters:

filename (str) – fully qualified path including filename .zip

Raises:

EngineCommandFailed – IOError occurred downloading snapshot

Returns:

None

download(filename=None)[source]

Download snapshot to filename

Parameters:

filename (str) – fully qualified path including filename .zip

Raises:

EngineCommandFailed – IOError occurred downloading snapshot

Returns:

None

download_html(filename=None)[source]

Download snapshot as HTML to filename

Parameters:

filename (str) – fully qualified path including filename .zip

Raises:

EngineCommandFailed – IOError occurred downloading snapshot

Returns:

None

VirtualResource

class smc.core.engine.VirtualResource(**meta)[source]

Bases: SubElement

A Virtual Resource is a container placeholder for a virtual engine within a Master Engine. When creating a virtual engine, each virtual engine must have a unique virtual resource for mapping. The virtual resource has an identifier (vfw_id) that specifies the engine ID for that instance.

This is called as a resource of an engine. To view all virtual resources:

list(engine.virtual_resource.all())

Available attributes:

Variables:
  • connection_limit (int) – Maximum number of connections for this virtual engine. 0 means unlimited (default: 0)

  • show_master_nic (bool) – Show the master engine NIC id’s in the virtual engine.

When updating this element, make modifications and call update()

property allocated_domain_ref

Domain that this virtual engine is allocated in. ‘Shared Domain’ is is the default if no domain is specified.

>>> for resource in engine.virtual_resource:
...   resource, resource.allocated_domain_ref
...
(VirtualResource(name=ve-1), AdminDomain(name=Shared Domain))
(VirtualResource(name=ve-8), AdminDomain(name=Shared Domain))
Returns:

AdminDomain element

Return type:

AdminDomain

create(name, vfw_id, domain='Shared Domain', show_master_nic=False, connection_limit=0, comment=None)[source]

Create a new virtual resource. Called through engine reference:

engine.virtual_resource.create(....)
Parameters:
  • name (str) – name of virtual resource

  • vfw_id (int) – virtual fw identifier

  • domain (str) – name of domain to install, (default Shared)

  • show_master_nic (bool) – whether to show the master engine NIC ID’s in the virtual instance

  • connection_limit (int) – whether to limit number of connections for this instance

Returns:

href of new virtual resource

Return type:

str

set_admin_domain(admin_domain)[source]

Virtual Resources can be members of an Admin Domain to provide delegated administration features. Assign an admin domain to this resource. Admin Domains must already exist.

Parameters:

admin_domain (str,AdminDomain) – Admin Domain to add

Returns:

None

property vfw_id

Read-Only virtual engine identifier. This is unique per virtual engine and is set when the virtual resource is created.

Returns:

vfw id

Return type:

int

AdvanceSettings

Engine advanced setting functionality such as LogModeration. These are common settings that are located under the SMC Advanced Settings.

class smc.core.advanced_settings.LogModeration(engine)[source]

This is the definition of Log Compression for the engine or for an interface. You can also configure Log Compression to save resources on the engine. By default, each generated Antispoofing and Discard log entry is logged separately and displayed as a separate entry in the Logs view. Log Compression allows you to define the maximum number of separately logged entries. When the defined limit is reached, a single Antispoofing log entry or Discard log entry is logged. The single entry contains information on the total number of the generated Antispoofing log entries or Discard log entries. After this, logging returns to normal and all the generated entries are once more logged and displayed separately.

add(burst=None, log_event=None, rate=None)[source]

Add log_moderation setting entry on interface or engine. :param str burst: The maximum number of matching entries in a single burst. The default value for Antispoofing entries is 1000. By default, Discard log entries are not compressed. :param int log_event: Log Moderation Event Type:

  1. antispoofing: Antispoofing entry (L3 engine only)

  2. discard: discard entry.

Parameters:

rate (int) – The maximum number of entries per second. The default value for

Antispoofing entries is 100 entries /s. By default, Discard log entries are not compressed.

contains(log_event)[source]

Check if specific log_moderation settings are present. :param int log_event: Log Moderation Event Type:

  1. antispoofing: Antispoofing entry (L3 engine only)

  2. discard: discard entry.

get(log_event)[source]

Return log_moderation entry with specific log_event :param str log_event: Log Moderation Event Type:

  1. antispoofing: Antispoofing entry (L3 engine only)

  2. discard: discard entry.

:rtype dict

remove(log_event)[source]

Remove the specific log_moderation setting. :param str log_event: Log Moderation Event Type:

  1. antispoofing: Antispoofing entry (L3 engine only)

  2. discard: discard entry.

Engine Types

IPS

class smc.core.engines.IPS(name=None, **meta)[source]

Creates an IPS engine with a default inline interface pair

classmethod create(name, mgmt_ip, mgmt_network, mgmt_interface=0, inline_interface='1-2', logical_interface='default_eth', log_server_ref=None, domain_server_address=None, zone_ref=None, enable_antivirus=False, enable_gti=False, comment=None, extra_opts=None, lldp_profile=None, discard_quic_if_cant_inspect=True, node_definition=None, **kw)[source]

Create a single IPS engine with management interface and inline pair

Parameters:
  • name (str) – name of ips engine

  • mgmt_ip (str) – ip address of management interface

  • mgmt_network (str) – management network in cidr format

  • mgmt_interface (int) – (optional) interface for management from SMC to engine

  • inline_interface (str) – interfaces to use for first inline pair

  • logical_interface (str) – name, str href or LogicalInterface (created if it doesn’t exist)

  • log_server_ref (str) – (optional) href to log_server instance

  • domain_server_address (list) – (optional) DNS server addresses

  • zone_ref (str) – zone name, str href or Zone for management interface (created if not found)

  • enable_antivirus (bool) – (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI

  • lldp_profile (LLDPProfile) – LLDP Profile represents a set of attributes used for

configuring LLDP :param bool discard_quic_if_cant_inspect: (optional) discard or allow QUIC

if inspection is not possible

Parameters:

extra_opts (dict) – extra options as a dict to be passed to the top level engine

:param node_definition information for the node itself :raises CreateEngineFailed: Failure to create with reason :return: smc.core.engine.Engine

Layer3Firewall

class smc.core.engines.Layer3Firewall(name=None, **meta)[source]

Changed in version 0.7.0: extra_opts can be passed to the top level engine dict to customize input

Represents a Layer 3 Firewall configuration. A layer 3 single engine is a standalone engine instance (not a cluster). You can use the create constructor and add interfaces after the engine exists, or use create_bulk to fully create the engine and interfaces in a single operation.

You can also pass arbitrary kwargs passed in to the engine dict by providing the extra_opts value as a dict. Therefore it can support any custom configurations as long as the format is valid. For example, enabling file reputation on a SMC >= 6.6:

extra_opts= {'file_reputation_settings':{'file_reputation_context': 'gti_cloud_only'}}
classmethod create(name, mgmt_ip, mgmt_network, mgmt_interface=0, log_server_ref=None, default_nat=False, reverse_connection=False, domain_server_address=None, zone_ref=None, enable_antivirus=False, enable_gti=False, location_ref=None, enable_ospf=False, sidewinder_proxy_enabled=False, known_host_lists=[], ospf_profile=None, snmp=None, ntp_settings=None, timezone=None, comment=None, extra_opts=None, engine_type=None, node_type='firewall_node', lldp_profile=None, link_usage_profile=None, quic_enabled=True, discard_quic_if_cant_inspect=True, node_definition=None, **kw)[source]

Create a single layer 3 firewall with management interface and DNS. Provide the interfaces keyword argument if adding multiple additional interfaces. Interfaces can be one of any valid interface for a layer 3 firewall. Unless the interface type is specified, physical_interface is assumed.

If providing the interfaces keyword during creation, the valid interface types are:

  • physical_interface (default if not specified)

  • tunnel_interface

  • switch_physical_interface

If providing all engine interfaces in a single operation, see create_bulk() for additional examples.

Parameters:
  • name (str) – name of firewall engine

  • mgmt_ip (str) – ip address of management interface

  • mgmt_network (str) – management network in cidr format

  • log_server_ref (str) – (optional) href to log_server instance for engine

  • mgmt_interface (int) – (optional) interface for management from SMC to engine

  • domain_server_address (list) – (optional) DNS server addresses

  • zone_ref (str) – zone name, str href or zone name for management interface (created if not found)

  • reverse_connection (bool) – should the NGFW be the mgmt initiator (used when behind NAT)

  • default_nat (bool) – (optional) Whether to enable default NAT for outbound

  • enable_antivirus (bool) – (optional) Enable antivirus (required DNS)

  • enable_gti (bool) – (optional) Enable GTI

  • sidewinder_proxy_enabled (bool) – Enable Sidewinder proxy functionality

  • known_host_lists (list) – hrefs of ssh known host list objects (comma separated)

  • location_ref (str) – location href or not for engine if needed to contact SMC behind NAT (created if not found)

  • enable_ospf (bool) – whether to turn OSPF on within engine

  • ospf_profile (str) – optional OSPF profile to use on engine, by ref

  • ntp_settings (NTPSettings) – NTP settings

  • lldp_profile (LLDPProfile) – LLDP Profile represents a set of attributes used for

configuring LLDP :param LinkUsageProfile link_usage_profile :param dict extra_opts: extra options as a dict to be passed to the top level engine :param kw: optional keyword arguments specifying additional interfaces :param bool quic_enabled: (optional) include QUIC ports for web traffic :param bool discard_quic_if_cant_inspect: (optional) discard or allow QUIC :param node_definition information for the node itself

if inspection is not possible

Raises:

CreateEngineFailed – Failure to create with reason

Returns:

smc.core.engine.Engine

classmethod create_bulk(name, interfaces=None, primary_mgt=None, backup_mgt=None, auth_request=None, log_server_ref=None, domain_server_address=None, nodes=1, nodes_definition=None, node_type='firewall_node', location_ref=None, default_nat=False, enable_antivirus=False, enable_gti=False, sidewinder_proxy_enabled=False, known_host_lists=[], enable_ospf=False, ospf_profile=None, comment=None, snmp=None, ntp_settings=None, timezone=None, extra_opts=None, engine_type=None, lldp_profile=None, link_usage_profile=None, quic_enabled=True, discard_quic_if_cant_inspect=True, **kw)[source]

Create a Layer 3 Firewall providing all of the interface configuration. This method provides a way to fully create the engine and all interfaces at once versus using create() and creating each individual interface after the engine exists.

Example interfaces format:

interfaces=[
    {'interface_id': 1},
    {'interface_id': 2,
     'interfaces':[{'nodes': [{'address': '2.2.2.2', 'network_value': '2.2.2.0/24'}]}],
     'zone_ref': 'myzone'},
    {'interface_id': 3,
     'interfaces': [{'nodes': [{'address': '3.3.3.3', 'network_value': '3.3.3.0/24'}],
                     'vlan_id': 3,
                     'zone_ref': 'myzone'},
                     {'nodes': [{'address': '4.4.4.4', 'network_value': '4.4.4.0/24'}],
                      'vlan_id': 4}]},
    {'interface_id': 4,
     'interfaces': [{'vlan_id': 4,
                     'zone_ref': 'myzone'}]},
    {'interface_id': 5,
     'interfaces': [{'vlan_id': 5}]},
    {'interface_id': 1000,
     'interfaces': [{'nodes': [{'address': '10.10.10.1',
                     'network_value': '10.10.10.0/24'}]}],
                     'type': 'tunnel_interface'}]

Sample of creating a simple two interface firewall:

firewall_def = {
    'name': 'firewall',
    'domain_server_address': ['192.168.122.1'],
    'primary_mgt': 0,
    'interfaces': [
        {'interface_id': 0,
         'interfaces': [{'nodes': [{'address': '192.168.122.100',
                        'network_value': '192.168.122.0/24', 'auth_request': False}]}
                        ]
         },
        {'interface_id': 1,
         'interfaces': [{'nodes': [{'address': '10.0.0.254',
                       'network_value': '10.0.0.0/24', 'auth_request': True}]}
                        ]
         }
    ]
}
fw = Layer3Firewall.create_bulk(**firewall_def)

Note

You can set primary_mgt, backup_mgt, outgoing, and auth_request within the interface definition itself to specify interface options. If provided in the constructor, this will be passed to the interface creation factory. You should use one or the other method, not both.

See smc.core.interfaces.Layer3PhysicalInterface for more advanced examples

classmethod create_dynamic(name, interface_id, dynamic_index=1, reverse_connection=True, automatic_default_route=True, domain_server_address=None, loopback_ndi='127.0.0.1', location_ref=None, log_server_ref=None, zone_ref=None, enable_gti=False, enable_antivirus=False, sidewinder_proxy_enabled=False, known_host_lists=[], default_nat=False, comment=None, extra_opts=None, engine_type=None, node_type='firewall_node', lldp_profile=None, link_usage_profile=None, quic_enabled=True, discard_quic_if_cant_inspect=True, node_definition=None, **kw)[source]

Create a single layer 3 firewall with only a single DHCP interface. Useful when creating virtualized engine’s such as in Microsoft Azure.

Parameters:
  • name (str) – name of engine

  • interface_id (str,int) – interface ID used for dynamic interface and management

  • reverse_connection (bool) – specifies the dynamic interface should initiate connections to management (default: True)

  • automatic_default_route (bool) – allow SMC to create a dynamic netlink for the default route (default: True)

  • domain_server_address (list) – list of IP addresses for engine DNS

  • loopback_ndi (str) – IP address for a loopback NDI. When creating a dynamic engine, the auth_request must be set to a different interface, so loopback is created

  • location_ref (str) – location by name for the engine

  • log_server_ref (str) – log server reference, will use the default or first retrieved if not specified

  • lldp_profile (LLDPProfile) – LLDP Profile represents a set of attributes used for

configuring LLDP :param dict extra_opts: extra options as a dict to be passed to the top level engine :param bool quic_enabled: (optional) include QUIC ports for web traffic :param bool discard_quic_if_cant_inspect: (optional) discard or allow QUIC :param node_definition information for the node itself

if inspection is not possible

Raises:

CreateElementFailed – failed to create engine

Returns:

smc.core.engine.Engine

property ha_settings

HA settings for the engine

Return type:

HAForSingleEngine or None

property quic_enabled

include QUIC ports for web traffic

Return type:

bool

Layer2Firewall

class smc.core.engines.Layer2Firewall(name=None, **meta)[source]

Creates a Layer 2 Firewall with a default inline interface pair To instantiate and create, call ‘create’ classmethod as follows:

engine = Layer2Firewall.create(name='myinline',
                               mgmt_ip='1.1.1.1',
                               mgmt_network='1.1.1.0/24')
classmethod create(name, mgmt_ip, mgmt_network, mgmt_interface=0, inline_interface='1-2', logical_interface='default_eth', log_server_ref=None, domain_server_address=None, zone_ref=None, enable_antivirus=False, enable_gti=False, comment=None, extra_opts=None, lldp_profile=None, discard_quic_if_cant_inspect=True, node_definition=None, **kw)[source]

Create a single layer 2 firewall with management interface and inline pair

Parameters:
  • name (str) – name of firewall engine

  • mgmt_ip (str) – ip address of management interface

  • mgmt_network (str) – management network in cidr format

  • mgmt_interface (int) – (optional) interface for management from SMC to engine

  • inline_interface (str) – interfaces to use for first inline pair

  • logical_interface (str) – name, str href or LogicalInterface (created if it doesn’t exist)

  • log_server_ref (str) – (optional) href to log_server instance

  • domain_server_address (list) – (optional) DNS server addresses

  • zone_ref (str) – zone name, str href or Zone for management interface (created if not found)

  • enable_antivirus (bool) – (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI

  • lldp_profile (LLDPProfile) – LLDP Profile represents a set of attributes used for

configuring LLDP :param bool discard_quic_if_cant_inspect: (optional) discard or allow QUIC

if inspection is not possible

:param node_definition information for the node itself :param dict extra_opts: extra options as a dict to be passed to the top level engine :raises CreateEngineFailed: Failure to create with reason :return: smc.core.engine.Engine

Layer3VirtualEngine

class smc.core.engines.Layer3VirtualEngine(name=None, **meta)[source]

Create a layer3 virtual engine and map to specified Master Engine Each layer 3 virtual firewall will use the same virtual resource that should be pre-created.

To instantiate and create, call ‘create’ as follows:

engine = Layer3VirtualEngine.create(
                        name='myips',
                        master_engine='mymaster_engine',
                        virtual_engine='ve-3',
                        interfaces=[{'interface_id': 0,
                                     'address': '5.5.5.5',
                                     'network_value': '5.5.5.5/30',
                                     'zone_ref': ''}]
classmethod create(name, master_engine, virtual_resource, interfaces, default_nat=False, outgoing_intf=0, domain_server_address=None, enable_ospf=False, ospf_profile=None, comment=None, extra_opts=None, quic_enabled=True, discard_quic_if_cant_inspect=True, **kw)[source]

Create a Layer3Virtual engine for a Master Engine. Provide interfaces as a list of dict items specifying the interface details in format:

{'interface_id': 1, 'address': '1.1.1.1', 'network_value': '1.1.1.0/24',
 'zone_ref': zone_by_name,href, 'comment': 'my interface comment'}
Parameters:
  • name (str) – Name of this layer 3 virtual engine

  • master_engine (str) – Name of existing master engine

  • virtual_resource (str) – name of pre-created virtual resource

  • interfaces (list) – dict of interface details

  • default_nat (bool) – Whether to enable default NAT for outbound

  • outgoing_intf (int) – outgoing interface for VE. Specifies interface number

  • interfaces – interfaces mappings passed in

  • enable_ospf (bool) – whether to turn OSPF on within engine

  • ospf_profile (str) – optional OSPF profile to use on engine, by ref

  • quic_enabled (bool) – (optional) include QUIC ports for web traffic

  • discard_quic_if_cant_inspect (bool) – (optional) discard or allow QUIC if inspection is not possible

  • extra_opts (dict) – extra options as a dict to be passed to the top level engine

Raises:
Returns:

smc.core.engine.Engine

property quic_enabled

include QUIC ports for web traffic

Return type:

bool

FirewallCluster

class smc.core.engines.FirewallCluster(name=None, **meta)[source]

Firewall Cluster Creates a layer 3 firewall cluster engine with CVI and NDI’s. Once engine is created, you can later add additional interfaces using the engine.physical_interface reference.

See also

smc.core.physical_interface.add_layer3_cluster_interface()

classmethod create(name, cluster_virtual, network_value, macaddress, interface_id, nodes, nodes_definition=[], vlan_id=None, cluster_mode='balancing', backup_mgt=None, primary_heartbeat=None, log_server_ref=None, domain_server_address=None, location_ref=None, zone_ref=None, default_nat=False, enable_antivirus=False, enable_gti=False, comment=None, snmp=None, ntp_settings=None, timezone=None, extra_opts=None, lldp_profile=None, link_usage_profile=None, quic_enabled=True, discard_quic_if_cant_inspect=True, **kw)[source]

Create a layer 3 firewall cluster with management interface and any number of nodes. If providing keyword arguments to create additional interfaces, use the same constructor arguments and pass an interfaces keyword argument. The constructor defined interface will be assigned as the primary management interface by default. Otherwise the engine will be created with a single interface and interfaces can be added after.

Changed in version 0.6.1: Chgnged cluster_nic to interface_id, and cluster_mask to network_value

Parameters:
  • name (str) – name of firewall engine

  • cluster_virtual (str) – ip of cluster CVI

  • network_value (str) – ip netmask of cluster CVI

  • macaddress (str) – macaddress for packet dispatch clustering

  • interface_id (str) – nic id to use for primary interface

  • nodes (list) – address/network_value/nodeid combination for cluster nodes

:param list nodes_definition : list of node info (name, comment..) :param str vlan_id: optional VLAN id for the management interface, i.e. ‘15’. :param str cluster_mode: ‘balancing’ or ‘standby’ mode (default: balancing) :param str,int primary_heartbeat: optionally set the primary_heartbeat. This is

automatically set to the management interface but can be overridden to use another interface if defining additional interfaces using interfaces.

Parameters:
  • backup_mgt (str,int) – optionally set the backup management interface. This is unset unless you define additional interfaces using interfaces.

  • log_server_ref (str) – (optional) href to log_server instance

  • domain_server_address (list) – (optional) DNS server addresses

  • location_ref (str) – location href or not for engine if needed to contact SMC behind NAT (created if not found)

  • zone_ref (str) – zone name, str href or Zone for management interface (created if not found)

  • enable_antivirus (bool) – (optional) Enable antivirus (required DNS)

  • enable_gti (bool) – (optional) Enable GTI

  • interfaces (list) – optional keyword to supply additional interfaces

  • snmp (dict) – SNMP dict should have keys snmp_agent str defining name of SNMPAgent, snmp_interface which is a list of interface IDs, and optionally snmp_location which is a string with the SNMP location name.

  • lldp_profile (LLDPProfile) – LLDP Profile represents a set of attributes used for

configuring LLDP :param LinkUsageProfile link_usage_profile: Link usage profile :param bool quic_enabled: (optional) include QUIC ports for web traffic :param bool discard_quic_if_cant_inspect: (optional) discard or allow QUIC

if inspection is not possible

Parameters:

extra_opts (dict) – extra options as a dict to be passed to the top level engine

Raises:

CreateEngineFailed – Failure to create with reason

Returns:

smc.core.engine.Engine

Example nodes parameter input:

[{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1},
 {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2},
 {'address':'5.5.5.4', 'network_value':'5.5.5.0/24', 'nodeid':3}]

You can also create additional CVI+NDI, or NDI only interfaces by providing the keyword argument interfaces using the same keyword values from the constructor:

interfaces=[
   {'interface_id': 1,
    'macaddress': '02:02:02:02:02:03',
    'interfaces': [{'cluster_virtual': '2.2.2.1',
                    'network_value': '2.2.2.0/24',
                    'nodes':[{'address': '2.2.2.2', 'network_value': '2.2.2.0/24',
                              'nodeid': 1},
                             {'address': '2.2.2.3', 'network_value': '2.2.2.0/24',
                              'nodeid': 2}]
                  }]
    },
   {'interface_id': 2,
    'interfaces': [{'nodes':[{'address': '3.3.3.2', 'network_value': '3.3.3.0/24',
                              'nodeid': 1},
                             {'address': '3.3.3.3', 'network_value': '3.3.3.0/24',
                              'nodeid': 2}]
                  }]
    }]

It is also possible to define VLAN interfaces by providing the vlan_id keyword. Example VLAN with NDI only interfaces. If nesting the zone_ref within the interfaces list, the zone will be applied to the VLAN versus the top level interface:

interfaces=[
   {'interface_id': 2,
    'interfaces': [{'nodes':[{'address': '3.3.3.2', 'network_value': '3.3.3.0/24',
                              'nodeid': 1},
                             {'address': '3.3.3.3', 'network_value': '3.3.3.0/24',
                              'nodeid': 2}],
                    'vlan_id': 22,
                    'zone_ref': 'private-network'
                  },
                  {'nodes': [{'address': '4.4.4.1', 'network_value': '4.4.4.0/24',
                              'nodeid': 1},
                             {'address': '4.4.4.2', 'network_value': '4.4.4.0/24',
                              'nodeid': 2}],
                   'vlan_id': 23,
                   'zone_ref': 'other_vlan'
                }]
}]

Tunnel interfaces can also be created. As all interfaces defined are assumed to be a physical interface type, you must specify the type parameter to indicate the interface is a tunnel interface. Tunnel interfaces do not have a macaddress or VLANs. They be configured with NDI interfaces by omitting the cluster_virtual and network_value top level attributes:

interfaces=[
    {'interface_id': 1000,
     'interfaces': [{'cluster_virtual': '100.100.100.1',
                     'network_value': '100.100.100.0/24',
                     'nodes':[{'address': '100.100.100.2', 'network_value':
                               '100.100.100.0/24', 'nodeid': 1},
                              {'address': '100.100.100.3', 'network_value':
                               '100.100.100.0/24', 'nodeid': 2}]
                   }],
     'zone_ref': 'AWStunnel',
     'type': 'tunnel_interface'
    }]

If setting primary_heartbeat or backup_mgt to a specific interface (the primary interface configured in the constructor will have these roles by default), you must define the interfaces in the interfaces keyword argument list.

Note

If creating additional interfaces, you must at minimum provide the interface_id and nodes to create an NDI only interface.

classmethod create_bulk(name, interfaces=None, nodes=2, nodes_definition=[], cluster_mode='balancing', primary_mgt=None, backup_mgt=None, primary_heartbeat=None, log_server_ref=None, domain_server_address=None, location_ref=None, default_nat=False, enable_antivirus=False, enable_gti=False, comment=None, snmp=None, ntp_settings=None, timezone=None, extra_opts=None, lldp_profile=None, link_usage_profile=None, quic_enabled=True, discard_quic_if_cant_inspect=True, **kw)[source]

Create bulk is called by the create constructor when creating a cluster engine. This allows for multiple interfaces to be defined and passed in during element creation.

Parameters:

snmp (dict) – SNMP dict should have keys snmp_agent str defining name of SNMPAgent, snmp_interface which is a list of interface IDs, and optionally snmp_location which is a string with the SNMP location name.

property quic_enabled

include QUIC ports for web traffic

Return type:

bool

MasterEngine

class smc.core.engines.MasterEngine(name=None, **meta)[source]

Creates a master engine in a firewall role. Layer3VirtualEngine should be used to add each individual instance to the Master Engine.

classmethod create(name, master_type, mgmt_ip, mgmt_network, mgmt_interface=0, log_server_ref=None, zone_ref=None, domain_server_address=None, enable_gti=False, enable_antivirus=False, comment=None, extra_opts=None, lldp_profile=None, cluster_mode='standby', reverse_connection=False, node_definition=None, **kw)[source]

Create a Master Engine with management interface

Parameters:
  • name (str) – name of master engine engine

  • master_type (str) – firewall|

  • mgmt_ip (str) – ip address for management interface

  • mgmt_network (str) – full netmask for management

  • mgmt_interface (str) – interface to use for mgmt (default: 0)

  • log_server_ref (str) – (optional) href to log_server instance

  • domain_server_address (list) – (optional) DNS server addresses

  • enable_antivirus (bool) – (optional) Enable antivirus (required DNS)

  • enable_gti (bool) – (optional) Enable GTI

  • extra_opts (dict) – extra options as a dict to be passed to the top level engine

  • lldp_profile (LLDPProfile) – LLDP Profile represents a set of attributes used for

configuring LLDP :param str cluster_mode: Defines whether the clustered engines are all online balancing the

traffic or whether one node is online at a time and the other engines are used as backup

Parameters:

reverse_connection (boolean) – Reverse connection.

:param node_definition information for the node itself :raises CreateEngineFailed: Failure to create with reason :return: smc.core.engine.Engine

MasterEngineCluster

class smc.core.engines.MasterEngineCluster(name=None, **meta)[source]

Master Engine Cluster Clusters are currently supported in an active/standby configuration only.

classmethod create(name, master_type, macaddress, nodes, nodes_definition=None, mgmt_interface=0, log_server_ref=None, domain_server_address=None, enable_gti=False, enable_antivirus=False, comment=None, extra_opts=None, lldp_profile=None, cluster_mode='standby', reverse_connection=False, **kw)[source]

Create Master Engine Cluster

Parameters:
  • name (str) – name of master engine engine

  • master_type (str) – firewall|

  • mgmt_ip (str) – ip address for management interface

  • mgmt_netmask (str) – full netmask for management

  • mgmt_interface (str) – interface to use for mgmt (default: 0)

  • nodes (list) – address/network_value/nodeid combination for cluster nodes

  • log_server_ref (str) – (optional) href to log_server instance

  • domain_server_address (list) – (optional) DNS server addresses

  • enable_antivirus (bool) – (optional) Enable antivirus (required DNS)

  • enable_gti (bool) – (optional) Enable GTI

  • extra_opts (dict) – extra options as a dict to be passed to the top level engine

  • lldp_profile (LLDPProfile) – LLDP Profile represents a set of attributes used for

configuring LLDP :param str cluster_mode: Defines whether the clustered engines are all online balancing the

traffic or whether one node is online at a time and the other engines are used as backup

Parameters:

reverse_connection (boolean) – Reverse connection.

:param list nodes_definition : list of node info (name, comment..) :raises CreateEngineFailed: Failure to create with reason :return: smc.core.engine.Engine

Example nodes parameter input:

[{'address':'5.5.5.2',
  'network_value':'5.5.5.0/24',
  'nodeid':1},
 {'address':'5.5.5.3',
  'network_value':'5.5.5.0/24',
  'nodeid':2},
 {'address':'5.5.5.4',
  'network_value':'5.5.5.0/24',
  'nodeid':3}]

CloudSGSingleFW

class smc.core.engines.CloudSGSingleFW(name=None, **meta)[source]

Creates a Cloud Firewall with a default dynamic interface To instantiate and create, call ‘create_dynamic’ classmethod as follows:

engine = CloudSGSingleFW.create_dynamic(interface_id=0,
                                        name='Cloud Single firewall 1')
classmethod create_dynamic(name, interface_id, dynamic_index=1, reverse_connection=True, automatic_default_route=True, domain_server_address=None, loopback_ndi='127.0.0.1', location_ref=None, log_server_ref=None, zone_ref=None, enable_gti=False, enable_antivirus=False, sidewinder_proxy_enabled=False, known_host_lists=[], default_nat=False, comment=None, extra_opts=None, **kw)[source]

Create a single layer 3 firewall with only a single DHCP interface. Useful when creating virtualized engine’s such as in Microsoft Azure.

Parameters:
  • name (str) – name of engine

  • interface_id (str,int) – interface ID used for dynamic interface and management

  • reverse_connection (bool) – specifies the dynamic interface should initiate connections to management (default: True)

  • automatic_default_route (bool) – allow SMC to create a dynamic netlink for the default route (default: True)

  • domain_server_address (list) – list of IP addresses for engine DNS

  • loopback_ndi (str) – IP address for a loopback NDI. When creating a dynamic engine, the auth_request must be set to a different interface, so loopback is created

  • location_ref (str) – location by name for the engine

  • log_server_ref (str) – log server reference, will use the default or first retrieved if not specified

  • lldp_profile (LLDPProfile) – LLDP Profile represents a set of attributes used for

configuring LLDP :param dict extra_opts: extra options as a dict to be passed to the top level engine :param bool quic_enabled: (optional) include QUIC ports for web traffic :param bool discard_quic_if_cant_inspect: (optional) discard or allow QUIC :param node_definition information for the node itself

if inspection is not possible

Raises:

CreateElementFailed – failed to create engine

Returns:

smc.core.engine.Engine

Dynamic Routing Elements

RouteMap

Route map rules and match condition elements for dynamic routing policies.

A RouteMap can be created and subsequent rules can be inserted within the route map policy.

A MatchCondition is the subject of the rule providing criteria to specify how a match is made. Elements used in match conditions are next_hop, peer_address, access_list and type metric.

See also

MatchCondition for more details on how to add match conditions to a rule or modify an existing rule.

Example of creating a RouteMap and subsequent rule, specifying match condition options as keyword arguments:

>>> from smc.routing.route_map import RouteMap
>>> from smc.routing.access_list import IPAccessList
>>> from smc.routing.bgp import ExternalBGPPeer
...
>>> rm = RouteMap.create(name='myroutemap')
>>> rm
RouteMap(name=myroutemap)
>>> rm.route_map_rules.create(name='rule1', action='permit',
        next_hop=IPAccessList('myacl'), peer_address=ExternalBGPPeer('bgppeer'),
        metric=20)
RouteMapRule(name=rule1)
...
>>> rule1 = rm.route_map_rules.get(0) # retrieve rule 1 from the route map
>>> for condition in rule1.match_condition:
...   condition
...
Condition(rank=1, element=ExternalBGPPeer(name=bgppeer), type=u'peer_address')
Condition(rank=2, element=IPAccessList(name=myacl), type='access_list')
Condition(rank=3, element=Metric(value=20), type=u'metric')

Instead of providing singular match condition keywords to the create constructor, you can also optionally provide a MatchCondition instance when creating a rule:

>>> from smc.routing.route_map import MatchCondition
>>> condition = MatchCondition()
>>> condition.add_access_list(IPAccessList('myacl'))
>>> condition.add_peer_address(ExternalBGPPeer('bgppeer'))
>>> condition.add_metric(20)
>>> condition
MatchCondition(entries=3)
>>> rm.route_map_rules.create(
...         name='foo2',
...         finish=False,
...         match_condition=condition)
RouteMapRule(name=foo2)

To remove a match condition, first obtain it’s rank. After making the modification be sure to call update on the rule element:

>>> rule = rm.route_map_rules.get(0)
>>> rule.match_condition.remove_condition(rank=2)
>>> rule.update()

You can also delete a rule by obtaining the rule, either through the route_map_rules collection reference or by iteration:

rule = rm.route_map_rules.get(1)
rule.delete()

Or by the name:

rule = rm.route_map_rules.get_exact('foo')
rule.delete()
class smc.routing.route_map.MatchCondition(rule=None)[source]

Bases: object

MatchCondition is an iterable container class that holds the match conditions for the route map rule. The list of conditions are ranked in order. You can add, remove and view conditions currently configured in this rule. After making modifications, call update on the rule to commit back to SMC.

When iterating over a match condition, a namedtuple is returned that provides the rank and element type for the condition. It is then possible to add by rank (ie: insert conditions in between others), or remove based on rank. If not rank is provided when adding new conditions, the condition is added to the bottom of the rank list.

Return type:

list(Condition)

add_access_list(accesslist, rank=None)[source]

Add an access list to the match condition. Valid access list types are IPAccessList (v4 and v6), IPPrefixList (v4 and v6), AS Path, CommunityAccessList, ExtendedCommunityAccessList.

add_metric(value, rank=None)[source]

Add a metric to this match condition

Parameters:

value (int) – metric value

add_next_hop(access_or_prefix_list, rank=None)[source]

Add a next hop condition. Next hop elements must be of type IPAccessList or IPPrefixList.

Raises:

ElementNotFound – If element specified does not exist

add_peer_address(ext_bgp_peer_or_fw, rank=None)[source]

Add a peer address. Peer address types are ExternalBGPPeer or Engine.

Raises:

ElementNotFound – If element specified does not exist

remove_condition(rank)[source]

Remove a condition element using it’s rank. You can find the rank and element for a match condition by iterating the match condition:

>>> rule1 = rm.route_map_rules.get(0)
>>> for condition in rule1.match_condition:
...   condition
...
Condition(rank=1, element=ExternalBGPPeer(name=bgppeer))
Condition(rank=2, element=IPAccessList(name=myacl))
Condition(rank=3, element=Metric(value=20))

Then delete by rank. Call update on the rule after making the modification.

Parameters:

rank (int) – rank of the condition to remove

Raises:

UpdateElementFailed – failed to update rule

Returns:

None

class smc.routing.route_map.RouteMap(name=None, **meta)[source]

Bases: Element

Use Route Map elements in more complex networks to control or manipulate routes. You can use Access List elements as a Matching Condition in a Route Map rule. RouteMaps are rule lists similar to normal policies and can be iterated:

>>> from smc.routing.route_map import RouteMap
>>> rm = RouteMap('myroutemap')
>>> for rule in rm.route_map_rules:
...   rule
...
RouteMapRule(name=Rule @115.13)
RouteMapRule(name=Rule @117.0)
classmethod create(name, comment=None)[source]

Create a new route map. After creation, you can add a rule and subsequent match conditions.

Parameters:
  • name (str) – name of route map

  • comment (str) – optional comment

Raises:

CreateElementFailed – failed creating route map

Return type:

RouteMap

property route_map_rules

IPv6NAT Rule entry point

Return type:

rule_collection(IPv6NATRule)

search_rule(search)[source]

Search the RouteMap policy using a search string

Parameters:

search (str) – search string for a contains match against the rule name and comments field

Return type:

list(RouteMapRule)

class smc.routing.route_map.RouteMapRule(**meta)[source]

Bases: RuleCommon, SubElement

A route map rule represents the rules to be processed for a route map assigned to a specific BGP network. A match condition can be provided which encapsulates using dynamic routing element types such as IPAccessList, IPPrefixList, etc.

property action

Action for this route map rule. Valid actions are ‘permit’ and ‘deny’.

Return type:

str

call_route_map(route_map)[source]

Call another route map after match of this rule. Call update on the rule to save after modification.

Parameters:

route_map (RouteMap) – Pass the route map element

Raises:

ElementNotFound – invalid RouteMap reference passed

Returns:

None

property comment

Get and set the comment for this rule.

Parameters:

value (str) – string comment

Return type:

str

create(name, action='permit', goto=None, finish=False, call=None, comment=None, add_pos=None, after=None, before=None, **match_condition)[source]

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.

Parameters:
  • name (str) – name for this rule

  • action (str) – permit or deny

  • goto (str) – specify a rule section to goto after if there is a match condition. This will override the finish parameter

  • finish (bool) – finish stops the processing after a match condition. If finish is False, processing will continue to the next rule.

  • call (RouteMap) – call another route map after matching.

  • comment (str) – optional comment for the rule

  • add_pos (int) – 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.

  • after (str) – Rule tag to add this rule after. Mutually exclusive with add_pos and before params.

  • before (str) – Rule tag to add this rule before. Mutually exclusive with add_pos and after params.

  • 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

  • ElementNotFound – if references elements in a match condition this can be raised when the element specified is not found.

See also

MatchCondition for valid elements and expected values for each type.

property finish

Is rule action goto set to finish on this rule match. If finish is False, then the policy will proceed to the next rule.

Return type:

bool

property goto

If the rule is set to goto a rule section, return the rule section, otherwise it will return None. Check the value of finish to determine if the rule is set to finish on match.

Returns:

RouteMap or None

goto_rule_section(rule_section)[source]

Set this rule to goto a specific rule section after match. If goto is None, then check value of finish.

Parameters:

rule_section (RouteMapRule) – pass rule section

Returns:

None

property is_disabled

Is the rule disabled

Return type:

bool

property match_condition

Return the match condition for this rule. This can then be modified in place. Be sure to call update on the rule to save.

Return type:

MatchCondition

class smc.routing.route_map.Metric(value)

Bases: tuple

A metric is a simple namedtuple for returning a Metric route map element

Variables:

value (int) – metric value for this BGP route

class smc.routing.route_map.Condition(rank, element, type)

Bases: tuple

A condition defines the type of dynamic element that is used in the match condition field of a route map.

Variables:
  • rank (str) – the rank in the match condition list

  • element (str) – the dynamic element type for this condition

  • type (str) – type defines the type of entry, i.e. metric, peer_address, next_hop, access_list

IPAccessList

AccessList module represents functionality that support dynamic routing filters based on IPv4 or IPv6 access lists such as OSPF and BGP.

class smc.routing.access_list.AccessList[source]

Bases: object

AccessList provides an iterable container that allows simple iteration over existing IPAccessList (v4 and v6), IPPrefixList (v4 and v6), CommunityAccessList and ExtendedCommunityAccessList entries. When using the create constructor, validate the keyword arguments based on the specific access list requirements.

Returns:

namedtuple based on access list type

add_entry(**kw)[source]

Add an entry to an AccessList. Use the supported arguments for the inheriting class for keyword arguments.

Raises:

UpdateElementFailed – failure to modify with reason

Returns:

None

classmethod create(name, entries=None, comment=None, **kw)[source]

Create an Access List Entry.

Depending on the access list type you are creating (IPAccessList, IPv6AccessList, IPPrefixList, IPv6PrefixList, CommunityAccessList, ExtendedCommunityAccessList), entries will define a dict of the valid attributes for that ACL type. Each class has a defined list of attributes documented in it’s class.

You can optionally leave entries blank and use the add_entry() method after creating the list container.

Parameters:
  • name (str) – name of IP Access List

  • entries (list) – access control entry

  • kw – optional keywords that might be necessary to create the ACL (see specific Access Control List documentation for options)

Raises:

CreateElementFailed – cannot create element

Returns:

The access list based on type

remove_entry(**field_value)[source]

Remove an AccessList entry by field specified. Use the supported arguments for the inheriting class for keyword arguments.

Raises:

UpdateElementFailed – failed to modify with reason

Returns:

None

classmethod update_or_create(with_status=False, overwrite_existing=False, **kw)[source]

Update or create the Access List. This method will not attempt to evaluate whether the access list has differences, instead it will update with the contents of the payload entirely. If the intent is to only add or remove a single entry, use ~add_entry and ~remove_entry methods.

Parameters:
  • with_status (bool) – return with 3-tuple of (Element, modified, created) holding status

  • overwrite_existing (bool) – if the access list exists but instead of an incremental update you want to overwrite with the newly defined entries, set this to True (default: False)

Returns:

Element or 3-tuple with element and status

class smc.routing.access_list.IPAccessList(name=None, **meta)[source]

Bases: AccessList, Element

IPAccessList is used by dynamic routing protocols to allow filtering of routes. Protocols like OSPF and BGP allow inbound and outbound filters using these.

Create an IPAccessList. When providing values for entries to the create constructor, use valid attributes as defined in AccessListEntry:

>>> ip = IPAccessList.create(name='mylist', entries=[
    {'subnet': '1.1.1.0/24', 'action': 'permit'},
    {'subnet': '2.2.2.0/24', 'action': 'deny'}])
...
>>> ip.add_entry(subnet='3.3.3.0/24', action='permit')
>>> ip.remove_entry(subnet='1.1.1.0/24')
>>> ip.update()
'https://172.18.1.151:8082/6.4/elements/ip_access_list/13'
>>> for entry in ip:
...   entry
...
AccessListEntry(subnet=u'2.2.2.0/24', action=u'deny', comment=None)
AccessListEntry(subnet=u'3.3.3.0/24', action=u'permit', comment=None)
...
>>> ip.delete()

This is an iterable container yielding AccessListEntry

See also

AccessListEntry for valid create and add/remove parameters

class smc.routing.access_list.IPv6AccessList(name=None, **meta)[source]

Bases: AccessList, Element

IPv6AccessList is used by dynamic routing protocols to allow filtering of routes. Protocols like OSPF and BGP allow inbound and outbound filters using these.

>>> acl6 = IPv6AccessList.create(name='aclv6', entries=[
...           {'subnet': '2001:db8:1::1/128', 'action': 'permit'}])
>>> acl6
IPv6AccessList(name=aclv6)
>>> for entry in acl6:
...   entry
...
AccessListEntry(subnet=u'2001:db8:1::1/128', action=u'permit', comment=None)

This is an iterable container yielding AccessListEntry

See also

IPAccessList for using this element.

class smc.routing.access_list.AccessListEntry(subnet, action, comment)

Bases: tuple

An AccessListEntry defines a simple entry for an IPAccessList used in dynamic routing configurations.

Variables:
  • subnet (str) – subnet associated with this entry

  • action (str) – action for the entry

  • comment (str) – optional comment for the entry

IPPrefixList

IP Prefix module represents prefix lists that can be used to filter networks for OSPF routing.

class smc.routing.prefix_list.IPPrefixList(name=None, **meta)[source]

Bases: AccessList, Element

An IP prefix list specifies a list of networks. When you apply an IP prefix list to a neighbor, the device sends or receives only a route whose destination is in the IP prefix list.

Creating and modifying an IPAccessList is similar to other access list methods:

>>> prefix = IPPrefixList.create(name='mylist', entries=[
...   {'subnet': '10.0.0.0/8', 'min_prefix_length': 16,
       'max_prefix_length': 32, 'action': 'deny'},
...   {'subnet': '192.16.1.0/24', 'min_prefix_length': 25,
       'max_prefix_length': 32, 'action': 'permit'}])
>>> prefix
IPPrefixList(name=mylist)
...
>>> prefix.add_entry(subnet='192.17.1.0/24', min_prefix_length=25,
                     max_prefix_length=32, action='deny')
>>> prefix.update()
'https://172.18.1.151:8082/6.4/elements/ip_prefix_list/16'
>>> prefix.remove_entry(subnet='192.16.1.0/24')
>>> prefix.update()
'https://172.18.1.151:8082/6.4/elements/ip_prefix_list/16'
>>> for entry in prefix:
...   entry
...
PrefixListEntry(subnet=u'10.0.0.0/8', action=u'deny', min_prefix_length=16,
                max_prefix_length=32, comment=None)
PrefixListEntry(subnet=u'192.17.1.0/24', action=u'deny', min_prefix_length=25,
                max_prefix_length=32, comment=None)
You can also create a PrefixList without using the min_prefix_length

and max_prefix_length fields:

>>> prefix = IPPrefixList.create(name='mylist', entries=[

… {‘subnet’: ‘10.0.0.0/8’, ‘action’: ‘deny’}, … {‘subnet’: ‘192.16.1.0/24’, ‘action’: ‘permit’}])

This is an iterable container yielding PrefixListEntry

See also

PrefixListEntry for valid create and add/remove parameters

class smc.routing.prefix_list.IPv6PrefixList(name=None, **meta)[source]

Bases: AccessList, Element

An IP prefix list specifies a list of networks. When you apply an IP prefix list to a neighbor, the device sends or receives only a route whose destination is in the IP prefix list.

>>> prefix6 = IPv6PrefixList.create(name='myipv6', entries=[
...   {'subnet': 'ab00::/64', 'min_prefix_length': 65, 'max_prefix_length': 128,
       'action': 'deny'}])
>>> prefix6
IPv6PrefixList(name=myipv6)
>>> for entry in prefix6:
...   entry
...
PrefixListEntry(subnet=u'ab00::/64', action=u'deny', min_prefix_length=65,
                max_prefix_length=128, comment=None)
You can also create a PrefixList without using the min_prefix_length

and max_prefix_length fields:

>>> prefix = IPPrefixList.create(name='mylist', entries=[

… {‘subnet’: ‘ab00::/64’, ‘action’: ‘deny’}

This is an iterable container yielding PrefixListEntry

See also

IPPrefixList for other common operations

class smc.routing.prefix_list.PrefixListEntry(subnet, action, min_prefix_length, max_prefix_length, comment)

Bases: tuple

A PrefixListEntry defines a simple entry for an PrefixList used in dynamic routing configurations.

Variables:
  • subnet (str) – subnet associated with this entry

  • action (str) – action for the entry

  • min_prefix_length (int) – minimum mask bits

  • max_prefix_length (int) – maximum mask bits

  • comment (str) – optional comment for the entry

BGP Elements

BGP Module representing BGP settings for Forcepoint NGFW layer 3 engines. BGP can be enabled and run on either single/cluster layer 3 firewalls or virtual engines.

For adding BGP configurations, several steps are required:

  • Enable BGP on the engine and specify the BGP Profile

  • Create or use an existing OSPFArea to be used

  • Modify the routing interface and add the BGP Peering

Enable BGP on an existing engine using the default BGP system profile:

engine.bgp.enable(
    autonomous_system=AutonomousSystem('myAS')
    announced_networks=[Network('172.18.1.0/24'), Network('1.1.1.0/24')])

Create a BGP Peering using the default BGP Connection Profile:

BGPPeering.create(name='mypeer')

Add the BGP Peering to the routing interface:

interface = engine.routing.get(0)
interface.add_bgp_peering(
    BGPPeering('mypeer'),
    ExternalBGPPeer('neighbor'))

Disable BGP on an engine:

engine.bgp.disable()

Finding profiles or elements can also be done through collections:

>>> list(BGPProfile.objects.all())
[BGPProfile(name=Default BGP Profile)]

>>> list(ExternalBGPPeer.objects.all())
[ExternalBGPPeer(name=bgp-02), ExternalBGPPeer(name=Amazon AWS), ExternalBGPPeer(name=bgp-01)]

The BGP relationship can be represented as:

Engine --uses an--> (BGP Profile --and--> Autonomous System --and--> Announced Networks)
Engine Routing --uses-an--> BGP Peering --has-a--> External BGP Peer

Only Layer3Firewall and Layer3VirtualEngine types can support running BGP.

class smc.routing.bgp.BGP(data=None)[source]

BGP represents the BGP configuration on a given engine. An instance is returned from an engine reference:

engine = Engine('myengine')
engine.dynamic_routing.bgp.status
engine.dynamic_routing.bgp.announced_networks
...

When making changes to the BGP configuration, any methods called that change the configuration also require that engine.update() is called once changes are complete. This way you can make multiple changes without refreshing the engine cache.

For example, adding advertised networks to the configuration:

engine.dynamic_routing.bgp.update_configuration(announced_networks=[Network('foo')])
engine.update()
Variables:
  • autonomous_system (AutonomousSystem) – AS reference for this BGP configuration

  • profile (BGPProfile) – BGP profile reference for this configuration

property announced_networks

Show all announced networks for the BGP configuration. Returns tuple of advertised network, routemap. Route map may be None.

for advertised in engine.bgp.advertisements:
    net, route_map = advertised
Returns:

list of tuples (advertised_network, route_map).

property bmp_router_id

Get the BMP router ID for this BGP configuration. Directly linked to ‘bmp_router_id_type’ attribute:

  • [0-255]:[0-65535]: AS Number : dedicated number

  • V.X.Y.Z:[0-255]: IPv4 Address : AS Number

  • [0-65535]:[0-255]: AS Number : dedicated number

Returns:

str or None

property bmp_router_id_type

Get the BMP router ID type for this BGP configuration. Accepted values:

  • 0: [0-255]:[0-65535] format

  • 1: V.X.Y.Z:[0-255] format

  • 2: [0-65535]:[0-255] format

Returns:

str or None

disable()[source]

Disable BGP on this engine.

Returns:

None

enable(autonomous_system, announced_networks, router_id=None, bgp_profile=None)[source]

Enable BGP on this engine. On master engine, enable BGP on the virtual firewall. When adding networks to announced_networks, the element types can be of type smc.elements.network.Host, smc.elements.network.Network or smc.elements.group.Group. If passing a Group, it must have element types of host or network.

Within announced_networks, you can pass a 2-tuple that provides an optional smc.routing.route_map.RouteMap if additional policy is required for a given network.

engine.dynamic_routing.bgp.enable(
    autonomous_system=AutonomousSystem('aws_as'),
    announced_networks=[Network('bgpnet'),Network('inside')],
    router_id='10.10.10.10')
Parameters:
  • autonomous_system (str,AutonomousSystem) – provide the AS element or str href for the element

  • bgp_profile (str,BGPProfile) – provide the BGPProfile element or str href for the element; if None, use system default

  • announced_networks (list) – list of networks to advertise via BGP Announced networks can be single networks,host or group elements or a 2-tuple with the second tuple item being a routemap element

  • router_id (str) – router id for BGP, should be an IP address. If not set, automatic discovery will use default bound interface as ID.

Raises:

ElementNotFound – OSPF, AS or Networks not found

Returns:

None

Note

For arguments that take str or Element, the str value should be the href of the element.

property router_id

Get the router ID for this BGP configuration. If None, then the ID will use the interface IP.

Returns:

str or None

property status

Is BGP enabled on this engine.

Return type:

bool

update_configuration(**kwargs)[source]

Update configuration using valid kwargs as defined in the enable constructor.

Parameters:

kwargs (dict) – kwargs to satisfy valid args from enable

Return type:

bool

class smc.routing.bgp.BGPAggregationEntry(data)[source]
classmethod create(mode, subnet)[source]
Parameters:
  • mode (str) – The Aggregation value: 1.aggregate: Aggregate mode. 2.aggregate_as_set: Aggregate with AS Set mode. 3.summary_only: Summary Only mode. 4.as_set_and_summary: Aggregate with AS Set and Summary mode.

  • subnet (str) – The Subnet Network element.

Return type:

dict

class smc.routing.bgp.BGPBMPSettings(bmp_address, bmp_port, bmp_connect_through_master)[source]

A BGP BMP Entry representing the BMP listening address (FQDN/IPv4/IPv6), the BMP listening port and the flag to know if the connection must be done through master.

class smc.routing.bgp.RedistributionEntry(data)[source]
classmethod create(redistribution_type, enabled=False, filter_type=None, **kwargs)[source]
Parameters:
  • redistribution_type (str) – The redistribution type: 1.kernel: Redistribution from Kernel. 2.static: Redistribution from Static. 3.connected: Redistribution from Connected. 4.bgp: Redistribution from BGP. Available for any dynamic routing protocols Profile element but BGP one. 5.ospfv2: Redistribution from OSPFv2. Available for any dynamic routing protocols Profile element but OSPFv2 one. 6.default_originate: Default Originate injection. Available just for OSPFv2 element.

  • enabled (bool) – This redistribution is enabled or not.

  • filter_type (str) – The filter type.

Return type:

dict

AutonomousSystem

class smc.routing.bgp.AutonomousSystem(name=None, **meta)[source]

Bases: Element

Autonomous System for BGP routing. AS is a required setting when enabling BGP on an engine and specifies a unique identifier for routing communications.

property as_number

The AS Number for this autonomous system

Returns:

AS number

Return type:

int

classmethod create(name, as_number, comment=None)[source]

Create an AS to be applied on the engine BGP configuration. An AS is a required parameter when creating an ExternalBGPPeer. You can also provide an AS number using an ‘asdot’ syntax:

AutonomousSystem.create(name='myas', as_number='200.600')
Parameters:
  • name (str) – name of this AS

  • as_number (int) – AS number preferred

  • comment (str) – optional string comment

Raises:
Returns:

instance with meta

Return type:

AutonomousSystem

classmethod update_or_create(with_status=False, **kwargs)[source]

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 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
Parameters:
  • filter_key (dict) – filter key represents the data attribute and value to use to find the element. If none is provided, the name field will be used.

  • kwargs – keyword arguments mapping to the elements create method.

  • with_status (bool) – 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:
Returns:

element instance by type

Return type:

Element

ExternalBGPPeer

class smc.routing.bgp.ExternalBGPPeer(name=None, **meta)[source]

Bases: Element

An External BGP represents the AS and IP settings for a remote BGP peer. Creating a BGP peer requires that you also pre-create an AutonomousSystem element:

AutonomousSystem.create(name='neighborA', as_number=500)
ExternalBGPPeer.create(name='name',
                       neighbor_as_ref=AutonomousSystem('neighborA'),
                       neighbor_ip='1.1.1.1')
Variables:

neighbor_as (AutonomousSystem) – AS for this external BGP peer

classmethod create(name, neighbor_as, neighbor_ip, neighbor_port=179, comment=None)[source]

Create an external BGP Peer.

Parameters:
  • name (str) – name of peer

  • neighbor_as_ref (str,AutonomousSystem) – AutonomousSystem element or href.

  • neighbor_ip (str) – ip address of BGP peer

  • neighbor_port (int) – port for BGP, default 179.

Raises:

CreateElementFailed – failed creating

Returns:

instance with meta

Return type:

ExternalBGPPeer

property neighbor_ip

IP address of the external BGP Peer

Returns:

ipaddress of external bgp peer

Return type:

str

property neighbor_port

Port used for neighbor AS

Returns:

neighbor port

Return type:

int

BGPPeering

class smc.routing.bgp.BGPPeering(name=None, **meta)[source]

Bases: Element

BGP Peering is applied directly to an interface and defines basic connection settings. A BGPConnectionProfile is required to create a BGPPeering and if not provided, the default profile will be used.

The most basic peering can simply specify the name of the peering and leverage the default BGPConnectionProfile:

BGPPeering.create(name='my-aws-peer')
Variables:

connection_profile (BGPConnectionProfile) – BGP connection profile for this peering

classmethod create(name, connection_profile_ref=None, md5_password=None, local_as_option='not_set', local_as_value=None, max_prefix_option='not_enabled', max_prefix_value=None, send_community='no', connected_check='disabled', orf_option='disabled', next_hop_self=True, override_capability=False, dont_capability_negotiate=False, remote_private_as=False, route_reflector_client=False, soft_reconfiguration=True, ttl_option='disabled', ttl_value=None, inbound_rm_filter=None, inbound_ip_filter=None, inbound_ipv6_filter=None, inbound_ipprefix_filter=None, inbound_ipv6prefix_filter=None, inbound_aspath_filter=None, outbound_rm_filter=None, outbound_ip_filter=None, outbound_ipv6_filter=None, outbound_ipprefix_filter=None, outbound_ipv6prefix_filter=None, outbound_aspath_filter=None, default_originate=False, bfd_enabled=False, bfd_interval=750, bfd_min_rx=500, bfd_multiplier=3, bfd_passive_mode=False, comment=None)[source]

Create a new BGPPeering configuration.

Parameters:
  • name (str) – name of peering

  • connection_profile_ref (str,BGPConnectionProfile) – required BGP connection profile. System default used if not provided.

  • md5_password (str) – optional md5_password

  • local_as_option (str) – The local AS mode. Valid options are: ‘not_set’, ‘prepend’, ‘no_prepend’, ‘replace_as’

  • local_as_value (str) – The Local AS value. Optional, depending on Local AS mode. Not required.

  • max_prefix_option (str) – The max prefix mode. Valid options are: ‘not_enabled’, ‘enabled’, ‘warning_only’

  • max_prefix_value (int) – The Max Prefix value. Optional, depending on Max Prefix mode. Not required

  • send_community (str) – the send community mode. Valid options are: ‘no’, ‘standard’, ‘extended’, ‘standard_and_extended’

  • connected_check (str) – the connected check mode. Valid options are: ‘disabled’, ‘enabled’, ‘automatic’

  • orf_option (str) – outbound route filtering mode. Valid options are: ‘disabled’, ‘send’, ‘receive’, ‘both’

  • next_hop_self (bool) – next hop self setting

  • override_capability (bool) – is override received capabilities

  • dont_capability_negotiate (bool) – do not send capabilities

  • remote_private_as (bool) – is remote a private AS

  • route_reflector_client (bool) – Route Reflector Client (iBGP only)

  • soft_reconfiguration (bool) – do soft reconfiguration inbound

  • ttl_option (str) – ttl check mode. Valid options are: ‘disabled’, ‘ttl-security’

  • ttl_value (int) – The Hops value for TTL Check Mechanism.If not set, it corresponds to Automatic. Not required

  • inbound_rm_filter (RouteMap) – The Route Map inbound filter. Not required

  • inbound_ip_filter (IPAccessList) – The IP Access List inbound filter. Not required

  • inbound_ipv6_filter (IPv6AccessList) – The IPv6 Access List inbound filter. Not required

  • inbound_ipprefix_filter (IPPrefixList) – The IP Prefix List inbound filter. Not required

  • inbound_ipv6prefix_filter (IPv6PrefixList) – The IPv6 Prefix List inbound filter. Not required.

  • inbound_aspath_filter (ASPathAccessList) – The AS Path Access List inbound filter. Not required.

  • outbound_rm_filter (RouteMap) – The Route Map outbound filter. Not required

  • outbound_ip_filter (IPAccessList) – The IP Access List outbound filter. Not required

  • outbound_ipv6_filter (IPv6AccessList) – The IPv6 Access List outbound filter. Not required.

  • outbound_ipprefix_filter (IPPrefixList) – The IP Prefix List outbound filter. Not required.

  • outbound_ipv6prefix_filter (IPv6PrefixList) – The IPv6 Prefix List outbound filter. Not required.

  • outbound_aspath_filter (ASPathAccessList) – The AS Path Access List outbound filter. Not required.

  • default_originate (bool) – Default originate. Default value is false. Not required.

  • bfd_enabled (bool) – Bidirectional Forwarding Detection flag. Default value is false. Not required

  • bfd_interval (int) – Bidirectional Forwarding Detection interval in ms. Not required.

  • bfd_min_rx (int) – Bidirectional Forwarding Detection min RX in ms. Not required.

  • bfd_multiplier (int) – Bidirectional Forwarding Detection multiplier. Not required.

  • bfd_passive_mode (bool) – Bidirectional Forwarding Detection passive mode flag. Not required.

Raises:

CreateElementFailed – failed creating profile

Returns:

instance with meta

Return type:

BGPPeering

BGPProfile

class smc.routing.bgp.BGPProfile(name=None, **meta)[source]

Bases: Element

A BGP Profile specifies settings specific to an engine level BGP configuration. A profile specifies engine specific settings such as distance, redistribution, and aggregation and port.

These settings are always in effect:

  • BGP version 4/4+

  • No autosummary

  • No synchronization

  • Graceful restart

Example of creating a custom BGP Profile with default administrative distances and custom subnet distances:

Network.create(name='inside', ipv4_network='1.1.1.0/24')
BGPProfile.create(
    name='bar',
    internal_distance=100,
    external_distance=200,
    local_distance=50,
    subnet_distance=[(Network('inside'), 100)])
property aggregation_entry

Specific subnet with mode :return: list of BGPAggregationEntry

property bmp_settings

BMP settings: list of address/port/connect_through_master

classmethod create(name, port=179, external_distance=20, internal_distance=200, local_distance=200, subnet_distance=None, bmp_settings=None, aggregation_entry=None, redistribution_entry=None)[source]

Create a custom BGP Profile

Parameters:
  • name (str) – name of profile

  • port (int) – port for BGP process

  • external_distance (int) – external administrative distance; (1-255)

  • internal_distance (int) – internal administrative distance (1-255)

  • local_distance (int) – local administrative distance (aggregation) (1-255)

  • subnet_distance (list) – configure specific subnet’s with respective distances

  • BGPBMPSettings (list) – configure the BMP listering settings (address/port/flag)

:param List(BGPAggregationEntry) aggregation_entry:This represents the BGP aggregation entry
with:

subnet: link to a network. mode: the aggregation mode.

:param List(RedistributionEntry) redistribution_entry:This represents an BGP or OSPF Profile

Redistribution Entry. There is one entry by BGP or OSPF Redistribution type (static, connected, kernel, ospfv2)

Raises:

CreateElementFailed – reason for failure

Returns:

instance with meta

Return type:

BGPProfile

property external_distance

External administrative distance (eBGP)

Returns:

distance setting

Return type:

int

property internal_distance

Internal administrative distance (iBGP)

Returns:

internal distance setting

Return type:

int

property local_distance

Local administrative distance (aggregation)

Returns:

local distance setting

Return type:

int

property port

Specified port for BGP

Returns:

value of BGP port

Return type:

int

property redistribution_entry

This represents an BGP or OSPF Profile Redistribution Entry. :return: list of RedistributionEntry

property subnet_distance

Specific subnet administrative distances

Returns:

list of tuple (subnet, distance)

BGPConnectionProfile

class smc.routing.bgp.BGPConnectionProfile(name=None, **meta)[source]

Bases: Element

A BGP Connection Profile will specify timer based settings and is used by a BGPPeering configuration.

Create a custom profile:

BGPConnectionProfile.create(
    name='fooprofile',
    md5_password='12345',
    connect_retry=200,
    session_hold_timer=100,
    session_keep_alive=150)
property connect_retry

The connect retry timer, in seconds

Returns:

connect retry in seconds

Return type:

int

classmethod create(name, md5_password=None, connect_retry=120, session_hold_timer=180, session_keep_alive=60)[source]

Create a new BGP Connection Profile.

Parameters:
  • name (str) – name of profile

  • md5_password (str) – optional md5 password

  • connect_retry (int) – The connect retry timer, in seconds

  • session_hold_timer (int) – The session hold timer, in seconds

  • session_keep_alive (int) – The session keep alive timer, in seconds

Raises:

CreateElementFailed – failed creating profile

Returns:

instance with meta

Return type:

BGPConnectionProfile

property session_hold_timer

The session hold timer, in seconds

Returns:

in seconds

Return type:

int

property session_keep_alive

The session keep alive, in seconds

Returns:

in seconds

Return type:

int

ASPathAccessList

class smc.routing.bgp_access_list.ASPathAccessList(name=None, **meta)[source]

Bases: AccessList, Element

An AS path is the autonomous systems that routing information passed through to get to a specified router. It indicates the origin of this route. The AS path is used to prevent routing loops in BGP.

ASPathAccessLists can be used as a MatchCondition in a RouteMap:

>>> aspath = ASPathAccessList.create(name='aspath', entries=[
...   {'expression': '123-456', 'action': 'permit'},
...   {'expression': '1234-567', 'action': 'deny'}])
>>> aspath
ASPathAccessList(name=aspath)
>>> aspath.add_entry(expression='897', action='permit')
>>> aspath.update()
'https://172.18.1.151:8082/6.4/elements/as_path_access_list/28'
...
>>> aspath.remove_entry(expression='123-456')
>>> aspath.update()
'https://172.18.1.151:8082/6.4/elements/as_path_access_list/28'
>>> for entry in aspath:
...   entry
...
ASPathListEntry(expression=u'1234-567', action=u'deny', comment=None)
ASPathListEntry(expression=u'897', action=u'permit', comment=None)

This is an iterable container yielding ASPathListEntry.

See also

ASPathListEntry for valid create and add/remove parameters

class smc.routing.bgp_access_list.ASPathListEntry(expression, action, comment)

Bases: tuple

The ASPathAccessList is an iterable container and will return instances of ASPathListEntry.

Variables:
  • expression (str) – string expression identifying the AS path

  • action (str) – ‘permit’ or ‘deny’

  • comment (str) – optional comment

CommunityAccessList

class smc.routing.bgp_access_list.CommunityAccessList(name=None, **meta)[source]

Bases: AccessList, Element

A CommunityAccessList is used to provide specific rules for BGP configurations providing and permit/deny capability based on the community defined. CommunityAccessLists can be used in a RouteMap match condition to refine the policy for a specific announced network.

When creating a new community ACL, entries is expecting a list of dict items using the valid field and values of this class. For example:

>>> from smc.routing.community_list import CommunityAccessList
>>> comm = CommunityAccessList.create(name='commacl',
        entries=[{'community': 123, 'action': 'permit'},
                 {'community': 456, 'action': 'deny'}],
        type='standard')
>>> comm
CommunityAccessList(name=commacl)

You can optionally also create an empty access list and use add_entry() to insert entries after:

>>> comm.add_entry(community=789, action='permit')
>>> comm.update()

Iterating the access list will return CommunityListEntry:

>>> for entries in comm:
...   entries
...
CommunityListEntry(community=u'789', action=u'permit', comment=None)
CommunityListEntry(community=u'456', action=u'deny', comment=None)
CommunityListEntry(community=u'123', action=u'permit', comment=None)

The type parameter for the create constructor can have values standard or expanded. If using expanded, the access list can then use a regex for matching the community string.

This is an iterable container yielding CommunityListEntry.

See also

CommunityListEntry for valid create and add/remove parameters

Variables:

type (str) – ‘standard’ or ‘expanded’ (specify as kw when in create constructor when creating the top level access list.

class smc.routing.bgp_access_list.CommunityListEntry(community, action, comment)

Bases: tuple

The CommunityAccessList represents the entries for the community access lists.

Variables:
  • community (str) – community id

  • action (str) – ‘permit’ or ‘deny’

  • comment (str) – optional comment

ExtendedCommunityAccessList

class smc.routing.bgp_access_list.ExtendedCommunityAccessList(name=None, **meta)[source]

Bases: AccessList, Element

Extended community access lists with the ability to specify route target or start of origin for an entry.

ExtendedCommunityAccessLists can be used in a RouteMap match condition to refine the policy for a specific announced network:

>>> comm = ExtendedCommunityAccessList.create(name='comm', entries=[
    ...   {'community': 123, 'action': 'permit', 'type': 'rt'},
    ...   {'community': 456, 'action': 'deny', 'type': 'soo'}],
    ...   type='standard')
    >>> comm
    ExtendedCommunityAccessList(name=comm)
    >>> comm.add_entry(community=789, action='permit', type='rt')
    >>> comm.update()
    ...
    >>> comm.remove_entry(community=123)
    >>> comm.update()
    'https://172.18.1.151:8082/6.4/elements/extended_community_access_list/25'
    >>> for entry in comm:
    ...   entry
    ...
    ExtCommunityListEntry(community=u'456', action=u'deny', comment=None, type=u'soo')
    ExtCommunityListEntry(community=u'789', action=u'permit', comment=None, type=u'rt')

This is an iterable container yielding ExtCommunityListEntry.

See also

ExtCommunityListEntry for valid create and add/remove parameters

Variables:

type (str) – ‘standard’ or ‘expanded’ (specify as kw when in create constructor when creating the top level access list.

class smc.routing.bgp_access_list.ExtCommunityListEntry(community, action, type)

Bases: tuple

The ExtCommunityListEntry represents the entries for the extended community access lists.

Variables:
  • community (str) – community id

  • action (str) – ‘permit’ or ‘deny’

  • type (str) – ‘rt’ (Route Target) or ‘soo’ (Site of Origin) (required)

OSPF Elements

Dynamic Routing can be enabled on devices configured in engine/VPN mode. Configuring dynamic routing consists of enabling the routing protocol on the engine and adding the routing elements on the interfaces at the engine routing level.

For adding OSPF configurations, several steps are required:

  • Enable OSPF on the engine and specific the OSPF Profile

  • Create or locate an existing OSPFArea to be used

  • Modify the routing interface and add the OSPFArea

Enable OSPF on an existing engine using the default OSPF system profile:

engine.ospf.enable()

Create an OSPFArea using the default OSPF Interface Setting profile:

OSPFArea.create(name='customOSPFArea')

Add OSPF area to an interface routing configuration (add to nicid ‘0’):

interface = engine.routing.get(0)
interface.add_ospf_area(area)

Disable OSPF on an engine:

engine.ospf.disable()

Finding profiles or elements can also be done through collections:

>>> list(OSPFProfile.objects.all())
[OSPFProfile(name=Default OSPFv2 Profile)]

>>> list(OSPFArea.objects.all())
[OSPFArea(name=area0)]

The OSPF relationship can be represented as:

Engine --uses an--> OSPF Profile --has-a--> OSPF Domain Setting
Engine Routing --uses-an--> OSPF Area --has-a--> OSPF Interface Setting

Only Layer3Firewall and Layer3VirtualEngine types can support running OSPF.

class smc.routing.ospf.OSPF(data=None)[source]

OSPF configuration on the engine. Access through an engine reference:

engine.dynamic_routing.ospf.status
engine.dynamic_rotuing.ospf.enable(....)

When making changes to the OSPF configuration, any methods called that change the configuration also require that engine.update() is called once changes are complete. This way you can make multiple changes without refreshing the engine cache.

Variables:

profile (OSPFProfile) – OSPFProfile reference for this engine

disable()[source]

Disable OSPF on this engine.

Returns:

None

enable(ospf_profile=None, router_id=None)[source]

Enable OSPF on this engine. For master engines, enable OSPF on the virtual firewall.

Once enabled on the engine, add an OSPF area to an interface:

engine.dynamic_routing.ospf.enable()
interface = engine.routing.get(0)
interface.add_ospf_area(OSPFArea('myarea'))
Parameters:
  • ospf_profile (str,OSPFProfile) – OSPFProfile element or str href; if None, use default profile

  • router_id (str) – single IP address router ID

Raises:

ElementNotFound – OSPF profile not found

Returns:

None

property router_id

Get the router ID for this OSPF configuration. If None, then the ID will use the interface IP.

Returns:

str or None

property status

Is OSPF enabled on this engine.

Return type:

bool

update_configuration(**kwargs)[source]

Update the OSPF configuration using kwargs that match the enable constructor.

Parameters:

kwargs (dict) – keyword arguments matching enable constructor.

Returns:

whether change was made

Return type:

bool

OSPFArea

class smc.routing.ospf.OSPFArea(name=None, **meta)[source]

Bases: Element

OSPF Area is an element that identifies general settings for an OSPF configuration applied to an engine routing node. The OSPFArea has a reference to an OSPFInterfaceSetting and is required when creating.

Create a basic OSPFArea with just area id:

OSPFArea.create(name='myarea', area_id=0)

Create an OSPFArea and use a custom OSPFInterfaceSetting element:

OSPFArea.create(
    name='customOSPFArea',
    interface_settings_ref=OSPFInterfaceSetting('myospf'),
    area_id=3)

Advanced example:

Adding ospf_virtual_links_endpoints:

OSPFArea.create(
    name='ospf',
    interface_settings_ref=intf,
    area_id=3,
    ospfv2_virtual_links_endpoints_container=
        [{'interface_settings_ref':
            'http://172.18.1.150:8082/6.1/elements/ospfv2_interface_settings/8',
          'router_id_endpoint_A': '192.168.1.1',
          'router_id_endpoint_B': '192.168.1.254'},
         {'router_id_endpoint_A': '172.18.1.254',
          'router_id_endpoint_B': '172.18.1.200'}])

When using ABR substitute rules, there are 3 actions, ‘aggregate’, ‘not_advertise’ and ‘substitute_with’. All references required are of type smc.elements.network.Network. These elements can either be created or retrieved using collections, or by getting the resource directly.

Example of creating an OSPF area and using ABR settings:

OSPFArea.create(
        name='area_with_abr',
        interface_settings_ref=intf,
        area_id=1,
        ospf_abr_substitute_container=[
            {'subnet_ref': 'http://172.18.1.150:8082/6.1/elements/network/143',
             'substitute_ref': 'http://172.18.1.150:8082/6.1/elements/network/1547',
             'substitute_type': 'substitute_with'},
            {'subnet_ref': 'http://172.18.1.150:8082/6.1/elements/network/979',
             'substitute_type': 'aggregate'}])
Variables:
classmethod create(name, interface_settings_ref=None, area_id=1, area_type='normal', outbound_filters=None, inbound_filters=None, shortcut_capable_area=False, ospfv2_virtual_links_endpoints_container=None, ospf_abr_substitute_container=None, comment=None, **kwargs)[source]

Create a new OSPF Area

Parameters:
  • name (str) – name of OSPFArea configuration

  • interface_settings_ref (str,OSPFInterfaceSetting) – an OSPFInterfaceSetting element or href. If None, uses the default system profile

  • name – area id

  • area_type (str) – |normal|stub|not_so_stubby|totally_stubby| totally_not_so_stubby

  • outbound_filters (list) – reference to an IPAccessList and or IPPrefixList. You can only have one outbound prefix or access list

  • inbound_filters (list) – reference to an IPAccessList and or IPPrefixList. You can only have one outbound prefix or access list

  • shortcut_capable_area – True|False

  • ospfv2_virtual_links_endpoints_container (list) – virtual link endpoints

  • ospf_abr_substitute_container (list) – substitute types: |aggregate|not_advertise|substitute_with

  • comment (str) – optional comment

Raises:

CreateElementFailed – failed to create with reason

Return type:

OSPFArea

classmethod update_or_create(with_status=False, **kwargs)[source]

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 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
Parameters:
  • filter_key (dict) – filter key represents the data attribute and value to use to find the element. If none is provided, the name field will be used.

  • kwargs – keyword arguments mapping to the elements create method.

  • with_status (bool) – 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:
Returns:

element instance by type

Return type:

Element

OSPFKeyChain

class smc.routing.ospf.OSPFKeyChain(name=None, **meta)[source]

Bases: Element

OSPF Key Chain is used for authenticating OSPFv2 packets. If required, create a key chain and specify authentication in the OSPFInterfaceSetting referencing this element.

Is message-digest authentication is required on an OSPFInterfaceSetting, first create the key chain and use the reference to create the ospf interface profile:

key_chain = OSPFKeyChain('secure-keychain') #obtain resource
OSPFInterfaceSetting.create(
    name='authenicated-ospf',
    authentication_type='message_digest',
    key_chain_ref=key_chain.href)
classmethod create(name, key_chain_entry)[source]

Create a key chain with list of keys

Key_chain_entry format is:

[{'key': 'xxxx', 'key_id': 1-255, 'send_key': True|False}]
Parameters:
  • name (str) – Name of key chain

  • key_chain_entry (list) – list of key chain entries

Raises:

CreateElementFailed – create failed with reason

Returns:

instance with meta

Return type:

OSPFKeyChain

OSPFProfile

class smc.routing.ospf.OSPFProfile(name=None, **meta)[source]

Bases: Element

An OSPF Profile contains administrative distance and redistribution settings. An OSPF Profile is set on the engine element when enabling OSPF.

These settings are always in effect:

  • No autosummary

Example of creating an OSPFProfile with the default domain profile:

OSPFProfile.create(name='myospf')

Note

Enable OSPF on engine using engine.ospf.enable()

Variables:
  • external_distance (int) – external distance metric

  • inter_distance (int) – inter distance metric

  • intra_distance (int) – intra distance metric

  • default_metric (int) – set a default metric for all unset areas

  • redistribution_entry (list) – settings for static, connected, etc

  • domain_settings_ref (OSPFDomainSetting) – OSPF Domain Settings profile used for this OSPF Profile

classmethod create(name, domain_settings_ref=None, external_distance=110, inter_distance=110, intra_distance=110, redistribution_entry=None, default_metric=None, comment=None)[source]

Create an OSPF Profile.

If providing a list of redistribution entries, provide in the following dict format:

{‘enabled’: boolean, ‘metric_type’: ‘external_1’ or ‘external_2’,

‘metric’: 2, ‘type’: ‘kernel’}

Valid types for redistribution entries are: kernel, static, connected, bgp, and default_originate.

You can also provide a ‘filter’ key with either an IPAccessList or RouteMap element to use for further access control on the redistributed route type. If metric_type is not provided, external_1 (E1) will be used.

An example of a redistribution_entry would be:

{u'enabled': True,
 u'metric': 123,
 u'metric_type': u'external_2',
 u'filter': RouteMap('myroutemap'),
 u'type': u'static'}
Parameters:
  • name (str) – name of profile

  • domain_settings_ref (str,OSPFDomainSetting) – OSPFDomainSetting element or href

  • external_distance (int) – route metric (E1-E2)

  • inter_distance (int) – routes learned from different areas (O IA)

  • intra_distance (int) – routes learned from same area (O)

  • redistribution_entry (list) – how to redistribute the OSPF routes.

Raises:

CreateElementFailed – create failed with reason

Return type:

OSPFProfile

classmethod update_or_create(filter_key=None, with_status=False, **kwargs)[source]

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 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
Parameters:
  • filter_key (dict) – filter key represents the data attribute and value to use to find the element. If none is provided, the name field will be used.

  • kwargs – keyword arguments mapping to the elements create method.

  • with_status (bool) – 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:
Returns:

element instance by type

Return type:

Element

OSPFDomainSetting

class smc.routing.ospf.OSPFDomainSetting(name=None, **meta)[source]

Bases: Element

An OSPF Domain Setting provides settings for area border router (ABR) type, throttle timer settings, and the max metric router link-state advertisement (LSA) settings.

An OSPF Profile requires a reference to an OSPF Domain Setting.

Create a custom OSPF Domain Setting element:

OSPFDomainSetting.create(
    name='mydomain',
    abr_type='standard',
    auto_cost_bandwidth=200,
    deprecated_algorithm=True)
classmethod create(name, abr_type='cisco', auto_cost_bandwidth=100, deprecated_algorithm=False, initial_delay=200, initial_hold_time=1000, max_hold_time=10000, shutdown_max_metric_lsa=0, startup_max_metric_lsa=0)[source]

Create custom Domain Settings

Domain settings are referenced by an OSPFProfile

Parameters:
  • name (str) – name of custom domain settings

  • abr_type (str) – cisco|shortcut|standard

  • auto_cost_bandwidth (int) – Mbits/s

  • deprecated_algorithm (bool) – RFC 1518 compatibility

  • initial_delay (int) – in milliseconds

  • initial_hold_type (int) – in milliseconds

  • max_hold_time (int) – in milliseconds

  • shutdown_max_metric_lsa (int) – in seconds

  • startup_max_metric_lsa (int) – in seconds

Raises:

CreateElementFailed – create failed with reason

Returns:

instance with meta

Return type:

OSPFDomainSetting

OSPFInterfaceSetting

class smc.routing.ospf.OSPFInterfaceSetting(name=None, **meta)[source]

Bases: Element

OSPF Interface Setting indicate specific configurations that are applied to the interface and OSPF Area configuration, including authentication.

If you require non-default settings applied to your interface OSPF instance, you can create a custom interface profile:

OSPFInterfaceSetting.create(
    name='myprofile',
    dead_interval=30,
    hello_interval=5)

When using authentication on interface settings, there are two types, password authentication (plain text) or message digest.

When specifying an authentication_type=’password’, the password parameter must be provided.

When specifying authentication_type=’message_digest’, the key_chain_ref parameter must be specified.

classmethod create(name, dead_interval=40, hello_interval=10, hello_interval_type='normal', dead_multiplier=1, mtu_mismatch_detection=True, retransmit_interval=5, router_priority=1, transmit_delay=1, authentication_type=None, password=None, key_chain_ref=None)[source]

Create custom OSPF interface settings profile

Parameters:
  • name (str) – name of interface settings

  • dead_interval (int) – in seconds

  • hello_interval (str) – in seconds

  • hello_interval_type (str) – |normal|fast_hello

  • dead_multipler (int) – fast hello packet multipler

  • mtu_mismatch_detection (bool) – True|False

  • retransmit_interval (int) – in seconds

  • router_priority (int) – set priority

  • transmit_delay (int) – in seconds

  • authentication_type (str) – |password|message_digest

  • password (str) – max 8 chars (required when authentication_type=’password’)

  • key_chain_ref (str,Element) – OSPFKeyChain (required when authentication_type=’message_digest’)

Raises:

CreateElementFailed – create failed with reason

Returns:

instance with meta

Return type:

OSPFInterfaceSetting

Policies

Policy module represents the classes required to obtaining and manipulating policies within the SMC.

Policy is the top level base class for all policy subclasses such as smc.policy.layer3.FirewallPolicy, smc.policy.layer2.Layer2Policy, smc.policy.ips.IPSPolicy, smc.policy.inspection.InspectionPolicy, smc.policy.file_filtering.FileFilteringPolicy

Policy represents actions that are common to all policy types, however for options that are not possible in a policy type, the method is overridden to return None. For example, ‘upload’ is not called on a template policy, but instead on the policy referencing that template. Therefore ‘upload’ is overidden.

Note

It is not required to call open() and save() on SMC API >= 6.1. It is also optional on earlier versions but if longer running operations are needed, calling open() will lock the policy from test_external modifications until save() is called.

class smc.policy.policy.Policy(name=None, **meta)[source]

Bases: Element

Policy is the base class for all policy types managed by the SMC. This base class is not intended to be instantiated directly.

Subclasses should implement create(….) individually as each subclass will likely have different input requirements.

All generic methods that are policy level, such as ‘open’, ‘save’, ‘force_unlock’, ‘export’, and ‘upload’ are encapsulated into this base class.

Variables:
  • template (Element) – The template associated with this policy. Can be None

  • inspection_policy (InspectionPolicy) – related inspection policy

  • file_filtering_policy (FileFilteringPolicy) – related file policy

force_unlock()[source]

Forcibly unlock a locked policy

Returns:

None

rule_counters(engine=None, duration_type='one_week', duration=0, start_time=0)[source]

New in version 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.

Parameters:
  • engine (Engine) – the target engine to obtain rule counters from

  • duration_type (str) – duration for obtaining rule counters. Valid options are: one_day, one_week, one_month, six_months, one_year, custom, since_last_upload

  • duration (int) – if custom set for duration type, specify the duration in seconds (Default: 0)

  • start_time (int) – start time in milliseconds (Default: 0)

Raises:

ActionCommandFailed

Returns:

list of rule counter objects

Return type:

RuleCounter

search_rule(search)[source]

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)
Parameters:

search (str) – search string

Returns:

rule elements matching criteria

Return type:

list(Element)

upload(engine, timeout=5, wait_for_finish=False, preserve_connections=True, generate_snapshot=True, **kw)[source]

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())
Parameters:
  • engine (str) – name of device to upload policy to

  • preserve_connections (bool) – flag to preserve connections (True by default)

  • generate_snapshot (bool) – flag to generate snapshot (True by default)

Raises:

TaskRunFailed

Returns:

TaskOperationPoller

InterfacePolicy

Interface Policies are applied at the engine level when layer 3 single engines or cluster layer 3 engines have layer 2 interfaces. The configuration is identical to creating Layer 2 Rules for layer 2 or IPS engines.

class smc.policy.interface.InterfacePolicy(name=None, **meta)[source]

Bases: InterfaceRule, Policy

Layer 2 Interface Policy represents a set of rules applied to layer 2 interfaces installed on a single or cluster layer 3 engine. Set the interface policy on the engine properties. Interface policies do not have inspection policies and instead inherit from the engines primary policy.

Instance Resources:

Variables:
  • layer2_ipv4_access_ruleslayer2_ipv4_access_rules

  • layer2_ipv6_access_ruleslayer2_ipv6_access_rules

  • layer2_ethernet_ruleslayer2_ethernet_rules

classmethod create(name, template)[source]

Create a new Layer 2 Interface Policy.

Parameters:
  • name (str) – name of policy

  • template (str) – name of the NGFW Engine template to base policy on

Raises:
Returns:

Layer2InterfacePolicy

inspection_policy()[source]

Descriptor to allow get/set operations on an element referenced in an Element.

May be defined with a supported version. ex.

monitoring_group = ElementRef((‘6.5’,’monitoring_group_ref’),

(‘6.6’,’tunnel_group_ref’))

class smc.policy.interface.InterfaceRule[source]

Bases: object

Layer 2 Interface Rules are the same as Layer 2 Engine/IPS rules.

property layer2_ethernet_rules

Layer 2 Ethernet access rule

Return type:

rule_collection(EthernetRule)

property layer2_ipv4_access_rules

Layer2 IPv4 access rule

Return type:

rule_collection(IPv4Layer2Rule)

property layer2_ipv6_access_rules

Layer 2 IPv6 access rule

class smc.policy.interface.InterfaceSubPolicy(name=None, **meta)[source]

Bases: Policy

A Interface Sub Policy is a rule section within a Interface policy that provides a container to create rules that are referenced from a ‘jump’ rule. Typically rules in a sub policy are similar in some fashion such as applying to a specific service. Sub Policies can also be delegated from an administrative perspective.

Interface Sub Policies only provide access to creating IPv4 rules.

p = InterfaceSubPolicy(‘MySubPolicy’) p.layer2_ethernet_rules.create(

name=’newule’, sources=’any’, destinations=’any’, services=[TCPService(‘SSH’)], action=’discard’)

classmethod create(name)[source]

Create a sub policy. Only name is required. Other settings are inherited from the parent firewall policy (template, policy, etc).

Parameters:

name (str) – name of sub policy

Raises:

CreateElementFailed – failed to create policy

Return type:

InterfaceSubPolicy

property layer2_ipv4_access_rules

IPv4 rule entry point

Return type:

rule_collection(EthernetRule)

class smc.policy.interface.InterfaceTemplatePolicy(name=None, **meta)[source]

Bases: InterfacePolicy

Interface Template Policy. Required when creating a new Interface Policy. Useful for containing global rules or best practice configurations which will be inherited by the assigned policy.

print(list(InterfaceTemplatePolicy.objects.all())
inspection_policy()[source]

Descriptor to allow get/set operations on an element referenced in an Element.

May be defined with a supported version. ex.

monitoring_group = ElementRef((‘6.5’,’monitoring_group_ref’),

(‘6.6’,’tunnel_group_ref’))

upload()[source]

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())
Parameters:
  • engine (str) – name of device to upload policy to

  • preserve_connections (bool) – flag to preserve connections (True by default)

  • generate_snapshot (bool) – flag to generate snapshot (True by default)

Raises:

TaskRunFailed

Returns:

TaskOperationPoller

FileFilteringPolicy

class smc.policy.file_filtering.FileFilteringPolicy(name=None, **meta)[source]

Bases: Policy

The File Filtering Policy references a specific file based policy for doing additional inspection based on file types. Use the policy parameters to specify how certain files are treated by either threat intelligence feeds,sandbox or by local AV scanning. You can also use this policy to disable threat prevention based on specific files.

classmethod create(name, comment=None)[source]

Create the custom File Filtering Policy :param str name: name of File Filtering Policy :param str comment: optional comment :raises CreateElementFailed: failed creating element with reason :return: instance with meta of File Filtering Policy. :rtype: FileFilteringPolicy

property file_filtering_rules

File filtering rules for this policy.

Return type:

rule_collection(FileFilteringRule)

class smc.policy.file_filtering.FileFilteringRule(**meta)[source]

Bases: RuleCommon, Rule, SubElement

Represents a file filtering rule.

create(name, sources=None, destinations=None, action='allow', log_options=None, connection_tracking=None, is_disabled=False, situations=None, add_pos=None, after=None, before=None, comment=None, validate=True, **kw)[source]

Create a file filtering rule.

Changed in version 0.7.0: Action field now requires a list of actions as strings when using API version >= 6.6

Example::

Api version <=6.5 action is a string rule_file = p.file_filtering_rules.create( name=”newrule”,

sources=[Network(“London Internal Network”)], destinations=[Network(“net-172.31.14.0/24”)], action=”apply_vpn”, vpn_policy=vpn)

Api version >=6.6 action is a list vpn_actions = Action() vpn_actions.action = [‘allow’, ‘apply_vpn’] p.file_filtering_rules.create(name=’new_rule’,

sources=[Network(“London Internal Network”)], destinations=[Network(“net-172.31.14.0/24”)], action=vpn_actions, vpn_policy=vpn)

Parameters:
  • name (str) – name of rule

  • sources (Source, list[str, Element]) – source/s for rule

  • destinations (Destination, list[str, Element]) – destination/s for rule

  • action (Action,str,list[str]) – allow,discard,continue,refuse,jump,apply_vpn,enforce_vpn,forward_vpn ,block_list,terminate,forward,next_hop,forced_next_hop (default: allow)

  • log_options (LogOptions) – LogOptions object

  • connection_tracking (ConnectionTracking) – custom connection tracking settings

  • is_disabled (bool) – whether to disable rule or not

  • situations (Situations,str,dict) – A set of matching criteria that defines the file types the rule matches. If nothing is specified, that means None and the Rule will be ignored.

  • add_pos (int) – 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.

  • after (str) – Rule tag to add this rule after. Mutually exclusive with add_pos and before params.

  • before (str) – Rule tag to add this rule before. Mutually exclusive with add_pos and after params.

  • comment (str) – optional comment for this rule

  • validate (bool) – validate the inspection policy during rule creation. Default: True

Raises:
  • MissingRequiredInput – when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified.

  • CreateRuleFailed – rule creation failure

Returns:

the created FileFilteringRule

Return type:

FileFilteringRule

get_action()[source]

Return action instance. rtype: FileFilteringRuleAction

property situations

Situations for this rule

Return type:

Situations

FirewallPolicy

Layer 3 Firewall Policy

Module that represents resources related to creating and managing layer 3 firewall engine policies.

To get an existing policy:

>>> from smc.policy.layer3 import FirewallPolicy
>>> policy = FirewallPolicy('Standard Firewall Policy with Inspection')
>>> print(policy.template)
FirewallTemplatePolicy(name=Firewall Inspection Template)

Or through collections:

>>> list(FirewallPolicy.objects.all())
[FirewallPolicy(name=Standard Firewall Policy with Inspection),
 FirewallPolicy(name=Layer 3 Virtual FW Policy)]

To create a new policy, use:

policy = FirewallPolicy.create(name='newpolicy', template='layer3_fw_template')

Example rule creation:

policy = FirewallPolicy('Amazon Cloud')
policy.open() #Only required for SMC API <= 6.0
policy.fw_ipv4_access_rules.create(name='mynewrule', sources='any',
                                   destinations='any', services='any',
                                   action='permit')
policy.save() #Only required for SMC API <= 6.0

Example rule deletion:

policy = FirewallPolicy('Amazon Cloud')
for rule in policy.fw_ipv4_access_rules.all():
    if rule.name == 'mynewrule':
        rule.delete()
class smc.policy.layer3.FirewallIPv6SubPolicy(name=None, **meta)[source]

Bases: FirewallSubPolicy

property fw_ipv6_access_rules

IPv6 rule entry point

Return type:

rule_collection(IPv4Rule)

class smc.policy.layer3.FirewallPolicy(name=None, **meta)[source]

Bases: FirewallRule, Policy

FirewallPolicy represents a set of rules installed on layer 3 devices. Layer 3 engine’s support either ipv4 or ipv6 rules.

They also have NAT rules and reference to an Inspection and File Filtering Policy.

Variables:

template – which policy template is used

Instance Resources:

Variables:
  • fw_ipv4_access_rulesfw_ipv4_access_rules

  • fw_ipv4_nat_rulesipv4_nat_rules

  • fw_ipv6_access_rulesipv6_access_rules

  • fw_ipv6_nat_rulesipv6_nat_rules

classmethod create(name, template='Firewall Inspection Template')[source]

Create Firewall Policy. Template policy is required for the policy. The template parameter should be the name of the firewall template.

This policy will then inherit the Inspection and File Filtering policy from the specified template.

Parameters:
  • name (str) – name of policy

  • template (str) – name of the NGFW engine template to base policy on

Raises:
Returns:

FirewallPolicy

To use after successful creation, reference the policy to obtain context:

FirewallPolicy('newpolicy')
update(cautious_update=True, **kwargs)[source]

Update Firewall Policy. By default this will load the etag from the API. This is to handle cases where a subelement has changed the etag of the policy. If the policy is updated prior to these additions then cautious_update can be turned off.

Cautious_update:

True to load etag from API before updating.

class smc.policy.layer3.FirewallRule[source]

Bases: object

Encapsulates all references to firewall rule related entry points. This is referenced by multiple classes such as FirewallPolicy and FirewallPolicyTemplate.

property fw_ipv4_access_rules

IPv4 rule entry point

Return type:

rule_collection(IPv4Rule)

property fw_ipv4_nat_rules

IPv4NAT Rule entry point

Return type:

rule_collection(IPv4NATRule)

property fw_ipv6_access_rules

IPv6 Rule entry point

Return type:

rule_collection(IPv6Rule)

property fw_ipv6_nat_rules

IPv6NAT Rule entry point

Return type:

rule_collection(IPv6NATRule)

class smc.policy.layer3.FirewallSubPolicy(name=None, **meta)[source]

Bases: Policy

A Firewall Sub Policy is a rule section within a firewall policy that provides a container to create rules that are referenced from a ‘jump’ rule. Typically rules in a sub policy are similar in some fashion such as applying to a specific service. Sub Policies can also be delegated from an administrative perspective.

Firewall Sub Policies only provide access to creating IPv4 rules. NAT is done on the parent firewall policy:

p = FirewallSubPolicy('MySubPolicy')
p.fw_ipv4_access_rules.create(
    name='newule',
    sources='any',
    destinations='any',
    services=[TCPService('SSH')],
    action='discard')
classmethod create(name)[source]

Create a sub policy. Only name is required. Other settings are inherited from the parent firewall policy (template, inspection policy, etc).

Parameters:

name (str) – name of sub policy

Raises:

CreateElementFailed – failed to create policy

Return type:

FirewallSubPolicy

property fw_ipv4_access_rules

IPv4 rule entry point

Return type:

rule_collection(IPv4Rule)

class smc.policy.layer3.FirewallTemplatePolicy(name=None, **meta)[source]

Bases: FirewallPolicy

All Firewall Policies will reference a firewall policy template.

Most templates will be pre-configured best practice configurations and rarely need to be modified. However, you may want to view the details of rules configured in a template or possibly insert additional rules.

For example, view rules in firewall policy template after loading the firewall policy:

policy = FirewallPolicy('Amazon Cloud')
for rule in policy.template.fw_ipv4_access_rules.all():
    print rule
upload()[source]

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())
Parameters:
  • engine (str) – name of device to upload policy to

  • preserve_connections (bool) – flag to preserve connections (True by default)

  • generate_snapshot (bool) – flag to generate snapshot (True by default)

Raises:

TaskRunFailed

Returns:

TaskOperationPoller

InspectionPolicy

class smc.policy.policy.InspectionPolicy(name=None, **meta)[source]

Bases: Policy

The Inspection Policy references a specific inspection policy that is a property (reference) to either a FirewallPolicy, IPSPolicy or Layer2Policy. This policy defines specific characteristics for threat based prevention. In addition, exceptions can be made at this policy level to bypass scanning based on the rule properties.

export()[source]

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)
Parameters:

filename (str) – filename to store exported element

Raises:

TaskRunFailed – invalid permissions, invalid directory, or this element is a system element and cannot be exported.

Returns:

DownloadTask

Note

It is not possible to export system elements

upload()[source]

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())
Parameters:
  • engine (str) – name of device to upload policy to

  • preserve_connections (bool) – flag to preserve connections (True by default)

  • generate_snapshot (bool) – flag to generate snapshot (True by default)

Raises:

TaskRunFailed

Returns:

TaskOperationPoller

IPSPolicy

IPS Engine policy

Module that represents resources related to creating and managing IPS engine policies.

To get an existing policy:

>>> policy = IPSPolicy('Default IPS Policy')
>>> print(policy.template)
IPSTemplatePolicy(name=High-Security IPS Template)

Or through collections:

>>> from smc.policy.ips import IPSPolicy
>>> list(IPSPolicy.objects.all())
[IPSPolicy(name=Default IPS Policy), IPSPolicy(name=High-Security Inspection IPS Policy)]

To create a new policy, use:

policy = IPSPolicy.create(name='my_ips_policy',
                          template='High Security Inspection Template')
policy.ips_ipv4_access_rules.create(name='ipsrule1',
                                    sources='any',
                                    action='continue')

for rule in policy.ips_ipv4_access_rules.all():
    print(rule)

Example rule deletion:

policy = IPSPolicy('Amazon Cloud')
for rule in policy.ips_ipv4_access_rules.all():
    if rule.name == 'ipsrule1':
        rule.delete()
class smc.policy.ips.IPSPolicy(name=None, **meta)[source]

Bases: IPSPolicyRule, Policy

IPS Policy represents a set of rules installed on an IPS / IDS engine. IPS mode supports both inline and SPAN interface types and ethernet based rules. Layer 2 and IPS engines do not current features that require routed interfaces.

Variables:

template – which policy template is used

Instance Resources:

Variables:
  • ips_ipv4_access_rulesips_ipv4_access_rules

  • ips_ipv6_access_rulesips_ipv6_access_rules

  • ips_ethernet_rulesips_ethernet_rules

classmethod create(name, template='High-Security IPS Template')[source]

Create an IPS Policy

Parameters:
  • name (str) – Name of policy

  • template (str) – name of template

Raises:

CreatePolicyFailed – policy failed to create

Returns:

IPSPolicy

class smc.policy.ips.IPSPolicyRule[source]

Bases: object

Encapsulates all references to IPS rule related entry points. This is referenced by multiple classes such as IPSPolicy and IPSPolicyTemplate.

property ips_ethernet_rules

IPS Ethernet access rule

Return type:

rule_collection(EthernetRule)

property ips_ipv4_access_rules

IPS ipv4 access rules

Return type:

rule_collection(IPv4Layer2Rule)

class smc.policy.ips.IPSSubPolicy(name=None, **meta)[source]

Bases: Policy

A IPS Sub Policy is a rule section within an IPS policy that provides a container to create rules that are referenced from a ‘jump’ rule. Typically rules in a sub policy are similar in some fashion such as applying to a specific service. Sub Policies can also be delegated from an administrative perspective.

p = IPSSubPolicy(‘MyIPSSubPolicy’) p.fw_ipv4_access_rules.create(

name=’newule’, sources=’any’, destinations=’any’, services=[TCPService(‘SSH’)], action=’discard’)

classmethod create(name)[source]

Create a sub policy. Only name is required. Other settings are inherited from the parent IPS policy (template, inspection policy, etc).

Parameters:

name (str) – name of sub policy

Raises:

CreateElementFailed – failed to create policy

Return type:

IPSSubPolicy

property ips_ipv4_access_rules

IPv4 rule entry point

Return type:

rule_collection(IPSRule)

class smc.policy.ips.IPSTemplatePolicy(name=None, **meta)[source]

Bases: IPSPolicy

All IPS Policies will reference an IPS policy template.

Most templates will be pre-configured best practice configurations and rarely need to be modified. However, you may want to view the details of rules configured in a template or possibly insert additional rules.

For example, view rules in an ips policy template after loading the ips policy:

policy = IPSPolicy('InlineIPS')
for rule in policy.template.ips_ipv4_access_rules.all():
    print(rule)
upload()[source]

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())
Parameters:
  • engine (str) – name of device to upload policy to

  • preserve_connections (bool) – flag to preserve connections (True by default)

  • generate_snapshot (bool) – flag to generate snapshot (True by default)

Raises:

TaskRunFailed

Returns:

TaskOperationPoller

Layer2Policy

Layer 2 Firewall Policy

Module that represents resources related to creating and managing layer 2 firewall engine policies.

To get an existing policy:

>>> from smc.policy.layer2 import Layer2Policy
>>> policy = Layer2Policy('MyLayer2Policy')
>>> print(policy.template)
Layer2TemplatePolicy(name=Layer 2 Firewall Inspection Template)

Or through collections:

>>> from smc.policy.layer2 import Layer2Policy
>>> list(Layer2Policy.objects.all())
[Layer2Policy(name=MyLayer2Policy)]

To create a new policy, use:

policy = Layer2Policy.create(name='newpolicy', template='layer2_fw_template')

Example rule creation:

policy = Layer2Policy('smcpython-l2')

policy.layer2_ipv4_access_rules.create(
                            name='nonerule',
                            sources='any',
                            destinations='any',
                            services='any',
                            logical_interfaces=[location_href_to_logical_interface])

Create Ethernet rule for layer 2 firewall:

policy.layer2_ethernet_rules.create(name='nonerule',
                                    sources='any',
                                    destinations='any',
                                    services='any')

Note

Leaving parameter logical_interfaces out of create will default to ‘ANY’.

Example rule deletion:

policy = Layer2Policy('Amazon Cloud')
for rule in policy.layer2_ipv4_access_rules.all():
    if rule.name == 'myrule':
        print rule.delete()
class smc.policy.layer2.Layer2Policy(name=None, **meta)[source]

Bases: Layer2Rule, Policy

Layer 2 Policy represents a set of rules installed on a layer 2 firewall engine. Layer 2 mode supports both inline and SPAN interface types and ethernet based rules. Layer 2 and IPS engines do not current features that require routed interfaces.

Variables:

template – which policy template is used

Instance Resources:

Variables:
classmethod create(name, template='Layer 2 Firewall Inspection Template')[source]

Create Layer 2 Firewall Policy. Template policy is required for the policy. The template parameter should be the name of the template.

The template should exist as a layer 2 template policy and should be referenced by name.

This policy will then inherit the Inspection and File Filtering policy from the specified template.

To use after successful creation, reference the policy to obtain context:

Layer2Policy('newpolicy')
Parameters:
  • name (str) – name of policy

  • template (str) – name of the NGFW engine template to base policy on

Raises:
Returns:

Layer2Policy

class smc.policy.layer2.Layer2Rule[source]

Bases: object

Encapsulates all references to layer 2 firewall rule related entry points. This is referenced by multiple classes such as Layer2Policy and Layer2TemplatePolicy.

property layer2_ethernet_rules

Layer 2 Ethernet access rule

Return type:

rule_collection(EthernetRule)

property layer2_ipv4_access_rules

Layer2 Firewall access rule

Return type:

rule_collection(IPv4Layer2Rule)

property layer2_ipv6_access_rules

Layer 2 IPv6 access rule

class smc.policy.layer2.Layer2TemplatePolicy(name=None, **meta)[source]

Bases: Layer2Policy

All Layer 2 Firewall Policies will reference a firewall policy template.

Most templates will be pre-configured best practice configurations and rarely need to be modified. However, you may want to view the details of rules configured in a template or possibly insert additional rules.

For example, view rules in the layer 2 policy template after loading the firewall policy:

policy = Layer2Policy('Amazon Cloud')
for rule in policy.template.layer2_ipv4_access_rules.all():
    print rule
upload()[source]

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())
Parameters:
  • engine (str) – name of device to upload policy to

  • preserve_connections (bool) – flag to preserve connections (True by default)

  • generate_snapshot (bool) – flag to generate snapshot (True by default)

Raises:

TaskRunFailed

Returns:

TaskOperationPoller

QoSPolicy

QoS Policy that would be applied to a rule set or physical / tunnel interface. QoS can also be applied at the VLAN level of an interface.

class smc.policy.qos.QoSClass(name=None, **meta)[source]

Bases: Element

This represents a QoS Class. It is an element that works as a link between a rule in a QoS Policy and one or more Firewall Actions. The traffic allowed in the access rule is assigned the QoS Class defined for the rule, and the QoS class is used as the matching criteria for applying QoS Policy rules.

classmethod create(name, comment=None, lsv_override=None, link_selection=None)[source]

Create the QoS Class.

Parameters:
  • name (str) – name of QoS Class

  • comment (str) – optional comment

  • lsv_override (bool) – optional can be True or False

:param object link_selection : optional value to override link selection value :raises CreateElementFailed: failed creating element with reason :return: instance with meta :rtype: QoSClass

class smc.policy.qos.QoSPolicy(name=None, **meta)[source]

Bases: Element

This represents a QoS Policy. A set of rules for Bandwidth Management and Traffic Prioritization for traffic that has a particular QoS Class, or rules for assigning QoS Classes based on a DSCP Match found in the traffic.

Sub Policies

Sub Policies are referenced from within a normal policy as a parameter to a ‘jump’ action. They provide rule encapsulation for similar rules and can be delegated to an Admin User for more granular policy control.

FirewallSubPolicy

class smc.policy.layer3.FirewallSubPolicy(name=None, **meta)[source]

Bases: Policy

A Firewall Sub Policy is a rule section within a firewall policy that provides a container to create rules that are referenced from a ‘jump’ rule. Typically rules in a sub policy are similar in some fashion such as applying to a specific service. Sub Policies can also be delegated from an administrative perspective.

Firewall Sub Policies only provide access to creating IPv4 rules. NAT is done on the parent firewall policy:

p = FirewallSubPolicy('MySubPolicy')
p.fw_ipv4_access_rules.create(
    name='newule',
    sources='any',
    destinations='any',
    services=[TCPService('SSH')],
    action='discard')
classmethod create(name)[source]

Create a sub policy. Only name is required. Other settings are inherited from the parent firewall policy (template, inspection policy, etc).

Parameters:

name (str) – name of sub policy

Raises:

CreateElementFailed – failed to create policy

Return type:

FirewallSubPolicy

property fw_ipv4_access_rules

IPv4 rule entry point

Return type:

rule_collection(IPv4Rule)

Rules

Represents classes responsible for configuring rule types.

Rule

class smc.policy.rule.Rule[source]

Bases: object

Top level rule construct with methods required to modify common behavior of any rule types. To retrieve a rule, access by reference:

policy = FirewallPolicy('mypolicy')
for rule in policy.fw_ipv4_nat_rules.all():
    print(rule.name, rule.comment, rule.is_disabled)
property action

Action for this rule.

Return type:

Action

property authentication_options

Read only authentication options field

Return type:

AuthenticationOptions

property comment

Optional comment for this rule.

Parameters:

value (str) – string comment

Return type:

str

property destinations

Destinations for this rule

Return type:

Destination

disable()[source]

Disable this rule

enable()[source]

Enable this rule

property history

New in version 0.6.3: Requires SMC version >= 6.5

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.5

Return type:

History

property is_disabled

Whether the rule is enabled or disabled

Parameters:

value (bool) – True, False

Return type:

bool

property is_rule_section

Is this rule considered a rule section

Return type:

bool

property match_vpn_options

Read only match vpn options field

Return type:

SourceVpn

move_rule_after(other_rule)[source]

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.

Parameters:

Rule (other_rule) – rule where this rule will be positioned after

Raises:

CreateRuleFailed – failed to duplicate this rule, no move is made

move_rule_before(other_rule)[source]

Move 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.

Parameters:

Rule (other_rule) – rule where this rule will be positioned before

Raises:

CreateRuleFailed – failed to duplicate this rule, no move is made

property name

Name attribute of rule element

property options

Options for this rule.

Return type:

LogOptions

property parent_policy

Read-only name of the parent policy

Returns:

smc.base.model.Element of type policy

save()[source]

After making changes to a rule element, you must call save to apply the changes. Rule changes are made to cache before sending to SMC.

Raises:

PolicyCommandFailed – failed to save with reason

Returns:

href of this rule

Return type:

str

property services

Services assigned to this rule

Return type:

Service

property sources

Sources assigned to this rule

Return type:

Source

property tag

Value of rule tag. Read only.

Returns:

rule tag

Return type:

str

update(validate=True, sources=None, destinations=None, services=None, action=None, **kwargs)[source]

update a rule

Parameters:
  • sources (str, list[Element] str can be "any" or json) – source/s for rule

  • destinations (str, list[Element] str can be "any" or json) – destination/s for rule

  • services (str, list[Element] str can be "any" or json) – service/s for rule

  • validate (bool) – validate the policy before update; default True

  • action (str, list[str] since API 6.6, json) – action/s for rule

Returns:

href of this rule

Return type:

str

IPv4Rule

class smc.policy.rule.IPv4Rule(**meta)[source]

Bases: RuleCommon, Rule, SubElement

Represents an IPv4 Rule for a layer 3 engine.

Create a rule:

policy = FirewallPolicy('mypolicy')
policy.fw_ipv4_access_rules.create(name='smcpython',
                                   sources='any',
                                   destinations='any',
                                   services='any')

Sources and Destinations can be one of any valid network element types defined in smc.elements.network.

Source entries by href:

sources=['http://1.1.1.1:8082/elements/network/myelement',
         'http://1.1.1.1:8082/elements/host/myhost'], etc

Source entries using network elements:

sources=[Host('myhost'), Network('thenetwork'), AddressRange('range')]

Services have a similar syntax and can take any type of smc.elements.service or the element href or both:

services=[TCPService('myservice'),
          'http://1.1.1.1/8082/elements/tcp_service/mytcpservice',
          'http://1.1.1.1/8082/elements/udp_server/myudpservice'], etc

You can obtain services and href for the elements by using the smc.base.collection collections:

 >>> services = list(TCPService.objects.filter('80'))
 >>> for service in services:
 ...   print(service, service.href)
 ...
(TCPService(name=tcp80443), u'http://172.18.1.150:8082/6.1/elements/tcp_service/3535')
(TCPService(name=HTTP to Web SaaS), u'http://172.18.1.150:8082/6.1/elements/tcp_service/589')
(TCPService(name=HTTP), u'http://172.18.1.150:8082/6.1/elements/tcp_service/440')

Services by application (get all facebook applications):

>>> applications = Search.objects.entry_point('application_situation').filter('facebook')
>>> print(list(applications))
[ApplicationSituation(name=Facebook-Plugins-Share-Button),
 ApplicationSituation(name=Facebook-Plugins]
...

Sources / Destinations and Services can also take the string value ‘any’ to allow all. For example:

sources='any'
create(name, sources=None, destinations=None, services=None, action='allow', log_options=None, authentication_options=None, match_vpn_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, validate=True, **kw)[source]

Create a layer 3 firewall rule

Changed in version 0.7.0: Action field now requires a list of actions as strings when using API version >= 6.6

Example::

Api version <=6.5 action is a string rule_vpn = p.fw_ipv4_access_rules.create( name=”newrule_vpn”,

sources=[Network(“London Internal Network”)], destinations=[Network(“net-172.31.14.0/24”)], services=”any”, action=”apply_vpn”, vpn_policy=vpn)

Api version >=6.6 action is a list vpn_actions = Action() vpn_actions.action = [‘allow’, ‘apply_vpn’] p.fw_ipv4_access_rules.create(name=’’,

sources=[Network(“London Internal Network”)], destinations=[Network(“net-172.31.14.0/24”)], services=’any’, action=vpn_actions, vpn_policy=vpn)

Parameters:
  • name (str) – name of rule

  • sources (Source, list[str, Element]) – source/s for rule

  • destinations (Destination, list[str, Element]) – destination/s for rule

  • services (Service, list[str, Element]) – service/s for rule

  • action (Action,str,list[str]) – allow,continue,discard,refuse,enforce_vpn, apply_vpn,forward_vpn, blacklist, forced_next_hop (default: allow)

  • log_options (LogOptions) – LogOptions object

  • connection_tracking (ConnectionTracking) – custom connection tracking settings

  • authentication_options (AuthenticationOptions) – options for auth if any

  • match_vpn_options (SourceVpn) – rule matches traffic from specific VPNs

  • vpn_policy (PolicyVPN,str) – policy element or str href; required for enforce_vpn, use_vpn and apply_vpn actions

  • mobile_vpn (bool) – 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

  • sub_policy (str,Element) – sub policy required when rule has an action of ‘jump’. Can be the FirewallSubPolicy element or href.

  • add_pos (int) – 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.

  • after (str) – Rule tag to add this rule after. Mutually exclusive with add_pos and before params.

  • before (str) – Rule tag to add this rule before. Mutually exclusive with add_pos and after params.

  • comment (str) – optional comment for this rule

  • validate (bool) – validate the inspection policy during rule creation. Default: True

Raises:
  • MissingRequiredInput – when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified.

  • CreateRuleFailed – rule creation failure

Returns:

the created ipv4 rule

Return type:

IPv4Rule

create_rule_section(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)
Parameters:
  • name (str) – create a rule section by name

  • add_pos (int) – 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.

  • after (str) – Rule tag to add this rule after. Mutually exclusive with add_pos and before params.

  • before (str) – 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.

  • CreateRuleFailed – rule creation failure

Returns:

the created ipv4 rule

Return type:

IPv4Rule

IPv4Layer2Rule

class smc.policy.rule.IPv4Layer2Rule(**meta)[source]

Bases: RuleCommon, Rule, SubElement

Create IPv4 rules for Layer 2 Firewalls

Example of creating an allow all rule:

policy = Layer2Policy('mylayer2')
policy.layer2_ipv4_access_rules.create(name='myrule',
                                       sources='any',
                                       destinations='any',
                                       services='any')
create(name, sources=None, destinations=None, services=None, action='allow', is_disabled=False, logical_interfaces=None, add_pos=None, after=None, before=None, comment=None, validate=True, sub_policy=None, **kw)[source]

Create an IPv4 Layer 2 Engine rule

Changed in version 0.7.0: Action field now requires a list of actions as strings when using SMC version >= 6.6.0

Parameters:
  • name (str) – name of rule

  • sources (list[str, Element]) – source/s for rule

  • destinations (list[str, Element]) – destination/s for rule

  • services (list[str, Element]) – service/s for rule

  • action (str, Action) – |allow|continue|discard|refuse|blacklist

  • is_disabled (bool) – whether to disable rule or not

  • logical_interfaces (list) – logical interfaces by name

  • add_pos (int) – 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.

  • after (str) – Rule tag to add this rule after. Mutually exclusive with add_pos and before params.

  • before (str) – Rule tag to add this rule before. Mutually exclusive with add_pos and after params.

  • comment (str) – optional comment for this rule

  • validate (bool) – validate the inspection policy during rule creation. Default: True

  • sub_policy (str,Element) – sub policy required when rule has an action of ‘jump’. Can be the IPSSubPolicy element or href.

Raises:
  • MissingRequiredInput – when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified.

  • CreateRuleFailed – rule creation failure

Returns:

newly created rule

Return type:

IPv4Layer2Rule

create_rule_section(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)
Parameters:
  • name (str) – create a rule section by name

  • add_pos (int) – 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.

  • after (str) – Rule tag to add this rule after. Mutually exclusive with add_pos and before params.

  • before (str) – 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.

  • CreateRuleFailed – rule creation failure

Returns:

the created ipv4 rule

Return type:

IPv4Rule

EthernetRule

class smc.policy.rule.EthernetRule(**meta)[source]

Bases: RuleCommon, Rule, SubElement

Ethernet Rule represents a policy on a layer 2 or IPS engine.

If logical_interfaces parameter is left blank, ‘any’ logical interface is used.

Create an ethernet rule for a layer 2 policy:

policy = Layer2Policy('layer2policy')
policy.layer2_ethernet_rules.create(name='l2rule',
                                    logical_interfaces=['dmz'],
                                    sources='any',
                                    action='discard')
create(name, sources=None, destinations=None, services=None, action='allow', is_disabled=False, logical_interfaces=None, add_pos=None, after=None, before=None, comment=None, validate=True, **kw)[source]

Create an Ethernet rule

Changed in version 0.7.0: Action field now requires a list of actions as strings when using SMC version >= 6.6.0

Parameters:
  • name (str) – name of rule

  • sources (list[str, Element]) – source/s for rule

  • destinations (list[str, Element]) – destination/s for rule

  • services (list[str, Element]) – service/s for rule

  • action (str) – |allow|continue|discard|refuse|blacklist

  • is_disabled (bool) – whether to disable rule or not

  • logical_interfaces (list) – logical interfaces by name

  • add_pos (int) – 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.

  • after (str) – Rule tag to add this rule after. Mutually exclusive with add_pos and before params.

  • before (str) – Rule tag to add this rule before. Mutually exclusive with add_pos and after params.

  • validate (bool) – validate the inspection policy during rule creation. Default: True

Raises:
  • MissingRequiredInput – when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified.

  • CreateRuleFailed – rule creation failure

Returns:

newly created rule

Return type:

EthernetRule

create_rule_section(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)
Parameters:
  • name (str) – create a rule section by name

  • add_pos (int) – 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.

  • after (str) – Rule tag to add this rule after. Mutually exclusive with add_pos and before params.

  • before (str) – 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.

  • CreateRuleFailed – rule creation failure

Returns:

the created ipv4 rule

Return type:

IPv4Rule

IPv6Rule

class smc.policy.rule.IPv6Rule(**meta)[source]

Bases: IPv4Rule

IPv6 access rule defines sources and destinations that must be in IPv6 format.

Note

It is possible to submit a source or destination in IPv4 format, however this will fail validation when attempting to push policy.

NATRule

class smc.policy.rule_nat.NATRule[source]

Bases: Rule

property action

Action for this rule.

Return type:

Action

property authentication_options

Read only authentication options field

Return type:

AuthenticationOptions

property dynamic_src_nat

Dynamic Source NAT configuration for this NAT rule.

Return type:

DynamicSourceNAT

property static_dst_nat

Static Destination NAT configuration for this NAT rule

Return type:

StaticDestNAT

property static_src_nat

Static Source NAT configuraiton for this NAT rule.

Return type:

StaticSourceNAT

update(validate=True, sources=None, destinations=None, services=None, dynamic_src_nat=None, dynamic_src_nat_ports=(1024, 65535), dynamic_src_nat_automatic_proxy=None, static_src_nat=None, static_dst_nat=None, static_dst_nat_ports=None, static_dst_nat_automatic_proxy=None, **kwargs)[source]

update a rule

Parameters:
  • sources (str, list[Element] str can be "any" or json) – source/s for rule

  • destinations (str, list[Element] str can be "any" or json) – destination/s for rule

  • services (str, list[Element] str can be "any" or json) – service/s for rule

  • validate (bool) – validate the policy before update; default True

  • dynamic_src_nat (str,Element) – str ip or Element for dest NAT

  • dynamic_src_nat_ports (tuple) – starting and ending ports for PAT. Default: (1024, 65535)

  • dynamic_src_nat_automatic_proxy (bool) – Is Automatic Proxy ARP enabled?

  • static_src_nat (str) – ip or element href of used for source NAT

  • static_dst_nat (str) – destination NAT IP address or element href

  • static_dst_nat_ports (tuple) – ports or port range used for original and destination ports (only needed if a different destination port is used and does not match the rules service port)

  • static_dst_nat_automatic_proxy (bool) – Is Automatic Proxy ARP enabled?

Returns:

href of this rule

Return type:

str

property used_on

Used on specific whether this NAT rule has a specific engine that this rule applies to. Default is ANY (unspecified).

Parameters:

value (str,Element) – Can be the strings ‘ANY’ or ‘NONE’ or an Engine element type.

Returns:

‘ANY’, ‘NONE’ or the Engine element

IPv4NATRule

class smc.policy.rule_nat.IPv4NATRule(**meta)[source]

Bases: RuleCommon, NATRule, SubElement

Create NAT Rules for relevant policy types. Rule requirements are similar to a normal rule with exception of the NAT field and no action field.

Like policy rules, specifying source/destination and services can be done either using the element href or element defined in element classes defined under package smc.elements. For example, using networks from smc.elements.network or services from smc.elements.service.

Example of creating a dynamic source NAT for host ‘kali’:

policy = FirewallPolicy('smcpython')
policy.fw_ipv4_nat_rules.create(name='mynat',
                                sources=[Host('kali')],
                                destinations='any',
                                services='any',
                                dynamic_src_nat='1.1.1.1',
                                dynamic_src_nat_ports=(1024,65535))

Example of creating a static source NAT for host ‘kali’:

policy.fw_ipv4_nat_rules.create(name='mynat',
                                sources=[Host('kali')],
                                destinations='any',
                                services='any',
                                static_src_nat='1.1.1.1')

Example of creating a destination NAT rule for destination host ‘3.3.3.3’ with destination translation address of ‘1.1.1.1’:

policy.fw_ipv4_nat_rules.create(name='mynat',
                                sources='any',
                                destinations=[Host('3.3.3.3')],
                                services='any',
                                static_dst_nat='1.1.1.1')

Destination NAT with destination port translation:

policy.fw_ipv4_nat_rules.create(name='aws_client',
                                sources='any',
                                destinations=[Alias('$$ Interface ID 0.ip')],
                                services='any',
                                static_dst_nat='1.1.1.1',
                                static_dst_nat_ports=(2222,22),
                                used_on=engine.href)

Create an any/any no NAT rule from host ‘kali’:

policy.fw_ipv4_nat_rules.create(name='nonat',
                                sources=[Host('kali')],
                                destinations='any',
                                services='any')
create(name, sources=None, destinations=None, services=None, dynamic_src_nat=None, dynamic_src_nat_ports=(1024, 65535), dynamic_src_nat_automatic_proxy=None, static_src_nat=None, static_dst_nat=None, static_dst_nat_ports=None, static_dst_nat_automatic_proxy=None, is_disabled=False, used_on='ANY', add_pos=None, after=None, before=None, comment=None, validate=True)[source]

Create a NAT rule.

When providing sources/destinations or services, you can provide the element href, network element or services from smc.elements. You can also mix href strings with Element types in these fields.

Parameters:
  • name (str) – name of NAT rule

  • sources (list(str,Element)) – list of sources by href or Element

  • destinations (list(str,Element)) – list of destinations by href or Element

  • services (list(str,Element)) – list of services by href or Element

  • dynamic_src_nat (str,Element) – str ip or Element for dest NAT

  • dynamic_src_nat_ports (tuple) – starting and ending ports for PAT. Default: (1024, 65535)

  • dynamic_src_nat_automatic_proxy (bool) – Is Automatic Proxy ARP enabled?

  • static_src_nat (str) – ip or element href of used for source NAT

  • static_dst_nat (str) – destination NAT IP address or element href

  • static_dst_nat_ports (tuple) – ports or port range used for original and destination ports (only needed if a different destination port is used and does not match the rules service port)

  • static_dst_nat_automatic_proxy (bool) – Is Automatic Proxy ARP enabled?

  • is_disabled (bool) – whether to disable rule or not

  • used_on (str,Element) – Can be None, ‘ANY’ or and Engine element. Default is ‘ANY’.

  • add_pos (int) – 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.

  • after (str) – Rule tag to add this rule after. Mutually exclusive with add_pos and before params.

  • before (str) – Rule tag to add this rule before. Mutually exclusive with add_pos and after params.

  • comment (str) – optional comment for the NAT rule

  • validate (bool) – validate the inspection policy during rule creation. Default: True

Raises:
Returns:

newly created NAT rule

Return type:

IPv4NATRule

create_rule_section(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)
Parameters:
  • name (str) – create a rule section by name

  • add_pos (int) – 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.

  • after (str) – Rule tag to add this rule after. Mutually exclusive with add_pos and before params.

  • before (str) – 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.

  • CreateRuleFailed – rule creation failure

Returns:

the created ipv4 rule

Return type:

IPv4Rule

IPv6NATRule

class smc.policy.rule_nat.IPv6NATRule(**meta)[source]

Bases: IPv4NATRule

Represents an IPv6 NAT rule. Source and/or destination (depending on NAT type) should be an IPv6 address. It will be possible to submit an IPv4 address however the policy validation engine will fail when being deployed to an engine and the rule will be ignored.

RuleElements

class smc.policy.rule_elements.RuleElement[source]

Rule Element encapsulates actions for source, destination and service fields.

add(data)[source]

Add a single entry to field.

Entries can be added to a rule using the href of the element or by loading the element directly. Element should be of type smc.elements.network. After modifying rule, call save().

Example of adding entry by element:

policy = FirewallPolicy('policy')
for rule in policy.fw_ipv4_nat_rules.all():
    if rule.name == 'therule':
        rule.sources.add(Host('myhost'))
        rule.save()

Note

If submitting type Element and the element cannot be found, it will be skipped.

Parameters:

data (Element or str) – entry to add

add_many(data)[source]

Add multiple entries to field. Entries should be list format. Entries can be of types relavant to the field type. For example, for source and destination fields, elements may be of type smc.elements.network or be the elements direct href, or a combination of both.

Add several entries to existing rule:

policy = FirewallPolicy('policy')
for rule in policy.fw_ipv4_nat_rules.all():
    if rule.name == 'therule':
        rule.sources.add_many([Host('myhost'),
                              'http://1.1.1.1/hosts/12345'])
        rule.save()
Parameters:

data (list) – list of sources

Note

If submitting type Element and the element cannot be found, it will be skipped.

all()[source]

Return all destinations for this rule. Elements returned are of the object type for the given element for further introspection.

Search the fields in rule:

for sources in rule.sources.all():
    print('My source: %s' % sources)
Returns:

elements by resolved object type

Return type:

list(Element)

all_as_href()[source]

Return all elements without resolving to smc.elements.network or smc.elements.service. Just raw representation as href.

Returns:

elements in href form

Return type:

list

property is_any

Is the field set to any

Return type:

bool

property is_none

Is the field set to none

Return type:

bool

set_any()[source]

Set field to any

set_none()[source]

Set field to none

unset_any()[source]

UnSet field to any

update_field(elements)[source]

Update the field with a list of provided values but only if the values are different. Return a boolean indicating whether a change was made indicating whether save should be called. If the field is currently set to any or none, then no comparison is made and field is updated.

Parameters:

elements (list) – list of elements in href or Element format to compare to existing field

Return type:

bool

Source

class smc.policy.rule_elements.Source(rule=None)[source]

Bases: RuleElement, NestedDict

Source fields for a rule

property src

All elements corresponding to the matching criteria (if not any or none).

Returns:

list value: source elements

Destination

class smc.policy.rule_elements.Destination(rule=None)[source]

Bases: RuleElement, NestedDict

Destination fields for a rule.

property dst

All elements corresponding to the matching criteria (if not any or none).

Returns:

list value: source elements

Service

class smc.policy.rule_elements.Service(rule=None)[source]

Bases: RuleElement, NestedDict

Service fields for a rule

property service

All elements corresponding to the matching criteria (if not any or none).

Returns:

list value: source elements

Action

class smc.policy.rule_elements.Action(rule=None)[source]

Bases: ActionMixin

This represents the action associated with the rule.

property antispam

Enable or disable anti-spam

Parameters:

value (bool) – True, False, None (inherit from continue rule)

Return type:

bool

property decrypting

New in version 0.6.0: Requires SMC version >= 6.3.3

Whether the decryption is enabled on this rule.

Parameters:

value (bool) – True, False, None (inherit from continue rule)

Return type:

bool

property deep_inspection

Selects traffic that matches this rule for checking against the Inspection Policy referenced by this policy. Traffic is inspected as the Protocol that is attached to the Service element in this rule.

Parameters:

value (bool) – True, False, None (inherit from continue rule)

Return type:

bool

property dos_protection

Enable or disable DOS protection mode

Parameters:

value (bool) – True, False, None (inherit from continue rule)

Return type:

bool

property file_filtering

(IPv4 Only) Inspects matching traffic against the File Filtering policy. Selecting this option should also activates the Deep Inspection option. You can further adjust virus scanning in the Inspection Policy.

Parameters:

value (bool) – True, False, None (inherit from continue rule)

Return type:

bool

property forced_next_hop_element

If action includes forced_next_hop, specify the forced next hop element.

Return type:

NetworkElement

property forced_next_hop_ip

If action includes forced_next_hop, specify the forced next hop IP address.

Return type:

str ip address

property mobile_vpn

Mobile VPN only applies to engines that support VPN and that have the action of ‘enforce_vpn’, ‘apply_vpn’ or ‘forward_vpn’ set. This will enable mobile VPN traffic on this VPN rule.

Parameters:

value (boolean) – set mobile vpn on or off

Return type:

boolean

property network_application_latency_monitoring

Enable or Disable the Application Health Monitoring for the matching Traffic

Parameters:
  • value (str) – True, False, None (inherit from continue rule) in 7.0

  • value – true, false, probing, None (inherit from continue rule) in 7.1 and above

Return type:

bool

property scan_detection

Enable or disable Scan Detection for traffic that matches the rule. This overrides the option set in the Engine properties.

Enable scan detection on this rule:

for rule in policy.fw_ipv4_access_rules.all():
    rule.action.scan_detection = 'on'
Parameters:

value (str) – on|off|undefined

Returns:

scan detection setting (on,off,undefined)

Return type:

str

property sub_policy

Sub policy is used when action=jump.

Return type:

FirewallSubPolicy

property user_response

Read-only user response setting

property valid_blacklister

Used when action=blacklist. If specified with blacklist action, you want to restrict allowed block listers for this rule. Black list entries are only accepted from the components you specify (and from the engine command line). NGFW Engines are always allowed to add entries to their own block lists. If not specified with blacklist action, any black list entries are accepted from all components.

Return type:

list(Engine)

Note

This method requires SMC version < 7.0

property valid_block_lister

Used when action=block_list. If specified with block_list action, you want to restrict allowed block listers for this rule. Block list entries are only accepted from the components you specify (and from the engine command line). NGFW Engines are always allowed to add entries to their own block lists. If not specified with block_list action, any block list entries are accepted from all components.

Return type:

list(Engine)

Note

This method requires SMC version >= 7.0

property vpn

Return vpn reference. Only used if ‘enforce_vpn’, ‘apply_vpn’, or ‘forward_vpn’ is the action type.

Parameters:

value (PolicyVPN) – set the policy VPN for VPN action

Return type:

PolicyVPN

ConnectionTracking

class smc.policy.rule_elements.ConnectionTracking(rule=None)[source]

Bases: NestedDict

Connection tracking settings can be configured on a per rule basis to control settings such as enforced MSS and how to handle connection states.

Configuring a rule to enable MSS and set connection state tracking to normal:

for rule in policy.fw_ipv4_access_rules.all():
    rule.action.connection_tracking_options.mss_enforced = True
    rule.action.connection_tracking_options.state = 'normal'
    rule.action.connection_tracking_options.mss_enforced_min_max = (1400, 1450)
    rule.action.connection_tracking_options.sync_connections = True
    rule.save()
property mss_enforced

Is MSS enforced

Parameters:

value (bool) – True, False

Returns:

bool

property mss_enforced_min_max

Allows entering the Minimum and Maximum value for the MSS in bytes. Headers are not included in the MSS value; MSS concerns only the payload portion of the packet.

Parameters:

value (tuple int) – tuple containing (min, max) in bytes

Returns:

(min, max) values

Return type:

tuple

property state

Connection tracking mode. See documentation for more info.

Parameters:

value (str) – no,loose,normal,strict

Returns:

str

property sync_connections

Are sync connections enabled for this engine. If None, then this is set to inherit from a continue rule.

:return True, False, None (inherit from continue rule)

property timeout

The timeout (in seconds) after which inactive connections are closed. This timeout only concerns idle connections. Connections are not cut because of timeouts while the hosts are still communicating.

Parameters:

value (int) – time in seconds

Returns:

int

LogOptions

class smc.policy.rule_elements.LogOptions(rule=None)[source]

Bases: NestedDict

Log Options represent the settings related to per rule logging.

Example of obtaining a rule reference and turning logging on for a particular rule:

policy = FirewallPolicy('smcpython')
for rule in policy.fw_ipv4_access_rules.all():
    if rule.name == 'foo':
        rule.options.log_accounting_info_mode = True
        rule.options.log_level = 'stored'
        rule.options.application_logging = 'enforced'
        rule.options.user_logging = 'enforced'
        rule.save()
property application_logging

Stores information about Application use. You can log application use even if you do not use Applications for access control.

Parameters:

value (str) – off|default|enforced

Returns:

str

property endpoint_executable_logging

Stores information about EndPoint Executable use. You can log EndPoint Executable use even if you do not use EndPoint Executables for accesscontrol.

Parameters:

value (str) – off|default|enforced

Returns:

str

property log_accounting_info_mode

Both connection opening and closing are logged and information on the volume of traffic is collected. This option is not available for rules that issue alerts. If you want to create reports that are based on traffic volume, you must select this option for all rules that allow traffic that you want to include in the reports.

Parameters:

value (bool) – log accounting information (bits/bytes transferred)

Returns:

bool

property log_alert

If Log Level is set to Alert, specifies the Alert that is sent. Specifying different Alerts for different types of rules allows more fine-grained alert escalation policies.

Returns:

AlertElement

property log_closing_mode

Specifying False means no log entries are created when connections are closed. True will mean both connection opening and closing are logged, but no information is collected on the volume of traffic.

Parameters:

value (bool) – enable/disable accounting data

Returns:

bool

property log_compression

Stores information about Compress Logs.

Parameters:

value (str) – off|only_access|also_inspection

Returns:

str

property log_compression_max_burst_size

If Compress Logs is selected, the max burst size.

Returns:

int. None if not defined.

property log_compression_max_log_rate

If Compress Logs is selected, the max log rate.

Returns:

int. None if not defined.

property log_level

Configure per rule logging. It is recommended to configure an Any/Any/Any/Continue rule in position 1 if global logging is required. This can be used to override any global logging setting.

Parameters:

value (str) – none|stored|transient|essential|alert|undefined

Returns:

str

property log_payload_excerpt

Stores an excerpt of the packet that matched. The maximum recorded excerpt size is 4 KB. This allows quick viewing of the payload in the logs view.

Parameters:

value (bool) – collect excerpt or not

Returns:

bool

property log_payload_record

Records the traffic up to the limit that is set in the Record Length field.

Parameters:

value (bool) – True, False

Returns:

bool

property log_severity

Read only log severity level :return: int

property qos_class

Matching QoS Classes. The QoS Rules are linked to different types of traffic using the QoS Classes. QoS Classes are matched to traffic in the Access rules with the following actions: - Access rules with the Allow action set a QoS Class for traffic

that matches the rules.

  • Access rules with the Continue action set a QoS Class for all subsequent matching rules that have no specific QoS Class defined.

  • Access rules with the Use VPN action (Firewall only) set a QoS Class for VPN traffic. Incoming VPN traffic may also match a normal Allow rule after decryption. Otherwise, for outgoing traffic, encryption is done after the QoS Policy is checked. For incoming traffic, decryption is done before the QoS Policy is checked.

However, if you only want to read and use DSCP markers set by other devices, the QoS Class is assigned according to the rules on the DSCP Match/Mark tab of the QoS Policy.

Returns:

QoSClass

property url_category_logging

Stores information about URL categories use.

Parameters:

value (str) – off|default|enforced

Returns:

str

property user_logging

Stores information about Users when they are used as the Source or Destination of an Access rule. You must select this option if you want Users to be referenced by name in log entries, statistics, reports, and user monitoring. Otherwise, only the IP address associated with the User at the time the log was created is stored.

Parameters:

value (str) – off|default|enforced

Returns:

str

AuthenticationOptions

class smc.policy.rule_elements.AuthenticationOptions(rule=None)[source]

Bases: NestedDict

Authentication options are set on a per rule basis and dictate whether a user requires identification to match.

property methods

Read only authentication methods enabled

Returns:

list value: auth methods enabled

property require_auth

Ready only authentication required

Returns:

boolean

property timeout

Timeout between authentications

Returns:

int

property users

List of users required to authenticate

Returns:

list

MatchExpression

class smc.policy.rule_elements.MatchExpression(name=None, **meta)[source]

Bases: Element

A match expression is used in the source / destination / service fields to group together elements into an ‘AND’ed configuration. For example, a normal rule might have a source field that could include network=172.18.1.0/24 and zone=Internal objects. A match expression enables you to AND these elements together to enforce the match requires both. Logically it would be represented as (network 172.18.1.0/24 AND zone Internal).

>>> from smc.elements.network import Host, Zone
>>> from smc.policy.rule_elements import MatchExpression
>>> from smc.policy.layer3 import FirewallPolicy
>>> match = MatchExpression.create(name='mymatch', network_element=Host('kali'),
                                   zone=Zone('Mail'))
>>> policy = FirewallPolicy('smcpython')
>>> policy.fw_ipv4_access_rules.create(name='myrule', sources=[match],
                                       destinations='any', services='any')
'http://172.18.1.150:8082/6.2/elements/fw_policy/261/fw_ipv4_access_rule/2099740'
>>> rule = policy.search_rule('myrule')
...
>>> for source in rule[0].sources.all():
...   print(source, source.values())
...
MatchExpression(name=MatchExpression _1491760686976_2) [Zone(name=Mail), Host(name=kali)]

Match expressions can also be used on service fields by providing values for service and service ports as follows:

match = MatchExpression.create(name='mymatch', service=ApplicationSituation('FTP'),
                               service_ports='TCPService('Any TCP Service')')

If the service match expression requires ANY ports, you can use the string of ‘any’ to provide this logic:

match = MatchExpression.create(name='mymatch', service=ApplicationSituation('FTP'),
                               service_ports='any')

Once the service match expression is created, you can use that in the policy rule:

policy.fw_ipv4_access_rules.create(name='myrule', sources='any', destinations='any',
                                   services=[match], action=['discard'])
classmethod create(name, user=None, network_element=None, domain_name=None, zone=None, executable=None, service=None, service_ports='any')[source]

Create a match expression

Parameters:
  • name (str) – name of match expression

  • user (str) – name of user or user group

  • network_element (Element) – valid network element type, i.e. host, network, etc

  • domain_name (DomainName) – domain name network element

  • zone (Zone) – zone to use

  • executable (str) – name of executable or group

  • service – any service type, i.e. TCPService, UDPService, ApplicationSituation

  • service_ports (str,Element) – specify the service ports for the given service. Provide ‘ANY’ as the value if the match expression requires a service/application and ANY ports

Raises:

ElementNotFound – specified object does not exist

Returns:

instance with meta

Return type:

MatchExpression

NATElements

class smc.policy.rule_nat.NATElement(rule=None)[source]

Common structure for source and destination NAT configurations.

property automatic_proxy

Is proxy arp enabled. Leaving this in the on state is recommended.

Parameters:

value (bool) – enable/disable proxy arp

Return type:

bool

property has_nat

Is NAT already enabled (assuming modification) or newly created.

Returns:

boolean

set_none()[source]

Clear the NAT field for this NAT rule. You must call update or save on the rule to commit this change.

Returns:

None

property translated_value

The translated value for this NAT type. If this rule does not have a NAT value defined, this will return None.

Returns:

NATValue or None

Return type:

NATValue

update_field(element_or_ip_address=None, start_port=None, end_port=None, **kw)[source]

Update the source NAT translation on this rule. You must call save or update on the rule to make this modification. To update the source target for this NAT rule, update the source field directly using rule.sources.update_field(…). This will automatically update the NAT value. This method should be used when you want to change the translated value or the port mappings for dynamic source NAT.

Starting and ending ports are only used for dynamic source NAT and define the available ports for doing PAT on the outbound connection.

Parameters:
  • element_or_ip_address (str,Element) – Element or IP address that is the NAT target

  • start_port (int) – starting port value, only used for dynamic source NAT

  • end_port (int) – ending port value, only used for dynamic source NAT

  • automatic_proxy (bool) – whether to enable proxy ARP (default: True)

Returns:

boolean indicating whether the rule was modified

Return type:

bool

DynamicSourceNAT

class smc.policy.rule_nat.DynamicSourceNAT(rule=None)[source]

Bases: NATElement

Dynamic source NAT is typically used for outbound traffic and typically uses a range of ports to perform PAT operations.

property end_port

Ending port specified for outbound dynamic source NAT (PAT)

Return type:

int

property start_port

Start port for dynamic source NAT (PAT)

Return type:

int

property translated_value

The translated value for this NAT type. If this rule does not have a NAT value defined, this will return None.

Returns:

NATValue or None

Return type:

NATValue

StaticSourceNAT

class smc.policy.rule_nat.StaticSourceNAT(rule=None)[source]

Bases: NATElement

Source NAT defines the available options for configuration. This is typically used for outbound traffic where you need to hide the original source address.

Example of changing existing source NAT rule to use a different source NAT address:

for rule in policy.fw_ipv4_nat_rules.all():
    if rule.name == 'sourcenat':
        rule.static_src_nat.translated_value = '10.10.50.50'
        rule.save()

DynamicSourceNAT

class smc.policy.rule_nat.DynamicSourceNAT(rule=None)[source]

Bases: NATElement

Dynamic source NAT is typically used for outbound traffic and typically uses a range of ports to perform PAT operations.

property end_port

Ending port specified for outbound dynamic source NAT (PAT)

Return type:

int

property start_port

Start port for dynamic source NAT (PAT)

Return type:

int

property translated_value

The translated value for this NAT type. If this rule does not have a NAT value defined, this will return None.

Returns:

NATValue or None

Return type:

NATValue

VPN

Represents classes responsible for configuring VPN settings such as PolicyVPN, RouteVPN and all associated configurations.

Note

See API reference documentation on the Engine for instructions on how to enable the engine for VPN.

PolicyVPN

class smc.vpn.policy.PolicyVPN(name=None, **meta)[source]

Bases: Element

Create a new VPN Policy.

>>> PolicyVPN.create(name='myvpn')
PolicyVPN(name=myvpn)
>>> v = PolicyVPN('myvpn')
>>> print(v.vpn_profile)
VPNProfile(name=VPN-A Suite)

When making VPN Policy modifications, you must first call open(), make your modifications and then call save() followed by close().

Variables:

vpn_profile (VPNProfile) – VPN Profile used by this Policy VPN

add_central_gateway(gateway)[source]

Add SMC managed internal gateway to the Central Gateways of this VPN

Parameters:

gateway (Engine,ExternalGateway) – An external gateway, engine or href for the central gateway

Raises:

PolicyCommandFailed – could not add gateway

Returns:

None

static add_internal_gateway_to_vpn(internal_gateway_href, vpn_policy, vpn_role='central')[source]

Add an internal gateway (managed engine node) to a VPN policy based on the internal gateway href.

Parameters:
  • internal_gateway_href (str) – href for engine internal gw

  • vpn_policy (str) – name of vpn policy

  • vpn_role (str) – central|satellite

Returns:

True for success

Return type:

bool

add_mobile_gateway(all_central_gateways=False, all_gateways=False, gateways=None)[source]

Add a mobile VPN gateway to this policy VPN. You can select all central gateways, all gateways in overall topology or specify a list of gateways to allow for mobile VPN.

Example of adding or removing a mobile VPN gateway:

policy_vpn = PolicyVPN('myvpn')
policy_vpn.update(mobile_vpn_topology_mode='Selected Gateways below')
policy_vpn.open()

policy_vpn.add_mobile_vpn_gateway(gateways=Engine('azure'))

policy_vpn.save()
policy_vpn.close()
Parameters:

gateway (Engine,ExternalGateway) – An external gateway, engine or href for the mobile gateway

Raises:

PolicyCommandFailed – could not add gateway

Return type:

None

add_satellite_gateway(gateway)[source]

Add gateway node as a satellite gateway for this VPN. You must first have the gateway object created. This is typically used when you either want a hub-and-spoke topology or the test_external gateway is a non-SMC managed device.

Parameters:

gateway (Engine,ExternalGateway) – An external gateway, engine or href for the central gateway

Raises:

PolicyCommandFailed – could not add gateway

Returns:

None

property central_gateway_node

Central Gateway Node acts as the hub of a hub-spoke VPN.

Return type:

SubElementCollection(GatewayNode)

close()[source]

Close the policy. This is only a valid method for SMC version <= 6.1

Raises:

PolicyCommandFailed – close failed with reason

Returns:

None

classmethod create(name, nat=False, mobile_vpn_topology_mode=None, vpn_profile=None, link_usage_profile=None)[source]

Create a new policy based VPN

Parameters:
  • name – name of vpn policy

  • nat (bool) – whether to apply NAT to the VPN (default False)

  • mobile_vpn_topology_mode – whether to allow remote vpn

  • vpn_profile (VPNProfile) – reference to VPN profile, or uses default

  • link_usage_profile (LinkUsageProfile) – reference to link usage profile of set

Return type:

PolicyVPN

enable_disable_nat()[source]

Enable or disable NAT on this policy. If NAT is disabled, it will be enabled and vice versa.

Returns:

None

property mobile_gateway_node

Mobile Gateway’s are represented by client endpoints connecting to the policy based VPN.

Return type:

SubElementCollection(GatewayNode)

property mobile_vpn_topology

Is the policy VPN configured for mobile VPN gateways. Valid modes: ‘Selected Gateways below’, ‘Only central Gateways from overall topology’, ‘All Gateways from overall topology’, ‘None’

property nat

Is NAT enabled on this vpn policy

Returns:

NAT enabled

Return type:

bool

open()[source]

Open the policy for editing. This is only a valid method for SMC version <= 6.1

Raises:

PolicyCommandFailed – couldn’t open policy with reason

Returns:

None

property satellite_gateway_node

Node level settings for configured satellite gateways

Return type:

SubElementCollection(GatewayNode)

save()[source]

Save the policy after editing. This is only a valid method for SMC version <= 6.1

Raises:

PolicyCommandFailed – save failed with reason

Returns:

None

property tunnels

Return all tunnels for this VPN. A tunnel is defined as two end points within the VPN topology. Endpoints are automatically configureed based on whether they are a central gateway or satellite gateway. This provides access to enabling/disabling and setting the preshared key for the linked endpoints. List all tunnel mappings for this policy vpn:

for tunnel in policy.tunnels:
    tunnela = tunnel.tunnel_side_a
    tunnelb = tunnel.tunnel_side_b
    print(tunnela.gateway)
    print(tunnelb.gateway)
Return type:

SubElementCollection(GatewayTunnel)

validate()[source]

Return a validation string from the SMC after running validate on this VPN policy.

Returns:

status as dict

Return type:

dict

RouteVPN

New in version 0.5.6: Route based VPNs with multi-domain support, requires SMC >=6.3

Module for configuring Route Based VPN. Creating a route based VPN consists of creating a local and remote tunnel endpoint. Once you have the required endpoints, use TunnelEndpoint classmethods to create the VPN by type (i.e. GRE, IPSEC).

List all existing route based VPNs:

print(list(RouteVPN.objects.all()))

Example of fully provisioning an IPSEC wrapped RBVPN using a third party remote GW:

engine = Layer3Firewall.create(name='myfw', mgmt_ip='1.1.1.1', mgmt_network='1.1.1.0/24')

# Add a second layer 3 interface for VPN
engine.physical_interface.add_layer3_interface(
    interface_id=1, address='10.10.10.10', network_value='10.10.10.0/24', zone_ref='vpn')

engine.tunnel_interface.add_layer3_interface(
    interface_id=1000,
    address='2.2.2.2',
    network_value='2.2.2.0/24')

# Enable VPN on the 'Internal Endpoint' interface
vpn_endpoint = engine.vpn_endpoint.get_contains('10.10.10.10')
vpn_endpoint.update(enabled=True)

# A Tunnel Endpoint pairs the interface of the NGFW with it's local VPN gateway.
# You must create a tunnel endpoint for both sides of the Route VPN.

# Create the local Tunnel Endpoint using the engine internal gateway
# and previously created tunnel interface
tunnel_if = engine.tunnel_interface.get(1000)
local_gateway = TunnelEndpoint.create_ipsec_endpoint(engine.vpn.internal_gateway, tunnel_if)

# Define the remote side details

# Create the remote side network elements
Network.create(name='remotenet', ipv4_network='172.18.10.0/24')

# An ExternalGateway defines the remote side as a 3rd party gateway
# Add the address of the remote gateway and the network element created
# that defines the remote network/s.
gw = ExternalGateway.create(name='remotegw')
gw.external_endpoint.create(name='endpoint1', address='10.10.10.10')
gw.vpn_site.create(name='remotesite', site_element=[Network('remotenet')])

# Create the remote Tunnel Endpoint using the external gateway
remote_gateway = TunnelEndpoint.create_ipsec_endpoint(gw)

RouteVPN.create_ipsec_tunnel(
    name='myvpn',
    preshared_key='abcdefgh123456789',
    local_endpoint=local_gateway,
    remote_endpoint=remote_gateway)

Create a GRE Tunnel Mode RBVPN with a remote gateway (non-SMC managed):

engine = Engine('fw')

# Enable VPN endpoint on interface 0
# Note: An interface can have multiple IP addresses in which case you
# may want to get the VPN endpoint match by address
vpn_endpoint = None
for endpoint in engine.vpn_endpoint:
    if endpoint.physical_interface.interface_id == '0':
        endpoint.update(enabled=True)
        vpn_endpoint = endpoint
        break

# Create a new Tunnel Interface for the engine
engine.tunnel_interface.add_layer3_interface(
    interface_id=3000, address='30.30.30.30', network_value='30.30.30.0/24')

tunnel_interface =  engine.tunnel_interface.get(3000)
local_endpoint = TunnelEndpoint.create_gre_tunnel_endpoint(
    endpoint=vpn_endpoint, tunnel_interface=tunnel_interface)

# Create GRE tunnel endpoint for remote gateway
remote_endpoint = TunnelEndpoint.create_gre_tunnel_endpoint(
    remote_address='10.1.1.2')

# Create the top level IPSEC tunnel to encapsulate RBVPN
policy_vpn = PolicyVPN.create(name='myIPSEC')

RouteVPN.create_gre_tunnel_mode(
    name='mytunnelvpn',
    local_endpoint=local_endpoint,
    remote_endpoint=remote_endpoint,
    policy_vpn=policy_vpn)

Create a no-encryption GRE route based VPN between two managed NGFWs:

engine1 = Layer3Firewall.create(name='engine1', mgmt_ip='1.1.1.1', mgmt_network='1.1.1.0/24')
engine1.tunnel_interface.add_layer3_interface(
    interface_id=1000,
    address='2.2.2.2',
    network_value='2.2.2.0/24')

# Obtain the 'internal endpoint' from the NGFW and enable VPN
for vpn in engine1.vpn_endpoint:
    internal_endpoint = vpn
    vpn.update(enabled=True)

tunnel_if = engine1.tunnel_interface.get(1000)
local_gateway = TunnelEndpoint.create_gre_tunnel_endpoint(
    internal_endpoint, tunnel_if)

engine2 = Layer3Firewall.create(name='engine2', mgmt_ip='1.1.1.1', mgmt_network='1.1.1.0/24')
engine2.tunnel_interface.add_layer3_interface(
    interface_id=1000,
    address='2.2.2.2',
    network_value='2.2.2.0/24')

# Obtain the 'internal endpoint' from the NGFW and enable VPN
for vpn in engine2.vpn_endpoint:
    internal_endpoint = vpn
    vpn.update(enabled=True)

tunnel_if = engine2.tunnel_interface.get(1000)
remote_gateway = TunnelEndpoint.create_gre_tunnel_endpoint(
    internal_endpoint, tunnel_if)

RouteVPN.create_gre_tunnel_no_encryption(
    name='openvpn',
    local_endpoint=local_gateway,
    remote_endpoint=remote_gateway)
class smc.vpn.route.EndpointTunnel(**meta)[source]

Bases: SubElement

An Endpoint tunnel represents the point to point connection between two IPSEC endpoints in a RouteVPN configuration. This provides access to see the point to point connections, whether the link is enabled.

enable_disable()[source]

Enable or disable the tunnel link between endpoints.

Raises:

UpdateElementFailed – failed with reason

Returns:

None

property enabled

Whether the VPN link between endpoints is enabled

Return type:

bool

class smc.vpn.route.RouteVPN(name=None, **meta)[source]

Bases: Element

Route based VPN in NGFW.

Variables:
classmethod create_geneve_mode(name, local_endpoint, remote_endpoint, geneve_vni=0, geneve_destination_port=6081, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None)[source]

Create a Geneve (Generic Network Virtualization Encapsulation) No Encryption tunnel. The Geneve packet format consists of a compact tunnel header encapsulated in UDP over either IPv4 or IPv6. :param bool enabled: to enable/disable the tunnel by default :param int geneve_destination_port: default 6081 (1-65535) :param int geneve_vni: Virtual network interface (0-16777215) :param str name: name of VPN :param TunnelEndpoint local_endpoint: the local side endpoint for

this VPN.

Parameters:
  • remote_endpoint (TunnelEndpoint) – the remote side endpoint for this VPN.

  • mtu (int) – Set MTU for this VPN tunnel (default: 0)

  • pmtu_discovery (boolean) – enable pmtu discovery (default: True)

  • ttl (int) – ttl for connections on the VPN (default: 0)

  • comment (str) – optional comment

Raises:

CreateVPNFailed – failed to create the VPN with reason

Return type:

RouteVPN

classmethod create_gre_transport_mode(*args, **kwargs)[source]

Create a transport based route VPN. This VPN type uses IPSEC for protecting the payload, therefore a VPN Profile is specified.

Parameters:
  • name (str) – name of VPN

  • local_endpoint (TunnelEndpoint) – the local side endpoint for this VPN.

  • remote_endpoint (TunnelEndpoint) – the remote side endpoint for this VPN.

  • preshared_key (str) – preshared key for RBVPN

  • monitoring_group (TunnelMonitoringGroup) – the group to place this VPN in for monitoring. (default: ‘Uncategorized’)

  • vpn_profile (VPNProfile) – VPN profile for this VPN. (default: VPN-A Suite)

  • mtu (int) – Set MTU for this VPN tunnel (default: 0)

  • pmtu_discovery (boolean) – enable pmtu discovery (default: True)

  • ttl (int) – ttl for connections on the VPN (default: 0)

  • comment (str) – optional comment

Raises:

CreateVPNFailed – failed to create the VPN with reason

Return type:

RouteVPN

classmethod create_gre_tunnel_mode(name, local_endpoint, remote_endpoint, policy_vpn, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None)[source]

Create a GRE based tunnel mode route VPN. Tunnel mode GRE wraps the GRE tunnel in an IPSEC tunnel to provide encrypted end-to-end security. Therefore a policy based VPN is required to ‘wrap’ the GRE into IPSEC.

Parameters:
  • name (str) – name of VPN

  • local_endpoint (TunnelEndpoint) – the local side endpoint for this VPN.

  • remote_endpoint (TunnelEndpoint) – the remote side endpoint for this VPN.

  • policy_vpn (PolicyVPN) – reference to a policy VPN

  • monitoring_group (TunnelMonitoringGroup) – the group to place this VPN in for monitoring. (default: ‘Uncategorized’)

  • mtu (int) – Set MTU for this VPN tunnel (default: 0)

  • pmtu_discovery (boolean) – enable pmtu discovery (default: True)

  • ttl (int) – ttl for connections on the VPN (default: 0)

  • comment (str) – optional comment

Raises:

CreateVPNFailed – failed to create the VPN with reason

Return type:

RouteVPN

classmethod create_gre_tunnel_no_encryption(name, local_endpoint, remote_endpoint, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None, gre_keepalive_period=None, gre_keepalive_retry=None)[source]

Create a GRE No Encryption route Based VPN.

Parameters:
  • name (str) – name of VPN

  • local_endpoint (TunnelEndpoint) – the local side endpoint for this VPN.

  • remote_endpoint (TunnelEndpoint) – the remote side endpoint for this VPN.

  • monitoring_group (TunnelMonitoringGroup) – the group to place this VPN in for monitoring. (default: ‘Uncategorized’)

  • mtu (int) – Set MTU for this VPN tunnel (default: 0)

  • pmtu_discovery (boolean) – enable pmtu discovery (default: True)

  • ttl (int) – ttl for connections on the VPN (default: 0)

  • gre_keepalive_period (int) – in s (1-32767s)

  • gre_keepalive_retry (int) – (0-255)

  • comment (str) – optional comment

Raises:

CreateVPNFailed – failed to create the VPN with reason

Return type:

RouteVPN

classmethod create_ipsec_tunnel(*args, **kwargs)[source]

The VPN tunnel type negotiates IPsec tunnels in the same way as policy-based VPNs, but traffic is selected to be sent into the tunnel based on routing.

Parameters:
  • name (str) – name of VPN

  • local_endpoint (TunnelEndpoint) – the local side endpoint for this VPN.

  • remote_endpoint (TunnelEndpoint) – the remote side endpoint for this VPN.

  • preshared_key (str) – required if remote endpoint is an ExternalGateway

  • monitoring_group (TunnelMonitoringGroup) – the group to place this VPN in for monitoring. Default: ‘Uncategorized’.

  • vpn_profile (VPNProfile) – VPN profile for this VPN. (default: VPN-A Suite)

  • mtu (int) – Set MTU for this VPN tunnel (default: 0)

  • pmtu_discovery (boolean) – enable pmtu discovery (default: True)

  • ttl (int) – ttl for connections on the VPN (default: 0)

  • enabled (bool) – enable the RBVPN or leave it disabled

  • comment (str) – optional comment

Raises:

CreateVPNFailed – failed to create the VPN with reason

Return type:

RouteVPN

disable()[source]

Disable this route based VPN

Returns:

None

enable()[source]

Enable this route based VPN

Returns:

None

property local_endpoint

The local endpoint for this RBVPN

Return type:

TunnelEndpoint

property remote_endpoint

The remote endpoint for this RBVPN

Return type:

TunnelEndpoint

set_preshared_key(new_key)[source]

Set the preshared key for this VPN. A pre-shared key is only present when the tunnel type is ‘VPN’ or the encryption mode is ‘transport’.

Returns:

None

set_tunnel_group(tunnel_group)[source]

Set the tunnel group for this RBVPN.

Returns:

None

property tunnel_mode

The tunnel mode for this RBVPN

Return type:

str

property tunnels

Return all tunnels for this RBVPN in case of Tunnel Type ‘VPN’. This provides access to enabling/disabling for the linked endpoints. List all tunnel mappings for this route vpn:

for tunnel in rb_vpn.tunnels:
    print(tunnel.enabled)
Return type:

SubElementCollection(EndpointTunnel)

class smc.vpn.route.RouteVPNTunnelMonitoringGroup(name=None, **meta)[source]

Bases: TunnelMonitoringGroup

Compatability class for 6.5 and earlier monitoring group entry point

class smc.vpn.route.TunnelEndpoint(gateway_ref=None, tunnel_interface_ref=None, endpoint_ref=None, ip_address=None)[source]

Bases: object

A Tunnel Endpoint represents one side of a route based VPN. Based on the RBVPN type required, you must create the local and remote endpoints and pass them into the RouteVPN create classmethods.

Variables:
classmethod create_gre_transport_endpoint(endpoint, tunnel_interface=None)[source]

Create the GRE transport mode endpoint. If the GRE transport mode endpoint is an SMC managed device, both an endpoint and a tunnel interface is required. If the GRE endpoint is an externally managed device, only an endpoint is required.

Parameters:
Return type:

TunnelEndpoint

classmethod create_gre_tunnel_endpoint(endpoint=None, tunnel_interface=None, remote_address=None)[source]

Create the GRE tunnel mode or no encryption mode endpoint. If the GRE tunnel mode endpoint is an SMC managed device, both an endpoint and a tunnel interface is required. If the endpoint is externally managed, only an IP address is required.

Parameters:
  • endpoint (InternalEndpoint,ExternalEndpoint) – the endpoint element for this tunnel endpoint.

  • tunnel_interface (TunnelInterface) – the tunnel interface for this tunnel endpoint. Required for SMC managed devices.

  • remote_address (str) – IP address, only required if the tunnel endpoint is a remote gateway.

Return type:

TunnelEndpoint

classmethod create_ipsec_endpoint(gateway, tunnel_interface=None)[source]

Create the VPN tunnel endpoint. If the VPN tunnel endpoint is an SMC managed device, both a gateway and a tunnel interface is required. If the VPN endpoint is an externally managed device, only a gateway is required.

Parameters:
Return type:

TunnelEndpoint

classmethod create_tunnel_endpoint(endpoint=None, tunnel_interface=None, remote_address=None)[source]

Create the and endpoint in tunnel mode or no encryption. If the tunnel mode endpoint is an SMC managed device, both an endpoint and a tunnel interface is required. If the endpoint is externally managed, only an IP address is required.

Parameters:
  • endpoint (InternalEndpoint,ExternalEndpoint) – the endpoint element for this tunnel endpoint.

  • tunnel_interface (TunnelInterface) – the tunnel interface for this tunnel endpoint. Required for SMC managed devices.

  • remote_address (str) – IP address, only required if the tunnel endpoint is a remote gateway.

Return type:

TunnelEndpoint

property endpoint

Endpoint is used to specify which interface is enabled for VPN. This is the InternalEndpoint property of the InternalGateway.

Note

This will only return a value if the tunnel type is GRE

Returns:

internal endpoint where VPN is enabled

Return type:

InternalEndpoint,ExternalGateway

property remote_address

Show the remote IP address configured for a GRE RBVPN using Tunnel or No Encryption Mode configurations.

property tunnel_interface

Show the tunnel interface for this TunnelEndpoint.

Returns:

interface for this endpoint

Return type:

TunnelInterface

class smc.vpn.route.TunnelMonitoringGroup(name=None, **meta)[source]

Bases: Element

A tunnel monitoring group is used to group route based VPNs for monitoring on the Home->VPN dashboard. :param str name: name tunnel group :param str comment: comment :param object/href link_usage_profile : link usage profile to use for rbvpn tunnel group

Gateways

ExternalGateway

VPN Elements are used in conjunction with Policy or Route Based VPN configurations. VPN elements consist of external gateway and VPN site settings that identify 3rd party gateways to be used as a VPN termination endpoint.

There are several ways to create an external gateway configuration. A step by step process which first creates a network element to be used in a VPN site, then creates the ExternalGatway, an ExternalEndpoint for the gateway, and inserts the VPN site into the configuration:

Network.create(name='mynetwork', ipv4_network='172.18.1.0/24')
gw = ExternalGateway.create(name='mygw')
gw.external_endpoint.create(name='myendpoint', address='10.10.10.10')
gw.vpn_site.create(name='mysite', site_element=[Network('mynetwork')])

You can also use the convenience method update_or_create on the ExternalGateway to fully provision in a single step. Note that the ExternalEndpoint and VPNSite also have an update_or_create method to limit the update to those respective configurations (SMC version 6.4.x):

>>> from smc.elements.network import Network
>>> from smc.vpn.elements import ExternalGateway
>>> network = Network.get_or_create(name='network-172.18.1.0/24', ipv4_network='172.18.1.0/24')
>>>
>>> g = ExternalGateway.update_or_create(name='newgw',
    external_endpoint=[
        {'name': 'endpoint1', 'address': '1.1.1.1', 'enabled': True},
        {'name': 'endpoint2', 'address': '2.2.2.2', 'enabled': True}],
    vpn_site=[{'name': 'sitea', 'site_element':[network]}])
>>> g
ExternalGateway(name=newgw)
>>> for endpoint in g.external_endpoint:
...   endpoint
...
ExternalEndpoint(name=endpoint1 (1.1.1.1))
ExternalEndpoint(name=endpoint2 (2.2.2.2))
>>> for site in g.vpn_site:
...   site, site.site_element
...
(VPNSite(name=sitea), [Network(name=network-172.18.1.0/24)])

In SMC version >= 6.5, you can also provide the connection_type_ref parameter when defining the external gateway:

.. note:: When calling `update_or_create` from the ExternalGateway, providing the
    parameters for external_endpoints and vpn_site is optional.
class smc.vpn.elements.ExternalGateway(name=None, **meta)[source]

Bases: Element

External Gateway defines an VPN Gateway for a non-SMC managed device. This will specify details such as the endpoint IP, and VPN site protected networks. Example of manually provisioning each step:

Network.create(name='mynetwork', ipv4_network='172.18.1.0/24')
gw = ExternalGateway.create(name='mygw')
gw.external_endpoint.create(name='myendpoint', address='10.10.10.10')
gw.vpn_site.create(name='mysite', site_element=[Network('mynetwork')])
Variables:

gateway_profile (GatewayProfile) – A gateway profile will define the capabilities (i.e. crypto) allowed for this VPN.

classmethod create(name, trust_all_cas=True, gateway_profile=None, **kwargs)[source]

Create new External Gateway

Parameters:
  • name (str) – name of test_external gateway

  • trust_all_cas (bool) – whether to trust all internal CA’s (default: True)

  • gateway_profile (GatewayProfile,href) – optional gateway profile, otherwise default

Returns:

instance with meta

Return type:

ExternalGateway

property external_endpoint

An External Endpoint is the IP based definition for the destination VPN peers. There may be multiple per External Gateway. Add a new endpoint to an existing test_external gateway:

>>> list(ExternalGateway.objects.all())
[ExternalGateway(name=cisco-remote-side), ExternalGateway(name=remoteside)]
>>> gateway.external_endpoint.create('someendpoint', '12.12.12.12')
'http://1.1.1.1:8082/6.1/elements/external_gateway/22961/external_endpoint/27467'
Return type:

CreateCollection(ExternalEndpoint)

property trust_all_cas

Gateway setting identifying whether all CA’s specified in the profile are supported or only specific ones.

Return type:

bool

classmethod update_or_create(name, external_endpoint=None, vpn_site=None, trust_all_cas=True, with_status=False)[source]

Update or create an ExternalGateway. The external_endpoint and vpn_site parameters are expected to be a list of dicts with key/value pairs to satisfy the respective elements create constructor. VPN Sites will represent the final state of the VPN site list. ExternalEndpoint that are pre-existing will not be deleted if not provided in the external_endpoint parameter, however existing elements will be updated as specified.

Parameters:
  • name (str) – name of external gateway

  • external_endpoint (list(dict)) – list of dict items with key/value to satisfy ExternalEndpoint.create constructor

  • vpn_site (list(dict)) – list of dict items with key/value to satisfy VPNSite.create constructor

  • with_status (bool) – If set to True, returns a 3-tuple of (ExternalGateway, modified, created), where modified and created is the boolean status for operations performed.

Raises:

ValueError – missing required argument/s for constructor argument

Return type:

ExternalGateway

property vpn_site

A VPN site defines a collection of IP’s or networks that identify address space that is defined on the other end of the VPN tunnel.

Return type:

CreateCollection(VPNSite)

ExternalEndpoint

class smc.vpn.elements.ExternalEndpoint(**meta)[source]

Bases: SubElement

External Endpoint is used by the External Gateway and defines the IP and other VPN related settings to identify the VPN peer. This is created to define the details of the non-SMC managed gateway. This class is a property of smc.vpn.elements.ExternalGateway and should not be called directly. Add an endpoint to existing External Gateway:

gw = ExternalGateway('aws')
gw.external_endpoint.create(name='aws01', address='2.2.2.2')

Changed in version 0.7.0: When using SMC >= 6.5, you can also provide a value for ConnectionType parameter when creating the element, for example:

gw = ExternalGateway('aws')
gw.external_endpoint.create(name='aws01', address='2.2.2.2',
                            connection_type=ConnectionType('Active'))

See also

ConnectionType

property connection_type_ref

The reference to the connection type for this external endpoint. A connection type specifies how the endpoint will behave in an active, standby or aggregate role.

Note

This will return None on SMC versions < 6.5

Return type:

ConnectionType

property contact_addresses

Contact Addresses are a mutable collection of contact addresses assigned to a supported element.

Return type:

ElementContactAddress

create(name, address=None, enabled=True, ipsec_vpn=True, nat_t=False, force_nat_t=False, dynamic=False, ike_phase1_id_type=None, ike_phase1_id_value=None, connection_type_ref=None, **kw)[source]

Create an test_external endpoint. Define common settings for that specify the address, enabled, nat_t, name, etc. You can also omit the IP address if the endpoint is dynamic. In that case, you must also specify the ike_phase1 settings.

Parameters:
  • name (str) – name of test_external endpoint

  • address (str) – address of remote host

  • enabled (bool) – True|False (default: True)

  • ipsec_vpn (bool) – True|False (default: True)

  • nat_t (bool) – True|False (default: False)

  • force_nat_t (bool) – True|False (default: False)

  • dynamic (bool) – is a dynamic VPN (default: False)

  • ike_phase1_id_type (int) – If using a dynamic endpoint, you must set this value. Valid options: 0=DNS name, 1=Email, 2=DN, 3=IP Address

  • ike_phase1_id_value (str) – value of ike_phase1_id. Required if ike_phase1_id_type and dynamic set.

  • connection_type_ref (ConnectionType) – SMC>=6.5 setting. Specifies the mode for this endpoint; i.e. Active, Aggregate, Standby. (Default: Active)

Raises:

CreateElementFailed – create element with reason

Returns:

newly created element

Return type:

ExternalEndpoint

enable_disable()[source]

Enable or disable this endpoint. If enabled, it will be disabled and vice versa.

Returns:

None

enable_disable_force_nat_t()[source]

Enable or disable NAT-T on this endpoint. If enabled, it will be disabled and vice versa.

Returns:

None

property enabled

Whether this endpoint is enabled.

Return type:

bool

property force_nat_t

Whether force_nat_t is enabled on this endpoint.

Return type:

bool

classmethod update_or_create(external_gateway, name, with_status=False, **kw)[source]

Update or create external endpoints for the specified external gateway. An ExternalEndpoint is considered unique based on the IP address for the endpoint (you cannot add two external endpoints with the same IP). If the external endpoint is dynamic, then the name is the unique identifier.

Parameters:
  • external_gateway (ExternalGateway) – external gateway reference

  • name (str) – name of the ExternalEndpoint. This is only used as a direct match if the endpoint is dynamic. Otherwise the address field in the keyword arguments will be used as you cannot add multiple external endpoints with the same IP address.

  • with_status (bool) – If set to True, returns a 3-tuple of (ExternalEndpoint, modified, created), where modified and created is the boolean status for operations performed.

  • kw (dict) – keyword arguments to satisfy ExternalEndpoint.create constructor

Raises:
Returns:

if with_status=True, return tuple(ExternalEndpoint, created). Otherwise return only ExternalEndpoint.

VPNSite

class smc.vpn.elements.VPNSite(**meta)[source]

Bases: SubElement

VPN Site information for an internal or test_external gateway Sites are used to encapsulate hosts or networks as ‘protected’ for VPN policy configuration.

Create a new vpn site for an engine:

engine = Engine('myengine')
network = Network('network-192.168.5.0/25') #get resource
engine.vpn.sites.create('newsite', [network.href])

Sites can also be added to ExternalGateway’s as well:

extgw = ExternalGateway('mygw')
extgw.vpn_site.create('newsite', [Network('foo')])

This class is a property of smc.core.engine.InternalGateway or smc.vpn.elements.ExternalGateway and should not be accessed directly.

Variables:

gateway (InternalGateway,ExternalGateway) – gateway referenced

add_site_element(element)[source]

Add a site element or list of elements to this VPN.

Parameters:

element (list(str,Network)) – list of Elements or href’s of vpn site elements

Raises:

UpdateElementFailed – fails due to reason

Returns:

None

create(name, site_element)[source]

Create a VPN site for an internal or external gateway

Parameters:
  • name (str) – name of site

  • site_element (list[str,Element]) – list of protected networks/hosts

Raises:

CreateElementFailed – create element failed with reason

Returns:

href of new element

Return type:

str

property site_element

Site elements for this VPN Site.

Returns:

Elements used in this VPN site

Return type:

list(Element)

classmethod update_or_create(external_gateway, name, site_element=None, with_status=False)[source]

Update or create a VPN Site elements or modify an existing VPN site based on value of provided site_element list. The resultant VPN site end result will be what is provided in the site_element argument (can also be an empty list to clear existing).

Parameters:
  • external_gateway (ExternalGateway) – The external gateway for this VPN site

  • name (str) – name of the VPN site

  • site_element (list(str,Element)) – list of resolved Elements to add to the VPN site

  • with_status (bool) – If set to True, returns a 3-tuple of (VPNSite, modified, created), where modified and created is the boolean status for operations performed.

Raises:

ElementNotFound – ExternalGateway or unresolved site_element

Other Elements

Other elements associated with VPN configurations

GatewaySettings

class smc.vpn.elements.GatewaySettings(name=None, **meta)[source]

Bases: Element

Gateway settings define various VPN related settings that are applied at the firewall level such as negotiation timers and mobike settings. A gateway setting is a property of an engine:

engine = Engine('myfw')
engine.vpn.gateway_settings
classmethod create(name, negotiation_expiration=200000, negotiation_retry_timer=500, negotiation_retry_max_number=32, negotiation_retry_timer_max=7000, certificate_cache_crl_validity=90000, mobike_after_sa_update=False, mobike_before_sa_update=False, mobike_no_rrc=True)[source]

Create a new gateway setting profile.

Parameters:
  • name (str) – name of profile

  • negotiation_expiration (int) – expire after (ms)

  • negotiation_retry_timer (int) – retry time length (ms)

  • negotiation_retry_max_num (int) – max number of retries allowed

  • negotiation_retry_timer_max (int) – maximum length for retry (ms)

  • certificate_cache_crl_validity (int) – cert cache validity (seconds)

  • mobike_after_sa_update (boolean) – Whether the After SA flag is set for Mobike Policy

  • mobike_before_sa_update (boolean) – Whether the Before SA flag is set for Mobike Policy

  • mobike_no_rrc (boolean) – Whether the No RRC flag is set for Mobike Policy

Raises:

CreateElementFailed – failed creating profile

Returns:

instance with meta

Return type:

GatewaySettings

GatewayNode

class smc.vpn.policy.GatewayNode(**meta)[source]

Bases: SubElement

Top level VPN gateway node operations. A gateway node is characterized by a Central Gateway, Satellite Gateway or Mobile Gateway node. This template class will return these as a collection. Gateway Node references need to be obtained from a VPN Policy reference:

>>> vpn = PolicyVPN('sg_vm_vpn')
>>> vpn.open()
>>> for gw in vpn.central_gateway_node.all():
...   list(gw.enabled_sites)
...
[GatewayTreeNode(name=Automatic Site for sg_vm_vpn)]
>>> vpn.close()
property disabled_sites

Return a collection of VPN Site elements that are disabled for this VPN gateway.

Return type:

SubElementCollection(VPNSite)

property enabled_sites

Return a collection of VPN Site elements that are enabled for this VPN gateway.

Return type:

SubElementCollection(VPNSite)

property name

Get the name from the gateway_profile reference

GatewayProfile

class smc.vpn.elements.GatewayProfile(name=None, **meta)[source]

Bases: Element

Gateway Profiles describe the capabilities of a Gateway, i.e. supported cipher, hash, etc. Gateway Profiles of Internal Gateways are read-only and computed from the firewall version and FIPS mode. Gateway Profiles of External Gateways are user-defined.

property capabilities

Capabilities are all boolean values that specify features or cryptography features to enable or disable on this gateway profile.To update or change these values, you can use the built in update with a key of ‘capabilities’ and dict value of attributes, i.e:

gateway_profile = GatewayProfile('myGatewayProfile')
pprint(gateway_profile.capabilities) # <-- show all options
gateway_profile.update(capabilities={'sha2_for_ipsec': True, 'sha2_for_ike': True})
Return type:

dict

classmethod create(name, capabilities=None, comment=None)[source]

Create new GatewayProfile :param str name: name of the gateway profile. :param dict capabilities: Capabilities are all boolean values that specify features or cryptography features to enable or disable on this gateway profile. Following additional boolean attributes can be set:

sha2_ike_hash_length sha2_ipsec_hash_length aes128_for_ike aes128_for_ipsec aes256_for_ike aes256_for_ipsec aes_gcm_256_for_ipsec aes_gcm_for_ipsec aes_xcbc_for_ipsec aggressive_mode ah_for_ipsec blowfish_for_ike blowfish_for_ipsec des_for_ike des_for_ipsec dh_group_14_for_ike dh_group_15_for_ike dh_group_16_for_ike dh_group_17_for_ike dh_group_18_for_ike dh_group_19_for_ike dh_group_1_for_ike dh_group_20_for_ike dh_group_21_for_ike dh_group_2_for_ike dh_group_5_for_ike dss_signature_for_ike ecdsa_signature_for_ike esp_for_ipsec external_for_ipsec forward_client_vpn forward_gw_to_gw_vpn ike_v1 ike_v2 ipcomp_deflate_for_ipsec main_mode md5_for_ike md5_for_ipsec null_for_ipsec pfs_dh_group_14_for_ipsec pfs_dh_group_15_for_ipsec pfs_dh_group_16_for_ipsec pfs_dh_group_17_for_ipsec pfs_dh_group_18_for_ipsec pfs_dh_group_19_for_ipsec pfs_dh_group_1_for_ipsec pfs_dh_group_20_for_ipsec pfs_dh_group_21_for_ipsec pfs_dh_group_2_for_ipsec pfs_dh_group_5_for_ipsec pre_shared_key_for_ike rsa_signature_for_ike sa_per_host sa_per_net sha1_for_ike sha1_for_ipsec sha2_for_ike sha2_for_ipsec triple_des_for_ike triple_des_for_ipsec vpn_client_dss_signature_for_ike vpn_client_ecdsa_signature_for_ike vpn_client_rsa_signature_for_ike vpn_client_sa_per_host vpn_client_sa_per_net

Parameters:

comment (str) – comment message

Return GatewayProfile:

instance with metadata

Return type:

GatewayProfile

VPNProfile

class smc.vpn.elements.VPNProfile(name=None, **meta)[source]

Bases: Element

A VPN Profile is used to specify cryptography and other Policy VPN specific features. Every PolicyVPN requires a VPNProfile. The system will provide common profiles labeled as System Element that can be used without modification.

property capabilities

Capabilities are all boolean values that specify features or cryptography features to enable or disable on this VPN profile. To update or change these values, you can use the built in update with a key of ‘capabilities’ and dict value of attributes, i.e:

vpn = VPNProfile('mySecureVPN')
pprint(vpn.capabilities) # <-- show all options
vpn.update(capabilities={'sha2_for_ipsec': True, 'sha2_for_ike': True})
Return type:

dict

classmethod create(name, capabilities=None, cn_authentication_for_mobile_vpn=False, disable_anti_replay=False, disable_path_discovery=False, hybrid_authentication_for_mobile_vpn=False, keep_alive=False, preshared_key_for_mobile_vpn=False, sa_life_time=86400, sa_to_any_network_allowed=False, trust_all_cas=True, trusted_certificate_authority=[], tunnel_life_time_kbytes=0, tunnel_life_time_seconds=28800, comment=None, **kw)[source]

Create a VPN Profile. There are a variety of kwargs that can be and also retrieved about a VPN Profile. Keyword parameters are specified below. To access a valid keyword, use the standard dot notation.

To validate supported keyword attributes for a VPN Profile, consult the native SMC API docs for your version of SMC. You can also optionally print the element contents after retrieving the element and use update to modify the element.

For example:

vpn = VPNProfile.create(name='mySecureVPN', comment='test comment')
pprint(vars(vpn.data))

Then once identifying the attribute, update the relevant top level attribute values:

vpn.update(sa_life_time=128000, tunnel_life_time_seconds=57600)
Parameters:
  • name (str) – Name of profile

  • capabilities (dict) – Capabilities are all boolean values that specify features or cryptography features to enable or disable on this VPN profile. To update or change these values, you can use the built in update with a key of ‘capabilities’ and dict value of attributes

  • cn_authentication_for_mobile_vpn (bool) – Indicates whether CN authentification is allowed or not, for a client using a certificate authentication.

  • disable_anti_replay (bool) – IPSEC_DISABLE_ANTI_REPLAY flag value

  • disable_path_discovery (bool) – NO_PATH_MTU_DISCOVERY flag value.

  • hybrid_authentication_for_mobile_vpn (bool) – Indicates whether Hybrid authentification is allowed or not, for a client using a certificate authentication.

  • keep_alive (bool) – Keep-alive option

  • preshared_key_for_mobile_vpn (bool) – Indicates whether preshared key authentification is allowed or not,together with a client certificate authentication.,

  • sa_life_time (int) – IKE Lifetime in seconds

  • sa_to_any_network_allowed (bool) – IPSEC_SA_To_ANY flag value.

  • trust_all_cas (bool) – Whether to trust all certificate authorities or not

  • trusted_certificate_authority (list) – List of trusted certificate authorities for this profile (if the trust all CAs attribute has been set to false)

  • tunnel_life_time_kbytes (int) – IPsec Lifetime in KBytes.

  • tunnel_life_time_seconds (int) – IPsec Lifetime in seconds.

  • comment (str) – optional comment

Raises:

CreateElementFailed – failed creating element with reason

Return type:

VPNProfile

GatewayTreeNode

class smc.vpn.policy.GatewayTreeNode(**meta)[source]

Bases: SubElement

Gateway Tree node is a list of VPN Site elements returned when retrieving a VPN policies enabled or disabled site list. These provide an enable_disable link to the VPN site.

for gw in policy.central_gateway_node.all():
    for site in list(gw.enabled_sites):
        site.enable_disable()
enable_disable()[source]

Enable or disable this VPN Site from within the VPN policy context.

Raises:

PolicyCommandFailed – enabling or disabling failed

Returns:

None

property vpn_site

The VPN Site element associated with this gateway

:return VPNSite element :rtype: VPNSite

GatewayTunnel

class smc.vpn.policy.GatewayTunnel(**meta)[source]

Bases: SubElement

A gateway tunnel represents the point to point connection between two IPSEC endpoints in a PolicyVPN configuration. The tunnel arrangement is based on whether the nodes are placed as a central gateway or a satellite gateway. This provides access to see the point to point connections, whether the link is enabled, and setting the presharred key.

Note

Setting the preshared key is only required if using an ExternalGateway element as one side of the VPN. Preshared keys are generated automatically but read only, therefore if two gateways are internally managed by SMC, the key is generated and shared between the gateways automatically. However for external gateways, you must set a new key to provide the same value to the remote gateway.

enable_disable()[source]

Enable or disable the tunnel link between endpoints.

Raises:

UpdateElementFailed – failed with reason

Returns:

None

property enabled

Whether the VPN link between endpoints is enabled

Return type:

bool

property endpoint_tunnels

Return all Endpoint tunnels for this gateway tunnel. A tunnel is defined as two end points within the VPN topology. Endpoints are automatically configureed based on whether they are a central gateway or satellite gateway. This provides access to enabling/disabling and setting the preshared key for the linked endpoints. List all Endpoint tunnel mappings for this policy vpn:

for tunnel in policy.tunnels:
    tunnela = tunnel.tunnel_side_a
    tunnelb = tunnel.tunnel_side_b
    print(tunnela.gateway)
    print(tunnelb.gateway)
    for endpointtunnel in tunnel.endpoint_tunnels:
        print(endpointtunnel)
Return type:

SubElementCollection(GatewayTunnel)

preshared_key(key)[source]

Set a new preshared key for the IPSEC endpoints.

Parameters:

key (str) – shared secret key to use

Raises:

UpdateElementFailed – fail with reason

Returns:

None

property tunnel_side_a

Return the gateway node for tunnel side A. This will be an instance of GatewayNode.

Return type:

GatewayNode

property tunnel_side_b

Return the gateway node for tunnel side B. This will be an instance of GatewayNode.

Return type:

GatewayNode

ConnectionType

class smc.vpn.elements.ConnectionType(name=None, **meta)[source]

Bases: Element

New in version 0.7.0: Introduced in SMC >= 6.5 to provide a way to group VPN element types

ConnectionTypes are used in various VPN configurations such as an ExternalGateway endpoint element to define how the endpoint should be treated, i.e. active, aggregate or standby.

Variables:
  • connectivity_group (int) – connectivity group for this connection type

  • mode (str) – mode, valid options: ‘active’, ‘aggregate’, ‘standby’

classmethod create(name, mode='active', connectivity_group=1, link_type_ref=None, comment=None)[source]

Create a connection type for an VPN endpoint.

ConnectionType.create(name='mygroup', mode='standby')
Parameters:
  • name (str) – name of connection type

  • mode (str) – mode of connection type, valid options active, standby, aggregate

  • connectivity_group (int) – integer used to group multiple connection types into a single monitoring group (default: 1)

  • link_type_ref (str) – Indicates link type for the connections. Not Required.

  • comment (str) – optional comment

Raises:

CreateElementFailed – reason for failure

Return type:

ConnectionType

VPNBrokerDomain

class smc.vpn.elements.VPNBrokerDomain(name=None, **meta)[source]

Bases: Element

VPN Broker Domain element defines the virtual network that contains the VPN Broker gateway and the VPN Broker members.

classmethod create(name, mac_address_prefix, file_ref, comment=None, **kw)[source]

Create a VPN broker domain.

VPNBrokerDomain.create(

name=”vpn1”, mac_address_prefix=”06:02:02”, file_ref=myfile.href

)

Parameters:
  • name (str) – name of vpn broker domain

  • mac_address_prefix (str) – unique identifier for the VPN Broker Domain in MAC address format. The length must be three octets. The first octet must be even. The address must be a unique unicast MAC address.

:param file_ref href or VPNBrokerConfigFile element

Raises:

CreateElementFailed – reason for failure

Return type:

VPNBrokerDomain

VPNBrokerConfigFile

class smc.vpn.elements.VPNBrokerConfigFile(name=None, **meta)[source]

Bases: Element

exported VPN Broker Domain element from the NGFW Manager

classmethod create(name, comment=None, **kw)[source]

Create a VPN broker config file

VPNBrokerConfigFile.create(name=”myfile”)

Parameters:

name (str) – name of config file

Raises:

CreateElementFailed – reason for failure

Return type:

VPNBrokerConfigFile

Collections Reference

Collections module provides interfaces to obtain resources from this API and provides searching mechanisms to auto-load resources into the correct class type.

An ElementCollection is bound to smc.base.model.Element as the objects class property and provides the ability to use an element as the base for iterating elements of that type:

for hosts in Host.objects.all():
    ...

SubElementCollections are used when references to element data require a fetch from the SMC, but these element references do not have a direct SMC entry point.

See Collections for examples on search capabilities.

ElementCollection

class smc.base.collection.ElementCollection(**params)[source]

ElementCollection is generated dynamically from the CollectionManager and provides methods to obtain data from the SMC. Filters can be chained together to generate more complex queries. Each time a filter is added, a clone is returned to preserve the parent query parameters.

Chaining filters do not affect the parent iterator:

>>> iterator = Host.objects.iterator()    <-- Obtain iterator from CollectionManager
>>> query1 = iterator.filter('10.10.10.1')
>>> query1._params, query1._iexact
({'filter': '10.10.10.1', 'exact_match': False, 'filter_context': 'router'}, None)
>>> query2 = query1.limit(2)
>>> query2._params, query2._iexact
({'filter': '10.10.10.1', 'exact_match': False, 'filter_context': 'router', 'limit': 2},
  None)
>>> query3 = query2.filter(address='10.10.10.1')
>>> query3._params, query3._iexact
({'filter': '10.10.10.1', 'exact_match': False, 'filter_context': 'router', 'limit': 2},
 {'address': '10.10.10.1'})

Searcb operations can access a collection directly through chained syntax:

>>> for router in Router.objects.filter('192.168'):
...   print(router)
...
Router(name=router-192.168.19.241)
Router(name=router-192.168.21.241)
Router(name=router-192.168.5.241)
Router(name=router-192.168.15.241)

Adding additional filtering via kwargs:

>>> print(list(Router.objects.filter(address='10.10.10.1')))
[Router(name=Router-10.10.10.1)]

Checking if items from the query exist before accessing:

>>> query1 = iterator.filter('10.10.10.1')
>>> if query1.exists():
...   list(query1.all())
...
[Router(name=Router-110.10.10.10), Router(name=Router-10.10.10.10),
 Router(name=Router-10.10.10.1)]

Helper methods first, last and exists are provided to simplify retrieving a result from the collection:

>>> query1 = iterator.filter('10.10.10.1')
>>> list(query1)
[Router(name=Router-110.10.10.10), Router(name=Router-10.10.10.10),
 Router(name=Router-10.10.10.1)]
>>> query1.first()
Router(name=Router-110.10.10.10)
>>> query1.last()
Router(name=Router-10.10.10.1)
>>> query1.count()
3
>>> query2 = query1.filter(address='10.10.10.1')  # change filter to kwarg
>>> list(query2)
[Router(name=Router-10.10.10.1)]

Note

exists does not perform filtering when using filter_key. Results on filter(kwargs) are only done by retrieving the list of results or iterating.

all()[source]

Retrieve all elements based on element type. When using the all option, any filters are automatically removed.

Returns:

ElementCollection

batch(num)[source]

Iterator returning results in batches. When making more general queries that might have larger results, specify a batch result that should be returned with each iteration.

Parameters:

num (int) – number of results per iteration

Returns:

iterator holding list of results

between(start, end)[source]

Specify a batch of records to return. Start and end correlate to which records to return from a batch. Convenience method to capture only a specific number of records, i.e:

>>> objects = situation.objects.between(1, 2)
>>> print(list(objects))
>>>
[InspectionSituation(name=MySQL_Oracle-MySQL-Dumpfile-DLL-Upload)]

Note

Limit is ignored if also chained to the iterator query.

Parameters:
  • start (str,int) – starting record

  • end (str,int) – ending record

Returns:

ElementCollection

count()[source]

Return number of results

Return type:

int

exists()[source]

Returns True if the query contains any results, and False if not. This is handy for checking existence without having to iterate.

>>> host = Host.objects.filter('1.1.1.1')
>>> if host.exists():
...   print(host.first())
...
Host(name=hax0r)
Return type:

bool

filter(*filter, **kw)[source]

Filter results for specific element type.

keyword arguments can be used to specify a match against the elements attribute directly. It’s important to note that if the search filter contains a / or -, the SMC will only search the name and comment fields. Otherwise other key fields of an element are searched. In addition, SMC searches are a ‘contains’ search meaning you may return more results than wanted. Use a key word argument to specify the elements attribute and value expected.

>>> list(Router.objects.filter('10.10.10.1'))
[Router(name=Router-110.10.10.10), Router(name=Router-10.10.10.10),
 Router(name=Router-10.10.10.1)]
>>> list(Router.objects.filter(address='10.10.10.1'))
[Router(name=Router-10.10.10.1)]
Parameters:
  • filter (str) – any parameter to attempt to match on. For example, if this is a service, you could match on service name ‘http’ or ports of interest, ‘80’.

  • exact_match (bool) – Can be passed as a keyword arg. Specifies whether the match needs to be exact or not (default: False)

  • case_sensitive (bool) – Can be passed as a keyword arg. Specifies whether the match is case sensitive or not. (default: True)

  • kw – keyword args can specify an attribute=value to use as an exact match against the elements attribute.

Returns:

ElementCollection

first()[source]

Returns the first object matched or None if there is no matching object.

>>> iterator = Host.objects.iterator()
>>> c = iterator.filter('kali')
>>> if c.exists():
>>>    print(c.count())
>>>    print(c.first())
7
Host(name=kali67)

If results are not needed and you only 1 result, this can be called from the CollectionManager:

>>> Host.objects.first()
Host(name=SMC)
Returns:

element or None

last()[source]

Returns the last object matched or None if there is no matching object.

>>> iterator = Host.objects.iterator()
>>> c = iterator.filter('kali')
>>> if c.exists():
>>>    print(c.last())
Host(name=kali-foo)
Returns:

element or None

limit(count)[source]

Limit provides the ability to limit the number of results returned from the collection.

Parameters:

count (int) – number of records to page

Returns:

ElementCollection

class smc.base.collection.CollectionManager(resource)[source]

CollectionManager takes a class type as input and dynamically creates an ElementCollection for that class. All classes of type Element have an objects property which returns a manager. You can consume the manager as a re-usable iterator or just called it and it’s methods directly.

To get an iterator object that can be re-used, obtain an iterator() from the manager:

it = Host.objects.iterator()
it.filter(....)
...

Or more simply call the managers proxied methods to return the ElementCollection for the class type it was called for:

>>> from smc.elements.network import Host
>>> for host in Host.objects.all():
...   host
...
Host(name=IGMP v3)
Host(name=ALL-PIM-ROUTERS)
Host(name=Microsoft Lync Online Servers)
...
Returns:

CollectionManager

all()[source]

Retrieve all elements based on element type. When using the all option, any filters are automatically removed.

Returns:

ElementCollection

batch(num)[source]

Iterator returning results in batches. When making more general queries that might have larger results, specify a batch result that should be returned with each iteration.

Parameters:

num (int) – number of results per iteration

Returns:

iterator holding list of results

between(start, end)[source]

Specify a batch of records to return. Start and end correlate to which records to return from a batch. Convenience method to capture only a specific number of records, i.e:

>>> objects = situation.objects.between(1, 2)
>>> print(list(objects))
>>>
[InspectionSituation(name=MySQL_Oracle-MySQL-Dumpfile-DLL-Upload)]

Note

Limit is ignored if also chained to the iterator query.

Parameters:
  • start (str,int) – starting record

  • end (str,int) – ending record

Returns:

ElementCollection

filter(*filter, **kw)[source]

Filter results for specific element type.

keyword arguments can be used to specify a match against the elements attribute directly. It’s important to note that if the search filter contains a / or -, the SMC will only search the name and comment fields. Otherwise other key fields of an element are searched. In addition, SMC searches are a ‘contains’ search meaning you may return more results than wanted. Use a key word argument to specify the elements attribute and value expected.

>>> list(Router.objects.filter('10.10.10.1'))
[Router(name=Router-110.10.10.10), Router(name=Router-10.10.10.10),
 Router(name=Router-10.10.10.1)]
>>> list(Router.objects.filter(address='10.10.10.1'))
[Router(name=Router-10.10.10.1)]
Parameters:
  • filter (str) – any parameter to attempt to match on. For example, if this is a service, you could match on service name ‘http’ or ports of interest, ‘80’.

  • exact_match (bool) – Can be passed as a keyword arg. Specifies whether the match needs to be exact or not (default: False)

  • case_sensitive (bool) – Can be passed as a keyword arg. Specifies whether the match is case sensitive or not. (default: True)

  • kw – keyword args can specify an attribute=value to use as an exact match against the elements attribute.

Returns:

ElementCollection

first()[source]

Returns the first object matched or None if there is no matching object.

>>> iterator = Host.objects.iterator()
>>> c = iterator.filter('kali')
>>> if c.exists():
>>>    print(c.count())
>>>    print(c.first())
7
Host(name=kali67)

If results are not needed and you only 1 result, this can be called from the CollectionManager:

>>> Host.objects.first()
Host(name=SMC)
Returns:

element or None

iterator(**kwargs)[source]

Return an iterator from the collection manager. The iterator can be re-used to chain together filters, each chaining event will be it’s own unique element collection.

Returns:

ElementCollection

limit(count)[source]

Limit provides the ability to limit the number of results returned from the collection.

Parameters:

count (int) – number of records to page

Returns:

ElementCollection

SubElementCollection

class smc.base.collection.SubElementCollection(href, cls)[source]

Collection class providing an iterable interface to sub elements referenced from a top level Element resource. Return types for this collection will be based on the class where the collection was obtained. Elements returned will be serialized into their Element types and only contain the top level meta for each element. The element cache will only be inflated (resulting in an additional query) if an operation is performed that requires the data (cache) attribute.

Helper methods are provided to simplify fetching from the collection without having to iterate and code the matching yourself. Fetching from the collection has the limitation that only the returned name field is used to find a match (to prevent inflating every element before it is needed). If you want to match an available attribute in the resulting class that requires the elements full json, use a loop to attempt your match.

Example of using SubElementCollection results to obtain matches from the collection:

>>> from smc.administration.system import System
>>> system = System()
>>> upgrades = system.engine_upgrade()
>>> upgrades
EngineUpgradeCollection(items: 29)
>>> list(upgrades)
[EngineUpgrade(name=Security Engine upgrade 6.1.2 build 17037 for x86-64),
 EngineUpgrade(name=Security Engine upgrade 6.2.3 build 18067 for x86-64),  ....]
>>> upgrades.get(5)
EngineUpgrade(name=Security Engine upgrade 5.8.8 build 12093 for i386)
>>> upgrades.get_contains('6.2')
EngineUpgrade(name=Security Engine upgrade 6.2.3 build 18067 for x86-64)
>>> upgrades.get_contains('6.1')
EngineUpgrade(name=Security Engine upgrade 6.1.2 build 17037 for x86-64)
>>> upgrades.get_all_contains('6.2')
[EngineUpgrade(name=Security Engine upgrade 6.2.3 build 18067 for x86-64),
 EngineUpgrade(name=Security Engine upgrade 6.2.2 build 18062 for x86-64), ...]
>>>
Raises:

FetchElementFailed – If the resource could not be retrieved

all()[source]

Generator returning collection for sub element types. Return full contents as list or iterate through each.

Returns:

element type based on collection

Return type:

list(SubElement)

count()[source]

Return the number of results in this collection

Returns:

int

get(index)[source]

Get the element by index. If index is out of bounds for the internal list, None is returned. Indexes cannot be negative.

Parameters:

index (int) – retrieve element by positive index in list

Return type:

SubElement or None

get_all_contains(value, case_sensitive=True)[source]

A partial match on the name field. Does an in comparsion to elements by the meta name field. Returns all elements that match the specified value.

See also

get_contains() for returning only a single item.

Parameters:
  • value (str) – searchable string for contains match

  • case_sensitive (bool) – whether the match should consider case (default: True)

Returns:

element or empty list

Return type:

list(SubElement)

get_contains(value, case_sensitive=True)[source]

A partial match on the name field. Does an in comparsion to elements by the meta name field. Sub elements created by SMC will generally have a descriptive name that helps to identify their purpose. Returns only the first entry matched even if there are multiple.

See also

get_all_contains() to return all matches

Parameters:
  • value (str) – searchable string for contains match

  • case_sensitive (bool) – whether the match should consider case (default: True)

Return type:

SubElement or None

get_exact(value)[source]

Get an element using an exact match based on the elements meta name field. The SMC is case sensitive so the name will need to honor the case for a valid value match.

See also

get_contains() and get_all_contains() for partial matching

Parameters:

value (str) – name to match

Return type:

SubElement or None

CreateCollection

class smc.base.collection.CreateCollection(href, cls)[source]

Bases: SubElementCollection

A CreateCollection extends SubElementCollection by dynamically proxying the elements create method into the collection. This provides a simplified way to create sub elements and also iterate through existing.

For example, obtaining VPN Sites from an engine returns a CreateCollection so existing sites can be iterated while still being able to create new sites:

>>> engine = Engine('dingo')
>>> print(engine.vpn.sites)
<smc.base.collection.VPNSite object at 0x1098a9ed0>
>>> print(help(engine.vpn.sites))
Help on VPNSite in module smc.base.collection object:

class VPNSite(CreateCollection)
 |  Method resolution order:
 |      VPNSite
 |      CreateCollection
 |      SubElementCollection
 |      __builtin__.object
 |
 |  Methods defined here:
 |
 |  create(self, name, site_element) from smc.vpn.elements.VPNSite
 |      Create a VPN site for an internal or external gateway
 |
 |      :param str name: name of site
 |      :param list site_element: list of protected networks/hosts
 |      :type site_element: list[str,Element]
 |      :raises CreateElementFailed: create element failed with reason
 |      :return: href of new element
 |      :rtype: str
 |
 ....

List existing sites:

list(engine.vpn.sites.all())

Creating new VPN sites:

engine.vpn.sites.create('mynewsite')
create(*args, **kwargs)[source]

The create function from the sub element is proxied by this collections class to provide the iterable functionality from the parent container, but also protected access to the create method of the instance.

RuleCollection

smc.base.collection.rule_collection(href, cls)[source]

Rule collections insert a create create_insert_point and create_rule_section method into the collection. This collection type is returned when accessing rules through a reference, as:

policy = FirewallPolicy('mypolicy')
policy.fw_ipv4_access_rules.create(....)
policy.fw_ipv4_access_rules.create_rule_section(...)
policy.fw_ipv4_access_rules.create_insert_point(...)

See the class types documentation, or use help():

print(help(policy.fw_ipv4_access_rules))
Return type:

SubElementCollection

BaseIterable

Common structures

class smc.base.structs.BaseIterable(items)[source]

A collections container that provides a pre-filled container. This container type is used when an element retrieval returns all of an elements data in a single query and will contain multiple values for the same serialized type. Elements can be retrieved from the container through iteration, slicing, or by using get and providing either the index or an attribute / value pair.

If subclassing, it may be useful to override get to provide a restricted interface to common attributes to fetch.

Examples:

>>> for status in engine.nodes[0].interface_status:
...   status
...
InterfaceStatus(aggregate_is_active=False, ....

By index:

>>> engine.nodes[0].interface_status[1]

Slicing:

>>> engine.nodes[0].interface_status[1:5:2]
>>> engine.nodes[0].interface_status[::-1]

Using get by index or attribute:

>>> engine.nodes[0].interface_status.get(1)
>>> engine.nodes[0].interface_status.get(interface_id=2)
Parameters:

item (iterable) – items for which to perform iteration. Can be another class with an __iter__ method also to chain iterators.

all()[source]

Return the iterable as a list

count()[source]

Return the number of entries

Return type:

int

get(*args, **kwargs)[source]

Get an element from the iterable by an arg or kwarg. Args can be a single positional argument that is an index value to retrieve. If the specified index is out of range, None is returned. Otherwise use kwargs to provide a key/value. The key is expected to be a valid attribute of the iterated class. For example, to get an element that has a attribute name of ‘foo’, pass name=’foo’.

Raises:

ValueError – An argument was missing

Returns:

the specified item, type is based on what is returned by this iterable, may be None

SerializedIterable

class smc.base.structs.SerializedIterable(items, model)[source]

Bases: BaseIterable

A pre-serialized list of elements. This is used when it’s easier to provide a pre-serialized class as long as all elements are of the same type.

Parameters:
  • item (iterable) – items for which to perform iteration. Can be another class with an __iter__ method also to chain iterators.

  • model – optional class to serialize each iteration.

Monitoring

Module that controls aspects of the getting Monitoring Status To get Monitoring Status for VPN and tunnels, do:

>>> vpn = PolicyVPN("Corporate VPN")
>>> status = MonitoringStatus.get_status(href=vpn.href)
>>> print("vpn status monitoring={}".format(status))
vpn status monitoring=VPNStatus=>_health_in_percent = 69, _jitter_in_ms = 3, _latency_in_ms = 71

>>> # get tunnel status in result
>>> for sub_status in status.result:
>>>     sub_status = MonitoringStatus.get_status(href=sub_status.get("href"))
>>>     print("tunnel status monitoring={}".format(sub_status))
...
tunnel status monitoring=VPNGatewayTunnelStatus=>_gatewayA = Helsinki VPN Gateway, _gatewayB =..
...
class smc.administration.monitoring_status.EngineNodeStatus(**data)[source]

Bases: MonitoringStatus

This represents the Node Status. For a node, this structure describes the state, version, current policy, … of the specified Node.

property active_policy
Returns:

The Currently Active Policy.

Return type:

str

property active_policy_ref
Returns:

The reference to Currently Active Policy.

Return type:

Policy

property configuration_status
Returns:

The Configuration status:

-Initial no initial configuration file is yet generated. -Declared initial configuration file is generated. -Configured initial configuration is done with the engine. -Installed policy is installed on the engine. :rtype: str

property dyn_up
Returns:

The dynamic update package received.

Return type:

str

property engine_node_status
Returns:

The engine status (“Not Monitored”/”Unknown”/”Online”/”Going Online”/

“Locked Online”/”Going Locked Online”/”Offline”/”Going Offline”/”Locked Offline”/ “Going Locked Offline”/”Standby”/”Going Standby”/”No Policy Installed” :rtype: str

property hw_info
Returns:

The information about the hardware.

Return type:

str

property installed_policy_ref
Returns:

The reference to Last Uploaded Policy.

Return type:

Policy

property last_upload_time
Returns:

The Upload Time of the Last Uploaded Policy.

Return type:

str

property local_alternative_policies
Returns:

The Local Alternative Policies.

Return type:

list str

property local_alternative_policy_activation_time
Returns:

The timestamp when Active Policy was activated, if it is a Local Alternative

Policy. :rtype: long

property master_node

Used by Virtual Firewall Node :return: master node. :rtype: MasterNode

property platform
Returns:

The engine platform.

Return type:

str

property version
Returns:

The engine version.

Return type:

str

class smc.administration.monitoring_status.MonitoringStatus(**data)[source]

Bases: object

MonitoringStatus represents the base class for all statuses returned by get_monitoring_status(href) for the element href Valid attributes (read-only) are:

Variables:
  • name – name of the element described by href

  • monitoring_state

    INITIAL For an Engine Node: Status not yet received.

    For a Composite Status: Composite Status value is not yet computed.

    READY For an Engine Node: Status is received.

    For a Composite Status: Composite Status value is computed.

    NO_STATUS For an Engine Node: No status received for the node during initial timeout. TIMEOUT For an Engine Node: Status was not received in time. ERROR Not used. SERVER_ERROR For an Engine Node: Status poll from log server failed. DELETED Status is deleted DUMMY For an Engine Node: Status is a dummy Status for Demo mode.

    For a Composite Status: Status is a dummy Status for Demo mode.

  • monitoring_status

    ANY Refers to any Status. NOT_MONITORED Indicates that Status element has currently Not Monitored Status. UNKNOWN For an Engine Node: Node has not sent status (or timeout).

    For a Composite Status: All children are unknown.

    OK For an Engine Node: Status is OK.

    For a Composite Status: All children are OK.

    PARTIAL_OK For a Composite Status: Some children are OK and others are unknown. WARNING For a Composite Status: Some children have warning. ERROR For an Engine Node: Status is KO.

    For a Composite Status: Some children are KO.

    IDLE For a VPN Node: Status is STANDBY.

    Composite: All children are STANDBY.

  • result – The API’s links of the children or SDWAN Branch Status if exists

static get_status(href)[source]

Return Monitoring Status for the given href element :param str href: the uri of the element to retrieve the status :raises NotMonitored: the element is not monitored :rtype: MonitoringStatus

property history

This function returns a history object. :return: history object. :rtype: History

property monitoring_state

The monitoring state:

*INITIAL* For an Engine Node: Status not yet received.

For a Composite Status: Composite Status value is not yet computed.

*READY* For an Engine Node: Status is received.

For a Composite Status: Composite Status value is computed.

*NO_STATUS* For an Engine Node: No status received for the node during initial timeout. *TIMEOUT* For an Engine Node: Status was not received in time. *ERROR* Not used. *SERVER_ERROR* For an Engine Node: Status poll from log server failed. *DELETED* Status is deleted. *DUMMY* For an Engine Node: Status is a dummy Status for Demo mode.

For a Composite Status: Status is a dummy Status for Demo mode.

Returns:

The monitoring state.

Return type:

str

property monitoring_status

The monitoring status:

*ANY* Refers to any Status. *NOT_MONITORED* Indicates that Status element has currently Not Monitored Status. *UNKNOWN* For an Engine Node: Node has not sent status (or timeout).

For a Composite Status: All children are unknown.

*OK* For an Engine Node: Status is OK. For a Composite Status: All children are OK. *PARTIAL_OK* For a Composite Status: Some children are OK and others are unknown. *WARNING* For a Composite Status: Some children have warning. *ERROR* For an Engine Node: Status is KO. For a Composite Status: Some children are KO. *IDLE* For a VPN Node: Status is STANDBY. Composite: All children are STANDBY.

Returns:

The monitoring status.

Return type:

str

property name

name of the element described by href

property result
Returns:

The API’s links of the children or SDWAN Branch Status if exists

Return type:

list str

class smc.administration.monitoring_status.SDWANBranchStatus(**data)[source]

Bases: MonitoringStatus

This represents the SDWAN branch Status.

property health_in_percent
Returns:

SDWAN Branch Health in percent

Return type:

int

class smc.administration.monitoring_status.SDWANBranchToBranchStatus(**data)[source]

Bases: MonitoringStatus

This represents the SDWAN branch to branch Status.

property health_in_percent
Returns:

SDWAN Branch Health in percent

Return type:

int

property jitter_in_ms
Returns:

SDWAN Branch to Branch Jitter in milliseconds

Return type:

int

property latency_in_ms
Returns:

SDWAN Branch to Branch Latency in milliseconds

Return type:

int

property packet_loss_in_permyriad
Returns:

SDWAN Branch to Branch Packet loss in permyriad (per ten thousands)

Return type:

int

property traffic_in_bits_per_sec
Returns:

SDWAN Branch to Branch Traffic in bits per second

Return type:

long

class smc.administration.monitoring_status.SDWANNetlinkElementStatus(**data)[source]

Bases: MonitoringStatus

This represents the SDWAN Netlink element Status.

property connection_count
Returns:

Connection Count

Return type:

long

property inbound_traffic_in_bits_per_sec
Returns:

Inbound traffic in bits per second

Return type:

long

property outbound_traffic_in_bits_per_sec
Returns:

Outbound traffic in bits per second

Return type:

long

property packet_loss_in_permyriad
Returns:

Packet loss in permyriad (per ten thousands)

Return type:

long

class smc.administration.monitoring_status.ServerStatus(**data)[source]

Bases: MonitoringStatus

This represents an SMC Server Status (Class ServerStatus).<br/> Field from the StatusDTO map the normal server status.

For an SMC Server, additionnal information is provided about: - replication states ( detailed content depend on server role ) - resource monitoring common to all servers ( memory only currenlty )

class smc.administration.monitoring_status.VPNEndpointTunnelStatus(**data)[source]

Bases: VPNGatewayTunnelStatus

This represents the Monitoring Status for an endpoint tunnel.

property endpointA
Returns:

Name of Endpoint A

Return type:

str

property endpointB
Returns:

Name of Endpoint B

Return type:

str

class smc.administration.monitoring_status.VPNGatewayTunnelStatus(**data)[source]

Bases: VPNStatus

This represents the Monitoring Status for a Gateway Tunnel.

property gatewayA
Returns:

Name of Gateway A

Return type:

str

property gatewayB
Returns:

Name of Gateway B

Return type:

str

class smc.administration.monitoring_status.VPNStatus(**data)[source]

Bases: MonitoringStatus

This represents the VPN Status

property health_in_percent
Returns:

VPN Health in percent.

Return type:

str

property jitter_in_ms
Returns:

VPN Jitter in milliseconds

Return type:

int

property latency_in_ms
Returns:

VPN Latency in milliseconds

Return type:

int

property packet_loss_in_permyriad
Returns:

VPN Packet loss in permyriad (per ten thousands)

Return type:

int

property traffic_in_bits_per_sec
Returns:

VPN Traffic in bits per second

Return type:

long

property vpn_status_code
Returns:

The Monitoring VPN Status Code.

Return type:

str

Advanced Usage

SMCRequest

Middle tier helper module to wrap CRUD operations and catch exceptions

SMCRequest is the general data structure that is sent to the send_request method in smc.api.web.SMCConnection to submit the data to the SMC.

class smc.api.common.SMCRequest(href=None, json=None, params=None, filename=None, etag=None, user_session=None, send_none_json=False, **kwargs)[source]

SMCRequest represents the data structure that will be submitted to the web layer for submission to the SMC API.

Parameters:
  • href (str) – href for request, required by all methods

  • json (dict) – json to submit, required by create, update

  • params (dict) – query string parameters

  • filename (str) – name of file for download, optional for create

  • etag (str) – etag of element, required for update

  • send_none_json (bool) – To force json to be none instead of {} set this boolean to True. In this case json param will be ignored.

etag

ETag for PUT or DELETE request modifications

filename

Filename if a file download is requested

headers

Default headers

href

href for this request

params

dictionary of query parameters

SMCResult

Operations being performed that involve REST calls to SMC will return an SMCResult object. This object will hold attributes that are useful to determine if the operation was successful and if not, the reason. An SMCResult is handled automatically and uses exceptions to provide statuses between modules and user interaction. The simplest way to get access to an SMCResult directly is to make an SMCRequest using smc.base.model.prepared_request() and observe the attributes in the return message. All response data is serialized into the SMCResult.json attribute when it is received by the SMC.

Web actions to SMC

SSL certificates are not verified to the CA authority, need to implement for urllib3: https://urllib3.readthedocs.io/en/latest/user-guide.html#ssl

class smc.api.web.SMCResult(respobj=None, msg=None, user_session=None)[source]

SMCResult will store the return data for operations performed against the SMC API. If the function returns an SMCResult, the following attributes are set. Note: SMC API will return a list if searches are done and a dict if the attempt is made to get the element directly from href.

Instance attributes:

Variables:
  • etag (str) – etag from HTTP GET, representing unique value from server

  • href (str) – href of location header if it exists

  • content (str) – content if return was application/octet

  • msg (str) – error message, if set

  • code (int) – http code

  • json (dict) – element full json

Example of using SMCRequest to fetch an element by href, returning an SMCResult:

>>> vars(SMCRequest(href='http://1.1.1.1:8082/6.2/elements/host/978').read())
{'code': 200, 'content': None, 'json': {u'comment': u'this is a searchable comment', u'read_only': False, u'ipv6_address': u'2001:db8:85a3::8a2e:370:7334', u'name': u'kali', u'third_party_monitoring': {u'netflow': False, u'snmp_trap': False}, u'system': False, u'link': [{u'href': u'http://1.1.1.1:8082/6.2/elements/host/978', u'type': u'host', u'rel': u'self'}, {u'href': u'http://1.1.1.1:8082/6.2/elements/host/978/export', u'rel': u'export'}, {u'href': u'http://1.1.1.1:8082/6.2/elements/host/978/search_category_tags_from_element', u'rel': u'search_category_tags_from_element'}], u'key': 978, u'address': u'1.1.11.1', u'secondary': [u'7.7.7.7']}, 'href': None, 'etag': '"OTc4MzExMzkxNDk2MzI1MTMyMDI4"', 'msg': None}

Waiters

Waiters are convenience classes that use blocking or non-blocking threads to monitor for a particular state of an engine node.

A waiter can have a callback added that will be executed after either the state has matched, a number of iterations exceeded or an exception is caught while monitoring. The callback should be a callable that takes a single argument.

They provide the ability to perform logical actions such as “wait for the engine to have status ‘Configured’, then fire a policy upload task”.

Example of waiting for an engine to be ready, then send policy:

class ContainerPolicyCallback(object):
    def __init__(self, container):
        self.engine = engine

    def __call__(self, status):
        if status == 'Configured':
            self.engine.upload(policy='MyPolicy')

engine = Engine('myengine')
callback = ContainerPolicyCallback(engine)

waiter = ConfigurationStatusWaiter(engine.nodes[0], 'Configured')
waiter.add_done_callback(callback)

Waiters can also be blocking while waiting for status. Example of using a waiter to block input while waiting for the engine to reach a specific status:

waiter = ConfigurationStatusWaiter(node, 'Initial', max_wait=5)
while not waiter.done():
    print("Status after 5 sec wait: %s" % waiter.result(5))
class smc.core.waiters.ConfigurationStatusWaiter(resource, status, **kw)[source]

Bases: NodeWaiter

Configuration status waiter provides a current engine status with respects to having a configuration.

Parameters:
  • resource (Node) – Engine node to check for status

  • status (str) – used defined status to wait for.

Raises:

NodeCommandFailed – Failure to obtain a status back from the engine. This can be thrown when getting initial status. If thrown after the thread has started, it is caught and returned in the result after ending the thread.

class smc.core.waiters.NodeStateWaiter(resource, status, **kw)[source]

Bases: NodeWaiter

Node State specifies where the engine is within it’s lifecycle, such as initial state, ready state, error, timeout, etc.

Parameters:
  • resource (Node) – Engine node to check for status

  • status (str) – used defined status to wait for.

Raises:

NodeCommandFailed – Failure to obtain a status back from the engine. This can be thrown when getting initial status. If thrown after the thread has started, it is caught and returned in the result after ending the thread.

class smc.core.waiters.NodeStatusWaiter(resource, status, **kw)[source]

Bases: NodeWaiter

Node Status specifies the current state of the engine such as offline, online, locked offline, no policy installed, etc.

Parameters:
  • resource (Node) – Engine node to check for status

  • status (str) – used defined status to wait for.

Raises:

NodeCommandFailed – Failure to obtain a status back from the engine. This can be thrown when getting initial status. If thrown after the thread has started, it is caught and returned in the result after ending the thread.

class smc.core.waiters.NodeWaiter(resource, status, timeout=5, max_wait=36, **kw)[source]

Bases: Thread

Node Waiter provides a common threaded interface to monitoring a nodes status and wait for a specific response.

add_done_callback(callback)[source]

Add a callback to run after the task completes. The callable must take 1 argument which will be the completed Task.

:param callable callback

done()[source]

Is the task still running or considered complete

Return type:

bool

result(timeout=None)[source]

Get current status result after waiting timeout Result does a join on the thread to get a status update. It is possible the first couple of statuses are None if an update has not yet been joined.

run()[source]

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

stop()[source]

Stop thread if it’s still running

wait(timeout=None)[source]

Blocking method to wait for thread

smc.core.waiters.STATE = frozenset({'DELETED', 'DUMMY', 'ERROR', 'INITIAL', 'NO_STATUS', 'READY', 'SERVER_ERROR', 'TIMEOUT'})

Node state constant values

smc.core.waiters.STATUS = frozenset({'Going Locked Offline', 'Going Locked Online', 'Going Offline', 'Going Online', 'Going Standby', 'Locked Offline', 'Locked Online', 'No Policy Installed', 'Not Monitored', 'Offline', 'Online', 'Policy Out Of Date', 'Standby', 'Unknown'})

Node status constant values

Exceptions

Exceptions thrown throughout smc-python. Be sure to check functions or class methods that have raises documentation. All exception classes subclass SMCException

Exceptions Module

exception smc.api.exceptions.ActionCommandFailed[source]

Bases: SMCException

Action type commands use this exception

exception smc.api.exceptions.AlertChainError[source]

Bases: SMCException

This exception is related to AlertChain based operations like AlertChain and Alert Chain Rule creation update, and deletion.

exception smc.api.exceptions.AlertPolicyError[source]

Bases: SMCException

This exception is related to AlertPolicy based operations like AlertPolicy and Alert Rule creation update, and deletion.

exception smc.api.exceptions.CertificateError[source]

Bases: SMCException

Related to certificate based operations like requests, signing, or creation. For example, engines that are not initialized can not respond to certificate creation requests and SMC API will return an error.

exception smc.api.exceptions.CertificateExportError[source]

Bases: CertificateError

Failure to export a certificate

exception smc.api.exceptions.CertificateImportError[source]

Bases: CertificateError

Failure to import a certificate or private key

exception smc.api.exceptions.ConfigLoadError[source]

Bases: SMCException

Thrown when there was a problem reading credential information from file. Typically caused by missing settings.

exception smc.api.exceptions.CreateElementFailed[source]

Bases: SMCException

Generic exception when there was a failure calling a create method

exception smc.api.exceptions.CreateEngineFailed[source]

Bases: SMCException

Thrown when a POST operation returns with a failed response. API based response will be returned as the exception message

exception smc.api.exceptions.CreatePolicyFailed[source]

Bases: SMCException

Thrown when failures occur when creating specific poliies like Firewall Policy, IPS, VPN, etc.

exception smc.api.exceptions.CreateRuleFailed[source]

Bases: SMCException

Indicates a failed response when creating a rule of any type.

exception smc.api.exceptions.CreateVPNFailed[source]

Bases: SMCException

Creating a policy or route based VPN failed.

exception smc.api.exceptions.DeleteElementFailed[source]

Bases: SMCException

Used when deletion fails, typically due to dependencies for the target element

exception smc.api.exceptions.EcaClientConfigExportError[source]

Bases: SMCException

Failure to export an ECA client config

exception smc.api.exceptions.ElementNotFound[source]

Bases: SMCException

Generic exception when an attempt is made to load an element that is not found.

exception smc.api.exceptions.EngineCommandFailed[source]

Bases: SMCException

Engines will have some commands that are specifically executed such as adding blacklist entries, flushing blacklist or adding routes. This exception will be thrown if the SMC API responds with any sort of error and wrap the response

exception smc.api.exceptions.FetchElementFailed[source]

Bases: SMCException

Failure when fetching results

exception smc.api.exceptions.HaCommandException(response=None)[source]

Bases: SMCOperationFailure

HAManagement will have some commands that are specifically executed, such as asset_active, set_standby, and full_replication. If the SMC API returns an error and wraps the response, this exception will be thrown.

exception smc.api.exceptions.InterfaceNotFound[source]

Bases: SMCException

Returned when attempting to fetch an interface directly

exception smc.api.exceptions.InvalidLogSeverity[source]

Bases: SMCException

Used within log option to prevent invalid submissions.

exception smc.api.exceptions.InvalidRuleValue[source]

Bases: SMCException

Used within rule creation methods to prevent invalid submissions

exception smc.api.exceptions.InvalidSearchFilter[source]

Bases: SMCException

Thrown by collections when using invalid search sequences.

exception smc.api.exceptions.LicenseError[source]

Bases: SMCException

Thrown when operations to perform Node specific license related operations such as bind license, fetch license or cancel license fail. For node licensing specific actions, see: :py:class: smc.core.node.Node

exception smc.api.exceptions.LoadElementFailed[source]

Bases: SMCException

Failure when attempting to obtain the settings for a specific element. This is more generic for a broad class of elements.

exception smc.api.exceptions.LoadEngineFailed[source]

Bases: SMCException

Thrown when attempting to load an engine that does not exist

exception smc.api.exceptions.LoadPolicyFailed[source]

Bases: SMCException

Failure when trying to load a specific policy type

exception smc.api.exceptions.MissingDependency[source]

Bases: SMCException

A dependency is missing for the given operation.

exception smc.api.exceptions.MissingRequiredInput[source]

Bases: SMCException

Some functinos will flat out fail if certain fields are not provided. This is to ensure that some functions have some protection in case the user doesn’t read the doc’s.

exception smc.api.exceptions.ModificationAborted[source]

Bases: SMCException

A previous requirement was not met which prevented an attempted change from being executed.

exception smc.api.exceptions.ModificationFailed[source]

Bases: SMCException

Used when making generic modifications to elements.

exception smc.api.exceptions.NodeCommandFailed[source]

Bases: SMCException

Each engine node will have multiple commands that can be executed such as go online, go offline, go standby, locking, etc. When these commands fail, this exception will be thrown and wrap the SMC API response. For all node specific command actions, see: :py:class: smc.core.node.Node

exception smc.api.exceptions.NotMonitored[source]

Bases: SMCException

Raised when attempting get monitoring status for not monitored element

exception smc.api.exceptions.PolicyCommandFailed[source]

Bases: SMCException

Generic policy related command failures such as opening or closing a VPN policy.

exception smc.api.exceptions.ResourceNotFound[source]

Bases: SMCException

Used to indicate a resource link is not found on the queried node. For example, the smc.core.engine.Engine class will expose available resources but some engines may not have those links.

exception smc.api.exceptions.SMCConnectionError[source]

Bases: SMCException

Thrown when there are connection related issues with the SMC. This could be that the underlying http requests library could not connect due to wrong IP address, wrong port, or time out

exception smc.api.exceptions.SMCException[source]

Bases: Exception

Base class for exceptions

exception smc.api.exceptions.SMCOperationFailure(response=None)[source]

Bases: SMCException

Exception class for storing results from calls to the SMC This is thrown for HTTP methods that do not return the expected HTTP status code. See each http_* method in smc.api.web for expected success status

Parameters:
  • response – response object returned from HTTP method

  • msg – optional msg to insert

Instance attributes:

Variables:
  • response – http request response object

  • code – http status code

  • status – status from SMC API

  • message – message attribute from SMC API

  • details – details list from SMC API (may not always exist)

  • smcresultsmc.api.web.SMCResult object for consistent returns

exception smc.api.exceptions.SessionManagerNotFound(message='')[source]

Bases: Exception

exception smc.api.exceptions.SessionNotFound[source]

Bases: SMCException

Retrieving a session by name did not succeed because the session did not already exist

exception smc.api.exceptions.TaskRunFailed[source]

Bases: SMCException

When running tasks such as policy upload, refresh policy, etc, if the result from SMC is a failure, possibly due to an incorrect input (i.e. missing policy), then this exception will be thrown

exception smc.api.exceptions.UnsupportedAlertChannel[source]

Bases: AlertChainError

The exception occurs when an unsupported alert channel is used.

exception smc.api.exceptions.UnsupportedAttribute[source]

Bases: SMCException

The exception occurs when an unsupported attribute is used.

exception smc.api.exceptions.UnsupportedEngineFeature[source]

Bases: SMCException

If an operation is performed on an engine that does not support the functionality, this is thrown. For example, only Master Engine has virtual resources. IPS and Layer 2 Firewall do not have internal gateways (used for VPN).

exception smc.api.exceptions.UnsupportedEntryPoint[source]

Bases: SMCException

An entry point was specified that was not found in this API version. This is likely due to using an older version of the SMC API that does not support that feature. The exception is thrown specifying the entry point specified.

exception smc.api.exceptions.UnsupportedInterfaceType[source]

Bases: SMCException

Some interface types are not supported on certain engines. For example, Virtual Engines only have Virtual Physical Interfaces. Layer 3 Firewalls do not support Capture or Inline Interfaces. This exception will be thrown when an attempt is made to enumerate interfaces for an engine type missing a reference to an unsupported interface type

exception smc.api.exceptions.UpdateElementFailed[source]

Bases: SMCException

Failure when updating element. When failure is due to ETag being invalid, target was modified before change was submitted. A resubmit would be required.

exception smc.api.exceptions.UserElementNotFound[source]

Bases: SMCException

Raised when attempting to find a user element that cannot be found in a mapped database (internal or external LDAP)