Esempio n. 1
0
 def test_access_before_loading(self):
     if session.api_version <= 6.0:
         engine = Engine('foo')
         self.assertRaises(AttributeError, lambda: engine.nodes)
     else:
         engine = Engine('foo')
         self.assertRaises(ElementNotFound, lambda: engine.nodes)
Esempio n. 2
0
def delete(ve, master_engine):
    #Delete easily. Just load the engine resource and call delete. Delete VE's first.
    #All elements descend from smc.base.model.Element
    #Note: Most operations will return an instance of smc.api.web.SMCResult so you 
    #can view the return attributes if necessary.
    ve = Engine('layer3-ve').load()
    ve.delete()
    
    master = Engine('engine-cluster').load()
    master.delete()
def vpn_create_ipsec(engine_name, interface_id, preshared_key, vpn_name,
                     vpn_num, remote_gateway):
    tunnel_if = Engine(engine_name).tunnel_interface.get(interface_id)
    local_gateway = TunnelEndpoint.create_ipsec_endpoint(
        Engine(engine_name).vpn.internal_gateway, tunnel_if)

    RouteVPN.create_ipsec_tunnel(name=f'{engine_name}-{vpn_name}-{vpn_num}',
                                 preshared_key=preshared_key,
                                 local_endpoint=local_gateway,
                                 remote_endpoint=remote_gateway,
                                 enabled=True,
                                 vpn_profile=VPNProfile('aws_profile'))
def bgp_elements(aws_ASN, vgw_id, tunnel_inside_ip_1, tunnel_inside_ip_2,
                 engine_name):
    engine = Engine(engine_name)
    try:
        AutonomousSystem().create(name='aws-as',
                                  as_number=aws_ASN,
                                  comment='aws VGW ASN')
    except CreateElementFailed as err:
        logging.info(err)

    try:
        AutonomousSystem().create(name='ngfw-as',
                                  as_number=65000,
                                  comment='NGFW ASN')
    except CreateElementFailed as err:
        logging.info(err)

    try:
        ExternalBGPPeer().create(
            name=f"peer-{vgw_id}-1",
            comment="aws bgp peering element for tunnel_1",
            neighbor_as=AutonomousSystem("aws-as"),
            neighbor_ip=tunnel_inside_ip_1)
    except CreateElementFailed as err:
        logging.info(err)

    try:
        ExternalBGPPeer().create(
            name=f"peer-{vgw_id}-2",
            comment="aws bgp peering element for tunnel_2",
            neighbor_as=AutonomousSystem("aws-as"),
            neighbor_ip=tunnel_inside_ip_2)
    except CreateElementFailed as err:
        logging.info(err)

    engine.dynamic_routing.bgp.enable(
        autonomous_system=AutonomousSystem(name='ngfw-as'),
        announced_networks=[Network('Any network')])

    try:
        BGPPeering.get('ngfw-bgp-peering')
    except ElementNotFound as err:
        BGPPeering.create(name='ngfw-bgp-peering')  # ngfw-bgp-peering

    Engine(engine_name).routing.get(2000).add_bgp_peering(
        BGPPeering('ngfw-bgp-peering'), ExternalBGPPeer(f'peer-{vgw_id}-1'))
    Engine(engine_name).routing.get(2001).add_bgp_peering(
        BGPPeering('ngfw-bgp-peering'), ExternalBGPPeer(f'peer-{vgw_id}-2'))

    engine.update()
Esempio n. 5
0
def blacklist_flush(name):
    """ Flush entire blacklist for node name

    :param name: name of node or cluster to remove blacklist
    :return: None
    :raises: EngineCommandFailed
    """
    engine = Engine(name).load()
    return engine.blacklist_flush()
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()
def add_tunnel_to_engine(engine_name, interface, address, cidr_range,
                         zone_ref):
    try:
        Engine(engine_name).tunnel_interface.add_layer3_interface(
            interface_id=interface,
            address=address,
            network_value=cidr_range,
            zone_ref=zone_ref)

    except SMCException as err:
        logging.info(err)
Esempio n. 8
0
def blacklist(name, src, dst, duration=3600):
    """ Add blacklist entry to engine node by name

    :param name: name of engine node or cluster
    :param src: source to blacklist, can be /32 or network cidr
    :param dst: dest to deny to, 0.0.0.0/32 indicates all destinations
    :param duration: how long to blacklist in seconds
    :return: :py:class:`smc.api.web.SMCResult`
    """
    engine = Engine(name).load()
    return engine.blacklist(src, dst, duration)
Esempio n. 9
0
def unbind_license(name):
    """
    Unbind license on single node engine

    :param name: name of engine
    :return: None
    :raises: LoadEngineFailed, NodeCommandFailed
    """
    engine = Engine(name).load()
    for node in engine.nodes:
        return node.unbind_license()
Esempio n. 10
0
    def create(cls,
               name,
               master_type,
               mgmt_ip,
               mgmt_network,
               mgmt_interface=0,
               log_server_ref=None,
               domain_server_address=None,
               enable_gti=False,
               enable_antivirus=False):
        """
        Create a Master Engine with management interface
        
        :param str name: name of master engine engine
        :param str master_type: firewall|
        :param str mgmt_ip: ip address for management interface
        :param str mgmt_network: full netmask for management
        :param str mgmt_interface: interface to use for mgmt (default: 0)
        :param str log_server_ref: (optional) href to log_server instance 
        :param list domain_server_address: (optional) DNS server addresses
        :param boolean enable_antivirus: (optional) Enable antivirus (required DNS)
        :param boolean enable_gti: (optional) Enable GTI
        :return: :py:class:`smc.core.engine.Engine`
        :raises: :py:class:`smc.api.exceptions.CreateEngineFailed`: Failure to create with reason
        """
        physical = PhysicalInterface()
        physical.add_node_interface(mgmt_interface,
                                    mgmt_ip,
                                    mgmt_network,
                                    primary_mgt=True,
                                    primary_heartbeat=True,
                                    outgoing=True)

        engine = Engine.create(name=name,
                               node_type=cls.node_type,
                               physical_interfaces=[physical()],
                               domain_server_address=domain_server_address,
                               log_server_ref=log_server_ref,
                               nodes=1,
                               enable_gti=enable_gti,
                               enable_antivirus=enable_antivirus)

        engine.update(master_type=master_type, cluster_mode='standby')

        href = search.element_entry_point('master_engine')
        result = prepared_request(href=href, json=engine).create()
        if result.href:
            return Engine(name=name,
                          meta=Meta(name=name,
                                    href=result.href,
                                    type='master_engine'))
        else:
            raise CreateEngineFailed('Could not create the engine, '
                                     'reason: {}'.format(result.msg))
Esempio n. 11
0
def l3route(name, gateway, ip_network):
    """ Add route to l3fw 
    This could be added to any engine type. Non-routable engine roles (L2/IPS) may
    still require route/s defined on the L3 management interface   

    :param l3fw: name of firewall to add route
    :param gw: next hop router object
    :param ip_network: next hop network behind gw
    :return: :py:class:`smc.qpi.web.SMCResult`
    """
    engine = Engine(name).load()
    return engine.add_route(gateway, ip_network)
Esempio n. 12
0
def l3interface(name, ipaddress, ip_network, interfaceid):
    """ Add L3 interface for single FW

    :param l3fw: name of firewall to add interface to
    :param ip: ip of interface
    :param network: network for ip
    :param interface_id: interface_id to use
    :return: :py:class:`smc.api.web.SMCResult`
    :raises: LoadEngineFailed
    """
    engine = Engine(name).load()
    result = engine.physical_interface.add_single_node_interface(
        interface_id=interfaceid, address=ipaddress, network_value=ip_network)
    return result
Esempio n. 13
0
    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')
Esempio n. 14
0
    def exec_module(self, **kwargs):
        for name, value in kwargs.items():
            setattr(self, name, value)

        result = ''
        try:
            engine = Engine(self.name)
            node = engine.nodes.get(self.nodeid)
            if not node:
                raise SMCException(
                    'Node specified for action %r was not found. This engine '
                    'has %s nodes (numbering starts at 1)' %
                    (self.action, len(engine.nodes)))

            self.check_provided_args(node, self.action)

            # Run command
            result = getattr(node, self.action)(**self.extra_args)
            self.results['changed'] = True
            #             if self.action == 'initial_contact':
            #                 self.results['state'].append(
            #                     node.initial_contact(**self.extra_args))
            #                 #enable_ssh=True, time_zone=None,
            #                 #keyboard=None,
            #                 #filename=None,
            #                 #as_base64=False
            #             elif self.action == 'change_ssh_pwd':
            #                 pass
            #                 # pwd
            #             elif self.action == 'sginfo':
            #                 pass
            #                 #include_core_files=False,
            #                 #include_slapcat_output=False,
            #                 #filename='sginfo.gz'
            #             elif self.action == 'ssh':
            #                 pass
            #                 # enabled
            #             elif self.action == 'bind_license':
            #                 pass
            #                 #license_item_id
            self.results['state'] = self.get_state_after_action(node)

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

        self.results['msg'] = result
        return self.results
    def exec_module(self, **kwargs):
        for name, value in kwargs.items():
            setattr(self, name, value)

        elements = []
        try:
            engine = Engine(self.filter)
            elements = [
                route_dict_from_obj(element)
                for element in engine.routing_monitoring
            ]

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

        self.results['ansible_facts'] = {'routes': elements}
        return self.results
def remove_smc_engines(engine_name, public_ip, private_ip):
    session_login()
    MASK = '255.255.255.0'
    engine = Engine(engine_name)
    routes = RouteVPN.objects.all()
    gateways_to_delete = []
    for route in list(routes):
        route_name = route.name
        if engine_name in route_name:
            RouteVPN().get(route_name).delete()
            gateways_to_delete.append((route_name.split(engine_name)[-1])[1:])
    engine.delete()
    for gw in gateways_to_delete:
        ExternalGateway.get(gw).delete()
    public_base = MyIPv4(public_ip) & MyIPv4(MASK)
    public_network = string_to_ip(str(public_base) + '/24')
    Network.get(f'awsnetwork-{public_network}').delete()
    session.logout()
Esempio n. 17
0
def capture_interface(name,
                      interface_id,
                      logical_interface_ref='default_eth',
                      zone=None):
    """ Add a capture interface. 
    Capture interfaces can only be added to Layer 2 Firewall or IPS roles.

    :param name: name of layer2 fw or ips to add to
    :param logical_interface_ref: logical interface, will find ref and create if it doesnt exist
    :param zone: optional zone name
    :return: :py:class:`smc.qpi.web.SMCResult`
    :raises: LoadEngineFailed
    """
    engine = Engine(name).load()
    result = engine.physical_interface.add_capture_interface(
        interface_id=interface_id,
        logical_interface_ref=logical_intf_helper(logical_interface_ref))
    return result
Esempio n. 18
0
def l2interface(name,
                interface_id,
                logical_interface_ref='default_eth',
                zone=None):
    """ Add layer 2 inline interface   
    Inline interfaces require two physical interfaces for the bridge and a logical 
    interface to be assigned. By default, interface 1,2 will be used if interface_id is 
    not specified. 
    The logical interface is used by SMC for policy to logically group both interfaces
    It is not possible to have inline and capture interfaces on the same node with the
    same logical interface definition. Automatically create logical interface if it does
    not already exist.

    :param node: node name to add inline interface pair
    :param interface_id [], int values of interfaces to use for inline pair (default: 1,2)
    :param logical_int: logical interface name to map to inline pair (default: 'default_eth')
    :return: :py:class:`smc.api.web.SMCResult`
    :raises: LoadEngineFailed
    """
    engine = Engine(name).load()
    result = engine.physical_interface.add_inline_interface(
        interface_id=interface_id,
        logical_interface_ref=logical_intf_helper(logical_interface_ref))
    return result
Esempio n. 19
0
 SMC without a "Target" specified.
   
 :rtype: list(smc.policy.policy.RuleCounter)
 """
 print("Rule counters by policy only\n------------------------")
 for counter in policy.rule_counters(engine=None):
     print(counter)
   
 """
 Get rule counters by specific engine
   
 :param Engine engine: the engine specified as element
 :rtype: list(smc.policy.policy.RuleCounter)
 """
 print("Rule counters by engine\n------------------------")
 for counter in policy.rule_counters(engine=Engine('sg_vm')):
     print(counter)
       
 """
 Durations can be used to specify how far back to retrieve the rule
 counters. 
   
 :param str duration_type: duration for obtaining rule counters. Valid
     options are: one_day, one_week, one_month, six_months, one_year,
     custom, since_last_upload; If custom is provided, set the `duration`
     attribute as well
 :rtype: list(smc.policy.policy.RuleCounter)
 """
 print("Rule counters for last month\n------------------------")
 for counter in policy.rule_counters(duration_type='one_month'):
     print(counter)
Esempio n. 20
0
    #engine = Engine('foo')
    
    #if session.session.verify and session.session.verify 

    #import sys
    #sys.exit(1)
    #TODO: BLACKLISTQUERY fails when using format ID's due to CombinedFilter.
    #import websocket
    websocket.enableTrace(True)
  
    #https://stackoverflow.com/questions/38501531/forcing-requests-library-to-use-tlsv1-1-or-tlsv1-2-in-python
    from smc_monitoring.models.query import Query
    #query = ConnectionQuery('lynn', check_hostname=False)
    #query = BlacklistQuery('sg_vm')
    
    engine = Engine('sg_vm')
    for bl in engine.blacklist_show(max_recv=5):
        print(bl)
           
    #query.request = {"query":{"definition":"BLACKLIST","target":"sg_vm"}, "fetch":{}, "format":{"type":"texts", "field_format": "name"}}
    #query = UserQuery('lynn', check_hostname=False)
    #query = VPNSAQuery('sg_vm')
    #query = SSLVPNQuery('lynn', check_hostname=False)
    #query = RoutingQuery('lynn')
    
    #print(Query.resolve_field_ids(BlacklistQuery.field_ids))
    #query.request = {"query":{"definition":"BLACKLIST","target":"lynn"}, "fetch":{}, "format":{"type":"texts"}}
    
    #myfilter = InFilter(FieldValue(LogField.SRC), [IPValue('192.168.4.82'), IPValue('172.18.1.152')])
   
    #query = LogQuery(fetch_size=50)
Esempio n. 21
0
    def create(cls,
               name,
               master_engine,
               virtual_resource,
               interfaces,
               default_nat=False,
               outgoing_intf=0,
               domain_server_address=None,
               enable_ospf=False,
               ospf_profile=None,
               comment=None,
               extra_opts=None,
               **kw):
        """
        Create a Layer3Virtual engine for a Master Engine. Provide interfaces
        as a list of dict items specifying the interface details in format::

            {'interface_id': 1, 'address': '1.1.1.1', 'network_value': '1.1.1.0/24',
             'zone_ref': zone_by_name,href, 'comment': 'my interface comment'}

        :param str name: Name of this layer 3 virtual engine
        :param str master_engine: Name of existing master engine
        :param str virtual_resource: name of pre-created virtual resource
        :param list interfaces: dict of interface details
        :param bool default_nat: Whether to enable default NAT for outbound
        :param int outgoing_intf: outgoing interface for VE. Specifies interface number
        :param list interfaces: interfaces mappings passed in
        :param bool enable_ospf: whether to turn OSPF on within engine
        :param str ospf_profile: optional OSPF profile to use on engine, by ref
        :param dict extra_opts: extra options as a dict to be passed to the top level engine
        :raises CreateEngineFailed: Failure to create with reason
        :raises LoadEngineFailed: master engine not found
        :return: :py:class:`smc.core.engine.Engine`
        """
        virt_resource_href = None  # need virtual resource reference
        master_engine = Engine(master_engine)

        for virt_resource in master_engine.virtual_resource.all():
            if virt_resource.name == virtual_resource:
                virt_resource_href = virt_resource.href
                break
        if not virt_resource_href:
            raise CreateEngineFailed(
                "Cannot find associated virtual resource for "
                "VE named: {}. You must first create a virtual resource for the "
                "master engine before you can associate a virtual engine. Cannot "
                "add VE".format(name))

        virtual_interfaces = []
        for interface in interfaces:
            nodes = {
                "address": interface.get("address"),
                "network_value": interface.get("network_value"),
            }

            layer3 = {
                "interface_id": interface.get("interface_id"),
                "interface": "single_node_interface",
                "comment": interface.get("comment", None),
                "zone_ref": interface.get("zone_ref"),
            }

            if interface.get("interface_id") == outgoing_intf:
                nodes.update(outgoing=True, auth_request=True)

            layer3["interfaces"] = [{"nodes": [nodes]}]

            virtual_interfaces.append({
                "virtual_physical_interface":
                Layer3PhysicalInterface(**layer3).data.data
            })

            engine = super(Layer3VirtualEngine, cls)._create(
                name=name,
                node_type="virtual_fw_node",
                physical_interfaces=virtual_interfaces,
                domain_server_address=domain_server_address,
                log_server_ref=None,  # Isn't used in VE
                nodes=1,
                default_nat=default_nat,
                enable_ospf=enable_ospf,
                ospf_profile=ospf_profile,
                comment=comment,
                **extra_opts if extra_opts else {})

            engine.update(virtual_resource=virt_resource_href)
            # Master Engine provides this service
            engine.pop("log_server_ref", None)

        try:
            return ElementCreator(cls, json=engine)

        except CreateElementFailed as e:
            raise CreateEngineFailed(e)
Esempio n. 22
0
def MockEngine(name='myengine'):
    engine = Engine(name=name, href='{}/engine'.format(url), type='single_fw')
    cache = {
        'name':
        'myengine',
        'nodes': [{
            'firewall_node': {
                'activate_test': True,
                'engine_version': 'version 6.1 #17028',
                'name': 'test node 1',
                'nodeid': 1
            }
        }],
        'link': [{
            'href': '{}/internal_gateway'.format(url),
            'rel': 'internal_gateway'
        }, {
            'href': '{}/nodes'.format(url),
            'rel': 'nodes'
        }, {
            'href': '{}/permissions'.format(url),
            'rel': 'permissions'
        }, {
            'href': '{}/blacklist'.format(url),
            'rel': 'blacklist'
        }, {
            'href': '{}/flush_blacklist'.format(url),
            'rel': 'flush_blacklist'
        }, {
            'href': '{}/add_route'.format(url),
            'rel': 'add_route'
        }, {
            'href': '{}/antispoofing'.format(url),
            'rel': 'antispoofing'
        }, {
            'href': '{}/alias_resolving'.format(url),
            'rel': 'alias_resolving'
        }, {
            'href': '{}/routing'.format(url),
            'rel': 'routing'
        }, {
            'href': '{}/routing_monitoring'.format(url),
            'rel': 'routing_monitoring'
        }, {
            'href': '{}/virtual_resources'.format(url),
            'rel': 'virtual_resources'
        }, {
            'href': '{}/interfaces'.format(url),
            'rel': 'interfaces'
        }, {
            'href': '{}/tunnel_interface'.format(url),
            'rel': 'tunnel_interface'
        }, {
            'href': '{}/physical_interface'.format(url),
            'rel': 'physical_interface'
        }, {
            'href': '{}/virtual_physical_interface'.format(url),
            'rel': 'virtual_physical_interface'
        }, {
            'href': '{}/modem_interface'.format(url),
            'rel': 'modem_interface'
        }, {
            'href': '{}/adsl_interface'.format(url),
            'rel': 'adsl_interface'
        }, {
            'href': '{}/wireless_interface'.format(url),
            'rel': 'wireless_interface'
        }, {
            'href': '{}/switch_physical_interface'.format(url),
            'rel': 'switch_physical_interface'
        }, {
            'href': '{}/refresh'.format(url),
            'rel': 'refresh'
        }, {
            'href': '{}/upload'.format(url),
            'rel': 'upload'
        }, {
            'href': '{}/generate_snapshot'.format(url),
            'rel': 'generate_snapshot'
        }, {
            'href': '{}/snapshots'.format(url),
            'rel': 'snapshots'
        }]
    }
    engine.data = SimpleElement(etag='abc123456', **cache)
    return engine
Esempio n. 23
0
    # pprint(query.request)
    # query = BlacklistQuery('sg_vm')
    # query.add_in_filter(
    #    FieldValue(LogField.BLACKLISTENTRYSOURCEIP), [IPValue('2.2.2.2')])

    # query.request = {"query":
    #    {
    #    "definition":"BLACKLIST","target":"sg_vm"},
    #    "fetch":{},
    #    "format":{
    #        "type": "texts",
    #        "field_format": "pretty",
    #        "resolving": {"senders": True}}
    #    }

    engine = Engine("sg_vm")
    # for bl in engine.blacklist_show(max_recv=5):
    #    print(bl)
    # query = VPNSAQuery('vm')
    # for record in query.fetch_raw():
    #    print(record)

    # for record in query.fetch_as_element():
    #    print(record, record.href)
    #    record.delete()

    #    print(vars(record))
    #    print(record, record.href)
    #    record.delete()
    # for record in query.fetch_raw():
    #    print(record)
def build_vpn_smc(smc_engine_name, gateway_profile, tunnel_config,
                  external_network_address_space, internal_vpn_endpoint_ip,
                  internal_vpn_address_space):
    engine = Engine(smc_engine_name)

    try:
        tunnel_if = engine.tunnel_interface.get(1000)
    except:
        tunnel_if = None
        print("Interface doesn't exist, creating it now...")

    if tunnel_if:
        print("tunnel interface already exists")
    else:
        engine.tunnel_interface.add_layer3_interface(
            interface_id=1000,
            address=internal_vpn_endpoint_ip,
            network_value=internal_vpn_address_space)

    # Enable VPN on the 'Internal Endpoint' interface
    vpn_endpoint = engine.vpn_endpoint.get_contains(tunnel_config[2])
    vpn_endpoint.update(enabled=True)

    tunnel_if = engine.tunnel_interface.get(1000)

    local_endpoint = TunnelEndpoint.create_ipsec_endpoint(
        engine.vpn.internal_gateway, tunnel_if)

    # Create the remote side network elements
    Network.get_or_create(name=smc_engine_name + ' Azure-vpn-internal-net',
                          ipv4_network=external_network_address_space)

    # TODO add gatewayProfile name to config and default to 'Default (all capabilities)' if empty
    if gateway_profile:
        print("Using gateway profie: " + gateway_profile)
        gw_profile = GatewayProfile(gateway_profile)
    else:
        print("Using gateway profie: Default (all capabilities)")
        gw_profile = GatewayProfile("Default (all capabilities)")

    gw = ExternalGateway.get_or_create(name=smc_engine_name + ' Azure-vpn-gw',
                                       gateway_profile=gw_profile)

    try:
        gw.external_endpoint.create(name=smc_engine_name +
                                    ' Azure-vpn-endpoint-1',
                                    address=tunnel_config[0][0])

        gw.external_endpoint.create(name=smc_engine_name +
                                    ' Azure-vpn-endpoint-2',
                                    address=tunnel_config[0][1])
    except:
        print("Endpoints already exist")

    try:
        gw.vpn_site.create(name=smc_engine_name + ' Azure-vpn-site',
                           site_element=[
                               Network(smc_engine_name +
                                       ' Azure-vpn-internal-net')
                           ])
    except:
        print("Azure-vpn-site already exists")

    remote_endpoint = TunnelEndpoint.create_ipsec_endpoint(gw)

    try:
        ipsec_tunnel = RouteVPN().get(name=smc_engine_name + ' Azure-VPN')
    except:
        print("IPSEC tunnels don't exist, creating them now...")
        ipsec_tunnel = None

    if ipsec_tunnel:
        print("IPSEC tunnel already exists")
    else:
        RouteVPN.create_ipsec_tunnel(name=smc_engine_name + ' Azure-VPN',
                                     preshared_key=tunnel_config[1],
                                     local_endpoint=local_endpoint,
                                     remote_endpoint=remote_endpoint)
def add_dynamic_routing_antispoofing(engine_name):
    engine = Engine(engine_name)
    engine.dynamic_routing.update_antispoofing([Network('Any network')])

    engine.update()
Esempio n. 26
0
    the specified policy. This is equivalent to running the rule counters in the
    SMC without a "Target" specified.

    :rtype: list(smc.policy.policy.RuleCounter)
    """
    print("Rule counters by policy only\n------------------------")
    for counter in policy.rule_counters(engine=None):
        print(counter)
    """
    Get rule counters by specific engine

    :param Engine engine: the engine specified as element
    :rtype: list(smc.policy.policy.RuleCounter)
    """
    print("Rule counters by engine\n------------------------")
    for counter in policy.rule_counters(engine=Engine("sg_vm")):
        print(counter)
    """
    Durations can be used to specify how far back to retrieve the rule
    counters.

    :param str duration_type: duration for obtaining rule counters. Valid
        options are: one_day, one_week, one_month, six_months, one_year,
        custom, since_last_upload; If custom is provided, set the `duration`
        attribute as well
    :rtype: list(smc.policy.policy.RuleCounter)
    """
    print("Rule counters for last month\n------------------------")
    for counter in policy.rule_counters(duration_type="one_month"):
        print(counter)
    """
Esempio n. 27
0
    #pprint(query.request)
    #query = BlacklistQuery('sg_vm')
    #query.add_in_filter(
    #    FieldValue(LogField.BLACKLISTENTRYSOURCEIP), [IPValue('2.2.2.2')])

    #query.request = {"query":
    #    {
    #    "definition":"BLACKLIST","target":"sg_vm"},
    #    "fetch":{},
    #    "format":{
    #        "type": "texts",
    #        "field_format": "pretty",
    #        "resolving": {"senders": True}}
    #    }

    engine = Engine('sg_vm')
    #for bl in engine.blacklist_show(max_recv=5):
    #    print(bl)
    #query = VPNSAQuery('vm')
    #for record in query.fetch_raw():
    #    print(record)

    #for record in query.fetch_as_element():
    #    print(record, record.href)
    #    record.delete()

    #    print(vars(record))
    #    print(record, record.href)
    #    record.delete()
    #for record in query.fetch_raw():
    #    print(record)
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:
        print("regular create method not supported : %s" % str(e))
        print("The example can continue..")

    # Retrieve the Engine
    print("Get cloud fw...")
    engine = Engine("Cloud Single firewall 1")
    print(list(engine.nodes))

    print("======================================================================================")
    print("Firewall name: %s" % engine)
    print("Firewall REF: %s" % engine.href)
    for node in engine.nodes:
        print("Firewall nodes: %s" % node)
        print("Firewall nodes: %s" % node.href)
    print("======================================================================================")

    # Check node status
    print("Get node status...")
    for node in engine.nodes:
        print("Firewall node %s status: %s" % (node.name, str(node.status())))
Esempio n. 29
0

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:
                    print "Failed adding network: {} with gateway: {}, reason: {}".format(\
                                                network, gateway, result.msg)
                else:
Esempio n. 30
0
    #Note: Most operations will return an instance of smc.api.web.SMCResult so you 
    #can view the return attributes if necessary.
    ve = Engine('layer3-ve').load()
    ve.delete()
    
    master = Engine('engine-cluster').load()
    master.delete()
    
if __name__ == '__main__':
    session.login(url='https://172.18.1.25:8082', api_key='avUj6vFZTUSZ7sr8mNsP0001', timeout=120,
                  verify=False)
    
    create_cluster_master_engine()
    
    #Load the existing master engine named 'master-eng'
    engine = Engine('engine-cluster').load()
    
    #Create a virtual resource named 've-1' with virtual firewall id 1
    #vfw_id should increment by 1 for each new virtual firewall under the
    #same Master Engine
    print engine.virtual_resource.create(name='ve-1', vfw_id=1)
    
    #Example of allocating the entire physical interface to a virtual engine
    #Create the interface mapping to virtual resource 've-1'
    print engine.physical_interface.add(interface_id=1,
                                        virtual_mapping=0,
                                        virtual_resource_name='ve-1')
    
    #Example of allocating a VLAN to a virtual engine on a specific physical
    #interface.
    #engine.physical_interface.add_vlan_to_node_interface(