Exemplo n.º 1
0
 def __init__(self, name, fw=None, pano=None):
     if pano:
         vr = n.VirtualRouter(name=name)
         pano.add(vr)
         vr.create()
     else:
         vr = n.VirtualRouter(name=name)
         fw.add(vr)
         vr.create()
 def test_static_routes(self):
     vr = network.VirtualRouter()
     self.d.add(vr)
     route = vr.add(
         network.StaticRoute("Default", "0.0.0.0/0", None, "10.5.5.2"))
     vr.create()
     vr.delete()
Exemplo n.º 3
0
    def create_tunnel_interface(self, tunnel_name):
        """
        Create a tunnel interface and associate it with a virtual router and security zone
        """
        # Logically create the tunnel interface

        tunnel_ref = self.tunnel_interfaces.get(tunnel_name)
        tunnel_intf = network.TunnelInterface(tunnel_ref.name,
                                              comment=tunnel_ref.comment)
        self.fw_dev_hndl.add(tunnel_intf)

        # Retrieve the existing zones
        fw_zones = network.Zone(tunnel_ref.security_zone)
        self.fw_dev_hndl.add(fw_zones)
        fw_zones.refresh()
        zone_intfs = fw_zones.interface

        # Add interface to the zone
        zone_intfs.append(tunnel_ref.name)

        fw_zones.interface = zone_intfs
        # Retrieve the existing list of virtual routers

        fw_vrs = network.VirtualRouter(tunnel_ref.virtual_router)
        self.fw_dev_hndl.add(fw_vrs)
        fw_vrs.refresh()

        vr_intfs = fw_vrs.interface
        vr_intfs.append(tunnel_ref.name)
        fw_vrs.interface = vr_intfs

        # Push all the configs to the device
        tunnel_intf.create()
        fw_zones.apply()
        fw_vrs.apply()
Exemplo n.º 4
0
def main():
    argument_spec = setup_args()

    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[x] for x in
            ('ip_address', 'username', 'password', 'api_key')]

    # exclude the default items from kwargs passed to the object
    exclude_list = ['ip_address', 'username', 'password', 'api_key', 'state', 'commit']

    # generate the kwargs for network.VirtualRouter
    obj_spec = dict((k, module.params[k]) for k in argument_spec.keys() if k not in exclude_list)

    name = module.params['name']
    state = module.params['state']
    commit = module.params['commit']

    # create the new state object
    virtual_router = network.VirtualRouter(**obj_spec)

    changed = False
    try:
        # Create the device with the appropriate pandevice type
        device = base.PanDevice.create_from_device(*auth)
        network.VirtualRouter.refreshall(device)

        # search for the virtual router
        vr = device.find(name, network.VirtualRouter)

        # compare differences between the current state vs desired state
        if state == 'present':
            if vr is None or not virtual_router.equal(vr, compare_children=False):
                device.add(virtual_router)
                virtual_router.create()
                changed = True
        elif state == 'absent':
            if vr is not None:
                vr.delete()
                changed = True
        else:
            module.fail_json(msg='[%s] state is not implemented yet' % state)
    except (PanDeviceError, KeyError):
        exc = get_exception()
        module.fail_json(msg=exc.message)

    if commit and changed:
        device.commit(sync=True, exception=True)

    if changed:
        module.exit_json(msg='Virtual router update successful.', changed=changed)
    else:
        module.exit_json(msg='no changes required.', changed=changed)
Exemplo n.º 5
0
    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()

        state.vr = network.VirtualRouter(testlib.random_name(),
                                         interface=state.eth)
        fw.add(state.vr)
        state.vr.create()
Exemplo n.º 6
0
    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()
Exemplo n.º 7
0
 def setup_state_obj(self, fw, state):
     state.obj = network.VirtualRouter(
         testlib.random_name(),
         interface=state.eth,
         ad_static=random.randint(10, 240),
         ad_static_ipv6=random.randint(10, 240),
         ad_ospf_int=random.randint(10, 240),
         ad_ospf_ext=random.randint(10, 240),
         ad_ospfv3_int=random.randint(10, 240),
         ad_ospfv3_ext=random.randint(10, 240),
         ad_ibgp=random.randint(10, 240),
         ad_ebgp=random.randint(10, 240),
         ad_rip=random.randint(10, 240),
     )
     fw.add(state.obj)
Exemplo n.º 8
0
    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()
Exemplo n.º 9
0
 def create_dependencies(self, fw, state):
     state.vr = network.VirtualRouter(testlib.random_name())
     fw.add(state.vr)
     state.vr.create()
Exemplo n.º 10
0
def config_builder(instanceList):
    global netObj_ike_list, netObj_ipsec_list, netObj_tunInt_list, netObj_vr_list, netObj_zone_list
    netObj_ike_list, netObj_ipsec_list, netObj_tunInt_list, netObj_vr_list, netObj_zone_list = [], [], [], [], []
    vrDict, zoneDict = {}, {}
    for item in instanceList:
        item = [i if i != '' else None for i in item[:]]
        netObj_tunInt = network.TunnelInterface()
        netObj_tunInt.name = item[0]
        netObj_tunInt.comment = item[1]
        netObj_tunInt.ip = item[2]
        netObj_tunInt.management_profile = item[3]
        netObj_tunInt_list.append(pan.add(netObj_tunInt))
        if item[4] not in vrDict.keys():
            vrDict[item[4]] = []
        vrDict[item[4]].append(item[0])
        if len(item[5]) > 31:
            print('*' * 6 + ' Warning -- IKE-GW - {} name truncated to {} due to length restriction'.format(item[5], item[5][:31]))
            item[5] = item[5][:31]
        if item[5] not in zoneDict.keys():
            zoneDict[item[5]] = []
        zoneDict[item[5]].append(item[0])
        if len(item[6]) > 31:
            print('*' * 6 + ' Warning -- IKE-GW - {} name truncated to {} due to length restriction'.format(item[6], item[6][:31]))
            item[6] = item[6][:31]
        netObj_ike = network.IkeGateway()
        netObj_ike.name = item[6]
        netObj_ike.interface = item[7]
        netObj_ike.local_ip_address_type = 'ip'
        netObj_ike.local_ip_address = item[8]
        netObj_ike.peer_ip_type = item[9]
        if netObj_ike.peer_ip_type != 'dynamic':
            netObj_ike.peer_ip_value = item[10]
        netObj_ike.pre_shared_key = item[11]
        if item[12] is not None:
            temp_item = item[12].replace(': ', ':').split(':')
            netObj_ike.local_id_type = temp_item[0]
            netObj_ike.local_id_value = temp_item[1]
        if item[13] is not None:
            temp_item = item[13].replace(': ', ':').split(':')
            netObj_ike.peer_id_type = temp_item[0]
            netObj_ike.peer_id_value = temp_item[1]
        if item[14] is not None and item[14].lower() == 'true':
            netObj_ike.enable_passive_mode = True
        else:
            netObj_ike.enable_passive_mode = False
        if item[15] is not None and item[15].lower() == 'true':
            netObj_ike.enable_nat_traversal = True
        else:
            netObj_ike.enable_nat_traversal = False
        netObj_ike.ikev1_exchange_mode = item[16]
        netObj_ike.ikev1_crypto_profile = item[17]
        if item[18] is not None and item[18].lower() == 'true':
            netObj_ike.enable_fragmentation = True
        else:
            netObj_ike.enable_fragmentation = False
        if item[19] is None or item[19].lower() == 'true':
            netObj_ike.enable_dead_peer_detection = True
        elif item[19].lower() == 'false':
            netObj_ike.enable_dead_peer_detection = False
        else:
            temp_item = item[19].replace('; ', ';').split(';')
            netObj_ike.enable_dead_peer_detection = True
            netObj_ike.dead_peer_detection_interval = temp_item[0]
            netObj_ike.dead_peer_detection_retry = temp_item[1]
        netObj_ike_list.append(pan.add(netObj_ike))
        if len(item[20]) > 31:
            print('*' * 6 + ' Warning -- IKE-GW - {} name truncated to {} due to length restriction'.format(item[20], item[20][:31]))
            item[20] = item[20][:31]
        netObj_ipsec = network.IpsecTunnel()
        netObj_ipsec.name = item[20]
        netObj_ipsec.tunnel_interface = item[21]
        if len(item[22]) > 31:
            print('*' * 6 + ' Warning -- IKE-GW - {} name truncated to {} due to length restriction'.format(item[22], item[22][:31]))
            item[22] = item[22][:31]
        netObj_ipsec.ak_ike_gateway = item[22]
        if item[23] is None:
            item[23] = 'default'
        netObj_ipsec.ak_ipsec_crypto_profile = item[23]
        netObj_ipsec_list.append(pan.add(netObj_ipsec))
        print('Building Config --- Tunnel-Int - {} // IKE-GW - {} // IPSec-Tunnel - {}'.format(netObj_tunInt.name, netObj_ike.name, netObj_ipsec.name))
    for key, value in vrDict.items():
        netObj_vr = network.VirtualRouter()
        netObj_vr.name = key
        netObj_vr.interface = value
        netObj_vr_list.append(pan.add(netObj_vr))
    for key, value in zoneDict.items():
        netObj_zone = network.Zone()
        netObj_zone.name = key
        netObj_zone.interface = value
        netObj_zone_list.append(pan.add(netObj_zone))
Exemplo n.º 11
0

un_zone = network.Zone("untrust", \
        mode = "layer3", \
        interface = "ethernet1/1")


fw.add(un_zone)
un_zone.create()
print(un_zone)


#creates master vr_master virtual router and assoictes ethernet1/1


vr_master = network.VirtualRouter("vr_master", \
        interface = ["ethernet1/1", "tunnel.100", "ethernet1/2"])


fw.add(vr_master)
vr_master.create()
print(vr_master)


# Creates IKE Crypto Profile


ikecp = network.IkeCryptoProfile("ICP-DH_G5-AUTH_SHA256-EN_AES256", \
        dh_group = "group5", \
        authentication = "sha256", \
        encryption = "aes-256-cbc", \
        lifetime_seconds = "3600")
Exemplo n.º 12
0

@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'

    assert expected == c.xpath_vsys()

    c.vsys = None
Exemplo n.º 13
0
def main():
    argument_spec = dict(ip_address=dict(required=True),
                         username=dict(default='admin'),
                         password=dict(no_log=True),
                         api_key=dict(no_log=True),
                         name=dict(type='str', required=True),
                         devicegroup=dict(type='str', required=False),
                         panorama_template=dict(),
                         priority=dict(type='int', required=True),
                         action=dict(type='str', required=True),
                         filter_type=dict(type='str', required=True),
                         vr=dict(type='str', required=True),
                         state=dict(default='present',
                                    choices=['present', 'absent']))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=False)

    if not HAS_LIB:
        module.fail_json(
            msg='pan-python and pandevice are required for this module.')

    ip_address = module.params['ip_address']
    username = module.params['username']
    password = module.params['password']
    api_key = module.params['api_key']
    name = module.params['name']
    devicegroup = module.params['devicegroup']
    state = module.params['state']
    priority = module.params['priority']
    action = module.params['action']
    filter_type = module.params['filter_type']
    vr = module.params['vr']

    changed = False

    try:
        device = base.PanDevice.create_from_device(ip_address,
                                                   username,
                                                   password,
                                                   api_key=api_key)

        dev_group = None
        if devicegroup and isinstance(device, panorama.Panorama):
            dev_group = get_devicegroup(device, devicegroup)
            if dev_group:
                device.add(dev_group)
            else:
                module.fail_json(
                    msg=
                    '\'%s\' device group not found in Panorama. Is the name correct?'
                    % devicegroup)

        active_vr = network.VirtualRouter(vr)
        device.add(active_vr)
        active_vr.refreshall(device)
        active_profs = network.RedistributionProfile.refreshall(active_vr)

        found = False
        for current_prof in active_profs:
            if current_prof.name == name:
                found = True
                del_obj = current_prof
                break
        #exit()
        # only change when present, and does not already exist
        if state == 'present' and not found:
            changed = True
            redist_prof = network.RedistributionProfile(
                name=name,
                priority=priority,
                action=action,
                filter_type=filter_type)
            selected_vr = network.VirtualRouter(vr)
            device.add(selected_vr)
            selected_vr.add(redist_prof)
            redist_prof.create()

        # only change when absent, and does already exist
        elif state == 'absent' and found:
            changed = True
            selected_vr = network.VirtualRouter(vr)
            device.add(selected_vr)
            selected_vr.add(del_obj)
            del_obj.delete()

    except PanDeviceError as e:
        module.fail_json(msg=e.message)

    module.exit_json(changed=changed)