API Reference

Session

Session module for tracking existing connection state to SMC

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.

api_version

Current API Version

Return type:str
domain

Logged in SMC domain

Return type:str
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
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
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, **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.
  • (optional) (api_version) – specify api version
  • 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()
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
manager

Return the session manager for this session

Return type:SessionManager
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
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

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

Session timeout in seconds

Return type:int
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 and json. 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 (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, **meta)[source]

Bases: smc.base.model.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
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)
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

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
name

Name of element

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
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: smc.base.model.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: smc.base.model.ElementBase

User element mixin for LDAP of Internal Domains. Provides comparison and encoding/decoding of the DN used in URIs.

unique_id

Fully qualified unique DN for this entry

Return type:str
class smc.core.resource.History[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
created_by

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

Return type:Element
last_modified

When the element was last modified as a datetime object

Return type:datetime
modified_by

The account that last modified this element.

Return type:Element
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, **meta)[source]

Bases: smc.base.model.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

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, **meta)[source]

Bases: smc.elements.user.UserMixin, smc.base.model.Element

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

Create an Admin:

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

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

admin = AdminUser('dlepage')
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, comment=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
  • enabled (bool) – is account enabled
  • engine_target (list) – engine to allow remote access to
Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

AdminUser

enabled

Read only enabled status

Return type:bool
class smc.elements.user.ApiClient(name, **meta)[source]

Bases: smc.elements.user.UserMixin, smc.base.model.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.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
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)

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

domain

Domain this permission applies to. Shared Domain if unspecified.

Return type:AdminDomain
granted_elements

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

Return type:list(Element)
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, **meta)[source]

Bases: smc.base.model.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
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)

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, **meta)[source]

Bases: smc.administration.certificates.tls_common.ImportExportIntermediate, smc.administration.certificates.tls_common.ImportPrivateKey, smc.administration.certificates.tls_common.ImportExportCertificate, smc.base.model.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(name, common_name, public_key_algorithm='rsa', signature_algorithm='rsa_sha_512', key_length=4096)[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
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
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, **meta)[source]

Bases: smc.base.model.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: smc.base.structs.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, **meta)[source]

Bases: smc.base.model.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

ClientProtectionCA

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

Bases: smc.administration.certificates.tls_common.ImportPrivateKey, smc.administration.certificates.tls_common.ImportExportCertificate, smc.base.model.Element

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(name)[source]

Create a client protection CA. Once the client protection CA is created, to activate you must then call import_certificate and import_private_key. Or optionally use the convenience classmethod import_signed().

Raises:CreateElementFailed – failed to create base Client CA
Return type:ClientProtectionCA
classmethod create_self_signed(name, prefix, password, public_key_algorithm='rsa', life_time=365, key_length=2048)[source]

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.
  • prefix (str) – prefix used for derivating file names
  • password (str) – password for private key
  • 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

Domains

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

Bases: smc.base.model.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)]

Note

Admin Domains require and SMC license.

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

Create a new Admin Domain element for SMC objects.

Example:

>>> AdminDomain.create(name='mydomain', comment='mycomment')
>>> AdminDomain(name=mydomain) 
Parameters:
  • name (str) – name of domain
  • comment (str) – optional comment
Raises:

CreateElementFailed – failed creating element with reason

Returns:

instance with meta

Return type:

AdminDomain

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.DeleteLogTask(name, **meta)[source]

Bases: smc.administration.scheduled_tasks.ScheduledTaskMixin, smc.base.model.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 UI.

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, **meta)[source]

Bases: smc.administration.scheduled_tasks.ScheduledTaskMixin, smc.base.model.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, **meta)[source]

Bases: smc.administration.scheduled_tasks.ScheduledTaskMixin, smc.base.model.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, **meta)[source]

Bases: smc.administration.scheduled_tasks.ScheduledTaskMixin, smc.base.model.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.FetchCertificateRevocationTask(name, **meta)[source]

Bases: smc.administration.scheduled_tasks.ScheduledTaskMixin, smc.base.model.Element

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

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

Bases: smc.administration.scheduled_tasks.ScheduledTaskMixin, smc.base.model.Element

Refresh a Master Engine and virtual policy task.

Note

This task is only relevant for engines that are Master Engines. This does not apply to standard single FW or clustered FW’s.

classmethod create(name, master_engines, comment=None)[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
Raises:

CreateElementFailed – failed to create the task

Returns:

the task

Return type:

RefreshMasterEnginePolicyTask

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

Bases: smc.administration.scheduled_tasks.ScheduledTaskMixin, smc.base.model.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.RenewGatewayCertificatesTask(name, **meta)[source]

Bases: smc.administration.scheduled_tasks.ScheduledTaskMixin, smc.base.model.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, **meta)[source]

Bases: smc.administration.scheduled_tasks.ScheduledTaskMixin, smc.base.model.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, **meta)[source]

Bases: smc.administration.scheduled_tasks.ScheduledTaskMixin, smc.base.model.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, **meta)[source]

Bases: smc.administration.scheduled_tasks.ScheduledTaskMixin, smc.base.model.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

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
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, **meta)[source]

Bases: smc.administration.scheduled_tasks.ScheduledTaskMixin, smc.base.model.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)[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
Raises:
Returns:

the task

Return type:

ServerBackupTask

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

Bases: smc.administration.scheduled_tasks.ScheduledTaskMixin, smc.base.model.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: smc.base.model.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()
activated

Whether this schedule is active for this task.

Return type:bool
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.UploadPolicyTask(name, **meta)[source]

Bases: smc.administration.scheduled_tasks.ScheduledTaskMixin, smc.base.model.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, **meta)[source]

Bases: smc.administration.scheduled_tasks.ScheduledTaskMixin, smc.base.model.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) – FW 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 FW 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

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, **meta)[source]

Bases: smc.base.model.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.

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
period_begin

Period when this report was specified to start.

Return type:datetime.datetime
period_end

Period when this report was specified to end.

Return type:datetime.datetime
class smc.administration.reports.ReportDesign(name, **meta)[source]

Bases: smc.base.model.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=0, end_time=0, 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:
  • period_begin (int) – milliseconds time defining start time for report
  • period_end (int) – milliseconds time defining end time for report
  • senders (list(Element)) – filter targets to use when generating report
  • wait_for_finish (bool) – enable polling for results
  • timeout (int) – timeout between polling
Raises:

TaskRunFailed – refresh failed, possibly locked policy

Return type:

TaskOperationPoller

report_files

Retrieve all reports that are currently available on the SMC.

Return type:list(Report)
class smc.administration.reports.ReportTemplate(name, **meta)[source]

Bases: smc.base.model.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 blacklists, 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, **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)]

Note

Admin Domains require and SMC license.

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

Create a new Admin Domain element for SMC objects.

Example:

>>> AdminDomain.create(name='mydomain', comment='mycomment')
>>> AdminDomain(name=mydomain) 
Parameters:
  • name (str) – name of domain
  • comment (str) – optional comment
Raises:

CreateElementFailed – failed creating element with reason

Returns:

instance with meta

Return type:

AdminDomain

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

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)
export_elements(filename='export_elements.zip', typeof='all')[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

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
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
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)
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_time

Return the SMC time as datetime object in UTC

:rtype datetime

smc_version

Return the SMC version

system_properties()[source]

List of all properties applied to the SMC

Raises:ActionCommandFailed – failure to retrieve resource
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)
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, **kw)[source]

Bases: smc.administration.tasks.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: smc.base.model.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
end_time

Task end time in UTC datetime format

Return type:datetime
progress

Percentage of completion

Return type:int
resource

The resource/s associated with this task

Return type:list(Element)
result_url

Link to result (this task)

Return type:str
start_time

Task start time in UTC datetime format

Return type:datetime
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

task

Access to task

Return type:Task
wait(timeout=None)[source]

Blocking wait for task status.

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

Bases: smc.base.model.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().

task

Return the task associated with this event

Return type:Task

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, 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
  • 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
release_notes

HTTP location of the release notes

Engine Upgrade

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

Bases: smc.administration.updates.PackageMixin, smc.base.model.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() 
platform

Platform for this engine upgrade

release_date

Release date for this engine upgrade

version

Engine upgrade version

Dynamic Update

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

Bases: smc.administration.updates.PackageMixin, smc.base.model.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() 
activation_date

Date this update was activated, if any

Return type:str
package_id

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

Return type:str
release_date

Date of release

Return type:str
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

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, **meta)[source]

Bases: smc.base.model.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)[source]

Create an alias.

Parameters:
  • name (str) – name of alias
  • comment (str) – comment for this alias
Raises:

CreateElementFailed – create failed with reason

Return type:

Alias

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
resolved_value = None

resolved value for alias

classmethod update_or_create(name, engine, translation_values=None, with_status=False)[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
Raises:
Return type:

Element

AddressRange

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

Bases: smc.base.model.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, **meta)[source]

Bases: smc.base.model.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, comment=None)[source]

Create domain name element

Parameters:name (str) – name of domain, i.e. lepages.net, www.lepages.net
Raises:CreateElementFailed – element creation failed with reason
Returns:instance with meta
Return type:DomainName

Expression

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

Bases: smc.base.model.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, **meta)[source]

Bases: smc.base.model.Element

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
add_secondary(address, append_lists=False)[source]

Add secondary IP addresses to this host element. If append_list is True, then add to existing list. Otherwise overwrite.

Parameters:
  • address (list) – ip addresses to add in IPv4 or IPv6 format
  • append_list (bool) – add to existing or overwrite (default: append)
Returns:

None

classmethod create(name, address=None, ipv6_address=None, secondary=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)
  • 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, **meta)[source]

Bases: smc.base.model.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

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, **meta)[source]

Bases: smc.base.model.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, 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)
  • 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, **meta)[source]

Bases: smc.base.model.Element

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
classmethod create(name, address=None, ipv6_address=None, secondary=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)
  • 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, **meta)[source]

Bases: smc.base.model.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
classmethod create(name, url_entry, comment=None)[source]

Create the custom URL list

Parameters:
  • name (str) – name of url list
  • url_entry (list) – list of url’s
  • comment (str) – optional comment
Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

URLListApplication

Zone

class smc.elements.network.Zone(name, **meta)[source]

Bases: smc.base.model.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.

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
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, **meta)[source]

Bases: smc.base.model.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, 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
  • comment (str) – optional comment
Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

EthernetService

ICMPService

class smc.elements.service.ICMPService(name, **meta)[source]

Bases: smc.base.model.Element

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
Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

ICMPService

ICMPIPv6Service

class smc.elements.service.ICMPIPv6Service(name, **meta)[source]

Bases: smc.base.model.Element

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', 139)
ICMPIPv6Service(name=api-Neighbor Advertisement Message)

Available attributes:

Variables:icmp_type (int) – ipv6 icmp type field
classmethod create(name, icmp_type, comment=None)[source]

Create the ICMPIPv6 service element

Parameters:
  • name (str) – name of service
  • icmp_type (int) – ipv6 icmp type field
Raises:

CreateElementFailed – failure creating element with reason

Returns:

instance with meta

Return type:

ICMPIPv6Service

IPService

class smc.elements.service.IPService(name, **meta)[source]

Bases: smc.elements.protocols.ProtocolAgentMixin, smc.base.model.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

protocol_number

Protocol number for this IP Service

Return type:int

TCPService

class smc.elements.service.TCPService(name, **meta)[source]

Bases: smc.elements.protocols.ProtocolAgentMixin, smc.base.model.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, **meta)[source]

Bases: smc.elements.protocols.ProtocolAgentMixin, smc.base.model.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, **meta)[source]

Bases: smc.base.model.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 UI 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, **meta)[source]

Bases: smc.base.model.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.

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
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: smc.base.structs.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 UI 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:

Mutable attributes are:

Variables:value (str) – The mutable value for this particular setting
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
name

Name of this protocol setting

Return type:str
type

The type of this parameter. Can be string value, integer value, etc. The type is returned as a string representation.

Return type:str
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: smc.elements.protocols.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
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: smc.elements.protocols.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
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
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)[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
Paran dict kwargs:
 

keyword arguments to satisfy the create constructor if the group needs to be created.

Raises:

CreateElementFailed – could not create element with reason

Returns:

element instance by type

Return type:

Element

ICMPServiceGroup

class smc.elements.group.ICMPServiceGroup(name, **meta)[source]

Bases: smc.elements.group.GroupMixin, smc.base.model.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, **meta)[source]

Bases: smc.elements.group.GroupMixin, smc.base.model.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

Group

class smc.elements.group.Group(name, **meta)[source]

Bases: smc.elements.group.GroupMixin, smc.base.model.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 retrieved the resolved list of elements.
classmethod create(name, members=None, comment=None)[source]

Create the group

Parameters:
  • name (str) – Name of element
  • members (str,Element) – group members by element names
  • comment (str) – optional comment
Raises:

CreateElementFailed – element creation failed with reason

Returns:

instance with meta

Return type:

Group

ServiceGroup

class smc.elements.group.ServiceGroup(name, **meta)[source]

Bases: smc.elements.group.GroupMixin, smc.base.model.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, **meta)[source]

Bases: smc.elements.group.GroupMixin, smc.base.model.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, **meta)[source]

Bases: smc.elements.group.GroupMixin, smc.base.model.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, **meta)[source]

Bases: smc.base.model.Element

Servers

Module that represents server based configurations

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

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

LogServer

class smc.elements.servers.LogServer(name, **meta)[source]

Bases: smc.elements.servers.ContactAddressMixin, smc.base.model.Element

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 management server reference through a collection:

>>> LogServer.objects.first()
LogServer(name=LogServer 172.18.1.150)

ManagementServer

class smc.elements.servers.ManagementServer(name, **meta)[source]

Bases: smc.elements.servers.ContactAddressMixin, smc.base.model.Element

Management Server configuration. Most configuration settings are better set through the SMC UI, 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)
Variables:
  • name – name of management server
  • address – address of Management Server

DNSServer

class smc.elements.servers.DNSServer(name, **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, **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.

classmethod create(name, address, proxy_port=8080, username=None, password=None, secondary=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)
  • comment (str) – optional comment
  • secondary (list) – secondary list of proxy server addresses
Raises:

CreateElementFailed – Failed to create the proxy element

Return type:

HttpProxy

ProxyServer

class smc.elements.servers.ProxyServer(name, **meta)[source]

Bases: smc.elements.servers.ContactAddressMixin, smc.base.model.Element

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
classmethod create(name, address, inspected_service, secondary=None, balancing_mode='ha', proxy_service='generic', location=None, comment=None, add_x_forwarded_for=False, trust_host_header=False, **kw)[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
  • 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 (str,Element) – 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
  • 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
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)
proxy_service

The proxy service for this proxy server configuration

Return type:str
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

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, Blacklist can be applied to an engine directly or system wide. This class will define the format when calling blacklist 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.

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.Category(name, **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 UI 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 element (str,) – 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, **meta)[source]

A Category Tag is a grouping of categories within SMC. Category Tags are used as filters (typically in the SMC UI) 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

addresses

List of addresses set as contact address

Return type:list
name

Location name for this contact address

Return type:str
class smc.elements.other.FilterExpression(name, **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.HTTPSInspectionExceptions(name, **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, **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
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, **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, **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.SituationTag(name, **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.

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.

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.

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, **meta)[source]

Bases: smc.base.model.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 UI 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 element (str,) – 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, **meta)[source]

Bases: smc.base.model.Element

A Category Tag is a grouping of categories within SMC. Category Tags are used as filters (typically in the SMC UI) 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, **meta)[source]

Bases: smc.base.model.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, **meta)[source]

Bases: smc.base.model.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
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, **meta)[source]

Bases: smc.base.model.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, **meta)[source]

Bases: smc.base.model.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, **meta)[source]

Bases: smc.base.model.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

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, **meta)[source]

Bases: smc.elements.situations.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, **meta)[source]

Bases: smc.elements.situations.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.

class smc.elements.situations.InspectionSituation(name, **meta)[source]

Bases: smc.elements.situations.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
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, **meta)[source]

Bases: smc.elements.situations.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, **meta)[source]

Bases: smc.base.model.Element

Situation defines a common interface for inspection and correlated situations.

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
description

The description for this situation

Return type:str
parameter_values

Parameter values for this inspection situation. This correlate to the the situation_context.

Return type:list(SituationParameterValue)
severity

The severity of this inspection situation, critical, high, low, information

Return type:int
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, **meta)[source]

Bases: smc.base.model.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
description

Description for this context

Return type:str
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, **meta)[source]

Bases: smc.base.model.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:InspectionContextGroup) sub_elements (list(InspectionContext,) – the members of this inspection context group
class smc.elements.situations.SituationParameter(**meta)[source]

Bases: smc.base.model.SubElement

A situation parameter defines the parameter type used to define the inspection situation context. For example, Regular Expression would be a situation parameter.

display_name

The display name as shown in the SMC

Return type:str
order

The order placement for this parameter. This is only relevant when there are multiple parameters in an inspection context definition.

Return type:int
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: smc.base.model.SubElement

The situation parameter value is associated with a situation parameter and as the name implies, provides the value payload for the given parameter.

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.DNSRelayProfile(name, **meta)[source]

Bases: smc.base.model.Element

DNS Relay Settings specify a profile to handle how the engine will interpret DNS queries. Stonesoft can act as a DNS relay, rewrite DNS queries or redirect domains to the specified DNS servers.

dns_answer_translation

Add a DNS answer translation

Return type:DNSAnswerTranslation
domain_specific_dns_server

Add domain to DNS server mapping

Return type:DomainSpecificDNSServer
fixed_domain_answer

Add a fixed domain answer entry.

Return type:FixedDomainAnswer
hostname_mapping

Add a hostname to IP mapping

Return type:HostnameMapping
class smc.elements.profiles.FixedDomainAnswer(profile)[source]

Bases: smc.elements.profiles.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: smc.elements.profiles.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
class smc.elements.profiles.DomainSpecificDNSServer(profile)[source]

Bases: smc.elements.profiles.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.DNSAnswerTranslation(profile)[source]

Bases: smc.elements.profiles.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.DNSRule(profile)[source]

Bases: object

DNSRule is the parent class for all DNS relay rules.

all()[source]

Return all entries

Return type:list(dict)

SNMPAgent

class smc.elements.profiles.SNMPAgent(name, **meta)[source]

Bases: smc.base.model.Element

Minimal implementation of SNMPAgent

Engine

class smc.core.engine.Engine(name, **meta)[source]

Bases: smc.base.model.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)[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_route(gateway, network)[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
Raises:

EngineCommandFailed – invalid route, possibly no network

Returns:

None

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
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
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
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 is only valid for SMC version < 6.4. Use blacklist_bulk() to add entries.

blacklist_bulk(blacklist)[source]

Add blacklist entries to the engine node in bulk. For blacklist to work, you must also create a rule with action “Apply Blacklist”. First create your blacklist entries using smc.elements.other.Blacklist then provide the blacklist to this method.

Parameters:Blacklist (blacklist) – pre-configured blacklist entries

Note

This method requires SMC version >= 6.4

blacklist_flush()[source]

Flush entire blacklist for engine

Raises:EngineCommandFailed – flushing blacklist failed with reason
Returns:None
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
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)
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
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
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
dynamic_routing

Dynamic Routing entry point. Access BGP, OSPF configurations

Raises:UnsupportedEngineFeature – Only supported on layer 3 engines
Return type:DynamicRouting
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_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
installed_policy

Return the name of the policy installed on this engine. If no policy, None will be returned.

Return type:str or None
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

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

Log server for this engine.

Returns:The specified log server
Return type:LogServer
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
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
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)
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
permissions

Retrieve the permissions for this engine instance.

>>> from smc.core.engine import Engine
>>> engine = Engine('myfirewall')
>>> for x in engine.permissions:
...   print(x)
... 
AccessControlList(name=ALL Elements)
AccessControlList(name=ALL Firewalls)
Raises:UnsupportedEngineFeature – requires SMC version >= 6.1
Returns:access control list permissions
Return type:list(AccessControlList)
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
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
refresh(timeout=3, wait_for_finish=False, **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()
while not poller.done():
    poller.wait(5)
    print('Percentage complete {}%'.format(poller.task.progress))
Parameters:timeout (int) – timeout between queries
Raises:TaskRunFailed – refresh failed, possibly locked policy
Return type:TaskOperationPoller
rename(name)[source]

Rename the firewall engine, nodes, and internal gateway (VPN gw)

Returns:None
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
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)
sandbox

Configure sandbox settings on the engine. Get current status:

engine.sandbox.status
Raises:UnsupportedEngineFeature – not supported on virtual engine
Return type:Sandbox
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
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)
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
switch_physical_interface

Get only switch physical 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
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
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, **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*')
for message in task.wait():
    print(message)
Parameters:
  • policy (str) – name of policy to upload to engine; if None, current policy
  • timeout (int) – timeout between queries
Raises:

TaskRunFailed – upload failed with reason

Return type:

TaskOperationPoller

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
version

Version of this engine. Can be none if the engine has not been initialized yet.

Return type:str or None
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
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)
vpn

VPN configuration for the engine.

Raises:UnsupportedEngineFeature: VPN is only supported on layer 3 engines.
Return type:VPN
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)
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)
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.VPN(engine)[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.

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
gateway_profile

Gateway Profile for this VPN. This is only a valid setting on layer 3 firewalls.

Return type:GatewayProfile
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, public_key_algorithm='rsa', signature_algorithm='rsa_sha_512', key_length=2048, signing_ca=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

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
Raises:

CertificateError – error generating certificate

Returns:

GatewayCertificate

internal_endpoint

Internal endpoints to enable VPN for the engine.

Return type:SubElementCollection(InternalEndpoint)
loopback_endpoint

Internal Loopback endpoints to enable VPN for the engine.

Return type:SubElementCollection(InternalEndpoint)
rename(name)[source]

Rename the internal gateway.

Parameters:name (str) – new name for internal gateway
Returns:None
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)
vpn_client

VPN Client settings for this engine.

Alias for internal_gateway.

Return type:InternalGateway
class smc.core.engine.VPNMapping[source]

Bases: smc.core.engine.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.

internal_gateway

Return the engines internal gateway as element

Return type:InternalGateway
is_central_gateway

Is this engine a central gateway in the VPN policy

Return type:bool
is_mobile_gateway

Is the engine specified as a mobile gateway in the Policy VPN configuration

Return type:bool
is_satellite_gateway

Is this engine a satellite gateway in the VPN policy

Return type:bool
vpn

The VPN policy for this engine mapping

Return type:PolicyVPN
class smc.core.engine.VPNMappingCollection(vpns)[source]

Bases: smc.base.structs.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
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
http_proxy

Return any HTTP Proxies that are configured for File Reputation.

Returns:list of http proxy instances
Return type:list(HttpProxy)
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

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
http_proxy

Return any HTTP Proxies that are configured for Url Filtering.

Returns:list of http proxy instances
Return type:list(HttpProxy)
status

Return the status of URL Filtering on the engine

Return type:bool

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’ or ‘cloud_sandbox’
  • 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

http_proxy

Return any HTTP Proxies that are configured for Sandbox.

Returns:list of http proxy instances
Return type:list(HttpProxy)
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
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

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 or smc.elements.servers.DNSServer (or combination of both). 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[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

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.

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

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
Raises:
interface

Return a list of physical interfaces that the SNMP agent is bound to.

Return type:list(PhysicalInterface)
location

Return the SNMP location string

Return type:str
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

policy

Return the InterfacePolicy for this layer 3 firewall.

Return type:InterfacePolicy

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 Stonesoft FW’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 FW 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: smc.base.model.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)

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’)
interface_id

Interface ID for this VPN endpoint

Returns:str interface id
physical_interface

Physical interface for this endpoint.

Return type:PhysicalInterface

InternalGateway

class smc.core.engine.InternalGateway(**meta)[source]

Bases: smc.base.model.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'

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) –
internal_endpoint

Internal endpoints to enable VPN for the engine.

Return type:SubElementCollection(InternalEndpoint)

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)
SwitchPhysicalInterfaceDynamic(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: smc.base.structs.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 a specific interface directly:

engine.interface.get(10)

Or use delegation 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.

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 or TunnelInterface

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: smc.base.structs.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: smc.core.collection.InterfaceCollection

PhysicalInterface Collection provides an interface to retrieving existing interfaces and helper methods to shortcut the creation of an interface.

add(interface_id, virtual_mapping=None, virtual_resource_name=None, zone_ref=None, comment=None)[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:
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 FW and IPS engines.

..note::
Capture interface are supported on Layer 3 FW/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 FW clusters, instead each node has a unique address and share a common macaddress. Adding multiple addresses to an interface is not supported with this method.

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)[source]

Add a DHCP interface on a single FW

Parameters:
  • interface_id (int) – interface id
  • dynamic_index (int) – index number for dhcp interface
  • primary_mgt (bool) – whether to make this primary mgt
  • zone_ref (str) – zone reference, can be name, href or Zone
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
  • href logical_interface_ref (str,) – 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
  • href zone_ref (str,) – zone reference by name or href for first interface
  • href second_zone_ref (str,) – 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 FW requires SMC and engine version >= 6.3.

An inline IPS interface is a new interface type for Layer 3 NGFW engines version >=6.3. Traffic passing an Inline IPS interface will have a access rule default action of Allow. Inline IPS interfaces are bypass capable. When using bypass interfaces and NGFW is powered off, in an offline state or overloaded, traffic is allowed through without inspection regardless of the access rules.

If the interface does not exist and a VLAN id is specified, the logical interface and zones will be applied to the top level physical interface. If adding VLANs to an existing inline ips pair, the logical and zones will be applied to the VLAN.

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 FW or cluster

An inline L2 FW interface is a new interface type for Layer 3 NGFW engines version >=6.3. Traffic passing an Inline Layer 2 Firewall interface will have a default action in access rules of Discard. Layer 2 Firewall interfaces are not bypass capable, so when NGFW is powered off, in an offline state or overloaded, traffic is blocked on this interface.

If the interface does not exist and a VLAN id is specified, the logical interface and zones will be applied to the top level physical interface. If adding VLANs to an existing inline ips pair, the logical and zones will be applied to the VLAN.

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, **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
  • 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, **kw)[source]

Add a layer 3 interface on a non-clustered engine. For Layer 2 FW and IPS engines, this interface type represents a layer 3 routed (node dedicated) interface. For clusters, use the cluster related methods such as add_cluster_virtual_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
  • kw – keyword arguments are passed to the sub-interface during create time. If the engine is a single FW, 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_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]