예제 #1
0
    def test_L2FW_create_good_policy_failed_rule_create(self):
        policy = Layer2Policy.create(
            name='layer2foo', template='Layer 2 Firewall Inspection Template')
        self.assertIsInstance(policy, Layer2Policy)

        # Fail create due to existing policy
        with self.assertRaises(CreatePolicyFailed):
            Layer2Policy.create(
                name='layer2foo',
                template='Layer 2 Firewall Inspection Template')

        # Validate template
        template = policy.template
        self.assertIsInstance(template, Layer2TemplatePolicy)
        self.assertEqual(template.name, 'Layer 2 Firewall Inspection Template')

        # Invalid to add a service and application together
        service = list(Search('tcp_service').objects.filter('HTTPS'))
        application = list(
            Search('application_situation').objects.filter('100Bao'))

        with self.assertRaises(CreateRuleFailed):
            policy.layer2_ipv4_access_rules.create(name='bogus',
                                                   sources='any',
                                                   destinations='any',
                                                   services=service +
                                                   application)

        policy.delete()
예제 #2
0
    def test_ospf_key_chain_and_ospf_interface_setting(self):
        key_chain = OSPFKeyChain.create(name='smcpython-keychain',
                                        key_chain_entry=[{
                                            'key': 'fookey',
                                            'key_id': 10,
                                            'send_key': True
                                        }])
        self.assertTrue(key_chain.href.startswith('http'))
        ospf_interface = OSPFInterfaceSetting.create(
            name='smcpython-ospf',
            authentication_type='message_digest',
            key_chain_ref=key_chain)
        self.assertTrue(ospf_interface.href.startswith('http'))
        o = OSPFInterfaceSetting('smcpython-ospf')
        self.assertTrue(o.href.startswith('http'))

        # Delete interface setting first
        ospf_intf = list(
            Search('ospfv2_interface_settings').objects.filter(
                'smcpython-ospf'))
        ospf_intf[0].delete()

        key_chain = list(
            Search('ospfv2_key_chain').objects.filter('smcpython-keychain'))
        key_chain[0].delete()
예제 #3
0
    def test_IPS_validate_fw_ethernet_rule_creation_with_fail(self):
        policy = IPSPolicy.create(name='layer2foo',
                                  template='High-Security IPS Template')
        self.assertIsInstance(policy, IPSPolicy)
        # Policy - notice action is not correct, will default to allow
        with self.assertRaises(CreateRuleFailed):
            policy.ips_ethernet_rules.create(name='myethernetrule',
                                             sources='any',
                                             action='foo',
                                             destinations='any',
                                             services='any')

        for rule in policy.ips_ethernet_rules.all():
            self.assertIsInstance(rule, EthernetRule)
            self.assertEqual(rule.name, 'myethernetrule')
            action = rule.data.get('action')
            self.assertEqual(action.get('action'), 'allow')
            rule.delete()

        service = list(Search('tcp_service').objects.filter('HTTPS'))
        application = list(
            Search('application_situation').objects.filter('100Bao'))

        with self.assertRaises(CreateRuleFailed):
            policy.ips_ethernet_rules.create(name='bogus',
                                             sources='any',
                                             destinations='any',
                                             services=service + application)

        policy.delete()
예제 #4
0
    def test_change_host_name_in_unicode(self):
        result = Host.create('Curaçao35', '12.12.12.12')
        self.assertTrue(result.href.startswith('http'))

        for host in list(Search('host').objects.filter('Curaçao35')):
            modified = host.modify_attribute(name='São Tomé Host35')
            self.assertTrue(modified.startswith('http'))

        for host in list(Search('host').objects.filter('São Tomé Host35')):
            host.delete()
예제 #5
0
    def test_ospf_unicast(self):

        for profile in list(Search('ospfv2_interface_settings').objects.all()):
            if profile.name.startswith('Default OSPF'):
                interface_profile = profile.href

        area = OSPFArea.create(name='smcpython-area',
                               interface_settings_ref=interface_profile,
                               area_id=0)
        self.assertTrue(area.href.startswith('http'))

        area = OSPFArea('smcpython-area')

        engine = Layer3Firewall.create(name='smcpython-ospf',
                                       mgmt_ip='172.18.1.30',
                                       mgmt_network='172.18.1.0/24',
                                       domain_server_address=['8.8.8.8'],
                                       enable_ospf=True)

        self.assertIsInstance(engine, Engine)
        host = Host.create(name='smcpython-ospf-user', address='23.23.23.23')

        # Get routing resources
        for interface in engine.routing.all():
            if interface.name == 'Interface 0':
                result = interface.add_ospf_area(area,
                                                 communication_mode='unicast',
                                                 unicast_ref=host)
                self.assertIsNone(result)

        engine.delete()
        area.delete()

        Host('smcpython-ospf-user').delete()
예제 #6
0
 def test_download_IPList_as_text(self):
     if session.api_version >= 6.1:
         location = list(
             Search('ip_list').objects.filter('smcpython-iplist'))
         if location:
             iplist = location[0]
             result = iplist.download(filename='iplist.txt', as_type='txt')
             self.assertIsNone(result)
예제 #7
0
    def test_upload_IPList_as_json(self):
        if session.api_version >= 6.1:
            location = list(
                Search('ip_list').objects.filter('smcpython-iplist'))
            if location:
                iplist = location[0]
                result = iplist.upload(
                    json={'ip': ['1.1.1.1', '2.2.2.2', '3.3.3.3']},
                    as_type='json')
                self.assertIsNone(result)

                with self.assertRaises(CreateElementFailed):
                    iplist.upload(json={'ip': ['1.1.1.1a']}, as_type='json')

        for iplist in list(
                Search('ip_list').objects.filter('smcpython-iplist')):
            iplist.delete()
예제 #8
0
    def test_search_known(self):
        host = Host.create('Réunion30', '30.30.30.30')
        self.assertTrue(host.href.startswith('http'))
        
        result = smc.actions.search.element_as_json('Réunion30')
        self.assertEqual(u'Réunion30', result.get('name'), result)

        for host in list(Search('host').objects.filter('Réunion30')):
            host.delete()
예제 #9
0
 def test_FAILED_download_IPList_as_text(self):
     # Fails if directory doesnt exist or is a directory
     if session.api_version >= 6.1:
         location = list(
             Search('ip_list').objects.filter('smcpython-iplist'))
         if location:
             iplist = location[0]
             with self.assertRaises(IOError):
                 iplist.download(filename='/blah/ahagsd/iplist.txt',
                                 as_type='txt')
예제 #10
0
 def test_download_IPList_as_zip(self):
     if session.api_version >= 6.1:
         location = list(
             Search('ip_list').objects.filter('smcpython-iplist'))
         if location:
             iplist = location[0]
             result = iplist.download(filename='iplist.zip', as_type='zip')
             self.assertIsNone(result)
             # Require the filename, will fail
             with self.assertRaises(MissingRequiredInput):
                 iplist.download(as_type='zip')
예제 #11
0
    def test_create_unicode_name_firewall(self):
        fw = Layer3Firewall.create(name='ĂĂĂĂrdvark36',
                                   mgmt_ip='1.1.1.1',
                                   mgmt_network='1.1.1.0/24')

        self.assertEquals(fw.name, u'ĂĂĂĂrdvark36',
                          'unicode fw names do not match')

        for fw in list(Search('single_fw').objects.all()):
            if fw.name == u'ĂĂĂĂrdvark36':  # Required b/c non-ascii. Otherwise use from futures import literals
                fw.delete()
예제 #12
0
    def test_ospf_key_chain(self):
        key_chain = OSPFKeyChain.create(name='smcpython-keychain',
                                        key_chain_entry=[{
                                            'key': 'fookey',
                                            'key_id': 10,
                                            'send_key': True
                                        }])
        self.assertTrue(key_chain.href.startswith('http'))

        # Find and delete through collections
        key_chain = list(
            Search('ospfv2_key_chain').objects.filter('smcpython-keychain'))
        key_chain[0].delete()
예제 #13
0
    def test_download_IPList_as_json(self):

        if session.api_version >= 6.1:
            location = list(
                Search('ip_list').objects.filter('smcpython-iplist'))
            iplist = location[0]
            result = iplist.download(as_type='json')
            # Version 6.1.2 has a problem when JSON is NOT returned when
            # specifying application/json headers
            if is_min_required_smc_version('6.1.2'):
                self.assertIsNone(result)
            else:
                ips = ['1.1.1.1', '2.2.2.2']
                print('ips: %s, result: %s' % (ips, result.json))
                self.assertEqual(ips, result.json.get('ip'))
예제 #14
0
    def test_FW_create_good_policy_failed_rule_create(self):
        policy = FirewallPolicy.create(name='myfoopolicy',
                                       template='Firewall Inspection Template')
        self.assertIsInstance(policy, FirewallPolicy)
        # Fail
        with self.assertRaises(CreatePolicyFailed):
            FirewallPolicy.create(name='myfoopolicy',
                                  template='Firewall Inspection Template')

        # Get the template
        self.assertIsInstance(policy.template, FirewallTemplatePolicy)

        service = list(Search('tcp_service').objects.filter('HTTPS'))
        application = list(
            Search('application_situation').objects.filter('100Bao'))

        with self.assertRaises(CreateRuleFailed):
            policy.fw_ipv4_access_rules.create(name='bogus',
                                               sources='any',
                                               destinations='any',
                                               services=service + application)

        self.assertIsNone(policy.force_unlock())
        policy.delete()
    def exec_module(self, **kwargs):
        state = kwargs.pop('state', 'present')
        for name, value in kwargs.items():
            setattr(self, name, value)

        # Validate whether the element type is valid
        entry_points = Search.object_types()

        for element in self.elements:
            for typeof, element_data in element.items():
                if typeof not in entry_points:
                    self.fail(msg='The specified element type: %s is not valid. '
                        'Data provided: %s' % (typeof, element))
                if 'name' not in element_data:
                    self.fail(msg='The name field is required to operate on all '
                        'elements. Data provided: %s' % element)

        try:
            if self.check_mode:
                return self.results

            for element in self.elements:
                for typeof, data in element.items():
                    try:
                        instance, updated, created = lookup_class(typeof).update_or_create(
                            with_status=True, **data)

                        action = 'none'

                        if updated:
                            action = 'updated'
                        elif created:
                            action = 'created'

                        if updated or created:
                            self.results['changed'] = True

                        self.results['state'].append(dict(name=instance.name,
                            typeof=instance.typeof, action=action))

                    except SMCException as e:
                        self.results['state'].append(dict(name=data.get('name'),
                            typeof=typeof, action='error', reason=str(e)))

        except SMCException as err:
            self.fail(msg=str(err), exception=traceback.format_exc())

        return self.results
예제 #16
0
    def test_upload_IPList_as_txt(self, mock_open):
        if session.api_version >= 6.1:
            cfg = ("1.1.1.1\n2.2.2.2")
            mock_open.return_value = io.StringIO(u'{}'.format(cfg))
            iplist = None
            location = list(
                Search('ip_list').objects.filter('smcpython-iplist'))
            if location:
                iplist = location[0]
            else:
                iplist = IPList.create(name='smcpython-iplist')
                self.assertTrue(iplist.href.startswith('http'))

            result = iplist.upload(filename='iplist.txt', as_type='txt')
            self.assertIsNone(result)
            iplist.delete()
예제 #17
0
    def testLocation(self):
        locations = list(Search('location').objects.filter('api-location'))
        if locations:
            self.assertIsNone(locations[0].delete())

        if session.api_version <= 6.0:
            self.assertRaises(UnsupportedEntryPoint,
                              lambda: Location.create('api-location'))
        else:
            result = Location.create('api-location')
            self.assertTrue(result.href.startswith('http'))
            location = Location('api-location')
            # No references but test the method that returns list
            if is_min_required_smc_version('6.2.0'):
                self.assertFalse(location.used_on)
            location.delete()
예제 #18
0
    def test_add_vpn_policy(self):
        result = VPNPolicy.create(name='smcpythonVPN', nat=True)
        self.assertIsInstance(result, VPNPolicy)
        self.assertTrue(result.nat)
        result.enable_disable_nat()  # Disable NAT
        self.assertFalse(result.nat)
        result.enable_disable_nat()  # Enable it again
        self.assertTrue(result.nat)

        with self.assertRaises(CreatePolicyFailed):
            VPNPolicy.create(name='smcpythonVPN')

        # Check VPN Profile
        self.assertIsNotNone(result.vpn_profile)

        for x in list(Search('vpn').objects.filter('smcpythonVPN')):
            self.assertTrue(x.href.startswith('http'))
            x.delete()
예제 #19
0
    def test_create_layer3_firewall_and_add_ospf(self):

        for profile in list(Search('ospfv2_interface_settings').objects.all()):
            if profile.name.startswith('Default OSPF'):
                interface_profile = profile.href

        area = OSPFArea.create(name='smcpython-area',
                               interface_settings_ref=interface_profile,
                               area_id=0)
        self.assertTrue(area.href.startswith('http'))

        area = OSPFArea('smcpython-area')

        engine = Layer3Firewall.create(name='smcpython-ospf',
                                       mgmt_ip='172.18.1.30',
                                       mgmt_network='172.18.1.0/24',
                                       domain_server_address=['8.8.8.8'],
                                       enable_ospf=True)

        self.assertIsInstance(engine, Engine)
        # Add IPv6 to make sure OSPF is skipped for that interface
        engine.physical_interface.add_single_node_interface(
            interface_id=0,
            address='2001:db8:85a3::8a2e:370:7334',
            network_value='2001:db8:85a3::/64')
        # Get routing resources
        for interface in engine.routing.all():
            # if interface.name == 'Interface 0':
            if interface.nicid == '0':
                # Apply OSPF 'area0' to interface 0
                interface.add_ospf_area(area)
                for networks in interface.all():  # Traverse networks
                    self.assertIn(networks.name, [
                        'network-172.18.1.0/24', 'network-2001:db8:85a3::/64'
                    ])
                    self.assertTrue(networks.level == 'network')

        # Add only to specified network
        for interface in engine.routing.all():
            if interface.name == 'Interface 0':
                interface.add_ospf_area(area, network='172.18.1.0/24')

        engine.delete()
        area.delete()
예제 #20
0
    def test_FW_rule_with_outliers(self):

        policy = FirewallPolicy.create(name='myfoopolicy',
                                       template='Firewall Inspection Template')
        self.assertIsInstance(policy, FirewallPolicy)

        host = Host.create('asourcehost', '1.1.1.1')

        services = list(Search('tcp_service').objects.filter('HTTP'))
        policy.fw_ipv4_access_rules.create(name='myrule',
                                           sources=[host],
                                           services=services)

        # Rule with no sources
        policy.fw_ipv4_access_rules.create(name='myrule',
                                           sources=[host],
                                           services=services)

        policy.delete()
        Host('asourcehost').delete()
예제 #21
0
    def test_upload_IPList_as_zip(self):
        if session.api_version >= 6.1:

            #zf = zipfile.ZipFile(io.BytesIO(), "a", zipfile.ZIP_DEFLATED, False)
            # Write the file to the in-memory zip
            #zf.writestr('ip_addresses', '1.1.1.1\n2.2.2.2\n3.3.3.3')
            # print(zf)

            #mock_open.return_value = ('iplist.zip', zf)
            iplist = None
            location = list(
                Search('ip_list').objects.filter('smcpython-iplist'))
            if location:
                iplist = location[0]
            else:
                iplist = IPList.create(name='smcpython-iplist')
                self.assertTrue(iplist.href.startswith('http'))

            result = iplist.upload(filename='iplist.zip')
            self.assertIsNone(result)
예제 #22
0
    def test_ospf_area(self):

        for profile in list(Search('ospfv2_interface_settings').objects.all()):
            if profile.name.startswith(
                    'Default OSPF'):  # Use the system default
                interface_profile = profile.href

        area = OSPFArea.create(name='area-smcpython',
                               interface_settings_ref=interface_profile,
                               area_id=0)
        self.assertTrue(area.href.startswith('http'))

        area = OSPFArea('area-smcpython')
        self.assertEqual(area.interface_settings_ref.name,
                         'Default OSPFv2 Interface Settings')
        area.delete()

        # Test without interface setting, it will use default
        intf = OSPFInterfaceSetting('Default OSPFv2 Interface Settings').href
        OSPFArea.create(name='area0', area_id=0)
        area = OSPFArea('area0')
        self.assertEqual(area.data.get('interface_settings_ref'), intf)
        area.delete()
예제 #23
0
 def test_fail_iterator_query_returns_empty_list(self):
     with mock.patch('smc.base.collection.Search._validate',
                     return_value='foo') as validate_function:
         assert validate_function() == 'foo'
         result = list(Search('foo').objects.all())
         self.assertTrue(len(result) == 0)
예제 #24
0
    def test_create_host_with_unicode(self):
        result = Host.create('Réunion33', '30.30.30.30')
        self.assertTrue(result.href.startswith('http'))

        for host in list(Search('host').objects.filter('Réunion33')):
            host.delete()
예제 #25
0
    def test_add_external_gateway_endpoint_and_vpnsite(self):
        for gw in list(
                Search('external_gateway').objects.filter(
                    'smcpython-externalgw')):
            gw.delete()

        result = ExternalGateway.create(name='smcpython-externalgw')
        self.assertIsInstance(result, ExternalGateway)
        e = ExternalGateway('smcpython-externalgw')
        self.assertTrue(e.trust_all_cas)
        self.assertIsInstance(e.gateway_profile, GatewayProfile)

        # For vpn site
        network = Network.create('py4.4.4.0', '4.4.4.0/24')

        e = ExternalGateway('smcpython-externalgw')
        # for x in list(Search('external_gateway').objects.filter('smcpython-externalgw')):
        #    self.assertIsNotNone(x.href) #have meta
        res = e.external_endpoint.create('myendpoint',
                                         '1.1.1.1')  # create endpoint
        self.assertTrue(res.startswith('http'))

        # Invalid endpoint
        with self.assertRaises(CreateElementFailed):
            e.external_endpoint.create('myendpoint', '1.1.1.1a')

        # Fail test_external gateway
        with self.assertRaises(CreateElementFailed):
            ExternalGateway.create('smcpython-externalgw')

        site = e.vpn_site.create('pythonsite', [network])  # Create vpn site
        self.assertTrue(site.startswith('http'))

        with self.assertRaises(CreateElementFailed):
            e.vpn_site.create('poosite', ['http://1.1.1.1'])

        # Add an additional network to an existing VPN Site
        network = Network.create('pythonnetwork', '23.23.23.0/24')

        gw = ExternalGateway('smcpython-externalgw')
        for sites in gw.vpn_site.all():
            self.assertEqual(sites.name, 'pythonsite')
            self.assertTrue(sites.site_element)
            sites.add_site_element([network])  # Add a network to site list
            for network in sites.site_element:
                self.assertIn(network.name, ['pythonnetwork', 'py4.4.4.0'])

            internal_gateway = sites.gateway
            self.assertEqual(internal_gateway.name, 'smcpython-externalgw')

        e = ExternalGateway('smcpython-externalgw')
        for endpoint in e.external_endpoint:
            self.assertFalse(endpoint.force_nat_t)  # Disabled
            endpoint.enable_disable_force_nat_t()  # Enable
            self.assertTrue(endpoint.force_nat_t)
            endpoint.enable_disable_force_nat_t()  # Disable again
            self.assertFalse(endpoint.force_nat_t)  # Disabled

            self.assertTrue(endpoint.enabled)  # Enabled
            endpoint.enable_disable()  # Disable
            self.assertFalse(endpoint.enabled)
            endpoint.enable_disable()  # Enable again
            self.assertTrue(endpoint.enabled)

        gw.delete()

        for network in list(Search('network').objects.all()):
            if network.name == 'py4.4.4.0' or network.name == 'pythonnetwork':
                network.delete()
예제 #26
0
 def test_file_filtering_policy(self):
     # Not fully implemented
     policy = list(Search('file_filtering_policy').objects.all())
     if policy:
         for rules in policy[0].file_filtering_rules.all():
             self.assertIsInstance(rules, FileFilteringRule)
예제 #27
0
 def test_element_references(self):
     for x in list(Search('log_server').objects.all()):
         # Dependent on Management Server
         result = smc.actions.search.element_references(x.href)
         self.assertTrue(len(result) > 0)
예제 #28
0
    def test_search_collections(self):
        entry_points = Search.object_types()
        self.assertIsInstance(entry_points, list)
        self.assertTrue(len(entry_points) > 0)

        # Object type with defined class
        results = list(Search('host').objects.all())
        self.assertIsInstance(results, list)
        for result in results:
            self.assertIsInstance(result, Host)

        # Object type without defined class
        results = list(Search('ids_alert').objects.all())
        self.assertIsInstance(results, list)
        for result in results:
            self.assertIsInstance(result, Element)

        with self.assertRaises(UnsupportedEntryPoint):
            Search('foo').objects.all()

        self.assertIsInstance(Search('host').objects, CollectionManager)

        # Access collection through element directly
        results = list(TCPService.objects.all())  # @UndefinedVariable
        self.assertIsInstance(results, list)
        for result in results:
            self.assertIsInstance(result, TCPService)

        filtered = list(
            TCPService.objects.filter('HTTP'))  # @UndefinedVariable
        self.assertIsInstance(filtered, list)
        for result in filtered:
            self.assertIsInstance(result, TCPService)

        # No results
        result = list(Search('host').objects.filter('blahblah'))
        self.assertFalse(result)

        # Test limit
        result = list(TCPService.objects.all().limit(5))  # @UndefinedVariable
        self.assertTrue(len(result) == 5)

        # Get iterator and test collection
        iterator = TCPService.objects.iterator()  # @UndefinedVariable
        results = list(iterator.all())
        self.assertTrue(results)
        self.assertTrue(len(results) == iterator.count())

        results = list(iterator.all().limit(5))
        self.assertTrue(len(result) == 5)

        self.assertIsNotNone(iterator.first())
        self.assertIsNotNone(iterator.last())

        self.assertIsNotNone(iterator.first())
        self.assertIsNotNone(iterator.last())
        self.assertTrue(iterator.count() > 0)

        results = iterator.filter('HTTP')
        self.assertIsInstance(results, ElementCollection)
        self.assertTrue(list(results))

        #limit in manager
        result = Host.objects.limit(3)  # @UndefinedVariable
        self.assertTrue(len(list(result)) == 3)

        # Filter based on multiple entry points at once
        for x in list(Search('router,host').objects.all()):
            self.assertTrue(isinstance(x, (Host, Router)))

        iterator = Host.objects
        self.assertIsInstance(iterator, CollectionManager)

        Router.create('R1', address='10.10.10.1')
        Router.create('R2', address='110.10.10.1')
        router = Router.objects.iterator()
        results = list(router.filter('10.10.10.1'))
        self.assertTrue(len(results) == 2)
        query1 = router.filter(address='10.10.10.1')
        self.assertTrue(query1.count() == 2)  # Not filtered until iterating
        results = list(query1)
        self.assertTrue(len(results) == 1)
        self.assertEqual(query1.first().name, 'R1')

        h1 = Host.create(name='host1',
                         address='1.1.1.1',
                         comment='host1comment')
        h2 = Host.create(name='host2', address='1.1.1.1')
        results = list(
            Host.objects.filter(address='1.1.1.1', comment='host1comment'))
        self.assertTrue(len(results) == 1)
        self.assertEqual(results[0].name, 'host1')

        results = list(Host.objects.filter(address='1.1.1.1', comment='foo'))
        self.assertFalse(results)

        h1.delete()
        h2.delete()

        # Test batch function
        it = TCPService.objects.batch(4)
        for _ in range(1, 5):
            self.assertTrue(len(next(it)) == 4)

        # Test batch running out
        it = Host.objects.batch(20)
        for x in it:
            self.assertTrue(len(x) <= 20)

        # Test cloning when using filter_key
        it = Router.objects.iterator()
        query1 = it.filter(address='10.10.10.1').limit(1)
        element = query1.first()
        self.assertEqual(element.name, 'R1')

        result = Router.objects.first()
        self.assertIsNotNone(result)

        for router in ['R1', 'R2']:
            Router(router).delete()