def create_dependencies(self, fw, state): state.eth_objs = [] state.eths = testlib.get_available_interfaces(fw, 2) state.eth_objs.append( network.EthernetInterface(state.eths[0], 'layer2')) state.eth_objs.append( network.EthernetInterface(state.eths[1], 'layer3')) for x in state.eth_objs: fw.add(x) fw.create_type(network.EthernetInterface)
def create_dependencies(self, fw, state): state.eth_obj = None state.eth = testlib.get_available_interfaces(fw)[0] state.eth_obj = network.EthernetInterface(state.eth, 'layer3', testlib.random_ip('/24')) fw.add(state.eth_obj) state.eth_obj.create()
def create_dependencies(self, fw, state): state.eth_objs = [] state.eths = testlib.get_available_interfaces(fw, 3) for eth in state.eths: state.eth_objs.append( network.EthernetInterface(eth, 'virtual-wire')) fw.add(state.eth_objs[-1]) state.eth_objs[-1].create()
def create_dependencies(self, fw, state): state.eth = None state.eth = testlib.get_available_interfaces(fw)[0] state.parent = network.EthernetInterface( state.eth, 'layer2', ) fw.add(state.parent) state.parent.create()
def create_dependencies(self, fw, state): state.eths = testlib.get_available_interfaces(fw, 2) state.eth_obj_v4 = network.EthernetInterface(state.eths[0], 'layer3', testlib.random_ip('/24')) fw.add(state.eth_obj_v4) state.eth_obj_v6 = network.EthernetInterface(state.eths[1], 'layer3', ipv6_enabled=True) fw.add(state.eth_obj_v6) state.eth_obj_v4.create_similar() state.vr = network.VirtualRouter(testlib.random_name(), state.eths) fw.add(state.vr) state.vr.create() if any((self.WITH_OSPF, self.WITH_AUTH_PROFILE, self.WITH_AREA, self.WITH_AREA_INTERFACE)): state.ospf = network.Ospf(True, testlib.random_ip()) state.vr.add(state.ospf) if self.WITH_AUTH_PROFILE: state.auth = network.OspfAuthProfile(testlib.random_name(), 'md5') state.ospf.add(state.auth) if self.WITH_AREA or self.WITH_AREA_INTERFACE: state.area = network.OspfArea(testlib.random_ip()) state.ospf.add(state.area) if self.WITH_AREA_INTERFACE: state.iface = network.OspfAreaInterface( state.eths[0], True, True, 'p2mp') state.area.add(state.iface) state.ospf.create()
def create_dependencies(self, fw, state): state.eth_objs = [] state.eths = testlib.get_available_interfaces(fw, 2) for eth in state.eths: state.eth_objs.append(network.EthernetInterface(eth, 'layer2')) fw.add(state.eth_objs[-1]) state.eth_objs[0].create_similar() state.vlan_interface = network.VlanInterface('vlan.{0}'.format( random.randint(100, 200))) fw.add(state.vlan_interface) state.vlan_interface.create()
def create_dependencies(self, fw, state): state.parent = None state.eth_objs = [] state.eths = testlib.get_available_interfaces(fw, 2) for eth in state.eths: state.eth_objs.append(network.EthernetInterface(eth, 'layer2')) fw.add(state.eth_objs[-1]) state.eth_objs[0].create_similar() state.parent = network.Vlan(testlib.random_name(), state.eths) fw.add(state.parent) state.parent.create()
def create_dependencies(self, fw, state): state.eth_obj = None state.eth = testlib.get_available_interfaces(fw)[0] state.eth_obj = network.EthernetInterface(state.eth, 'layer3', testlib.random_ip('/24')) fw.add(state.eth_obj) state.eth_obj.create() tag = random.randint(1, 4000) state.parent = network.Layer3Subinterface( '{0}.{1}'.format(state.eth, tag), tag, testlib.random_ip('/24')) state.eth_obj.add(state.parent) state.parent.create()
def create_dependencies(self, fw, state): state.eth_objs = [] state.vr = None state.eths = testlib.get_available_interfaces(fw, 2) for e in state.eths: state.eth_objs.append( network.EthernetInterface(e, 'layer3', testlib.random_ip('/24'))) fw.add(state.eth_objs[-1]) state.eth_objs[-1].create() state.vr = network.VirtualRouter(testlib.random_name(), state.eths) fw.add(state.vr) state.vr.create()
def create_dependencies(self, fw, state): state.eth_obj = None state.eth = testlib.get_available_interfaces(fw)[0] state.eth_obj = network.EthernetInterface(state.eth, 'layer3', testlib.random_ip('/24'), ipv6_enabled=True) fw.add(state.eth_obj) state.eth_obj.create() state.vr = network.VirtualRouter(testlib.random_name(), interface=state.eth) fw.add(state.vr) state.vr.create()
def create_dependencies(self, fw, state): state.management_profile = network.ManagementProfile( testlib.random_name(), ping=True) state.eth = None fw.add(state.management_profile) state.management_profile.create() state.eth = testlib.get_available_interfaces(fw)[0] state.parent = network.EthernetInterface( state.eth, 'layer3', ip=testlib.random_ip('/24'), ) fw.add(state.parent) state.parent.create()
def setup_state_obj(self, fw, state): state.obj = network.EthernetInterface( state.eth, 'layer3', testlib.random_ip('/24'), ipv6_enabled=False, management_profile=state.management_profiles[0], mtu=random.randint(600, 1500), adjust_tcp_mss=True, link_speed='auto', link_duplex='auto', link_state='auto', comment='This is my interface', ipv4_mss_adjust=random.randint(40, 300), ipv6_mss_adjust=random.randint(60, 300), ) fw.add(state.obj)
def setup_state_obj(self, fw, state): state.obj = network.EthernetInterface( state.eth, 'layer2', management_profile=state.management_profiles[0]) fw.add(state.obj)
# First, let's create the firewall object that we want to modify. fw = firewall.Firewall(HOSTNAME, USERNAME, PASSWORD) print('Firewall system info: {0}'.format(fw.refresh_system_info())) # Sanity Check #1: the intent here is that the interface we # specified above should not already be in use. If the interface is # already in use, then just quit out. #Creates Untrust Interface untrust_int = network.EthernetInterface("ethernet1/1", \ mode = "layer3", \ ip = untrust_cidr) fw.add(untrust_int) untrust_int.create() print(untrust_int) #Creates Management Untagged Gateway Interface mgmt_int = network.EthernetInterface("ethernet1/2", \ mode = "layer3", \ ip = '{{ item.mgmt_gw }}')
def main(): # Before we begin, you'll need to use the pandevice documentation both # for this example and for any scripts you may write for yourself. The # docs can be found here: # # http://pandevice.readthedocs.io/en/latest/reference.html # # First, let's create the firewall object that we want to modify. fw = firewall.Firewall(HOSTNAME, USERNAME, PASSWORD) print('Firewall system info: {0}'.format(fw.refresh_system_info())) print('Desired interface: {0}'.format(INTERFACE)) # Sanity Check #1: the intent here is that the interface we # specified above should not already be in use. If the interface is # already in use, then just quit out. print('Making sure interface is not currently in use...') interfaces = network.EthernetInterface.refreshall(fw, add=False) for eth in interfaces: if eth.name == INTERFACE: print('Interface {0} already in use! Please choose another'.format( INTERFACE)) return # Sanity Check #2: this has to be a multi-vsys system. So let's make # sure that we have multiple vsys to work with. If there is only one # vsys, quit out. # # Pulling the entire vsys config from each vsys is going to be large amount # of XML, so we'll specify that we only need the names of the different # vsys, not their entire subtrees. vsys_list = device.Vsys.refreshall(fw, name_only=True) print('Found the following vsys: {0}'.format(vsys_list)) if len(vsys_list) < 2: print('Only {0} vsys present, need 2 or more.'.format(len(vsys_list))) return # Let's make our base interface that we're going to make subinterfaces # out of. print('Creating base interface {0} in layer2 mode'.format(INTERFACE)) base = network.EthernetInterface(INTERFACE, 'layer2') # Like normal, after creating the object, we need to add it to the # firewall, then finally invoke "create()" to create it. fw.add(base) base.create() # Now let's go ahead and make all of our subinterfaces. eth = None for tag in range(1, 601): name = '{0}.{1}'.format(INTERFACE, tag) eth = network.Layer2Subinterface(name, tag) # Choose one of the vsys at random to put it into. vsys = random.choice(vsys_list) # Now add the subinterface to that randomly chosen vsys. vsys.add(eth) # You'll notice that we didn't invoke "create()" on the subinterfaces like # you would expect. This is because we're going to use the bulk create # function to create all of the subinterfaces in one shot, which has huge # performance gains from doing "create()" on each subinterface one-by-one. # # The function we'll use is "create_similar()". Create similar is saying, # "I want to create all objects similar to this one in my entire pandevice # object tree." In this case, since we'd be invoking it on a subinterface # of INTERFACE (our variable above), we are asking pandevice to create all # subinterfaces of INTERFACE, no matter which vsys it exists in. # # We just need any subinterface to do this. Since our last subinterface # was saved to the "eth" variable in the above loop, we can just use that # to invoke "create_similar()". print('Creating subinterfaces...') start = datetime.datetime.now() eth.create_similar() print('Creating subinterfaces took: {0}'.format( datetime.datetime.now() - start)) # Now let's explore updating them. Let's say this is a completely # different script, and we want to update all of the subinterfaces # for INTERFACE. Since this is a completely new script, we don't have any # information other than the firewall and the interface INTERFACE. So # let's start from scratch at this point, and remake the firewall object # and connect. print('\n--------\n') fw = firewall.Firewall(HOSTNAME, USERNAME, PASSWORD) print('Firewall system info: {0}'.format(fw.refresh_system_info())) print('Desired interface: {0}'.format(INTERFACE)) # Make the base interface object and connect it to our pandevice tree. base = network.EthernetInterface(INTERFACE, 'layer2') fw.add(base) # Now let's get all the subinterfaces for INTERFACE. Since our firewall's # default vsys is "None", this will get all subinterfaces of INTERFACE, # regardless of which vsys it exists in. print('Refreshing subinterfaces...') subinterfaces = network.Layer2Subinterface.refreshall(base) print('Found {0} subinterfaces'.format(len(subinterfaces))) # Now let's go ahead and update all of them. for eth in subinterfaces: eth.comment = 'Tagged {0} and in vsys {1}'.format(eth.tag, eth.vsys) # Now that we have updated all of the subinterfaces, we need to save # the changes to the firewall. But hold on a second, the vsys for these # subinterfaces is currently "None". We first need to organize these # subinterfaces into the vsys they actually exist in before we can # apply these changes to the firewall. # # This is where you can use the function "organize_into_vsys()". This # takes all objects currently attached to your pandevice object tree # and organizes them into the vsys they belong to. # # We haven't gotten the current vsys yet (this is a new script, remember), # but the function can take care of that for us. So let's just invoke it # to organize our pandevice object tree into vsys. print('Organizing subinterfaces into vsys...') fw.organize_into_vsys() # Now we're ready to save our changes. We'll use "apply_similar()", # and it behaves similarly to "create_similar()" in that you can invoke # it from any subinterface of INTERFACE and it will apply all of the # changes to subinterfaces of INTERFACE only. # # We just need one subinterface to invoke this function. Again, we'll # simply use the subinterface currently saved in the "eth" variable # from our update loop we did just above. # # NOTE: As an "apply()" function, apply does a replace of config, not # a simple update. So you must be careful that all other objects are # currently attached to your pandevice object tree when using apply # functions. In our case, we have already refreshed all layer2 # subinterfaces, and we are the only ones working with INTERFACE, so we # are safe to use this function. print('Updating all subinterfaces...') start = datetime.datetime.now() eth.apply_similar() print('Updating subinterfaces took: {0}'.format( datetime.datetime.now() - start)) # Finally, all that's left is to delete all of the subinterfaces. This # is just like you think: we first need to refresh all of the # subinterfaces of INTERFACE, organize them into their appropriate vsys, # then invoke "delete_similar()" to delete everything. print('Deleting all subinterfaces...') start = datetime.datetime.now() eth.delete_similar() print('Deleting subinterfaces took: {0}'.format( datetime.datetime.now() - start)) # Lastly, let's just delete the base interface INTERFACE. print('Deleting base interface...') base.delete() # And now we're done! If performance is a bottleneck in your automation, # or dealing with vsys is troublesome, consider using the vsys organizing # and/or bulk functions! print('Done!')
def main(): argument_spec = dict( ip_address=dict(required=True), password=dict(no_log=True), username=dict(default='admin'), api_key=dict(no_log=True), operation=dict(default='add', choices=['add', 'update', 'delete']), if_name=dict(required=True), mode=dict(default='layer3', choices=['layer3', 'layer2', 'virtual-wire', 'tap', 'ha', 'decrypt-mirror', 'aggregate-group']), ip=dict(type='list'), ipv6_enabled=dict(), management_profile=dict(), mtu=dict(), adjust_tcp_mss=dict(), netflow_profile=dict(), lldp_enabled=dict(), lldp_profile=dict(), netflow_profile_l2=dict(), link_speed=dict(), link_duplex=dict(), link_state=dict(), aggregate_group=dict(), comment=dict(), ipv4_mss_adjust=dict(), ipv6_mss_adjust=dict(), enable_dhcp=dict(type='bool', default=True), create_default_route=dict(type='bool', default=False), dhcp_default_route_metric=dict(), zone_name=dict(required=True), vr_name=dict(default='default'), vsys_dg=dict(default='vsys1'), commit=dict(type='bool', default=True), ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, required_one_of=[['api_key', 'password']]) if not HAS_LIB: module.fail_json(msg='Missing required libraries.') # Get the firewall / panorama auth. auth = ( module.params['ip_address'], module.params['username'], module.params['password'], module.params['api_key'], ) # Get the object params. spec = { 'name': module.params['if_name'], 'mode': module.params['mode'], 'ip': module.params['ip'], 'ipv6_enabled': module.params['ipv6_enabled'], 'management_profile': module.params['management_profile'], 'mtu': module.params['mtu'], 'adjust_tcp_mss': module.params['adjust_tcp_mss'], 'netflow_profile': module.params['netflow_profile'], 'lldp_enabled': module.params['lldp_enabled'], 'lldp_profile': module.params['lldp_profile'], 'netflow_profile_l2': module.params['netflow_profile_l2'], 'link_speed': module.params['link_speed'], 'link_duplex': module.params['link_duplex'], 'link_state': module.params['link_state'], 'aggregate_group': module.params['aggregate_group'], 'comment': module.params['comment'], 'ipv4_mss_adjust': module.params['ipv4_mss_adjust'], 'ipv6_mss_adjust': module.params['ipv6_mss_adjust'], 'enable_dhcp': module.params['enable_dhcp'] or None, 'create_dhcp_default_route': module.params['create_default_route'] or None, 'dhcp_default_route_metric': module.params['dhcp_default_route_metric'], } # Get other info. operation = module.params['operation'] zone_name = module.params['zone_name'] vr_name = module.params['vr_name'] vsys_dg = module.params['vsys_dg'] commit = module.params['commit'] # Open the connection to the PANOS device. con = base.PanDevice.create_from_device(*auth) # Set vsys if firewall, device group if panorama. parent = con if hasattr(con, 'refresh_devices'): # Panorama # Normally we want to set the device group here, but there are no # interfaces on Panorama. So if we're given a Panorama device, then # error out. ''' groups = panorama.DeviceGroup.refreshall(con, add=False) for parent in groups: if parent.name == vsys_dg: con.add(parent) break else: module.fail_json(msg="'{0}' device group is not present".format(vsys_dg)) ''' module.fail_json(msg="Ethernet interfaces don't exist on Panorama") else: # Firewall # Normally we should set the vsys here, but since interfaces are # vsys importables, we'll use organize_into_vsys() to help find and # cleanup when the interface is imported into an undesired vsys. #con.vsys = vsys_dg pass # Retrieve the current config. try: interfaces = network.EthernetInterface.refreshall(con, add=False, name_only=True) zones = network.Zone.refreshall(con) routers = network.VirtualRouter.refreshall(con) vsys_list = device.Vsys.refreshall(con) except errors.PanDeviceError: e = get_exception() module.fail_json(msg=e.message) # Build the object based on the user spec. eth = network.EthernetInterface(**spec) con.add(eth) # Which action should we take on the interface? if operation == 'delete': if eth.name not in [x.name for x in interfaces]: module.fail_json(msg='Interface {0} does not exist, and thus cannot be deleted'.format(eth.name)) try: con.organize_into_vsys() set_zone(con, eth, None, zones) set_virtual_router(con, eth, None, routers) eth.delete() except (errors.PanDeviceError, ValueError): e = get_exception() module.fail_json(msg=e.message) elif operation == 'add': if eth.name in [x.name for x in interfaces]: module.fail_json(msg='Interface {0} is already present; use operation "update" to update it'.format(eth.name)) con.vsys = vsys_dg # Create the interface. try: eth.create() set_zone(con, eth, zone_name, zones) set_virtual_router(con, eth, vr_name, routers) except (errors.PanDeviceError, ValueError): e = get_exception() module.fail_json(msg=e.message) elif operation == 'update': if eth.name not in [x.name for x in interfaces]: module.fail_json(msg='Interface {0} is not present; use operation "add" to create it'.format(eth.name)) # If the interface is in the wrong vsys, remove it from the old vsys. try: con.organize_into_vsys() except errors.PanDeviceError: e = get_exception() module.fail_json(msg=e.message) if eth.vsys != vsys_dg: try: eth.delete_import() except errors.PanDeviceError: e = get_exception() module.fail_json(msg=e.message) # Move the ethernet object to the correct vsys. for vsys in vsys_list: if vsys.name == vsys_dg: vsys.add(eth) break else: module.fail_json(msg='Vsys {0} does not exist'.format(vsys)) # Update the interface. try: eth.apply() set_zone(con, eth, zone_name, zones) set_virtual_router(con, eth, vr_name, routers) except (errors.PanDeviceError, ValueError): e = get_exception() module.fail_json(msg=e.message) else: module.fail_json(msg="Unsupported operation '{0}'".format(operation)) # Commit if we were asked to do so. if commit: try: con.commit(sync=True, exceptions=True) except errors.PanDeviceError: e = get_exception() module.fail_json(msg='Performed {0} but commit failed: {1}'.format(operation, e.message)) # Done! module.exit_json(changed=True, msg='okey dokey')
def test_xpath_for_device_root(vsys, with_pano): obj = device.SystemSettings(hostname='example') _check(obj, vsys, with_pano) @pytest.mark.parametrize('vsys', [None, 'vsys1', 'vsys3']) @pytest.mark.parametrize('with_pano', [False, True]) def test_xpath_for_mgtconfig_root(vsys, with_pano): obj = device.Administrator('newadmin') _check(obj, vsys, with_pano) @pytest.mark.parametrize('vsys', [None, 'vsys1', 'vsys3']) @pytest.mark.parametrize('with_pano', [False, True]) @pytest.mark.parametrize('obj', [ network.EthernetInterface('ethernet1/3', 'layer3'), network.Layer3Subinterface('ethernet1/4.42', 42), network.Layer2Subinterface('ethernet1/4.420', 420), network.VirtualRouter('someroute'), network.VirtualWire('tripwire'), network.Vlan('myvlan'), ]) def test_xpath_import(vsys, with_pano, obj): _check(obj, vsys, with_pano, True) def test_vsys_xpath_unchanged(): expected = "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys3']" c = firewall.Firewall('127.0.0.1', 'admin', 'admin') c.vsys = 'vsys3'
def deploy(): # Get the credentials from the user selected_fwip = request.form.get('firewall').encode('utf-8') interface = request.form.get('interface').encode('utf-8') router = request.form.get('router').encode('utf-8') if interface == 'none selected': error = "ERR2222-Go back you didn't select an interface" return render_template('main/gen_error.html', error=error) ''' Handling HA # Don't assume either firewall is primary or active. # Just start by telling pandevice they are an HA pair # and how to connect to them. fw = Firewall('10.0.0.1', 'admin', 'password') fw.set_ha_peers(Firewall('10.0.0.2', 'admin', 'password')) fw.refresh_ha_active() # Now, verify the config is synced between the devices. # If it's not synced, force config synchronization from active to standby if not fw.config_synced(): fw.synchronize_config() # blocks until synced or error ''' for i in Creds.objects: fwip = i.fwip.encode('utf-8') username = i.username.encode('utf-8') password = i.password.encode('utf-8') if fwip == None: error = 'ERR2222-No creds in the Creds DB. Log out and login again' return render_template('main/dberror.html') # First, let's create the firewall object that we want to modify. fw = firewall.Firewall(selected_fwip, username, password) # Get vsys vsys_list = device.Vsys.refreshall(fw, name_only=True) # This works...need to figure out a better way vsys = random.choice(vsys_list) # Let's make our base interface that we're going to make subinterfaces base = network.EthernetInterface(interface, "layer3") fw.add(base) base.create() # Now let's go ahead and make all of our subinterfaces. for i in Networks.objects: gateway = i.gateway.encode('utf-8') tag = i.tag.encode('utf-8') comment = i.comment.encode('utf-8') zone = i.zone.encode('utf-8') # Build subinterface name = "{0}.{1}".format(interface, tag) sub_intf = network.Layer3Subinterface(name, tag, gateway, comment) # Now add the subinterface to that randomly chosen vsys. vsys.add(sub_intf) vr = sub_intf.set_virtual_router(virtual_router_name=router) security_zone = sub_intf.set_zone(zone_name=zone) # Creat all subinterfaces at once sub_intf.create_similar() vsys.add(vr) vsys.add(security_zone) vr.create() security_zone.create() return render_template('main/deploy_success.html', fwip=selected_fwip)