Example #1
0
    def testGroup(self):
        # Member not href
        with self.assertRaises(CreateElementFailed):
            Group.create('foogroup', ['test'], 'comment')

        # Same as above
        with self.assertRaises(CreateElementFailed):
            Group.create('foogroup', ['172.18.1.80'])

        # Empty group
        group = Group.create('foogroup')
        self.assertTrue(group.href.startswith('http'))

        # Get context
        group = Group('foogroup')

        # Members
        Host.create('groupmember', '1.1.1.1')
        Network.create(name='anetwork', ipv4_network='1.1.1.0/24')

        self.assertIsNone(group.update_members(members=[Host('groupmember')]))
        # ETag in cache matches server after update
        etag = search.element_by_href_as_smcresult(group.href).etag
        self.assertEqual(group.etag, etag)

        # Get the members back and verify
        for member in group.obtain_members():
            self.assertIn(member.name, ['groupmember'])

        # Check Host has a reference to group
        refs = Host('groupmember').referenced_by
        self.assertEqual(refs[0].name, 'foogroup')

        # Add second member and append
        group.update_members(members=[Network('anetwork')], append_lists=True)
        members = group.obtain_members()
        self.assertTrue(len(members) == 2)
        etag = search.element_by_href_as_smcresult(group.href).etag
        self.assertEqual(group.etag, etag)

        # Overwrite (test sending in as a href)
        group.update_members(members=[Host('groupmember').href],
                             append_lists=False)
        members = group.obtain_members()
        self.assertTrue(len(members) == 1)
        self.assertEqual(members[0].name, 'groupmember')
        etag = search.element_by_href_as_smcresult(group.href).etag
        self.assertEqual(group.etag, etag)

        # Delete all members
        group.empty_members()
        self.assertTrue(len(group.obtain_members()) == 0)
        group.rename('group2')
        # Delete
        Host('groupmember').delete()
        group = Group('group2')
        group.delete()
def smc_configuration(engine_name, public_ip, private_ip, public_network):
    session_login()
    vpn_name, tunnel_1, tunnel_2 = get_vpn(public_ip)

    network_name = f'awsnetwork-{public_network}'
    try:
        Network.create(name=network_name, ipv4_network=public_network)
    except CreateElementFailed as err:
        logging.info(err)

    l3fw_policy('transit_gw_policy')
    policy = firewall_rule('transit_gw_policy')

    add_tunnel_to_engine(engine_name, '2000', tunnel_1.get('outside_ip'),
                         tunnel_1.get('inside_ip_cidr'), 'tunnelA')
    add_tunnel_to_engine(engine_name, '2001', tunnel_2.get('outside_ip'),
                         tunnel_2.get('inside_ip_cidr'), 'tunnelB')

    try:
        remote_gateway_first = external_gateway(
            name=f'{vpn_name}-{1}',
            endpoint_name='endpoint_1',
            address=tunnel_1.get('outside_ip'),
            network_name=network_name
        )  # site-to-site vpn connection VPN ID include number at the end
    except CreateElementFailed as err:
        logging.info(err)

    try:
        remote_gateway_second = external_gateway(
            name=f'{vpn_name}-{2}',
            endpoint_name='endpoint_2',
            address=tunnel_2.get('outside_ip'),
            network_name=network_name
        )  # site-to-site vpn connection VPN ID include number at the end
    except CreateElementFailed as err:
        logging.info(err)

    bgp_elements(
        64512, vpn_name, tunnel_1.get('gateway'), tunnel_2.get('gateway'),
        engine_name
    )  # transit gateway : Amazon ASN inside ip is from tunnel of vpn - the /30

    add_dynamic_routing_antispoofing(engine_name)

    vpn_endpoint = Engine(engine_name).vpn_endpoint.get_contains(private_ip)
    vpn_endpoint.update(enabled=True)

    vpn_create_ipsec(engine_name, 2000, tunnel_1.get('pre_shared_key'),
                     vpn_name, 1, remote_gateway_first)
    vpn_create_ipsec(engine_name, 2001, tunnel_2.get('pre_shared_key'),
                     vpn_name, 2, remote_gateway_second)

    policy.upload(engine_name)

    session.logout()
Example #3
0
    def test_network_ipv6(self):
        network = Network.create(name='mixednetwork', ipv6_network='fc00::/7')
        self.assertTrue(network.href.startswith('http'))

        network = Network('mixednetwork')
        self.assertEqual(network.ipv6_network, 'fc00::/7')
        network.delete()
Example #4
0
    def test_multilink_member(self):
        Network.create(name='comcast', ipv4_network='10.10.0.0/16')
        Router.create(name='nexthop', address='10.10.1.254')

        StaticNetlink.create(name='isp1',
                             gateway=Router('nexthop'),
                             network=[Network('comcast')],
                             probe_address=['10.10.0.1'])

        member1 = multilink_member(StaticNetlink('isp1'),
                                   nat_range='10.10.0.1-10.10.0.1')

        self.assertEqual(member1['ip_range'], '10.10.0.1-10.10.0.1')
        self.assertEqual(member1['netlink_ref'], StaticNetlink('isp1').href)
        self.assertEqual(member1['netlink_role'], 'active')
        self.assertEqual(member1['network_ref'], Network('comcast').href)

        # Add a second member to the static netlink
        n = StaticNetlink('isp1')
        Network.create('att', ipv4_network='192.168.1.0/24')
        n.add_network(Network('att'))

        # creating a multilink member fails when there are more than one
        # networks defined and one has not been specified
        with self.assertRaises(MissingRequiredInput):
            multilink_member(StaticNetlink('isp1'),
                             nat_range='10.10.0.1-10.10.0.1')

        # Now provide that specific network
        member1 = multilink_member(StaticNetlink('isp1'),
                                   nat_range='192.168.1.1-192.168.1.1',
                                   netlink_network=Network('att'))

        self.assertEqual(member1['ip_range'], '192.168.1.1-192.168.1.1')
        self.assertEqual(member1['netlink_ref'], StaticNetlink('isp1').href)
        self.assertEqual(member1['netlink_role'], 'active')
        self.assertEqual(member1['network_ref'], Network('att').href)

        m = Multilink.create(name='testmultilink', multilink_members=[member1])
        self.assertTrue(m.href.startswith('http'))

        Multilink('testmultilink').delete()
        StaticNetlink('isp1').delete()
        Network('comcast').delete()
        Network('att').delete()
        Router('nexthop').delete()
Example #5
0
    def test_bgp_profile(self):
        """
        Test BGP Profiles
        """
        Network.create(name='bgpnet', ipv4_network='1.1.1.0/24')
        profile = BGPProfile.create(name='myprofile',
                                    port=300,
                                    external_distance=100,
                                    internal_distance=150,
                                    local_distance=200,
                                    subnet_distance=[(Network('bgpnet'), 100)])

        self.assertTrue(profile.href.startswith('http'))
        myprofile = BGPProfile('myprofile')

        self.assertEqual(myprofile.port, 300)
        self.assertEqual(myprofile.internal_distance, 150)
        self.assertEqual(myprofile.external_distance, 100)
        self.assertEqual(myprofile.local_distance, 200)
        for subnet in myprofile.subnet_distance:
            self.assertEqual(subnet[0].name, 'bgpnet')
            self.assertEqual(subnet[1], 100)
        myprofile.delete()
        Network('bgpnet').delete()
Example #6
0
    def testNetwork(self):
        # Invalid host bits
        with self.assertRaises(CreateElementFailed):
            Network.create('foonetwork', '12.1.1.1/24', 'comment')

        Network.create('foonetwork',
                       ipv4_network='12.1.1.0/24',
                       ipv6_network='2001:db8:abcd:12::/64')

        network = Network('foonetwork')
        self.assertEqual(network.ipv4_network, '12.1.1.0/24')
        self.assertEqual(network.ipv6_network, '2001:db8:abcd:12::/64')
        network.rename('foonetwork2')
        network = Network('foonetwork2')
        network.delete()

        # Not CIDR format
        with self.assertRaises(CreateElementFailed):
            Network.create('foonetwork', '12.1.1.0/255.255.255.0')
Example #7
0
    """
    external_gateway = ExternalGateway.create("mygw")
    """
    An external endpoint is defined within the external gateway and specifies the
    IP address settings and other VPN specific settings for this endpoint
    After creating, add to the external gateway
    """
    external_gateway.external_endpoint.create(name="myendpoint",
                                              address="2.2.2.2")
    """
    Lastly, 'sites' need to be configured that identify the network/s on the
    other end of the VPN. You can either use pre-existing network elements, or create
    new ones as in the example below.
    Then add this site to the external gateway
    """
    network = Network.create("remote-network", "1.1.1.0/24").href

    external_gateway.vpn_site.create("remote-site", [network])
    """
    Retrieve the internal gateway for SMC managed engine by loading the
    engine configuration. The internal gateway reference is located as
    engine.internal_gateway.href
    """
    engine = Engine("testfw").load()
    """
    Create the VPN Policy
    """
    vpn = PolicyVPN.create(name="myVPN", nat=True)
    print(vpn.name, vpn.vpn_profile)

    vpn.open()
Example #8
0
    """
    external_gateway = ExternalGateway.create('mygw')
    """
    An external endpoint is defined within the external gateway and specifies the
    IP address settings and other VPN specific settings for this endpoint
    After creating, add to the external gateway
    """
    external_gateway.external_endpoint.create(name='myendpoint',
                                              address='2.2.2.2')
    """
    Lastly, 'sites' need to be configured that identify the network/s on the
    other end of the VPN. You can either use pre-existing network elements, or create
    new ones as in the example below.
    Then add this site to the external gateway
    """
    network = Network.create('remote-network', '1.1.1.0/24').href

    external_gateway.vpn_site.create('remote-site', [network])
    """
    Retrieve the internal gateway for SMC managed engine by loading the
    engine configuration. The internal gateway reference is located as
    engine.internal_gateway.href
    """
    engine = Engine('testfw').load()
    """
    Create the VPN Policy
    """
    vpn = PolicyVPN.create(name='myVPN', nat=True)
    print vpn.name, vpn.vpn_profile

    vpn.open()
Example #9
0
    def test_create_engine_add_bgp_peering(self):

        engine = Layer3Firewall.create(name='myfw',
                                       mgmt_ip='1.1.1.1',
                                       mgmt_network='1.1.1.0/24')

        engine.physical_interface.add_single_node_interface(
            interface_id=0, address='5.5.5.5', network_value='5.5.5.0/24')

        Network.create(name='bgpnet', ipv4_network='2.2.2.0/24')
        AutonomousSystem.create(name='aws_as', as_number=20000)
        engine.enable_bgp(autonomous_system=AutonomousSystem('aws_as'),
                          announced_networks=[Network('bgpnet')])
        BGPPeering.create(name='mypeer')
        ExternalBGPPeer.create(name='neighbor',
                               neighbor_as_ref=AutonomousSystem('aws_as'),
                               neighbor_ip='3.3.3.3')

        # Only add to a single network
        for route in engine.routing.all():
            if route.nicid == '0':
                route.add_bgp_peering(BGPPeering('mypeer'),
                                      ExternalBGPPeer('neighbor'),
                                      network='5.5.5.0/24')

        # Traverse the nested routing tree..
        for route in engine.routing.all():
            if route.nicid == '0':
                for bgp_peering in route.all():
                    if bgp_peering.ip == '5.5.5.0/24':
                        for peering in bgp_peering.all():  # BGPPeering
                            self.assertEqual(peering.name, 'mypeer')
                            for external_peer in peering.all(
                            ):  # ExternalBGPPeer
                                self.assertEqual(external_peer.name,
                                                 'neighbor')
        engine.delete()

        # Add BGP to all interfaces
        engine = Layer3Firewall.create(name='myfw',
                                       mgmt_ip='1.1.1.1',
                                       mgmt_network='1.1.1.0/24')

        engine.physical_interface.add_single_node_interface(
            interface_id=0, address='5.5.5.5', network_value='5.5.5.0/24')
        # Only add to a single network
        interface = engine.routing.get(0)
        # for route in engine.routing.all():
        #    if route.nicid == '0':
        interface.add_bgp_peering(BGPPeering('mypeer'),
                                  ExternalBGPPeer('neighbor'))

        for route in engine.routing.all():
            if route.nicid == '0':
                for bgp_peering in route.all():
                    for peering in bgp_peering.all():
                        self.assertEqual(peering.name, 'mypeer')  # BGPPeering
                        for external_peer in peering.all():
                            # ExternalBGPPeer
                            self.assertEqual(external_peer.name, 'neighbor')
        engine.delete()
Example #10
0
cnameV4 = cname + '-v4'
cnameV6 = cname + '-v6'
cnameNAT = cname + '-NAT'

#################
#Host NAT Element erstellen
#################

Host.create(name=cnameNAT, address=NATIP, comment='Erstellt via Script')

#################
#Network IPv6 Element erstellen
#################

Network.create(name=cnameV6, ipv6_network=IPV6Network, comment='Erstellt via Script')

#################
#IPv6 Sub Policy erstellen
#################

p = FirewallIPv6SubPolicy.create(name=cnameV6)
p.fw_ipv6_access_rules.create_rule_section(name='Outbound')
p.fw_ipv6_access_rules.create(name='Default Outgoing', sources=[Network(cnameV6)], destinations='any', services=[TCPService('SSH'), TCPService('HTTP'), TCPService('HTTPS'), UDPService('NTP (UDP)'), ServiceGroup('DNS')], action='allow', after='Outbound')
p.fw_ipv6_access_rules.create_rule_section(name='Inbound', add_pos=30)

#################
#IPv4 Sub Policy erstellen
#################

q = FirewallSubPolicy.create(name=cnameV4)
Example #11
0
    def test_layer3_engine_methods(self):
        # Test each of the top level engine methods
        engine = Layer3Firewall.create(name='smcpython-fw',
                                       mgmt_ip='1.1.1.1',
                                       mgmt_network='1.1.1.0/24')
        self.assertIsInstance(engine, Engine)

        if session.api_version >= 6.1:
            test = Engine('smcpython-fw')
            self.assertTrue(test.type == 'single_fw')
            self.assertTrue(test.href.startswith('http'))
            self.assertTrue(test.version is None)
            self.assertTrue(isinstance(test.nodes, list))

        # Modify an attribute, i.e. antivirus:
        self.assertTrue(
            engine.modify_attribute(
                antivirus={
                    'antivirus_enabled': False,
                    'antivirus_update': 'daily',
                    'antivirus_update_day': 'mo',
                    'antivirus_update_time': 21600000,
                    'virus_log_level': 'none',
                    'virus_mirror': 'update.nai.com/Products/CommonUpdater'
                }).startswith('http'))

        # Test Fail load using wildcard
        Host.create('testengine', '1.1.1.1')
        Host.create('testengine2', '2.2.2.2')
        with self.assertRaises(ElementNotFound):
            foo = Engine('testengine*')
            foo.href

        Host('testengine').delete()
        Host('testengine2').delete()

        # Engine type
        self.assertEqual(engine.type, 'single_fw')
        # Get the node type
        self.assertEqual(engine.nodes[0].type, 'firewall_node')

        # Iterate nodes
        for node in engine.nodes:
            self.assertIsInstance(repr(node), str)
            self.assertIsInstance(node, Node)

        # Get permissions, only for SMC API >- 6.1
        if session.api_version >= 6.1:
            for x in engine.permissions:
                self.assertIsInstance(x, AccessControlList)
        else:
            self.assertRaises(UnsupportedEngineFeature,
                              lambda: engine.permissions())

        # Get aliases
        aliases = engine.alias_resolving()
        for alias in aliases:
            self.assertIsInstance(alias, Alias)
            self.assertIsNotNone(alias.name)
            self.assertTrue(alias.href.startswith('http'))
            self.assertIsInstance(alias.resolved_value, list)

        # Resolve the IP address alias for this engine
        alias = Alias('$$ Interface ID 0.ip')
        self.assertIn('1.1.1.1', alias.resolve('smcpython-fw'))

        # Blacklist, will fail as engine is not live or connected to SMC
        self.assertRaises(EngineCommandFailed,
                          lambda: engine.blacklist('1.1.1.1/32', '0.0.0.0/0'))

        # Blacklist flush, same as above
        self.assertRaises(EngineCommandFailed,
                          lambda: engine.blacklist_flush())

        # Add route, valid
        result = engine.add_route('1.1.1.254', '192.168.1.0/24')
        self.assertIsNone(result)

        # Add route, invalid, msg attribute set
        self.assertRaises(EngineCommandFailed,
                          lambda: engine.add_route('2.2.2.2', '10.10.10.0/22'))

        # Get routes, will catch SMCConnectionException because the engine doesnt
        # exist and will be unresponsive. It should catch and return empty list
        # A response is sent back in 6.1.2, but should be none
        if is_min_required_smc_version('6.1.2'):
            self.assertRaises(EngineCommandFailed,
                              lambda: engine.routing_monitoring)
        else:  # Timeout in version 6.1.1 or earlier
            self.assertRaises(EngineCommandFailed,
                              lambda: engine.routing_monitoring)

        # Get antispoofing info
        Network.create(name='network-10.1.2.0/24', ipv4_network='10.1.2.0/24')

        spoofing = engine.antispoofing
        self.assertIsInstance(spoofing, Antispoofing)
        for entry in engine.antispoofing.all():
            if entry.name == 'Interface 0':
                self.assertEqual(entry.level, 'interface')
                self.assertEqual(entry.validity, 'enable')
                entry.add(Network('network-10.1.2.0/24'))

        # Look for our network
        for entry in engine.antispoofing.all():
            if entry.name == 'Interface 0':
                for network in entry.all():
                    if network.name == 'network-10.1.2.0/24':
                        self.assertEqual(network.ip, '10.1.2.0/24')

        self.assertTrue(
            engine.internal_gateway.name.startswith('smcpython-fw'))

        # Get internal gateway
        for gw in engine.internal_gateway.internal_endpoint.all():
            self.assertEqual(gw.name, '1.1.1.1')  # matches interface IP

        # Get vpn sites
        for sites in engine.internal_gateway.vpn_site.all():
            self.assertTrue(
                sites.name.startswith('Automatic Site for smcpython-fw'))

        # Gen certificate for internal gateway, fail because engine can't gen
        # cert
        v = VPNCertificate('myorg', 'foo.org')
        self.assertRaises(
            CertificateError,
            lambda: engine.internal_gateway.generate_certificate(v))

        # Gateway certificate request, not implemented as of 0.3.7
        self.assertTrue(
            len(engine.internal_gateway.gateway_certificate()) == 0)

        # Gateway certificate, not implemented as of 0.3.7
        self.assertTrue(
            len(engine.internal_gateway.gateway_certificate_request()) == 0)

        # Get a virtual resource on non supported device type
        self.assertRaises(UnsupportedEngineFeature,
                          lambda: engine.virtual_resource)

        # Get interfaces
        for intf in engine.interface.all():
            self.assertEqual(intf.name, 'Interface 0')

        # Get virtual physical interface, not supported on layer 3 engine
        self.assertRaises(UnsupportedInterfaceType,
                          lambda: engine.virtual_physical_interface)

        # Get modem interfaces
        self.assertTrue(len(engine.modem_interface) == 0)

        # Get adsl interfaces
        self.assertTrue(len(engine.adsl_interface) == 0)

        # Get wireless interface
        self.assertTrue(len(engine.wireless_interface) == 0)

        # Get switch interface
        self.assertTrue(len(engine.switch_physical_interface) == 0)

        # Get tunnel interfaces
        engine.tunnel_interface.add_single_node_interface(
            tunnel_id=1000, address='2.2.2.2', network_value='2.2.2.0/24')
        intf = engine.interface.get(1000)
        self.assertIsInstance(intf, TunnelInterface)

        # Query tunnel interfaces
        for intf in engine.tunnel_interface.all():
            self.assertEqual(intf.name, 'Tunnel Interface 1000')

        # Refresh policy, fails as engine not ready
        self.assertRaises(TaskRunFailed, lambda: engine.refresh())

        # Upload, policy doesn't exist
        self.assertRaises(TaskRunFailed, lambda: engine.upload(policy='foo'))

        # Generate snapshot #TODO: Bug
        with self.assertRaises(EngineCommandFailed):
            engine.generate_snapshot()

        # See snapshots. Policy hasnt been pushed yet so they wont exist
        self.assertTrue(len(list(engine.snapshots)) == 0)

        # Delete
        engine.delete()
        Network('network-10.1.2.0/24').delete()
Example #12
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()
    """
    An external endpoint is defined within the external gateway and specifies the
    IP address settings and other VPN specific settings for this endpoint
    After creating, add to the external gateway
    """
    external_gateway.external_endpoint.create(name='myendpoint',
                                              address='2.2.2.2')

    """
    Lastly, 'sites' need to be configured that identify the network/s on the
    other end of the VPN. You can either use pre-existing network elements, or create
    new ones as in the example below.
    Then add this site to the external gateway
    """
    network = Network.create('remote-network', '1.1.1.0/24').href

    external_gateway.vpn_site.create('remote-site', [network])

    """
    Retrieve the internal gateway for SMC managed engine by loading the
    engine configuration. The internal gateway reference is located as
    engine.internal_gateway.href
    """
    engine = Engine('testfw').load()

    """
    Create the VPN Policy
    """
    vpn = PolicyVPN.create(name='myVPN', nat=True)
    print vpn.name, vpn.vpn_profile