示例#1
0
 def run(self):
     alertId = self.get_param('data.id')
     response = self.api.get_alert(alertId)
     ioc = None
     ioc_clear = []
     for i in list(response.json().get("artifacts")):
         if 'url' in str(i):
             ioc = i.get("data")
             for i in ioc:
                 if i == "[" or i == "]":
                     continue
                 else:
                     ioc_clear.append(i)
             ioc = "".join(ioc_clear)
     fw = firewall.Firewall(self.hostname_PaloAltoNGFW,
                            api_username=self.User_PaloAltoNGFW,
                            api_password=self.Password_PaloAltoNGFW)
     panos.objects.CustomUrlCategory.refreshall(fw)
     block_list = fw.find(self.name_internal_URL_category,
                          panos.objects.CustomUrlCategory)
     ioc_list = block_list.about().get('url_value')
     if ioc not in ioc_list:
         ioc_list.append(ioc)
         temp1 = panos.objects.CustomUrlCategory(
             self.name_internal_URL_category, url_value=ioc_list)
         fw.add(temp1)
         temp1.create()
     self.report({'message': 'message sent'})
示例#2
0
 def run(self):
     alertId = self.get_param('data.id')
     response = self.api.get_alert(alertId)
     ioc = None
     ioc_clear = []
     for i in list(response.json().get("artifacts")):
         if 'ip' in str(i):
             ioc = i.get("data")
             for i in ioc:
                 if i == "[" or i == "]":
                     continue
                 else:
                     ioc_clear.append(i)
             ioc = "".join(ioc_clear)
     fw = firewall.Firewall(self.hostname_PaloAltoNGFW,
                            api_username=self.User_PaloAltoNGFW,
                            api_password=self.Password_PaloAltoNGFW)
     panos.objects.AddressObject.refreshall(fw)
     if ioc not in str(fw.find(ioc, panos.objects.AddressObject)):
         new_ioc_object = panos.objects.AddressObject(
             ioc, ioc, description="Blocked ip address")
         fw.add(new_ioc_object)
         new_ioc_object.create()
     panos.objects.AddressGroup.refreshall(fw)
     block_list = fw.find(self.name_external_Address_Group,
                          panos.objects.AddressGroup)
     ioc_list = block_list.about().get('static_value')
     if ioc not in ioc_list:
         ioc_list.append(ioc)
         temp1 = panos.objects.AddressGroup(
             self.name_external_Address_Group, static_value=ioc_list)
         fw.add(temp1)
         temp1.apply()
     self.report({'message': 'message sent'})
 def run(self):
     self.instance_type = self.get_param('data._type')
     if self.instance_type == 'case_artifact':
             user = self.get_param('data.data')
     if self.instance_type == 'alert':
         alertId = self.get_param('data.id')
         response = self.api.get_alert(alertId)
         user=None
         user_list_alert=[]
         for i in list(response.json().get("artifacts")):
             if 'username' in str(i):
                 ioc = i.get("data")
                 for i in ioc:
                     if i == "[" or i == "]":
                         continue
                     else:
                         user_list_alert.append(i)
                 user="".join(user_list_alert)
     if self.instance_type == 'case':
         import requests
         case_id = self.get_param('data._id')
         payload = {
             "query": { "_parent": { "_type": "case", "_query": { "_id": case_id } } },
             "range": "all"
         }
         headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer {}'.format(self.TheHive_API_key) }
         thehive_api_url_case_search = '{}/api/case/artifact/_search'.format(self.TheHive_instance)
         r = requests.post(thehive_api_url_case_search, data=json.dumps(payload), headers=headers)
         if r.status_code != requests.codes.ok:
             self.error(json.dumps(r.text))
         a=None
         data = r.json()
         for n in data:
            if n.get('dataType') == 'username':
                user=n.get('data')
     fw = firewall.Firewall(self.hostname_PaloAltoNGFW, api_username=self.User_PaloAltoNGFW, api_password=self.Password_PaloAltoNGFW)
     rulebase = panos.policies.Rulebase()
     fw.add(rulebase)
     current_security_rules =panos.policies.SecurityRule.refreshall(rulebase)
     user_list=[]
     for i in current_security_rules:
         if i.about().get('name') == self.name_security_rule:
             user_list=i.about().get("source_user")
     if user not in user_list:
         user_list.append(user)
         if "any" in user_list:
             user_list.remove("any")
     desired_rule_params = None
     for i in current_security_rules:
         if self.name_security_rule == i.about().get("name"):
             rule_atrib = i.about()
             rule_atrib.update({"source_user": user_list})
             desired_rule_params = rule_atrib
     new_rule = panos.policies.SecurityRule(**desired_rule_params)
     rulebase.add(new_rule)
     new_rule.apply()
     fw.commit()
     self.report({'message': 'Responder successfully added %s to %s' % (user,self.name_security_rule)})
示例#4
0
 def run(self):
     self.instance_type = self.get_param('data._type')
     if self.instance_type == 'case_artifact':
             ioc = self.get_param('data.data')
     if self.instance_type == 'alert':
         alertId = self.get_param('data.id')
         response = self.api.get_alert(alertId)
         ioc=None
         ioc_clear=[]
         for i in list(response.json().get("artifacts")):
             if 'ip' in str(i):
                 ioc = i.get("data")
                 for i in ioc:
                     if i == "[" or i == "]":
                         continue
                     else:
                         ioc_clear.append(i)
                 ioc="".join(ioc_clear)
     if self.instance_type == 'case':
         import requests
         case_id = self.get_param('data._id')
         payload = {
             "query": { "_parent": { "_type": "case", "_query": { "_id": case_id } } },
             "range": "all"
         }
         headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer {}'.format(self.TheHive_API_key) }
         thehive_api_url_case_search = '{}/api/case/artifact/_search'.format(self.TheHive_instance)
         r = requests.post(thehive_api_url_case_search, data=json.dumps(payload), headers=headers)
         if r.status_code != requests.codes.ok:
             self.error(json.dumps(r.text))
         a=None
         data = r.json()
         for n in data:
            if n.get('dataType') == 'ip':
                ioc=n.get('data')
     fw = firewall.Firewall(self.hostname_PaloAltoNGFW, api_username=self.User_PaloAltoNGFW, api_password=self.Password_PaloAltoNGFW)
     panos.objects.AddressGroup.refreshall(fw)            
     block_list = fw.find(self.name_external_Address_Group, panos.objects.AddressGroup)
     ioc_list = block_list.about().get('static_value')
     if f"thehive-{ioc}" in ioc_list:
         ioc_list.remove(f"thehive-{ioc}")
         temp1 = panos.objects.AddressGroup(self.name_external_Address_Group, static_value=ioc_list)
         fw.add(temp1)
         temp1.apply()
         
     panos.objects.AddressObject.refreshall(fw)
     if f"thehive-{ioc}" in str(fw.find(f"thehive-{ioc}", panos.objects.AddressObject)):
         try:
             deleted_ioc = fw.find(f"thehive-{ioc}", panos.objects.AddressObject)
             deleted_ioc.delete()
         except:
             self.report({'message': 'Responder did not comlite. Warning in AddressObject'})
     
     self.report({'message': 'Responder successfully deleted %s from %s' % (f"thehive-{ioc}",self.name_external_Address_Group)})
     fw.commit()
示例#5
0
    def run(self):
        alertId = self.get_param('data.id')
        response = self.api.get_alert(alertId)
        data_list = []
        data = None
        for i in response.json().get("artifacts"):
            if "'port'," in str(i):
                ioc = i.get("data")
                data_list.append(i.get("data"))
            elif "'protocol'," in str(i):
                ioc = i.get("data")
                data_list.append(i.get("data"))
            data = " ".join(data_list)
        protocol = re.findall(r'[a-z]+', str(data))
        protocol = str("".join(protocol)).lower()
        port = re.findall(r'[0-9]+', str(data))
        port = "".join(port)
        fw = firewall.Firewall(self.hostname_PaloAltoNGFW,
                               api_username=self.User_PaloAltoNGFW,
                               api_password=self.Password_PaloAltoNGFW)
        panos.objects.ServiceGroup.refreshall(fw)
        raise IOError("to")
        block_list = fw.find(self.name_internal_Service_Group,
                             panos.objects.ServiceGroup)
        port_list = block_list.about().get('value')
        if port in port_list:
            port_list.remove(port)
            temp1 = panos.objects.ServiceGroup(
                self.name_internal_Service_Group, value=port_list)
            fw.add(temp1)
            temp1.apply()

        block_list = fw.find(self.name_external_Service_Group,
                             panos.objects.ServiceGroup)
        port_list = block_list.about().get('value')
        if port in port_list:
            port_list.remove(port)
            temp1 = panos.objects.ServiceGroup(
                self.name_external_Service_Group, value=port_list)
            fw.add(temp1)
            temp1.apply()

        panos.objects.ServiceObject.refreshall(fw)
        if port in str(fw.find(port, panos.objects.ServiceObject)):
            deleted_ioc = fw.find(port, panos.objects.ServiceObject)
            deleted_ioc.delete()

        self.report({'message': 'message sent'})
示例#6
0
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
    vsys = device.Vsys("vsys3")
    c.add(vsys)

    assert expected == vsys.xpath_vsys()

    zone = network.Zone("myzone")
    vsys.add(zone)

    assert expected == zone.xpath_vsys()
示例#7
0
def _check(obj, vsys, with_pano, chk_import=False):
    if chk_import:
        func = "xpath_import_base"
    else:
        func = "xpath"
    fw = firewall.Firewall("127.0.0.1", "admin", "admin", serial="01234567890")
    fw.vsys = vsys
    fw.add(obj)

    if with_pano:
        pano = panorama.Panorama("127.0.0.1", "admin2", "admin2")
        pano.add(fw)

    expected = getattr(obj, func)()

    fw.remove(obj)
    fw.vsys = None
    vsys = device.Vsys(vsys or "vsys1")
    fw.add(vsys)
    vsys.add(obj)

    result = getattr(obj, func)()

    assert expected == result
def main():
    # Before we begin, you'll need to use the pan-os-python documentation both
    # for this example and for any scripts you may write for yourself.  The
    # docs can be found here:
    #
    # http://pan-os-python.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 pan-os-python
    # object tree."  In this case, since we'd be invoking it on a subinterface
    # of INTERFACE (our variable above), we are asking pan-os-python 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 pan-os-python 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 pan-os-python 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 pan-os-python 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 pan-os-python 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 run(self):
     self.instance_type = self.get_param('data._type')
     if self.instance_type == 'case_artifact':
         ioc = self.get_param('data.data')
     if self.instance_type == 'alert':
         alertId = self.get_param('data.id')
         response = self.api.get_alert(alertId)
         ioc = None
         ioc_clear = []
         for i in list(response.json().get("artifacts")):
             if 'ip' in str(i):
                 ioc = i.get("data")
                 for i in ioc:
                     if i == "[" or i == "]":
                         continue
                     else:
                         ioc_clear.append(i)
                 ioc = "".join(ioc_clear)
     if self.instance_type == 'case':
         import requests
         case_id = self.get_param('data._id')
         payload = {
             "query": {
                 "_parent": {
                     "_type": "case",
                     "_query": {
                         "_id": case_id
                     }
                 }
             },
             "range": "all"
         }
         headers = {
             'Content-Type': 'application/json',
             'Authorization': 'Bearer {}'.format(self.TheHive_API_key)
         }
         thehive_api_url_case_search = '{}/api/case/artifact/_search'.format(
             self.TheHive_instance)
         r = requests.post(thehive_api_url_case_search,
                           data=json.dumps(payload),
                           headers=headers)
         if r.status_code != requests.codes.ok:
             self.error(json.dumps(r.text))
         a = None
         data = r.json()
         for n in data:
             if n.get('dataType') == 'ip':
                 ioc = n.get('data')
     fw = firewall.Firewall(self.hostname_PaloAltoNGFW,
                            api_username=self.User_PaloAltoNGFW,
                            api_password=self.Password_PaloAltoNGFW)
     panos.objects.AddressObject.refreshall(fw)
     rulebase = panos.policies.Rulebase()
     fw.add(rulebase)
     current_security_rules = panos.policies.SecurityRule.refreshall(
         rulebase)
     if f"thehive-{ioc}" not in str(
             fw.find(f"thehive-{ioc}", panos.objects.AddressObject)):
         new_ioc_object = panos.objects.AddressObject(
             f"thehive-{ioc}",
             ioc,
             description="TheHive Blocked ip address")
         fw.add(new_ioc_object)
         new_ioc_object.create()
     panos.objects.AddressGroup.refreshall(fw)
     block_list = fw.find("TheHive Block list external IP address",
                          panos.objects.AddressGroup)
     if block_list != None:
         ioc_list = block_list.about().get('static_value')
         if f"thehive-{ioc}" not in ioc_list:
             ioc_list.append(f"thehive-{ioc}")
             temp1 = panos.objects.AddressGroup(
                 "TheHive Block list external IP address",
                 static_value=ioc_list)
             fw.add(temp1)
             temp1.apply()
     elif block_list == None:
         temp1 = panos.objects.AddressGroup(
             "TheHive Block list external IP address",
             static_value=f"thehive-{ioc}")
         fw.add(temp1)
         temp1.apply()
     desired_rule_params = None
     for i in current_security_rules:
         if self.name_security_rule == i.about().get("name"):
             rule_atrib = i.about()
             temp_rule_atrib = rule_atrib.get("destination")
             if "TheHive Block list external IP address" not in temp_rule_atrib:
                 temp_rule_atrib.append(
                     "TheHive Block list external IP address")
                 if "any" in temp_rule_atrib:
                     temp_rule_atrib.remove("any")
                 rule_atrib.update({"destination": temp_rule_atrib})
                 desired_rule_params = rule_atrib
             else:
                 desired_rule_params = rule_atrib
     new_rule = panos.policies.SecurityRule(**desired_rule_params)
     rulebase.add(new_rule)
     new_rule.apply()
     fw.commit()
     self.report({
         'message':
         'Responder successfully added %s into TheHive Block list external IP address from %s'
         % (ioc, self.name_security_rule)
     })
示例#10
0
#               Use config.toml for the settings. No commit command is sent the firewall. Commits will need to be
#               ran manually from the GUI to verify the correct config.
#
########################################################################################################################

from panos import firewall, objects, network, policies

import toml
import csv

# load settings
settings = toml.load('config.toml')

# connect to firewalls
print("Connecting to Firewalls")
fw = firewall.Firewall(settings['firewalls']['fw'], api_key=settings['api_key']['key'])
fw.set_ha_peers(firewall.Firewall(settings['firewalls']['fw_ha'], api_key=settings['api_key']['key']))

# Check HA pair first #########################
print("Checking HA configuration")
fw.refresh_ha_active()
if not fw.config_synced():
    print("I need to sync the configs first.")
    fw.synchronize_config()
###############################################

# Open endpoints csv
cradle_reader = csv.DictReader(open('endpoints.csv', 'rt', encoding='utf8'))

#######################################################################################################################
示例#11
0
    def run(self):
        self.instance_type = self.get_param('data._type')
        if self.instance_type == 'case_artifact':
                data = self.get_param('data.data')
                port=str(data).split('-')[0]
                protocol=str(data).split('-')[1]
                protocol=re.findall(r'[a-z]+',str(protocol)); protocol=str("".join(protocol)).lower()
                port=re.findall(r'[0-9]+',str(port)); port="".join(port)
        if self.instance_type == 'alert':
            alertId = self.get_param('data.id')
            response = self.api.get_alert(alertId)
            data_list=[]
            data=None
            for i in response.json().get("artifacts"):
                if "'port-protocol'," in str(i):
                   data_list.append(i.get("data"))
                port=str(data_list).split('-')[0]
                protocol=str(data_list).split('-')[1]
            protocol=re.findall(r'[a-z]+',str(protocol)); protocol=str("".join(protocol)).lower()
            port=re.findall(r'[0-9]+',str(port)); port="".join(port)
        if self.instance_type == 'case':
            import requests
            case_id = self.get_param('data._id')
            payload = {
                "query": { "_parent": { "_type": "case", "_query": { "_id": case_id } } },
                "range": "all"
            }
            headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer {}'.format(self.TheHive_API_key) }
            thehive_api_url_case_search = '{}/api/case/artifact/_search'.format(self.TheHive_instance)
            r = requests.post(thehive_api_url_case_search, data=json.dumps(payload), headers=headers)
            if r.status_code != requests.codes.ok:
                self.error(json.dumps(r.text))
            a=None
            data = r.json()
            data_list = []
            for n in data:
               if "'port-protocol'," in str(n):
                   data_list.append(n.get("data"))
               port=str(data_list).split('-')[0]
               protocol=str(data_list).split('-')[1]
            protocol=re.findall(r'[a-z]+',str(protocol)); protocol=str("".join(protocol)).lower()
            port=re.findall(r'[0-9]+',str(port)); port="".join(port)
        fw = firewall.Firewall(self.hostname_PaloAltoNGFW, api_username=self.User_PaloAltoNGFW, api_password=self.Password_PaloAltoNGFW)
        panos.objects.ServiceObject.refreshall(fw)
        rulebase = panos.policies.Rulebase()
        fw.add(rulebase)
        current_security_rules =panos.policies.SecurityRule.refreshall(rulebase)
        if f"thehive-{port}-{protocol}" not in str(fw.find(f"thehive-{port}-{protocol}", panos.objects.ServiceObject)):
            new_port_object = panos.objects.ServiceObject(f"thehive-{port}-{protocol}", protocol, description="TheHive Blocked port",destination_port=port)
            fw.add(new_port_object)
            new_port_object.create()    

            
        panos.objects.ServiceGroup.refreshall(fw)
        block_list = fw.find("TheHive Block list for external port communication", panos.objects.ServiceGroup)
        if block_list != None:
            port_list = block_list.about().get('value')
            if f"thehive-{port}-{protocol}" not in port_list:
                port_list.append(f"thehive-{port}-{protocol}")
                temp1 = panos.objects.ServiceGroup("TheHive Block list for external port communication", value=port_list)
                fw.add(temp1)
                temp1.apply()
        elif block_list == None:
            temp1 = panos.objects.ServiceGroup("TheHive Block list for external port communication", value=f"thehive-{port}-{protocol}")
            fw.add(temp1)
            temp1.apply()
        desired_rule_params = None
        for i in current_security_rules:
            if self.name_security_rule == str(i.about().get("name")):
                rule_atrib = i.about()
                temp_rule_atrib = rule_atrib.get("service")
                if "TheHive Block list for external port communication" not in temp_rule_atrib:
                    temp_rule_atrib.append("TheHive Block list for external port communication")
                    if "application-default" in temp_rule_atrib:
                        temp_rule_atrib.remove("application-default")
                    rule_atrib.update({"service": temp_rule_atrib})
                    desired_rule_params = rule_atrib
                else:
                    desired_rule_params = rule_atrib
        new_rule = panos.policies.SecurityRule(**desired_rule_params)
        rulebase.add(new_rule)
        new_rule.apply()
        fw.commit()
        self.report({'message': 'Responder successfully added %s into TheHive Block list for external port communication to %s' % (port,self.name_security_rule)})
示例#12
0
def init():
    """
    Environment variables:
        PD_USERNAME
        PD_PASSWORD
        PD_PANORAMAS
        PD_FIREWALLS
    """
    global live_devices
    global one_fw_per_version
    global one_device_per_version
    global one_panorama_per_version
    global ha_pairs
    global panorama_fw_combinations

    # Get os.environ stuff to set the live_devices global.
    try:
        username = os.environ["PD_USERNAME"]
        password = os.environ["PD_PASSWORD"]
        panos = os.environ["PD_PANORAMAS"].split()
        fws = os.environ["PD_FIREWALLS"].split()
    except KeyError as e:
        print('NOT RUNNING LIVE TESTS - missing "{0}"'.format(e))
        return

    # Add each panorama to the live_devices.
    for hostname in panos:
        c = panorama.Panorama(hostname, username, password)
        try:
            c.refresh_system_info()
        except Exception as e:
            raise ValueError("Failed to connect to panorama {0}: {1}".format(
                hostname, e))

        # There should only be one panorama per version.
        version = c._version_info
        if version in live_devices:
            raise ValueError("Two panoramas, same version: {0} and {1}".format(
                live_devices[version]["pano"].hostname, hostname))
        live_devices.setdefault(version, {"fws": [], "pano": None})
        live_devices[version]["pano"] = c

    # Add each firewall to the live_devices.
    for hostname in fws:
        c = firewall.Firewall(hostname, username, password)
        try:
            c.refresh_system_info()
        except Exception as e:
            raise ValueError("Failed to connect to firewall {0}: {1}".format(
                hostname, e))

        # Multiple firewalls are allowed per version, but only ever the first
        # two will be used.
        version = c._version_info
        live_devices.setdefault(version, {"fws": [], "pano": None})
        live_devices[version]["fws"].append(c)

    # Set:
    #   one_fw_per_version
    #   one_device_type_per_version
    #   one_panorama_per_version
    for version in live_devices:
        pano = live_devices[version]["pano"]
        fws = live_devices[version]["fws"]
        if fws:
            fw = random.choice(fws)
            one_device_type_per_version.append((fw, desc(fw=version)))
            one_fw_per_version.append((fw, desc(fw=version)))
        if pano is not None:
            one_panorama_per_version.append((pano, desc(pano=version)))
            one_device_type_per_version.append((pano, desc(pano=version)))

    # Set: ha_pairs
    for version in live_devices:
        fws = live_devices[version]["fws"]
        if len(fws) >= 2:
            ha_pairs.append((fws[:2], version))

    # Set panorama_fw_combinations
    for pano_version in live_devices:
        pano = live_devices[pano_version]["pano"]
        if pano is None:
            continue

        for fw_version in live_devices:
            fws = live_devices[fw_version]["fws"]
            if not fws or pano_version < fw_version:
                continue

            fw = random.choice(fws)
            panorama_fw_combinations.append((
                (pano, fw),
                desc(pano_version, fw_version),
            ))
示例#13
0
    def run(self):
        self.instance_type = self.get_param('data._type')
        if self.instance_type == 'case_artifact':
            data = self.get_param('data.data')
            port = str(data).split('-')[0]
            protocol = str(data).split('-')[1]
            protocol = re.findall(r'[a-z]+', str(protocol))
            protocol = str("".join(protocol)).lower()
            port = re.findall(r'[0-9]+', str(port))
            port = "".join(port)
        if self.instance_type == 'alert':
            alertId = self.get_param('data.id')
            response = self.api.get_alert(alertId)
            data_list = []
            data = None
            for i in response.json().get("artifacts"):
                if "'port-protocol'," in str(i):
                    data_list.append(i.get("data"))
                port = str(data_list).split('-')[0]
                protocol = str(data_list).split('-')[1]
            protocol = re.findall(r'[a-z]+', str(protocol))
            protocol = str("".join(protocol)).lower()
            port = re.findall(r'[0-9]+', str(port))
            port = "".join(port)
        if self.instance_type == 'case':
            import requests
            case_id = self.get_param('data._id')
            payload = {
                "query": {
                    "_parent": {
                        "_type": "case",
                        "_query": {
                            "_id": case_id
                        }
                    }
                },
                "range": "all"
            }
            headers = {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer {}'.format(self.TheHive_API_key)
            }
            thehive_api_url_case_search = '{}/api/case/artifact/_search'.format(
                self.TheHive_instance)
            r = requests.post(thehive_api_url_case_search,
                              data=json.dumps(payload),
                              headers=headers)
            if r.status_code != requests.codes.ok:
                self.error(json.dumps(r.text))
            a = None
            data = r.json()
            data_list = []
            for n in data:
                if "'port-protocol'," in str(n):
                    data_list.append(n.get("data"))
                port = str(data_list).split('-')[0]
                protocol = str(data_list).split('-')[1]
            protocol = re.findall(r'[a-z]+', str(protocol))
            protocol = str("".join(protocol)).lower()
            port = re.findall(r'[0-9]+', str(port))
            port = "".join(port)
        fw = firewall.Firewall(self.hostname_PaloAltoNGFW,
                               api_username=self.User_PaloAltoNGFW,
                               api_password=self.Password_PaloAltoNGFW)
        panos.objects.ServiceGroup.refreshall(fw)
        block_list = fw.find(self.name_internal_Service_Group,
                             panos.objects.ServiceGroup)
        port_list = block_list.about().get('value')
        if f"thehive-{port}-{protocol}" in port_list:
            port_list.remove(f"thehive-{port}-{protocol}")
            temp1 = panos.objects.ServiceGroup(
                self.name_internal_Service_Group, value=port_list)
            fw.add(temp1)
            temp1.apply()

        panos.objects.ServiceObject.refreshall(fw)

        self.report({
            'message':
            'Responder successfully deleted %s from %s' %
            (port, self.name_internal_Service_Group)
        })
        fw.commit()
示例#14
0
def eastwesthelper(pa_ip, username, password, pa_type, filename=None):
    """
    Main point of entry.
    Connect to PA/Panorama.
    Grab security rules from pa/pan.
    Modify them for intra-zone migration.
    """

    for subnet in settings.EXISTING_TRUST_SUBNET:
        if subnet.endswith("/32"):
            mem.singleip = True

    if pa_type == "panorama":

        # Grab 'start' time
        start = time.perf_counter()

        panfw = panorama.Panorama(pa_ip, username, password)
        # Grab the Device Groups and Template Names, we don't need Template names.
        pa = pa_api.api_lib_pa(pa_ip, username, password, pa_type)
        device_group = get_device_group(pa)
        pre_rulebase = policies.PreRulebase()
        post_rulebase = policies.PostRulebase()
        dg = panorama.DeviceGroup(device_group)
        dg.add(pre_rulebase)
        dg.add(post_rulebase)
        panfw.add(dg)

        # Grab Objects and Rules
        mem.address_object_entries = objects.AddressObject.refreshall(dg, add=False)#,add=False)
        mem.address_group_entries = objects.AddressGroup.refreshall(dg, add=False)#,add=False)

        #Grabbing the Shared address objects and groups..
        shared = panorama.DeviceGroup('shared')
        panfw.add(shared)

        shared_objects = objects.AddressObject.refreshall(shared, add=False)
        mem.address_object_entries += shared_objects
        shared_groups = objects.AddressGroup.refreshall(shared, add=False)
        mem.address_group_entries += shared_groups

        # Add parent DG (like Shared), if used. Ask Chris Evans or me for details.
        if settings.OBJ_PARENT_DEVICE_GROUP:
            parent_dg = panorama.DeviceGroup(settings.OBJ_PARENT_DEVICE_GROUP)
            panfw.add(parent_dg)

            parent_objects = objects.AddressObject.refreshall(parent_dg, add=False)
            mem.address_object_entries += parent_objects
            parent_groups = objects.AddressGroup.refreshall(parent_dg, add=False)
            mem.address_group_entries += parent_groups

        # GRAB PRE/POST RULES
        pre_security_rules = policies.SecurityRule.refreshall(pre_rulebase)#, add=False)
        post_security_rules = policies.SecurityRule.refreshall(post_rulebase)#, add=False)

        # Modify the rules, Pre & Post
        if pre_security_rules:
            eastwest_addnew_zone(pre_security_rules, panfw, pre_rulebase)
        if post_security_rules:
            eastwest_addnew_zone(post_security_rules, panfw, post_rulebase)
            
    elif pa_type == "pa":
        # Grab 'start' time
        start = time.perf_counter()

        panfw = firewall.Firewall(pa_ip, username, password)

        # Grab Rules
        mem.address_object_entries = objects.AddressObject.refreshall(panfw,add=False)
        mem.address_group_entries = objects.AddressGroup.refreshall(panfw,add=False)

        rulebase = policies.Rulebase()
        panfw.add(rulebase)
        security_rules = policies.SecurityRule.refreshall(rulebase)

        # Modify the rules
        if security_rules:
            modified_rules = eastwest_addnew_zone(security_rules, panfw, rulebase)

    # Finished
    end = time.perf_counter()
    runtime = end - start
    print(f"Took {runtime} Seconds.\n")
示例#15
0
    #parser.add_argument("-x", "--xml", help="Optional XML Filename", type=str)
    parser.add_argument("-u", "--username", help="Username", type=str)#, required=argrequired)
    parser.add_argument("-i", "--ipaddress", help="IP or FQDN of PA/Panorama", type=str)#, required=argrequired)
    args = parser.parse_args()

    # IF XML, do not connect to PA/Pan
    # if args.xml:
    #     print("NO LONGER IMPLEMENTED")
    #     sys.exit(0)

    # Gather input
    pa_ip = args.ipaddress
    username = args.username
    password = getpass("Enter Password: "******"Error connecting to: {pa_ip}\nCheck username/password and network connectivity.")
        print()
        print(e)
        sys.exit(0)

    # PA or Panorama?
    pa_type = pa_api.get_pa_type()

    # Run program
    print("\nThank you...connecting..\n")
    eastwesthelper(pa_ip, username, password, pa_type)