def test_login_credentials_in_constructor(self, m): """ Log in using credentials in the constructor. Double check the sesison object to make sure settings are set. """ m.register_uri('GET', '/api', json=self.version_dict()) # Initial connect # Get entry points m.register_uri('GET', '/6.1/api', json=self.entry_point_dict()) m.register_uri('POST', '/6.1/login', status_code=200) session.login(url='http://1.1.1.1:8082', api_key='12345', api_version=6.1, timeout=60, domain='mydomain') self.assertEqual(session.url, 'http://1.1.1.1:8082') self.assertEqual(session.api_version, 6.1) self.assertEqual(session.timeout, 60) self.assertEqual(session.api_key, '12345') self.assertEqual(session.domain, 'mydomain') # Fail the logout, nothing should be returned unless logging m.register_uri('PUT', '/6.1/logout', status_code=400) self.assertIsNone(session.logout())
def test_invalid_format_api_version(self, m): # Initial connect m.register_uri('GET', '/api', json=self.version_dict()) m.register_uri('GET', '/6.1/api', json=self.entry_point_dict()) m.register_uri('POST', '/6.1/login', status_code=200) session.login(url='http://1.1.1.1:8082', api_key='12345', api_version='blahfoo') # Version dict has max 6.1. Check session to verify self.assertEqual(session.api_version, 6.1)
def test_login_from_environ(self): import os from smc.tests.constants import url, api_key os.environ['SMC_ADDRESS'] = url os.environ['SMC_API_KEY'] = api_key os.environ['SMC_TIMEOUT'] = '200' session.login() self.assertEqual(session.timeout, 200) self.assertEqual(session.url, url) self.assertEqual(session.api_key, api_key)
def test_session_login_pass_from_file(self, mock_open, m): """ Test a valid login session through smc.api.session. Login will be done through the login file method of session.login(alt_filepath='foo'). Verify the session afterwards. """ cfg = ("[smc]\n" "smc_address=1.1.1.1\n" "smc_apikey=12345\n" "timeout=60\n" "api_version=6.1\n" "domain=mydomain") mock_open.return_value = io.StringIO(u'{}'.format(cfg)) entry_points = self.entry_point_dict() m.register_uri('GET', '/api', json=self.version_dict()) m.register_uri('GET', '/6.1/api', json=entry_points) m.register_uri('POST', '/6.1/login', status_code=200) session.login(alt_filepath='foo') # Session object now has everything we need self.assertIsInstance(session.entry_points, _EntryPoint) self.assertEqual(session.api_key, '12345') self.assertIsInstance(session.connection, SMCAPIConnection) self.assertEqual(session.timeout, 60) self.assertEqual(session.url, 'http://1.1.1.1:8082') self.assertEqual(session.api_version, 6.1) self.assertEqual(session.domain, 'mydomain') # Entry points should match self.assertEqual( entry_points.get('entry_point')[0].get('href'), session.entry_points.get('logout')) # Get an entry point that doesn't exist self.assertRaises(UnsupportedEntryPoint, lambda: session.entry_points.get('foo')) # Entry points by name; without href,rel,method entry_rel = [p.get('rel') for p in entry_points.get('entry_point')] self.assertEqual(entry_rel, session.entry_points.all()) #self.assertEqual(session.entry_points.all(), # session.cache.entry_points) # Successful logout. No status returned.. m.register_uri('PUT', '/6.1/logout', status_code=204) self.assertIsNone(session.logout()) # Session logged out. This would indicate no valid login session self.assertRaises(SMCConnectionError, lambda: session.entry_points.get('boo'))
def destroy(namespace): resource_client = client() if resource_client.resource_groups.check_existence( namespace.resource_group): poller = resource_client.resource_groups.delete( # AzureOperationPoller namespace.resource_group) session.login() try: Layer3Firewall(namespace.resource_group).delete() except (ElementNotFound, DeleteElementFailed) as e: logger.error('Problem deleting engine: {}'.format(e)) session.logout() return poller.result(timeout=10)
def setUp(self): session.login(url='http://172.18.1.150:8082', api_key='EiGpKD4QxlLJ25dbBEp20001', verify=True) try: global engine engine = Engine(running_firewall) except LoadEngineFailed: print("Running firewall engine NOT defined. ") raise global engine_not_initialized engine_not_initialized = Layer3Firewall.create( 'smc-python-api-nodetest', mgmt_ip='1.1.1.1', mgmt_network='1.1.1.0/24')
def test_requests_error_during_connection(self, m): """ Requests can raise exceptions during connecting, such as time out when the IP address of SMC is incorrect. """ m.register_uri('GET', '/api', json=self.raise_requests_exception) self.assertRaises( SMCConnectionError, lambda: session.login( url='http://1.1.1.1:8082', api_key='12345', api_version=6.1))
def test_requests_error_during_logout_with_ssl(self, m): # Initial connect m.register_uri('GET', '/api', json=self.version_dict()) # Get entry points m.register_uri('GET', '/6.1/api', json=self.entry_point_dict()) m.register_uri('POST', '/6.1/login', status_code=200) session.login(url='http://1.1.1.1:8082', api_key='12345', api_version=6.1) m.register_uri('PUT', '/6.1/logout', json=self.raise_requests_ssl_exception) # Entry point cache exists self.assertTrue(len(session.entry_points) > 0) # Logout will catch an SSL Error self.assertIsNone(session.logout()) # Entry point cache is still removed with self.assertRaises(SMCConnectionError): session.entry_points
def test_session_login_fail(self, mock_open): """ Session login is called via session.login() or session.login(alt_filepath='/path') or by specifying credentials directly in login constructor. In case of reading from file, verify exception bubbles up. """ cfg = ("[smc]\n") mock_open.return_value = io.StringIO(u'{}'.format(cfg)) self.assertRaises(ConfigLoadError, lambda: session.login(alt_filepath='foo'))
def connect(self, params): """ Get the SMC connection. If the credentials are provided in the module, then use them. Otherwise credentials gathering falls back to using smc-python native methods. Session is maintained for ansible run. :param dict params: dict of the SMC credential information """ try: if params.get('smc_logging') is not None: if 'path' not in params['smc_logging']: self.fail(msg='You must specify a path for SMC logging.') session.set_file_logger(log_level=params['smc_logging'].get( 'level', 10), path=params['smc_logging']['path']) if 'smc_address' and 'smc_api_key' in params: extra_args = params.get('smc_extra_args') # When connection parameters are defined, alt_filepath is ignored. session.login(url=params.get('smc_address'), api_key=params.get('smc_api_key'), api_version=params.get('smc_api_version'), timeout=params.get('smc_timeout'), domain=params.get('smc_domain'), **(extra_args or {})) elif 'smc_alt_filepath' in params: # User specified to look in file session.login(alt_filepath=params['smc_alt_filepath']) else: # From user ~.smcrc or environment session.login() except (ConfigLoadError, SMCException) as err: self.fail(msg=str(err), exception=traceback.format_exc())
def test_login_failed(self, m): """ Verify proper return for failed login attempt. Expected HTTP response is status code 200 """ m.register_uri('GET', '/api', json=self.version_dict()) # Initial connect # Get entry points m.register_uri('GET', '/6.1/api', json=self.entry_point_dict()) m.register_uri('POST', '/6.1/login', status_code=400) self.assertRaises( SMCConnectionError, lambda: session.login( url='http://1.1.1.1:8082', api_key='12345', api_version=6.1))
def test_session_login_find_api_version_failed_reply(self, mock_open, m): cfg = ("[smc]\n" "smc_address=1.1.1.1\n" "smc_apikey=12345\n" "timeout=60") mock_open.return_value = io.StringIO(u'{}'.format(cfg)) # First call is without an api_version specified m.register_uri('GET', '/api', json=self.version_dict()) # Unexpected reply back from call to API m.register_uri('GET', '/6.1/api', status_code=400) self.assertRaises(SMCConnectionError, lambda: session.login(alt_filepath='foo'))
def test_login_refresh(self): import os from smc.tests.constants import url, api_key os.environ['SMC_ADDRESS'] = url os.environ['SMC_API_KEY'] = api_key os.environ['SMC_TIMEOUT'] = '200' session.login(beta=True) self.assertEqual(url, 'http://172.18.1.26:8082') self.assertEqual(session._extra_args.get('beta'), True) session.refresh() self.assertEqual(url, 'http://172.18.1.26:8082') self.assertEqual(session._extra_args.get('beta'), True) session.logout() session._api_key = None # Raises because we do not have a session already with self.assertRaises(SMCConnectionError): session.refresh() # Somehow credential is bad during retry. This will just raise with self.assertRaises(SMCConnectionError): session._api_key = 'foo' session.refresh()
def login(self): # Validate endpoint if self.endpoint == '': logging.fatal( 'Endpoint "smc_endpoint" cannot be empty in configuration file.' ) if not self.endpoint.startswith( 'https://') and not self.endpoint.startswith('http://'): logging.warning( 'Endpoint "smc_endpoint" should start with "https://" or "http://" to be valid. Adding in now.' ) self.endpoint = f'http://{self.endpoint}' if self.endpoint.endswith('/'): logging.warning( 'Endpoint "smc_endpoint" should not end with "/". Removing now.' ) self.endpoint = self.endpoint[:len(self.endpoint) - 2] # Validate port if self.port == 0: logging.fatal( 'Port number must be set. The SMC cannot run on port 0.') # Validate api key if self.api_key == '': logging.fatal( "API Key for SMC must be present in the configuration.") # Attempt to login for session url = f'{self.endpoint}:{self.port}' session.login(url=url, api_key=self.api_key, api_version=self.api_version)
def get_smc_session(smc): """ Get SMC session and validate settings exist :raises: smc.api.exceptions.SMCConnectionError on failure """ if smc: if smc.get('smc_address') and smc.get('smc_apikey'): session.login(**transform_login(smc)) else: session.login() else: session.login() logger.debug("Successful connection to SMC")
def run_query_and_upload(): aws_integration = cfg.get('aws-integration', False) azure_integration = cfg.get('azure-integration', False) # Create default insights if they don't already exist if aws_integration: threading.Thread(target=create_default_insights).start() setup_sec_hub() enable_batch_import_findings() default_filter = __setup_smc_query_filter(cfg['default-filter']) smc_url = cfg['host-ip'] + ':' + cfg['host-port'] api_version = __get_latest_api_version(smc_url) session.login(url=smc_url, api_key=cfg['client-api-key'], api_version=api_version) try: query = LogQuery(fetch_size=int(cfg['fetch-size'])) translated_filter = query.add_translated_filter() # Create default filter specified in the config file translated_filter.update_filter(default_filter) # Query the SMC for events matching the filter and flatten the list of result-lists into a single list record_list = list(itertools.chain(*query.fetch_raw())) extra_filters_enabled = cfg['extra-filters-enabled'] # Check to see if extra filters are enabled and if any are present before iterating over them and requesting # matching events from the SMC and appending to the original results list if bool(extra_filters_enabled): extra_filters = cfg['extra-filters'] if bool(extra_filters): for log_filter in extra_filters: translated_filter.update_filter(__setup_smc_query_filter(log_filter)) record_list.extend(list(itertools.chain(*query.fetch_raw()))) if record_list: # Find the max date in the record list and store this to add to the filter for subsequent queries # to avoid uploading duplicates/wasting bandwidth. This value is written to the cfg.json file max_finding_date = format_date_smc_filter(max(item['Creation Time'] for item in record_list)) loop = asyncio.get_event_loop() # Map to appropriate format and upload if integration is active if aws_integration: aws_task = loop.create_task( amazon_security_hub_batch_upload(list(map(create_asff_object, record_list)), max_finding_date)) loop.run_until_complete(aws_task) if azure_integration: send_sentinel_data(list(map(format_smc_logs_to_cef, record_list)), max_finding_date) # This catches any issues related to requesting events with a malformed filter except FetchAborted as exception: print(exception) write_to_log(exception) session.logout()
""" Example of creating a single firewall with multiple interface types. Once interfaces are defined, add routes that are needed. Note that to add a default route, use the 0.0.0.0/0 address as the gateway address. Specify a policy to upload once the single FW instance has made the initial contact. This will be queued and kick off once the contact is complete. Generate the initial contact information for sg-reconfigure on the virtual or appliance. """ from smc import session from smc.core.engines import Layer3Firewall if __name__ == '__main__': session.login(url='http://172.18.1.25:8082', api_key='4366TuolHMJp3nHaUeF60001') # Create base engine specifying management IP info and management # interface number engine = Layer3Firewall.create('myfirewall', mgmt_ip='172.18.1.160', mgmt_network='172.18.1.0/24', mgmt_interface=0, domain_server_address=['8.8.8.8']) if engine: print "Successfully created Layer 3 firewall, adding interfaces.." # Create a new physical interface for single firewall engine.physical_interface.add_single_node_interface( interface_id=1, address='1.1.1.1', network_value='1.1.1.0/24') # Create a second interface using VLANs and assign IP info
def setUp(self): session.login(url=url, api_key=api_key, verify=verify) Host.create('test-common-api-user', '12.12.12.12') # used for wildcard searches Host.create('test-api-user', '12.12.12.12')
""" # Python Base Import import sys from smc import session from smc.core.engine import Engine from smc.elements.network import Expression from smc.elements.service import ApplicationSituation, TCPService from smc.policy.rule_elements import MatchExpression from smc_info import * if __name__ == '__main__': session.login(url=SMC_URL, api_key=API_KEY, verify=False, timeout=120, api_version=API_VERSION) print("session OK") try: # check for all engines engine_list = list(Engine.objects.all()) # Create a match_expression me = MatchExpression.create(name='mymatch', service=ApplicationSituation('FTP'), service_ports=TCPService('Any TCP Service')) # Get Name for first match_expression name = MatchExpression.objects.iterator().first().name
logging.basicConfig(level=logging.ERROR) """ from smc import session from smc.core.engines import FirewallCluster from smc.elements.helpers import zone_helper import logging logging.getLogger() # logging.basicConfig(level=logging.ERROR) if __name__ == '__main__': session.login(url='https://172.18.1.25:8082', api_key='avUj6vFZTUSZ7sr8mNsP0001', verify=False) # Create the Firewall Cluster engine = FirewallCluster.create(name='mycluster', cluster_virtual='1.1.1.1', cluster_mask='1.1.1.0/24', cluster_nic=0, macaddress='02:02:02:02:02:02', nodes=[{ 'address': '1.1.1.2', 'network_value': '1.1.1.0/24', 'nodeid': 1 }, { 'address': '1.1.1.3', 'network_value': '1.1.1.0/24',
from smc.elements.network import Host, Alias import json import logging logging.getLogger() logging.basicConfig(level=logging.INFO) if __name__ == '__main__': # edit ~/.smcrc # [smc] # smc_address=192.168.100.7 # smc_apikey=xxxxxxxxxxx # smc_port=8082 # smc_ssl=False # verify_ssl=False session.login() policy = FirewallPolicy.get('mynatpolicy1', raise_exc=False) if policy: policy.delete() policy = FirewallPolicy.create(name='mynatpolicy1', template='Firewall Inspection Template') kali_host = Host.get_or_create(name='kali', address='1.1.1.1') host3 = Host.get_or_create(name='host-3.3.3.3', address='3.3.3.3') # Example of creating a dynamic source NAT for host 'kali': policy.fw_ipv4_nat_rules.create(name='mynatrule-srcdyn', sources=[Host('kali')], destinations='any', services='any',
line below and set the logging level (recommend ERROR unless troubleshooting):: logging.basicConfig(level=logging.ERROR) """ from smc import session from smc.core.engines import FirewallCluster from smc.elements.helpers import zone_helper import logging logging.getLogger() # logging.basicConfig(level=logging.ERROR) if __name__ == '__main__': session.login(url='https://172.18.1.25:8082', api_key='avUj6vFZTUSZ7sr8mNsP0001', verify=False) # Create the Firewall Cluster engine = FirewallCluster.create(name='mycluster', cluster_virtual='1.1.1.1', cluster_mask='1.1.1.0/24', cluster_nic=0, macaddress='02:02:02:02:02:02', nodes=[{'address': '1.1.1.2', 'network_value': '1.1.1.0/24', 'nodeid': 1}, {'address': '1.1.1.3', 'network_value': '1.1.1.0/24', 'nodeid': 2}, {'address': '1.1.1.4', 'network_value': '1.1.1.0/24', 'nodeid': 3}], domain_server_address=['1.1.1.1'], zone_ref=zone_helper('Internal'), enable_antivirus=True, enable_gti=True,
import sys, json from websocket import create_connection from smc import session from smc_monitoring.monitors.neighbors import NeighborQuery from smc_monitoring.models.values import FieldValue, StringValue from smc_monitoring.models.constants import LogField if __name__ == '__main__': URLSMC = 'localhost:8082' APIKEYSMC = 'HuphG4Uwg4dN6TyvorTR0001' ENGINENAME = 'Plano' try: session.login(url="http://" + URLSMC, api_key=APIKEYSMC, verify=False, timeout=120) except BaseException as exception_retournee: sys.exit(-1) print("session OK") print("Retrieve Neighbors using websocket library") ws = create_connection("ws://" + URLSMC + "/6.9/monitoring/session/socket", cookie=session.session_id) query = { "query": { "definition": "NEIGHBORS", "target": ENGINENAME },
#logging.basicConfig(level=logging.DEBUG) filename = '/Users/davidlepage/statis routes.txt' firewall = 'mcafee2' def mask_convertor(network_and_netmask): netmask = network_and_netmask.split('/') cidr = sum([bin(int(x)).count('1') for x in netmask.pop().split('.')]) netmask.append(str(cidr)) return '/'.join(netmask) if __name__ == '__main__': session.login(url='http://172.18.1.150:8082', api_key='EiGpKD4QxlLJ25dbBEp20001') #Load the engine configuration; raises LoadEngineFailed for not found engine engine = Engine(firewall).load() with open(filename) as f: for line in f: for match in re.finditer('route=(.*) gateway=(.*) distance.*?', line, re.S): network = mask_convertor(match.group(1)) gateway = match.group(2) print "Adding route to network: {}, via gateway: {}".format(\ network, gateway) result = engine.add_route(gateway, str(network)) if not result.href:
Create a new Firewall policy, open (lock) the policy, create a rule and save, then delete a rule by name. ''' from smc import session from smc.policy.layer3 import FirewallPolicy from smc.elements.network import Host from smc.elements.collection import describe_tcp_service import logging logging.getLogger() logging.basicConfig(level=logging.INFO) if __name__ == '__main__': session.login(url='http://172.18.1.25:8082', api_key='4366TuolHMJp3nHaUeF60001') """ Create a new Firewall Policy using the Firewall Inspection Template """ FirewallPolicy.create(name='smcpython', template='Firewall Inspection Template') """ Get an existing policy """ policy = FirewallPolicy('smcpython') """ Open the policy for editing, create a rule, and save the policy """
def create_iplist_with_data(name, iplist): """ Create an IPList with initial list contents. :param str name: name of IPList :param list iplist: list of IPList IP's, networks, etc :return: href of list location """ iplist = IPList.create(name=name, iplist=iplist) return iplist if __name__ == '__main__': session.login(url='http://172.18.1.26:8082', api_key='xxxxxxxxxxxxxxxxxxx', timeout=45) # Create initial list programmatically result = create_iplist_with_data(name='mylistlist', iplist=[ '123.123.123.123', '23.23.23.23']) print('This is the href location for the newly created list: %s' % result) # print upload_as_text('mylist', # '/Users/username/git/smc-python/src/smc/examples/ip_addresses') # print upload_as_json('mylist', {'ip': ['1.1.1.1', '2.2.2.2', '3.3.3.3']}) # print upload_as_zip('mylist', # '/Users/username/git/smc-python/src/smc/examples/iplist.zip') # print create_iplist(name='newlist')
from smc import session smc_url = "http://localhost:8082" smc_key = "HuphG4Uwg4dN6TyvorTR0001" smc_domain = "" api_version = "6.9" timeout = 180 ################################################ # Login the api session.login( url=smc_url, domain=smc_domain, api_key=smc_key, api_version=api_version, timeout=timeout, verify=False, ) try: # Cloud engine creation print("Create cloud fw: Cloud Single firewall 1...") CloudSGSingleFW.create_dynamic(interface_id=0, name="Cloud Single firewall 1") # Should not use regular create method but create_dynamic instead # Since cloud firewall should use dynamic interface try: CloudSGSingleFW.create(name="test cloud name", mgmt_ip="1.1.1.1", mgmt_network="1.1.1.0/24") except Exception as e:
def create(namespace): if namespace.template_path: with open(namespace.template_path, 'r') as template_file_fd: template = json.load(template_file_fd) pub_ssh_key_path = os.path.expanduser( '~/.ssh/id_rsa.pub') # the path to rsa public key file with open(pub_ssh_key_path, 'r') as pub_ssh_file_fd: pub_ssh_key = pub_ssh_file_fd.read() session.login() if namespace.force_remove: try: Layer3Firewall(namespace.resource_group).delete() except ElementNotFound: pass engineCfg = provision_stonesoft(name=namespace.resource_group, vnet=None, location=namespace.engine_location) parameters = { 'engineCfg': engineCfg, 'engineUsername': namespace.engine_username, 'sshKey': pub_ssh_key } parameters = {k: {'value': v} for k, v in parameters.items()} resource_client = client() resource_group_params = { 'location': namespace.location_id, 'tags': { 'stonesoft': namespace.tag_value } } try: resource_client.resource_groups.create_or_update( namespace.resource_group, resource_group_params) deployment_properties = { 'mode': DeploymentMode.incremental, 'parameters': parameters, 'template': None, 'template_link': None } if namespace.template_path: deployment_properties.update(template=template) else: deployment_properties.update( template_link=TemplateLink(namespace.template_link)) deployment_async_operation = resource_client.deployments.create_or_update( resource_group_name=namespace.resource_group, deployment_name=namespace.deployment_name, properties=deployment_properties) # AzureOperationPoller initial_result = deployment_async_operation.result(timeout=30) logger.info('Starting Azure deployment; correlation id: %s', initial_result.properties.correlation_id) logger.info('Azure provisioning state: %s', initial_result.properties.provisioning_state) while not deployment_async_operation.done(): deployment_async_operation.wait(timeout=30) status = resource_client.deployments.get( namespace.resource_group, deployment_name=namespace.deployment_name) logger.info('Azure provisioning state: %s', status.properties.provisioning_state) result = deployment_async_operation.result() elapsed_time = result.properties.timestamp - initial_result.properties.timestamp logger.info('Elapsed Time: %s (seconds)', elapsed_time.total_seconds()) if namespace.engine_policy: provision_stonesoft_policy(namespace.engine_policy) for k, v in result.properties.outputs.items(): logger.info('{} -> {}'.format(k, v.get('value'))) except CloudError: Layer3Firewall(namespace.resource_group).delete() raise finally: session.logout()
a list of all firewall policies :param str name: name of policy; If None, return all policies :raises ElementNotFound: raised if policy was specified and it didn't exist :rtype: list(FirewallPolicy) or FirewallPolicy """ if name: return FirewallPolicy.get(name) return [fp for fp in FirewallPolicy.objects.all()] if __name__ == '__main__': from smc import session session.login(url='http://172.18.1.150:8082', api_key='EiGpKD4QxlLJ25dbBEp20001', timeout=30, verify=False, retry_on_busy=True) """ Obtain the policy based on it's type. This example uses a FirewallPolicy type but all policy types are supported, i.e: IPSPolicy or Layer2Policy; as well as templates, i.e: IPSTemplatePolicy, FirewallTemplatePolicy, Layer2TemplatePolicy .. note:: NAT rules and IPv6 rules are included in the output and do not need to be handled separately. """ policy = FirewallPolicy.get('Standard Firewall Policy with Inspection') #policy = get_firewall_policy('Standard*') # <-- Wildcard will only return first match """ Rule counters on a given policy can be obtained for all engines using
if published.action == 'create': add_policy(published.element) elif published.action == 'trashed': remove_policy(published.element) from smc_monitoring.pubsub.subscribers import Notification, Event import threading import time if __name__ == '__main__': #session.login(url='http://172.18.1.26:8082', api_key='kKphtsbQKjjfHR7amodA0001', timeout=45, # beta=True) session.login(url='http://172.18.1.150:8082', api_key='EiGpKD4QxlLJ25dbBEp20001', timeout=30, api_version='6.4') #session.login(url='https://172.18.1.151:8082', api_key='xJRo27kGja4JmPek9l3Nyxm4', # verify=False) pprint(session._get_log_schema()) #TODO: BLACKLISTQUERY fails when using format ID's due to CombinedFilter. query = BlacklistQuery('ve-1') query.add_in_filter(FieldValue(LogField.BLACKLISTENTRYSOURCEIP), [IPValue('3.3.3.3/32')]) for record in query.fetch_as_element( ): # <-- must get as element to obtain delete() method
throttle timer settings, and the max metric router link-state advertisement (LSA) settings. """ OSPFDomainSetting.create(name='custom', abr_type='cisco') ospf_domain = OSPFDomainSetting('custom') # obtain resource ospf_profile = OSPFProfile.create(name='myospfprofile', domain_settings_ref=ospf_domain.href) print(ospf_profile) if __name__ == '__main__': session.login(url='http://172.18.1.150:8082', api_key='EiGpKD4QxlLJ25dbBEp20001', timeout=60) """ Create an OSPF area using the default OSPF Interface Setting element, create a layer 3 firewall, enabling OSPF and applying the OSPF Area to Interface 0 """ for profile in describe_ospfv2_interface_settings(): if profile.name.startswith('Default OSPF'): profile_ref = profile.href area = OSPFArea.create(name='area0', interface_settings_ref=profile_ref, area_id=0) area = OSPFArea('area0') # obtain resource
azure_remote_ips = {} for gateway_config in azure_config: for vpn_site_connection in gateway_config['vpnSiteConnections']: azure_region = vpn_site_connection['hubConfiguration']['Region'] psk = vpn_site_connection['connectionConfiguration']['PSK'] ip_addrs = [] for ip in vpn_site_connection['gatewayConfiguration']['IpAddresses'].values(): ip_addrs.append(ip) azure_remote_ips[azure_region] = (ip_addrs, psk) session.login(url=smc_url, api_key=smc_api_key, api_version=str(smc_api_version)) ngfw_external_endpoint_ips = config.get_smc('ngfw-external-interface-ip') ngfw_internal_vpn_endpoint_ips = config.get_smc('ngfw-internal-vpn-interface-ip') ngfw_external_network_address_space = config.get_smc('ngfw-external-address-space') ngfw_internal_vpn_address_space = config.get_smc('ngfw-internal-vpn-address-space') for ngfw_azure_location in config.get_smc('ngfw-azure-locations'): for key in ngfw_azure_location.keys(): build_vpn_smc( key, gateway_profile, azure_remote_ips[ngfw_azure_location[key]] + (ngfw_external_endpoint_ips[key],), ngfw_external_network_address_space[key], ngfw_internal_vpn_endpoint_ips[key], ngfw_internal_vpn_address_space[key]
from smc.elements.network import Host, Alias import json import logging logging.getLogger() logging.basicConfig(level=logging.INFO) if __name__ == '__main__': # edit ~/.smcrc # [smc] # smc_address=192.168.100.7 # smc_apikey=xxxxxxxxxxx # smc_port=8082 # smc_ssl=False # verify_ssl=False session.login() policy = FirewallPolicy.get('mynatpolicy1', raise_exc=False) if policy: policy.delete() policy = FirewallPolicy.create(name='mynatpolicy1', template='Firewall Inspection Template') kali_host = Host.get_or_create(name = 'kali', address='1.1.1.1') host3 = Host.get_or_create(name='host-3.3.3.3', address='3.3.3.3') # Example of creating a dynamic source NAT for host 'kali': policy.fw_ipv4_nat_rules.create(name='mynatrule-srcdyn', sources=[Host('kali')],
def setUp(self): session.login(url=url, api_key=api_key, verify=verify)
def create_iplist_with_data(name, iplist): """ Create an IPList with initial list contents. :param str name: name of IPList :param list iplist: list of IPList IP's, networks, etc :return: href of list location """ iplist = IPList.create(name=name, iplist=iplist) return iplist if __name__ == '__main__': session.login(url='http://172.18.1.26:8082', api_key='xxxxxxxxxxxxxxxxxxx', timeout=45) # Create initial list programmatically result = create_iplist_with_data(name='mylistlist', iplist=[ '123.123.123.123', '23.23.23.23']) print('This is the href location for the newly created list: %s' % result) # print upload_as_text('mylist', # '/Users/davidlepage/git/smc-python/src/smc/examples/ip_addresses') # print upload_as_json('mylist', {'ip': ['1.1.1.1', '2.2.2.2', '3.3.3.3']}) # print upload_as_zip('mylist', # '/Users/davidlepage/git/smc-python/src/smc/examples/iplist.zip') # print create_iplist(name='newlist')