示例#1
0
    def __init__(self):
        Responder.__init__(self)
        # Mail settings
        server = self.get_param("config.server", None,
                                "Missing server in config")
        self.username = self.get_param("config.username", None,
                                       "Missing username in config")
        self.password = self.get_param("config.password", None,
                                       "Missing password in config")
        try:
            fingerprint_path = "{}/fingerprints.txt".format(
                os.path.dirname(__file__))
            fingerprint = json.loads(open(fingerprint_path,
                                          "r").read())[server]
            self.client_args = APIClientArgs(server=server,
                                             fingerprint=fingerprint)
        except:
            self.error(
                "Fingerprint check failed. It should be locate here {}".format(
                    fingerprint_path))

        self.service = self.get_param("config.service", None)
        self.group_name = self.get_param("config.group_name", None,
                                         "Missing group_name in config")
        self.exclusions = self.get_param("config.exclusions", [])
        self.added_tag = self.get_param("config.added_tag", None)
        self.removed_tag = self.get_param("config.removed_tag", None)
def install_policy():

    client_args = APIClientArgs(server=mgmt_ip, port=4434, api_version=1.5)
    message = ""

    with APIClient(client_args) as client:

        login_res = client.login(username=mgmt_user, password=mgmt_password)
        if login_res.success is False:
            message = "Login failed: {}".format(login_res.error_message)
            print(login_res)

        else:
            api_res = client.api_call(
                "install-policy", {
                    "policy-package": mgmt_policy,
                    "targets": mgmt_target_gateway,
                    "access": 0,
                    "threat-prevention": 1
                })

            if api_res.success:
                message = "Policy installed successfully!"

            else:
                message = "Policy was UNABLE to be installed :("

    return message
示例#3
0
    def __init__(self, ipaddr, username, password, domain=None, port="443"):

        self.api_server = ipaddr
        self.username = username
        self.password = password
        self.port = port
        #self.urlbase = "https://{ipaddr}:{port}/".format(ipaddr=self.ipaddr,port=self.port)
        #self.timeout = timeout
        if domain:
            self.domain = domain
        client_args = APIClientArgs(server=self.api_server, port=self.port)
        self.client = APIClient(client_args)
        if self.client.check_fingerprint() is False:
            print(
                "Could not get the server's fingerprint - Check connectivity with the server."
            )
            exit(1)

        # login to server:
        if domain:
            login_res = self.client.login(self.username, self.password, False,
                                          self.domain)
        else:
            login_res = self.client.login(self.username, self.password)

        if login_res.success is False:
            print("Login failed:\n{}".format(login_res.error_message))
            exit(1)
def main():
    user_args = populate_parser()

    Utils.log_file = open(
        os.path.dirname(os.path.abspath(__file__)) + os.sep +
        'replace_references_' +
        (user_args.domain if user_args.domain else "") + '_' +
        str(Utils.DATETIME_NOW_SEC) + '.txt', 'w+')
    client_args = APIClientArgs(server=user_args.management,
                                port=user_args.port)

    with APIClient(client_args) as client:
        # The API client, would look for the server's certificate SHA1 fingerprint in a file.
        # If the fingerprint is not found on the file, it will ask the user if he accepts the server's fingerprint.
        # In case the user does not accept the fingerprint, exit the program.
        if client.check_fingerprint() is False:
            Utils.print_msg(
                "Could not get the server's fingerprint - Check connectivity with the server."
            )
            exit(1)

        Utils.login(user_args, client)
        original_object = get_object(client, user_args.original_reference)
        new_object = get_object(client, user_args.new_reference)

        if not find_usages(client, original_object):
            Utils.print_msg("WARNING: " + original_object.get("name") +
                            " not in use")

        replace_original_with_new_reference(client, original_object,
                                            new_object)

        res = client.api_call("publish")
        Utils.exit_failure("Publish operation failed ", res, client)
        Utils.log_file.close()
def fun_getipsver_mgmt():
    global output_text
    global output_code
    global ipsver_mgmt
    client_args = APIClientArgs(server=args.api_server, context=args.api_context, unsafe='True')
    with APIClient(client_args) as client:
        # If Errer occurs due to fingerprtnt mismatch
        if client.check_fingerprint() is False:
            output_text.update="Could not get the server's fingerprint - Check connectivity with the server."
            output_code.append("UNKNOWN")
        # login to server:
        login_res = client.login(args.api_user, args.api_pwd)
        logging.debug('API Login done: '+str(login_res))
        # when login failed
        if login_res.success is False:
            output_text.update="Login failed: {}".format(login_res.error_message)
            output_code.append("UNKNOWN")
        else:
            #API Call "show ips status"
            res_ipsver_mgmt = client.api_call("show-ips-status")
            ipsver_mgmt=res_ipsver_mgmt.data["installed-version"]
    if ipsver_mgmt:
        #getting version numbers
        ips_current_ver_info=res_ipsver_mgmt.data["installed-version"]
        ips_update_ver_info=res_ipsver_mgmt.data["latest-version"]
        #bool update available - yes/no
        ips_bool_update=res_ipsver_mgmt.data["update-available"]
        #install dates
        ips_date_last_install=res_ipsver_mgmt.data["last-updated"]
        ips_date_last_install_iso=ips_date_last_install["iso-8601"]
        ips_date_last_install_posix=ips_date_last_install["posix"]
        ips_date_update=res_ipsver_mgmt.data["latest-version-creation-time"]
        ips_date_update_posix=ips_date_update["posix"]
        #
        #
        ips_update_date_delta=((ips_date_last_install_posix/1000 - ips_date_update_posix/1000))/(60*60*24)
        logging.debug('Fetched Management IPS Version: '+str(ips_current_ver_info)+", most recent:"+str(ips_current_ver_info)+" From:"+str(ips_date_last_install_iso))
        #work with it
        if not ips_bool_update:
            logging.debug("Update available: " +str(ips_bool_update))
            output_text.update({"Monitor Management IPS Version": {"Result" : "OK! No Update available - Last installed update: "+str(ips_date_last_install_iso)+" - Installed Version "+str(ips_current_ver_info)+" - Newest: "+str(ips_update_ver_info)}})
            output_code.append("OK")
        elif ips_update_date_delta > 3:
            logging.debug("Update available: " +str(ips_bool_update))
            output_text.update({"Monitor Management IPS Version": {"Result" : "CRITICAL! Updates available -  Last installed update: "+str(ips_date_last_install_iso)+" - last Installed version "+str(ips_current_ver_info)+"  - Newest: "+str(ips_update_ver_info)+" - Update Date Delta: "+str(ips_update_date_delta)+" Days!"}})
            output_code.append("CRITICAL")
        elif ips_update_date_delta > 0 and ips_update_date_delta < 3:
            logging.debug("Update available: " +str(ips_bool_update))
            output_text.update({"Monitor Management IPS Version": {"Result" : "WARNING! Updates available -  Last installed update: "+str(ips_date_last_install_iso)+" - last Installed version "+str(ips_current_ver_info)+"  - Newest: "+str(ips_update_ver_info)+" - Update Date Delta: "+str(ips_update_date_delta)+" Days!"}})
            output_code.append("WARNING")
        else:
            logging.debug("Something is wrong - API Response: " +str(login_res))
            output_text.update({"Monitor Management IPS Version": {"Result" : "There is something wrong - please check! API Response (with -v)"}})
            output_code.append("UNKNOWN")
    else:
        logging.debug("Soomething is wron - API Response: " +str(login_res))
        output_text.update({"meh - something went wrong"})
        output_code.append("UNKNOWN")

    return output_text,output_code,ipsver_mgmt
示例#6
0
def publish_changes():
    client_args = APIClientArgs(server=config.api_server)
    with APIClient(client_args) as client:
        client.debug_file = "api_calls.json"
        if client.check_fingerprint() is False:
            print(
                "Could not get the server's fingerprint - Check connectivity with the server."
            )
            logging.warning(
                "Could not get the server's fingerprint - Check connectivity with the server."
            )
            sys.exit(1)
        login_res = client.login(config.username, config.password, "True",
                                 config.domain)
        if login_res.success is False:
            print("Login failed: {}".format(login_res.error_message))
            logging.warning("Login failed: {}".format(login_res.error_message))
            sys.exit(1)
        set_package = client.api_call("set-package", {"name": config.package})
        publish_res = client.api_call("publish", {})
        if publish_res.success:
            print("The changes were published successfully.")
            logging.info("The changes were published successfully.")
        else:
            print("Failed to publish the changes.")
            logging.warning("Failed to publish the changes.")
示例#7
0
def main():
    # getting details from the user
    api_server = input("Enter server IP address or hostname:")
    username = input("Enter username: "******"Enter password: "******"Attention! Your password will be shown on the screen!")
        password = input("Enter password: "******"Enter the name of the access rule: ")

        #
        # The API client, would look for the server's certificate SHA1 fingerprint in a file.
        # If the fingerprint is not found on the file, it will ask the user if he accepts the server's fingerprint.
        # In case the user does not accept the fingerprint, exit the program.
        if client.check_fingerprint() is False:
            print(
                "Could not get the server's fingerprint - Check connectivity with the server."
            )
            exit(1)

        # login to server:
        login_res = client.login(username, password)

        if login_res.success is False:
            print("Login failed:\n{}".format(login_res.error_message))
            exit(1)

        # add a rule to the top of the "Network" layer
        add_rule_response = client.api_call("add-access-rule", {
            "name": rule_name,
            "layer": "Network",
            "position": "top"
        })

        if add_rule_response.success:

            print(
                "The rule: '{}' has been added successfully".format(rule_name))

            # publish the result
            publish_res = client.api_call("publish", {})
            if publish_res.success:
                print("The changes were published successfully.")
            else:
                print("Failed to publish the changes.")
        else:
            print("Failed to add the access-rule: '{}', Error:\n{}".format(
                rule_name, add_rule_response.error_message))
def main():
    # getting details from the user
    api_server = input("Enter server IP address or hostname:")
    username = input("Enter username: “)

    if sys.stdin.isatty():
        password = getpass.getpass("Enter password: "******"Attention! Your password will be shown on the screen!")
        password = input("Enter password: "******"Could not get the server's fingerprint - Check connectivity with the server.")
            exit(1)

        # login to server:
        login_res = client.login(username, password)

        if login_res.success is False:
            print("Login failed:\n{}".format(login_res.error_message))
            exit(1)

        csv_filepath = input("Enter the filepath: ")
        # delete network objects listed in a csv file
        # read the file
        with open(csv_filepath, 'r') as read_obj:
            # pass the file object to reader() to get the reader object
            csv_reader = reader(read_obj)
            # Iterate over each row in the csv using reader object
            for host in csv_reader:
                # host variable is a list that represents a row in csv
                unused_host_data = {'name':'{}'.format(str(host[0]))}

                delete_objects_response = client.api_call("delete-host", unused_host_data)
                
                if delete_object_response.success:
                    print("The network object {} has been deleted successfully".format(unused_host_data))            
                else:
                    print("Failed to delete network object {}, Error:\n{}".format(unused_host_data, delete_objects_response.error_message))
                
        # publish the result
        publish_res = client.api_call("publish", {})
        if publish_res.success:
            print("The changes were published successfully.")
        else:
            print("Failed to publish the changes.")
示例#9
0
    def run(self):
        Responder.run(self)

        client_args = APIClientArgs(server=self.server_ip, unsafe=True)

        with APIClient(client_args) as client:

             POST {{server}}/login
             Content-Type: application/json

             {
               "api-key" : "hqreK1MmmM4T1AYA0jOJpg=="
             }
示例#10
0
def main():
    # getting details from the user
    api_server = input("Enter server IP address or hostname:")
    username = input("Enter username: "******"Enter password: "******"Attention! Your password will be shown on the screen!")
        password = input("Enter password: "******"Could not get the server's fingerprint - Check connectivity with the server."
            )
            exit(1)

        # login to server:
        login_res = client.login(username, password)

        if login_res.success is False:
            print("Login failed:\n{}".format(login_res.error_message))
            exit(1)

        show_sessions_res = client.api_query("show-sessions", "full")

        if not show_sessions_res.success:
            print("Failed to retrieve the sessions")
            return

        for sessionObj in show_sessions_res.data:
            # Ignore sessions that were not created with WEB APIs or CLI
            if sessionObj["application"] != "WEB_API":
                continue

            discard_res = client.api_call("discard",
                                          {"uid": sessionObj['uid']})
            if discard_res.success:
                print("Session '{}' discarded successfully".format(
                    sessionObj['uid']))
            else:
                print("Session '{}' failed to discard".format(
                    sessionObj['uid']))
示例#11
0
def main():
    # getting details from the user
    api_server = input("Enter server IP address or hostname:")

    if sys.stdin.isatty():
        api_key = getpass.getpass("Enter api-key: ")
    else:
        print("Attention! Your api-key will be shown on the screen!")
        api_key = input("Enter api-key: ")

    client_args = APIClientArgs(server=api_server)

    with APIClient(client_args) as client:

        group_name = input("Enter the name of the group: ")

        #
        # The API client, would look for the server's certificate SHA1 fingerprint in a file.
        # If the fingerprint is not found on the file, it will ask the user if he accepts the server's fingerprint.
        # In case the user does not accept the fingerprint, exit the program.
        if client.check_fingerprint() is False:
            print(
                "Could not get the server's fingerprint - Check connectivity with the server."
            )
            exit(1)

        # login to server:
        login_res = client.login_with_api_key(api_key)

        if login_res.success is False:
            print("Login failed:\n{}".format(login_res.error_message))
            exit(1)

        # add the group
        add_group_response = client.api_call("add-group", {"name": group_name})

        if add_group_response.success:

            print("The group: '{}' has been added successfully".format(
                group_name))

            # publish the result
            publish_res = client.api_call("publish", {})
            if publish_res.success:
                print("The changes were published successfully.")
            else:
                print("Failed to publish the changes.")
        else:
            print("Failed to add the group: '{}', Error:\n{}".format(
                group_name, add_group_response.error_message))
def add():
    username, password = util.get_credentials_access()

    client_args = APIClientArgs()

    with APIClient(client_args) as client:
        #
        # The API client, would look for the server's certificate SHA1 fingerprint in a file.
        # If the fingerprint is not found on the file, it will ask the user if he accepts the server's fingerprint.
        # In case the user does not accept the fingerprint, exit the program.
        if client.check_fingerprint() is False:
            print(
                "Could not get the server's fingerprint - Check connectivity with the server."
            )
            exit(1)

        # login to server:
        login_res = client.login(username, password)

        if login_res.success is False:
            print("Login failed:\n{}".format(login_res.error_message))
            exit(1)

        for i in range(_PORT, _PORT + 3000):
            add_service_response = client.api_call("add-service-tcp", {
                "name": 'TCP-' + str(i),
                "port": i
            })
            if add_service_response.success:
                print("The service: '{}' has been added successfully".format(
                    add_service_response.data['name']))
            else:
                print("Port: '{}'\n{}".format(
                    i, add_service_response.error_message))
                print("[{}] {}: {}".format(
                    add_service_response.status_code,
                    add_service_response.data['code'],
                    add_service_response.data['message']))

        # publish the result
        publish_res = client.api_call("publish", {})
        if publish_res.success:
            print("The changes were published successfully.")
        else:
            print("Failed to publish the changes.")
示例#13
0
def login():
    client_args = APIClientArgs(server=config.api_server)
    client = APIClient(client_args)
    client.debug_file = "api_calls.json"
    if client.check_fingerprint() is False:
        print(
            "Could not get the server's fingerprint - Check connectivity with the server."
        )
        logging.warning(
            "Could not get the server's fingerprint - Check connectivity with the server."
        )
        sys.exit(1)
    login_res = client.login(config.username, config.password, "True",
                             config.domain)
    if login_res.success is False:
        print("Login failed: {}".format(login_res.error_message))
        logging.warning("Login failed: {}".format(login_res.error_message))
        sys.exit(1)
    config.session = client
def fun_getipsver_gws():
    global ipsver_mgmt
    global output_text
    global output_code
    client_args = APIClientArgs(server=args.api_server, context=args.api_context, unsafe='True')
    with APIClient(client_args) as client:
        # If Errer occurs due to fingerprint mismatch
        if client.check_fingerprint() is False:
            output_text.update({"Monitor Logging into Mgmt API": {"Result": "Could not get the server's fingerprint - Check connectivity with the server."}})
            output_code.append("UNKNOWN")

        # login to server:r
        login_res = client.login(args.api_user,args.api_pwd)

        # when login failed
        if login_res.success is False:
            logging.debug("Something is wrong - API Response: " +str(login_res))
            output_text.update({"Monitor Logging into Mgmt API": {"Result": "Login failed: {}".format(login_res.error_message)}})
            output_code.append("UNKNOWN")
        res_getmanagedgws = client.api_call("show-simple-gateways",{"limit":"500"})
        gwselector=0
        totalgws=res_getmanagedgws.data['total']
        logging.debug("Checking IPS version on "+str(res_getmanagedgws.data['total'])+" Gateways")
        dict_ipsver_gw={}
        while gwselector < totalgws:
            gwname=res_getmanagedgws.data['objects'][gwselector]['name']
            res_ipsvermgmt_task = client.api_call("run-script",{"script-name":"get ips version","script":"clish -c \"show security-gateway ips status\"","targets" : gwname}) 
            ipsver_gw=re.search('IPS Update Version: (.+?), ', res_ipsvermgmt_task.data['tasks'][0]['task-details'][0]['statusDescription'])
            dict_ipsver_gw.update({ gwname: {"gwversion" : ipsver_gw.group(1),"mgmtversion" : ipsver_mgmt,"gwmgmtsame" : ipsver_mgmt==ipsver_gw.group(1)}})
            if ipsver_mgmt!=ipsver_gw.group(1):
                output_text.update({"Monitor Gateway "+str(gwname)+" IPS Version": {"Result":"has not the same version as Management! Management:"+str(ipsver_mgmt)+" - Gw:"+str(ipsver_gw.group(1))+""}})
                output_code.append("WARNING")
            elif ipsver_mgmt==ipsver_gw.group(1):
                output_text.update({"Monitor Gateway "+str(gwname)+" IPS Version": {"Result":"OK! Mgmt "+str(ipsver_mgmt)+" - Gw "+str(ipsver_gw.group(1))+""}})
                output_code.append("OK")
            else:
                output_text.update({"Monitor Gateway "+str(gwname)+" IPS Version": {"Result":"UNKNOWN! Something weird happened"}})
                output_code.append("UNKNOWN")
            logging.debug("IPS version on "+str(gwname)+": "+ipsver_gw.group(1))
            gwselector=gwselector+1
    return output_text, output_code
示例#15
0
def main():
    # getting details from the user
    api_server = input("Enter server IP address or hostname:")
    username = input("Enter username: "******"Enter password: "******"Attention! Your password will be shown on the screen!")
        password = input("Enter password: "******"1",
                                unsafe=True,
                                context="gaia_api")

    with APIClient(client_args) as client:

        # login to server:
        login_res = client.login(username, password)

        if login_res.success is False:
            print("Login failed: {}".format(login_res.error_message))
            exit(1)

        interface_name = input("Enter interface name: ")
        api_res = client.api_call("show-physical-interface",
                                  {"name": interface_name})
        if api_res.success:
            # in order to access any field within the data that had
            # returned, simple use api_res.data["field name"] or refer to
            # the documentation page -
            # https://sc1.checkpoint.com/documents/latest/GaiaAPIs/
            print("Physical interface name is '{}' , ipv4 address is '{}', "
                  "interface mtu is '{}' ".format(api_res.data["name"],
                                                  api_res.data["ipv4-address"],
                                                  api_res.data["mtu"]))
        else:
            print("Failed to get physical interface data '{}'".format(
                api_res.data))
示例#16
0
def main():
    # getting details from the user
    api_server = raw_input("Enter server IP address or hostname:")
    username = raw_input("Enter username: "******"Enter password: "******"Attention! Your password will be shown on the screen!")
        password = raw_input("Enter password: "******"hostname value to be defined:")

    client_args = APIClientArgs(server=api_server,
                                api_version="1",
                                unsafe=True,
                                context="gaia_api")

    with APIClient(client_args) as client:

        # login to server:
        login_res = client.login(username, password)

        if login_res.success is False:
            print("Login failed: {}".format(login_res.error_message))
            exit(1)

        # request to show hostname
        api_res = client.api_call("show-hostname", {})
        if api_res.success:
            print("Hostname is '{}'".format(api_res.data["name"]))
        else:
            print("Failed to get hostname '{}'".format(api_res.data))

        # request to set hostname
        api_res = client.api_call("set-hostname", {"name": hostname})
        if api_res.success:
            print("Hostname name changed to '{}'".format(api_res.data["name"]))
        else:
            print("Failed to get hostname '{}'".format(api_res.data))
示例#17
0
文件: find_dup_ip.py 项目: aque/cpapi
def main():
    # getting details from the user
    api_server = input("Enter server IP address or hostname:")
    username = input("Enter username: "******"Enter password: "******"Attention! Your password will be shown on the screen!")
        password = input("Enter password: "******"api_calls.json"

        # The API client, would look for the server's certificate SHA1 fingerprint in a file.
        # If the fingerprint is not found on the file, it will ask the user if he accepts the server's fingerprint.
        # In case the user does not accept the fingerprint, exit the program.
        if client.check_fingerprint() is False:
            print(
                "Could not get the server's fingerprint - Check connectivity with the server."
            )
            exit(1)

        # login to server:
        login_res = client.login(username, password)

        if login_res.success is False:
            print("Login failed:\n{}".format(login_res.error_message))
            exit(1)

        # show hosts
        print("Processing. Please wait...")
        show_hosts_res = client.api_query("show-hosts", "standard")
        if show_hosts_res.success is False:
            print("Failed to get the list of all host objects:\n{}".format(
                show_hosts_res.error_message))
            exit(1)

    # obj_dictionary - for a given IP address, get an array of hosts (name, unique-ID) that use this IP address.
    obj_dictionary = {}

    # dup_ip_set - a collection of the duplicate IP addresses in all the host objects.
    dup_ip_set = set()

    for host in show_hosts_res.data:
        ipaddr = host.get("ipv4-address")
        if ipaddr is None:
            print(host["name"] + " has no IPv4 address. Skipping...")
            continue
        host_data = {"name": host["name"], "uid": host["uid"]}
        if ipaddr in obj_dictionary:
            dup_ip_set.add(ipaddr)
            obj_dictionary[ipaddr] += [host_data
                                       ]  # '+=' modifies the list in place
        else:
            obj_dictionary[ipaddr] = [host_data]

    # print list of duplicate IP addresses to the console
    print("\n")
    print("List of Duplicate IP addresses: ")
    print("------------------------------- \n")

    if len(dup_ip_set) == 0:
        print("No hosts with duplicate IP addresses")

    # for every duplicate ip - print hosts with that ip:
    for dup_ip in dup_ip_set:
        print("\nIP Address: " + dup_ip + "")
        print("----------------------------------")

        for obj in obj_dictionary[dup_ip]:
            print(obj["name"] + " (" + obj["uid"] + ")")
示例#18
0
def main():
    # Login to the Server
    # getting details from the support files
    #

    with open('./auth/mycpapi.json') as json_file:
        server = json.load(json_file)

    api_server = server['chkp']['host']

    with open('./auth/mycpauth.json') as json_file:
        auth = json.load(json_file)

    username = auth['user']
    password = auth['password']

    client_args = APIClientArgs(server=api_server)

    with APIClient(client_args) as client:

        # create debug file. The debug file will hold all the communication between the python script and
        # Check Point's management server.
        client.debug_file = "api_calls.json"

        # The API client, would look for the server's certificate SHA1 fingerprint in a file.
        # If the fingerprint is not found on the file, it will ask the user if he accepts the server's fingerprint.
        # In case the user does not accept the fingerprint, exit the program.
        if client.check_fingerprint() is False:
            print("Could not get the server's fingerprint - Check connectivity with the server.")
            exit(1)

        # login to server:
        login_res = client.login(username, password)
        # print(login_res.data.get("sid"))
        # sid = login_res.data.get("sid")
        # print(sid)

        if login_res.success is False:
            print("Login failed:\n{}".format(login_res.error_message))
            exit(1)

        ### Actual Code Starts here ###

        mycmd = 'set-session'
        myobj = {}
        myobj['description'] = "Session Description"
        myobj['new-name'] = "New Session Name"
        session_res = client.api_call(mycmd, myobj)

        with open('./host.json') as json_file:
            myfile = json.load(json_file)

        # print(myfile['remove'])
        removearr = myfile['remove']

        print("Entering Set-Group")
        cmd = 'set-group'
        if removearr[cmd]:
            for group in removearr[cmd]:

                cmddata = {}
                cmddata['name'] = group['name']
                cmddata['details-level'] = "uid"
                show_group_res = client.api_call("show-group", cmddata)
                show_group = show_group_res.data
                if len(show_group['members']) > 1:
                    cmddata['members'] = group['members']
                    cmddata['details-level'] = "standard"
                    print("set-group ", cmddata)

                    set_group_res = client.api_call(cmd, cmddata)
                    if set_group_res.success is False:
                        print("Setting Group Failed:\n{}".format(set_group_res.error_message))
                        exit(1)

                    # removecmd_res = client.api_call(cmd, cmddata)
                    # print(removecmd_res.data)

                    cmddata['members'] = {'add': group['members']['remove']}
                    print("RESTORE: set-group", cmddata)
                    tmplist = [cmd, cmddata]
                    myfile['restore'].insert(0, tmplist)

                else:
                    print("Only member, might as well clean up group")

        print("Exit Set-Group")

        print("Entering Set-Access-Rule")
        if removearr['set-access-rule']:
            for rule in removearr['set-access-rule']:
                cmddata = {}
                cmddata['layer'] = rule['layer']
                cmddata['uid'] = rule['uid']
                cmddata['details-level'] = "uid"
                show_access_rule_res = client.api_call("show-access-rule", cmddata)
                cmd = "set-access-rule"
                cmddata['details-level'] = "standard"
                if 'destination' in rule:
                    if len(show_access_rule_res.data['destination']) > 1:
                        cmddata['destination'] = rule['destination']
                        print(cmd, cmddata)

                        set_access_rule_res = client.api_call(cmd, cmddata)
                        if set_access_rule_res.success is False:
                            print("Setting Access Rule Failed:\n{}".format(set_access_rule_res.error_message))
                            exit(1)

                        cmddata['destination'] = {'add': rule['destination']['remove']}
                        print("RESTORE: ", cmd, " ", cmddata)
                        tmplist = [cmd, cmddata]
                        myfile['restore'].insert(0, tmplist)
                    else:
                        print("rule has no more destinations, disable")

                if 'source' in rule:
                    if len(show_access_rule_res.data['source']) > 1:
                        cmddata['source'] = rule['source']
                        print(cmd, cmddata)

                        set_access_rule_res = client.api_call(cmd, cmddata)
                        if set_access_rule_res.success is False:
                            print("Setting Access Rule Failed:\n{}".format(set_access_rule_res.error_message))
                            exit(1)

                        cmddata['source'] = {'add': rule['source']['remove']}
                        print("RESTORE: ", cmd, " ", cmddata)
                        tmplist = [cmd, cmddata]
                        myfile['restore'].insert(0, tmplist)

                    else:
                        print("rule has no more sources, disable")

        print("Exiting Set-Access-Rule")

        cmd = "delete-host"
        print("Entering ", cmd)
        if removearr[cmd]:
            for host in removearr[cmd]:
                cmddata = {}
                cmddata['name'] = host['name']
                print(cmd, cmddata)
                show_host_res = client.api_call('show-host', cmddata)
                if show_host_res.success is False:
                    print("Show host Failed:\n{}".format(delete_host_res.error_message))
                    exit(1)

                delete_host_res = client.api_call(cmd, cmddata)
                if delete_host_res.success is False:
                    print("Delete Host Failed:\n{}".format(delete_host_res.error_message))
                    exit(1)

                host = show_host_res.data

                cmd = "add-host"
                data = {}
                data['name'] = host['name']
                data['ipv4-address'] = host['ipv4-address']
                data['color'] = host['color']
                data['comments'] = host['comments']
                if 'host-servers' in host:
                    data['host-servers'] = host['host-servers']
                print("the restore data is: ", data)
                tmplist = [cmd, data]
                myfile['restore'].insert(0, tmplist)

        print(myfile['restore'])
        print("Exiting ", cmd)

        res = client.api_call("publish", {})
        if res.success is False:
            discard_write_to_log_file(api_client,
                                      "Publish failed. Error:\n{}\nAborting all changes.".format(res.error_message))
            return False

        client.api_call("logout", {})

        myfile_pretty = json.dumps(myfile, indent=2)
        with open('host.json', 'w') as outfile:
            outfile.write(myfile_pretty)
示例#19
0
def main():
    # Try / Catch to get exceptions regarding
    # excel file connections and
    # checkpoint api client initialization
    try:
        # Logger configurations
        logger_config()

        # Read data from file
        dataframe = pd.read_excel(settings.object_data_path)
        # Since blank cells return 'nan' instead of empty string
        # we replace all 'nan' with an empty string
        dataframe = dataframe.fillna("")

        # Initialize the SMS session
        client_args = APIClientArgs(server=settings.sms_ip,
                                    api_version=settings.api_version)

        with APIClient(client_args) as client:

            # Login to SMS:
            login_res = client.login(settings.sms_username,
                                     settings.sms_password)

            # If login is not successful, raise an error message.
            if login_res.success is False:
                raise Exception(Const.ERROR_LOGIN_FALED)
            else:
                # Displays a message that we
                # successfully connected to the sms
                display(
                    Const.MESSAGE_CONNECTION_SMS_SUCCESSFULL.format(
                        settings.sms_ip))

                access_rules = []

                # Iterate through each row
                # in the excel table
                # Index is not used here but should
                # NOT BE REMOVED
                for index, row in dataframe.iterrows():

                    object_name = row["Object Name"]

                    # Make an API call to fetch
                    # basic rule details where the object
                    # is being used
                    policy_rules_dict = fetch_basic_rule(client, object_name)

                    if policy_rules_dict != None:
                        # Make multiple API calls for each access rules in each
                        # policy returned
                        a_rules = fetch_access_rules(client, policy_rules_dict,
                                                     object_name)

                        if a_rules != None:
                            # Extend the list
                            access_rules.extend(a_rules)

                if access_rules != None:
                    # Export access rules
                    export_rules(access_rules)

    except Exception as e:
        # Prints the error message
        display(Const.ERROR_INTERNAL.format(e))

        exit(1)
示例#20
0
def process_args_and_login(parser=None,
                           client=None,
                           showparameter=None,
                           fields=None):
    # initializing command line arguments and variables to be used later
    args = args_initializer(parser=parser, param=showparameter)
    global debug
    global log_file
    if not showparameter:
        showparameter = args.showparameter[0] if args.showparameter else None
    if not fields:
        try:
            fields = {
                "whitelist": args.fields,
                "blacklist": [],
                "translate": []
            }
        except AttributeError:
            fields = {"whitelist": [], "blacklist": [], "translate": []}
    management = args.management[0] if args.management else None
    domain = args.domain[0] if args.domain else None
    debug = None
    log_file = None
    if args.debug[0] == "on":
        debug = True
    if (debug or __debug__) and args.log_file is not None:
        try:
            log_file = open(args.log_file, "wb")
        except IOError:
            debug_log(
                "Could not open given log file for writing, sending debug information to stderr."
            )
    # open the output file if given one
    output_file = open(args.output[0], "wb") if args.output else None
    output_file_format = args.format[0].lower()
    user_created = (args.user_created[0].lower()
                    == "true") if args.user_created else True

    # trying to get login credentials
    username, password, session_id = get_login_credentials(
        args.username[0] if args.username else None,
        args.password[0] if args.password else None,
        args.session_id[0] if args.session_id else None,
        args.session_file[0] if args.session_file else None,
        args.root[0] if args.root else None)
    debug_log(
        "Got the following login credentials:\n    Username: {0}\n    Password: {1}\n    Session ID: {2}"
        .format(username, '*' * len(password) if password else None,
                session_id))
    if not args.root or args.root[0] == "true":
        unsafe = (args.unsafe[0] == "true")
        unsafe_auto_accept = (args.unsafe_auto_accept[0] == "true")
        if not client:
            client = APIClient(APIClientArgs(server=management))
        if unsafe or (unsafe_auto_accept
                      and validate_fingerprint_without_prompt(
                          client, management, auto_accept=unsafe_auto_accept)
                      ) or client.check_fingerprint():
            login(client, management, domain, username, password, session_id)
        else:
            raise APIClientException(
                "The server's fingerprint is different than your local record of it. The script cannot operate in this unsecure manner (unless running with --unsafe). Exiting..."
            )
    else:
        login(client,
              management,
              domain,
              session_id=session_id,
              username=None,
              password=None)
    return output_file, output_file_format, user_created, client, args
示例#21
0
def main(argv):
    # Initialize arguments
    global_domain = "Global"
    auto_assign = False

    if argv:
        parser = argparse.ArgumentParser()
        parser.add_argument("-s", type=str, action="store", help="Server IP address or hostname", dest="server")
        parser.add_argument("-u", type=str, action="store", help="User name", dest="username")
        parser.add_argument("-p", type=str, action="store", help="Password", dest="password")
        parser.add_argument("-o", type=str, action="store", help="Original host IP", dest="origin_ip")
        parser.add_argument("-n", type=str, action="store", help="New host name", dest="new_name")
        parser.add_argument("-m", type=str, action="store", help="New host IP", dest="new_ip")
        parser.add_argument("-g", type=str, action="store", help="Global domain name", dest="global_name")
        parser.add_argument("-a", action="store_true", default=False,
                            help="Indicates that the script will do assign of global domain")

        args = parser.parse_args()

        required = "server username password origin_ip new_name new_ip".split()
        for r in required:
            if args.__dict__[r] is None:
                parser.error("parameter '%s' required" % r)

        server = args.server
        username = args.username
        password = args.password
        orig_host_ip = args.origin_ip
        cloned_host_name = args.new_name
        cloned_host_ip = args.new_ip
        auto_assign = args.a

        if args.global_name is not None:
            global_domain = args.global_name

    else:
        server = raw_input("Enter server IP address or hostname:")
        username = raw_input("Enter username: "******"Enter password: "******"Attention! Your password will be shown on the screen!")
            password = raw_input("Enter password: "******"Enter host IP address: ")
        cloned_host_name = raw_input("Enter new host name: ")
        cloned_host_ip = raw_input("Enter new host server IP :")
        global_domain_input = raw_input("Enter global domain name in case of MDS server: [In order to use the default "
                                        "value ('Global') or in case of CMA hit 'Enter']")
        if global_domain_input != "":
            global_domain = global_domain_input

        auto_assign_input = raw_input("Enter 'True' if you want the script to do "
                                      "assign of the global domain [In order to use the default value "
                                      "('False') hit 'Enter']")
        if auto_assign_input != "" and auto_assign_input == "True":
            auto_assign = auto_assign_input

    with APIClient(APIClientArgs(server=server)) as client:
        # Creates debug file. The debug file contains all the communication
        # between the python script and Check Point's management server.
        client.debug_file = "api_calls.json"

        global log_file
        log_file = open('logfile.txt', 'w+')

        # The API client, would look for the server's certificate SHA1 fingerprint in a file.
        # If the fingerprint is not found on the file, it will ask the user if he
        # accepts the server's fingerprint.
        # In case the user does not accept the fingerprint, exit the program.
        log("\n\tChecking the fingerprint for server {}...".format(server))
        if client.check_fingerprint() is False:
            write_message_close_log_file_and_exit("Could not get the server's fingerprint"
                                                  " - Check connectivity with the server.")

        # login to server
        log("\n\tLogging in to server {}...".format(server))
        login_res = client.login(username, password)
        if login_res.success is False:
            write_message_close_log_file_and_exit("Login failed:\n{}".format(login_res.error_message))

        # show session details in order to check if the server is MDS
        log("\n\tVerifying the type of server {}...".format(server))
        session_res = client.api_call("show-session", {}, login_res.data["sid"])
        if session_res.success is False:
            write_message_close_log_file_and_exit("Login failed:\n{}".format(session_res.error_message))

        # the server is not MDS, perform clone host only on the this server
        if session_res.data["domain"]["domain-type"] != "mds":
            log("\n\tLogged into SM server {}".format(server))
            find_host_by_ip_and_clone(client, orig_host_ip, cloned_host_name, cloned_host_ip)
        # the server is MDS, run clone host on each of the existing domains
        else:
            log("\n\tLogged into MD server {}".format(server))
            client_domain = APIClient(APIClientArgs(server=server))
            client_domain.debug_file = "api_domain_calls.json"

            try:
                # handle global domain
                log("\n\tChecking on Global Domain...")
                handle_global_domain(client, username, password, client_domain, global_domain, auto_assign,
                                     orig_host_ip, cloned_host_name, cloned_host_ip)

                # get list of domains
                domains = client.api_query("show-domains")
                if domains.success is False:
                    discard_write_to_log_file(client,
                                              "Failed to get the domains data:\n{}".format(domains.error_message))
                    # login out the MDS server
                    client.api_call("logout", {})
                    log_file.close()
                    exit(1)

                # go over all the existing domains
                for domain in domains.data:
                    log("\n\tChecking on Local Domain {}".format(domain["name"]))
                    handle_local_domain(client_domain, domain, username, password, orig_host_ip, cloned_host_name,
                                        cloned_host_ip)
            finally:
                client_domain.save_debug_data()

        # close the log file
        log_file.close()
示例#22
0
def add():
    username, password = util.get_credentials_access()

    client_args = APIClientArgs()

    with APIClient(client_args) as client:
        # The API client, would look for the server's certificate SHA1 fingerprint in a file.
        # If the fingerprint is not found on the file, it will ask the user if he accepts the server's fingerprint.
        # In case the user does not accept the fingerprint, exit the program.
        if client.check_fingerprint() is False:
            print(
                "Could not get the server's fingerprint - Check connectivity with the server."
            )
            exit(1)

        # login to server:
        login_res = client.login(username, password)

        if login_res.success is False:
            print("Login failed:\n{}".format(login_res.error_message))
            exit(1)

        session_id = login_res.data['uid']

        for i in range(4):
            for j in range(1, 251):
                ip_address = '13.0.' + str(i) + '.' + str(j)
                host = {"name": 'H-' + ip_address, "ip-address": ip_address}

                add_host_response = client.api_call("add-host", host)

                if add_host_response.success:
                    print("The host: '{}' has been added successfully".format(
                        add_host_response.data["name"]))
                else:
                    print("Failed to add-host: '{}', Error:\n{}".format(
                        ip_address, add_host_response.error_message))

                subnet = '103.' + str(i) + '.' + str(j) + '.0'
                network = {
                    "name": 'N-' + subnet + '_24',
                    "subnet": subnet,
                    "subnet-mask": "255.255.255.0"
                }
                add_network_response = client.api_call("add-network", network)

                if add_network_response.success:
                    print(
                        "The network: '{}' has been added successfully".format(
                            add_network_response.data["name"]))
                else:
                    print("Failed to add-network: '{}', Error:\n{}".format(
                        subnet, add_network_response.error_message))

        print(
            "Now, publishing the result ... REMEMBER session_id: {}!!!".format(
                session_id))

        # publish the result
        publish_res = client.api_call("publish", {})
        if publish_res.success:
            print("The changes were published successfully.")
        else:
            print("Failed to publish the changes.")
from exporting.export_package import export_package
from importing.import_package import import_package
from utils import process_arguments, extract_sid_from_session_file, handle_login_fail

debug = None
log_file = None
output_file = None
client = None


if __name__ == "__main__":

    arg_parser = argparse.ArgumentParser(description="R80.X Policy Package Export/Import Tool, V3.0")
    args = process_arguments(arg_parser)
    args_for_client = APIClientArgs(server=args.management, port=args.port,
                                    sid=args.session_id, debug_file=log_file, api_version=args.version,
                                    proxy_host=args.proxy, proxy_port=args.proxy_port, unsafe=args.unsafe,
                                    unsafe_auto_accept=args.unsafe_auto_accept)

    with APIClient(args_for_client) as client:

        if args.login == '1':
            login_reply = client.login(username=args.username, password=args.password, domain=args.domain,
                                       payload={"read-only": "true" if args.operation == "export" else "false"})
            handle_login_fail(not login_reply.success, "Login to management server failed. " + str(login_reply))
        elif args.login == '2':
            client.login_as_root(domain=args.domain)
        elif args.login == '3':
            client.sid = extract_sid_from_session_file(args.session_file)
            handle_login_fail(not client.sid, "Could not extract SID form Session-File!")
            test_reply = client.api_call("show-hosts", {"limit": 1})
            handle_login_fail(not test_reply.success, "Extract SID is invalid!")
示例#24
0
def main():
    # Login to the Server
    # getting details from the support files
    #

    with open('./auth/mycpapi.json') as json_file:
        server = json.load(json_file)

    api_server = server['chkp']['host']

    with open('./auth/mycpauth.json') as json_file:
        auth = json.load(json_file)

    username = auth['user']
    password = auth['password']

    client_args = APIClientArgs(server=api_server)

    with APIClient(client_args) as client:

        # create debug file. The debug file will hold all the communication between the python script and
        # Check Point's management server.
        client.debug_file = "api_calls.json"

        # The API client, would look for the server's certificate SHA1 fingerprint in a file.
        # If the fingerprint is not found on the file, it will ask the user if he accepts the server's fingerprint.
        # In case the user does not accept the fingerprint, exit the program.
        if client.check_fingerprint() is False:
            print(
                "Could not get the server's fingerprint - Check connectivity with the server."
            )
            exit(1)

        # login to server:
        login_res = client.login(username, password)
        # print(login_res.data.get("sid"))
        # sid = login_res.data.get("sid")
        # print(sid)

        if login_res.success is False:
            print("Login failed:\n{}".format(login_res.error_message))
            exit(1)

        ### Actual Code Starts here ###

        print("Processing. Please wait...")
        show_access_layers_res = client.api_query("show-access-layers",
                                                  "standard")
        if show_access_layers_res.success is False:
            print("Failed to get the list of all host objects:\n{}".format(
                show_access_layers_res.error_message))
            exit(1)

        layerarr = []

        # print(show_access_layers_res.data)
        layers = show_access_layers_res.data['access-layers']

        for layer in layers:
            ##print(layer['name'])
            layerarr.append(layer['name'])

        print(layerarr)

        print("************************")

        awrulebase = {}

        cmddata = {
            'name': "",
            'use-object-dictionary': 'true',
            'show-hits': 'true'
        }

        for layer in layerarr:
            cmddata['name'] = layer
            cmddata['offset'] = 0
            show_access_rulebase_res = client.api_call("show-access-rulebase",
                                                       cmddata)
            awrulearr = show_access_rulebase_res.data['rulebase']
            while show_access_rulebase_res.data[
                    'total'] > show_access_rulebase_res.data['to']:
                cmddata['offset'] = show_access_rulebase_res.data['to']
                show_access_rulebase_res = client.api_call(
                    "show-access-rulebase", cmddata)
                awrulearr += show_access_rulebase_res.data['rulebase']

            awrulebase[layer] = awrulearr

        awrulebase_pretty = json.dumps(awrulebase, indent=2)
        print(awrulebase_pretty)

        with open('awpyrules.json', 'w') as outfile:
            outfile.write(awrulebase_pretty)
def main():
    # getting details from the user
    results = argpar.parse_args()

    api_server = results.management
    user = results.username
    password = results.password
    port = results.port
    gdomain = results.globaldomain
    if not user:
        user = input("Username:"******"Management IP:")
    if not password:
        password = getpass.getpass("Enter password: "******"Global domain name:")
    client_args = APIClientArgs(server=api_server)
    with APIClient(client_args) as client:
        if client.check_fingerprint() is False:
            print(
                "Could not get the server's fingerprint - Check connectivity with the server."
            )
            exit(1)
        login_res = client.login(user, password)
        if login_res.success is False:
            print("Login failed: {}".format(login_res.error_message))
            exit(1)
        objects_dict = dict()
        obj_type = ["group", 'network', 'host', 'address-range']
        # obj_type = ["group"]

        domains = client.api_query("show-domains")
        client.api_call("logout")
        domains_list = list()
        for domain in domains.data:
            domains_list.append(domain['name'])
        print(domains_list)
        login_res = client.login(user, password, domain=gdomain)
        if login_res.success is False:
            print("Login failed: {}".format(login_res.error_message))
            exit(1)
        for obj_typ in obj_type:
            list_all = dict()
            print("Working on: ", obj_typ)
            global_type = client.api_query("show-" + obj_typ + "s", "standard")
            print("Total amount: ", global_type.data.__len__())
            for item in global_type.data:
                list_all[item['uid']] = [item['name'], item['domain']['name']]
            objects_dict[obj_typ] = list_all
        domain = "global"
        for k, v in objects_dict.items():
            fout = open(domain + "_" + k + ".csv", 'w')
            for x, y in v.items():
                fout.write("{};{}\r".format(x, y))
            fout.close()
        client.api_call("logout")
        results_csv = open('results.csv', 'w')
        results_csv.write(obj_typ + ",occurencies,object_name,uid\r")
        usage_obj_counter_result = list()
        for domain in domains_list:
            for obj_typ, type_objects in objects_dict.items():
                usage_obj_counter = where_global_used(client, user, password,
                                                      type_objects, domain)
                print("done with ", obj_typ, "on", domain)
                usage_obj_counter_result += usage_obj_counter
                summary = (Counter(usage_obj_counter_result))
                for uid, hitcount in summary.items():
                    if hitcount > (len(domains_list) - 2):
                        if type_objects.get(uid):
                            cli_command = "delete {} uid {}".format(
                                obj_typ, uid)
                            results_csv.write(obj_typ + "," + str(hitcount) +
                                              "," + type_objects[uid][0] +
                                              "," + uid + "," + cli_command +
                                              "\r")

        results_csv.close()
示例#26
0
def main():
    # Login to the Server
    # getting details from the support files
    #

    with open('./auth/mycpapi.json') as json_file:
        server = json.load(json_file)

    api_server = server['chkp']['host']

    with open('./auth/mycpauth.json') as json_file:
        auth = json.load(json_file)

    username = auth['user']
    password = auth['password']

    client_args = APIClientArgs(server=api_server)

    with APIClient(client_args) as client:

        # create debug file. The debug file will hold all the communication between the python script and
        # Check Point's management server.
        client.debug_file = "api_calls.json"

        # The API client, would look for the server's certificate SHA1 fingerprint in a file.
        # If the fingerprint is not found on the file, it will ask the user if he accepts the server's fingerprint.
        # In case the user does not accept the fingerprint, exit the program.
        if client.check_fingerprint() is False:
            print("Could not get the server's fingerprint - Check connectivity with the server.")
            exit(1)

        login_res = client.login(username, password)

        if login_res.success is False:
            print("Login failed:\n{}".format(login_res.error_message))
            exit(1)

        ### Actual Code Starts here ###

        if len(sys.argv) == 1:
            res = client.api_call("show-sessions", {"details-level": "full"})
            openchanges = False
            for session in res.data['objects']:
                if session['changes'] > 0:
                    print(session['user-name'], " has ", session['changes'], " changes open and is UID: ",
                          session['uid'])
                    openchanges = True

            if openchanges == False:
                print("No sessions with changes pending")

        elif len(sys.argv) > 1:
            sessionid = sys.argv[1]
            client.api_call("switch-session", {"uid": sessionid})

            res = client.api_call("publish", {})
            if res.success is False:
                discard_write_to_log_file(api_client,
                                          "Publish failed. Error:\n{}\nAborting all changes.".format(res.error_message))
                return False

        client.api_call("logout", {})
示例#27
0
def main():

    # Try / Catch to get exceptions regarding
    # excel file connections and
    # checkpoint api client initialization
    try:

        # Logger configurations
        logger_config()

        # Get settings from Settings class
        settings = Settings()

        # Read data from file
        dataframe = pd.read_excel(settings.object_data_path)
        # Since blank cells return 'nan' instead of empty string
        # we replace all 'nan' with an empty string
        dataframe = dataframe.fillna("")

        # Initialize the SMS session
        client_args = APIClientArgs(server=settings.sms_ip,
                                    api_version=settings.api_version)

        with APIClient(client_args) as client:

            # Try / Catch to get exceptions regarding
            # all checkpoint operations
            try:
                # Login to SMS:
                login_res = client.login(settings.sms_username,
                                         settings.sms_password)

                # If login is not successful, raise an error message.
                if login_res.success is False:
                    raise Exception(Const.ERROR_LOGIN_FALED)
                else:
                    # Displays a message that we
                    # successfully connected to the sms
                    display(
                        Const.MESSAGE_CONNECTION_SMS_SUCCESSFULL.format(
                            settings.sms_ip))

                    # Iterate through each row
                    # in the excel table
                    # Index is not used here but should
                    # NOT BE REMOVED
                    for index, row in dataframe.iterrows():

                        object_name = row["Object Name"]
                        object_ip = row["Object IP"]
                        object_groups = str(row["Object Groups"]).split(";")

                        # Creates the object
                        # and returns an Object object
                        object_created = create_object(client, object_name,
                                                       object_ip)

                        # Assign object to group
                        object_assignment(client, object_created,
                                          object_groups)

                    # Publish the session
                    publish(client)

            except Exception as e:
                # Prints the error message
                # and starts discarding the session
                display(Const.ERROR_INTERNAL.format(e))
                display(Const.MESSAGE_SESSION_DISCARDING)

                # Discard the active session
                discard(client)

                exit(1)

    except Exception as e:
        # Prints the error message
        display(Const.ERROR_INTERNAL.format(e))

        exit(1)
示例#28
0
def add():
    username, password = util.get_access_credentials()

    client_args = APIClientArgs()

    with APIClient(client_args) as client:
        # The API client, would look for the server's certificate SHA1 fingerprint in a file.
        # If the fingerprint is not found on the file, it will ask the user if he accepts the server's fingerprint.
        # In case the user does not accept the fingerprint, exit the program.
        if client.check_fingerprint() is False:
            print(
                "Could not get the server's fingerprint - Check connectivity with the server."
            )
            exit(1)

        # login to server:
        login_res = client.login(username, password)

        if login_res.success is False:
            print("Login failed:\n{}".format(login_res.error_message))
            exit(1)

        session_id = login_res.data['uid']

        rule_name = "WEB_API-RULE"

        for index_port in range(_PORT, _PORT + 3000):
            source = 'NG-1'
            destination = 'NG-2'

            # add a rule to the top of the "Network" layer
            add_rule_response = client.api_call(
                "add-access-rule", {
                    "name": rule_name,
                    "layer": "Network",
                    "source": source,
                    "destination": destination,
                    "action": "Accept",
                    "service": 'TCP-' + str(index_port),
                    "track": {
                        "type": "Log"
                    },
                    "position": "top"
                })

            if add_rule_response.success:
                print("Rule for port '{}' has been added successfully".format(
                    index_port))
            else:
                print("Failed to add the access-rule: '{}', Error:\n{}".format(
                    rule_name, add_rule_response.error_message))
                print("[{}] {}: {}".format(add_rule_response.status_code,
                                           add_rule_response.data['code'],
                                           add_rule_response.data['message']))

        print(
            "Now, publishing the result ... REMEMBER session_id: {}!!!".format(
                session_id))

        # publish the result
        response = client.api_call("publish", {})
        if response.success:
            print("The changes were published successfully.")
        else:
            print("Failed to publish the changes.")

        print("Now, validating the policy ...")

        # Verifies the policy package
        response = client.api_call("verify-policy",
                                   {"policy-package": "standard"})
        if response.success:
            print("The rule were verified successfully.\n{}".format(
                response.data))
        else:
            print("Failed to publish the changes.")
def main():
    global DATETIME_NOW

    print()

    # Store output file information, will be serialize to JSON file
    plan = {}

    # Parse user arguments
    user_args = parse_arguments()

    client_args = APIClientArgs(server=user_args.management, port=user_args.port)

    with APIClient(client_args) as client:

        # The API client, would look for the server's certificate SHA1 fingerprint in a file.
        # If the fingerprint is not found on the file, it will ask the user if he accepts the server's fingerprint.
        # In case the user does not accept the fingerprint, exit the program.
        if client.check_fingerprint() is False:
            print_msg("Could not get the server's fingerprint - Check connectivity with the server.")
            exit(1)

        # Login to server, (read-only in non-apply operations)
        login(user_args, client)

        # Get global thresholds (disable & delete)
        global_thresholds = get_global_thresholds()

        # Check if running on MDS and didn't supply domain
        check_validation_for_mds(client, user_args.domain)

        # Plan
        if is_plan(user_args):

            print_msg("Plan")

            # Store list of all packages information that we should run on
            plan['packages'] = packages_to_run(user_args.package, client)

            # If management hit count flag in off, hits won't be counted - exit
            mgmt_hitcount_on(client, plan['packages'][0]["domain"])

            # Pre-processing to calculate all invalid targets
            print_msg("Validate targets")
            valid_targets = valid_packages_targets(plan['packages'], client)

            groups = get_groups(client)
            for package in plan.get('packages'):
                # Skip invalid packages (all installation targets are invalid)
                if validate_package(package, valid_targets) is False:
                    continue

                print_msg("Package {}".format(package['name']))

                # Loop over policy layers
                for layer in package.get('access-layers'):

                    print_msg("  Layer {}".format(layer['name']))

                    # Skip invalid layers (global layers)
                    if validate_layer(layer) is False:
                        continue

                    layer['skipped-rules'] = []
                    layer['disable-rules'] = []
                    layer['delete-rules'] = []
                    sub_dictionary = {}

                    show_access_rulebase_res = show_access_rulebase(layer, client)
                    object_dictionary_as_map = get_object_dictionary(show_access_rulebase_res)

                    # Get full rule-base as a list of rules
                    rulebase = get_rulebase(show_access_rulebase_res)
                    if rulebase is None:
                        continue

                    # Loop over layer rules
                    for rule in rulebase:

                        # Rule is enabled
                        if rule.get('enabled') is True:

                            # Skip rule with invalid target in install-on list OR rule modify after installation
                            if validate_rule(rule, package, valid_targets, client, groups) is False:
                                if 'skipped-reason' in rule:
                                    layer['skipped-rules'].append(rule)
                                continue

                            # Check if rule should be disabled - no hits for too long
                            if rule_should_be_disabled(rule, global_thresholds) is True:
                                objects_of_rule_to_add = get_objects_of_rule_from_objects_dictionary(rule,
                                                                                                     object_dictionary_as_map)
                                sub_dictionary = add_to_sub_dictionary(objects_of_rule_to_add, sub_dictionary)

                                # Add to plan that the rule should be disabled
                                layer['disable-rules'].append(rule)

                        # Rule is disabled
                        else:
                            # check if the rule should be deleted - disabled too long
                            if rule_should_be_deleted(rule, global_thresholds) is True:
                                objects_of_rule_to_add = get_objects_of_rule_from_objects_dictionary(rule,
                                                                                                     object_dictionary_as_map)
                                sub_dictionary = add_to_sub_dictionary(objects_of_rule_to_add, sub_dictionary)

                                # Add to plan that the rule should be deleted
                                layer['delete-rules'].append(rule)

                    layer['objects-dictionary'] = parse_sub_objects_dictionary_map_to_list_of_value(sub_dictionary)

            summary = {};
            plan = build_output_structure(plan, summary, user_args.operation)

            if valid_targets['packages-targets']:
                print_summary(summary)

            # Write plan to log file in JSON format
            write_plan_json(plan, user_args.output_file)

            print_msg('Plan process has finished.\n')
            print_msg('The output file in: {}'.format(os.path.abspath(user_args.output_file)))

        # Get plan-file path as argument
        else:
            plan = read_plan_json(user_args.import_plan_file)

        # Apply plan only when the operation is apply/apply_without_publish
        if is_apply_operation(user_args.operation) is True:

            print()
            print_msg("Apply plan")

            # Disable & Delete rules by the plan. If apply failed in one of them - stop and discard changes
            if apply_plan(client, plan) is False:
                print_msg("Discard")
                discard_res = client.api_call("discard")
                is_failure("Failed to discard changes.", discard_res)
                print()
                exit(1)

            # Publish changes only when the operation is apply
            if is_publish_operation(user_args.operation):

                print_msg("Publish")
                publish_res = client.api_call("publish")
                is_failure("Failed to publish changes.", publish_res)

            else:

                print_msg("Continue session in smartconsole")
                continue_smartconsole_res = client.api_call("continue-session-in-smartconsole")
                is_failure("Failed to continue session in smartconsole.", continue_smartconsole_res)

            print_msg('Apply process has finished successfully.')

        print()
示例#30
0
def main():
    global was_changed
    # Initializing parameters to variables:
    command = module.params["command"]
    parameters = module.params.get("parameters")
    session_data = module.params.get("session-data")
    fingerprint = module.params.get("fingerprint")
    context = module.params.get("context")
    api_version = module.params.get("api_version")
    if parameters:
        parameters = parameters.replace("None", "null")
        parameters = parameters.replace("'", '"')
        # The following replace method must be the last replace option!!!
        # This is intended for running run-script API command in CLISH mode, where the "'" character is required inside the script parameter.
        # Example: "clish -c 'show core-dump status'"
        # For such case, the YML must be in the following format: 'clish -c \"show core-dump status\"'
        parameters = parameters.replace("\\\\\"", "'")
        parameters = parameters.replace("True", "true")
        parameters = parameters.replace("False", "false")
        # Finally, parse to JSON
        parameters = json.loads(parameters)
    if command == "login":
        # Login parameters:
        username = parameters.get("user", parameters.get("username"))
        password = parameters.get("pass", parameters.get("password"))
        management = parameters.get("management", "127.0.0.1")
        port = parameters.get("port", 443)
        domain = parameters.get("domain")
        session_timeout = parameters.get("session-timeout", 600)
        payload = {"session-timeout": session_timeout}
        client_args = APIClientArgs(server=management, port=port, context=context, api_version=api_version)
        client = APIClient(client_args)
        # Validate fingerprint:
        validate_fingerprint(client, fingerprint)
        # Tries to login:
        client.login(username=username, password=password, domain=domain, payload=payload)
        # Building a session data object
        session_data = {
            "url": management + ":" + str(port),
            "domain": domain,
            "sid": client.sid,
            "fingerprint": client.fingerprint,
            "context": client.context,
            "api_version": client.api_version
        }
        resp = session_data
    else:
        # Parsing the session-data argument:
        try:
            session_data = ast.literal_eval(session_data)["response"]
        except (ValueError, KeyError):
            if not session_data:
                error("You must specify session-data for commands that are not login (use the command \"login\""
                      " to obtain the session data).")
            else:
                error("session-data variable is invalid.")

        session_id = session_data["sid"]
        domain = session_data["domain"]
        context = session_data["context"]
        if api_version is None:
            api_version = session_data["api_version"]
        management = session_data["url"].split('//')[1].split('/')[0].split(':')[0] if '//' in session_data["url"] else \
            session_data["url"].split('/')[0].split(':')[0]
        if '//' in session_data["url"] and len(session_data["url"].split('//')[1].split('/')[0].split(':')) > 1 and is_int(session_data["url"].split('//')[1].split('/')[0].split(':')[1]):
            port = int(session_data["url"].split('//')[1].split('/')[0].split(':')[1])
        elif len(session_data["url"].split('/')[0].split(':')) > 1 and is_int(session_data["url"].split('/')[0].split(':')[1]):
            port = int(session_data["url"].split('/')[0].split(':')[1])
        else:
            port = 443
        fingerprint = session_data["fingerprint"]
        client_args = APIClientArgs(server=management, port=port, sid=session_id, context=context, api_version=api_version)
        client = APIClient(client_args)
        client.domain = domain
        validate_fingerprint(client, fingerprint)

        # Doesn't run commands that act immediately (not waiting for 'publish'), like install-policy, publish, etc.
        if module.check_mode and command in unavailable_in_check_commands:
            error("Can't run the following commands in check mode: " + str(unavailable_in_check_commands) +
                  ". Know that your script ran fine up to this point " +
                  ("and we've discarded the changes made, you can now run it without check mode." if
                   command == "publish" else "and we are skipping this command."),
                  client=client if command == "publish" else None, discard=True, logout=False, exit=True, fail=False)

        if command == "install-policy" and module.check_mode:
            command = "verify-policy"
            parameters = {"policy-package": parameters["policy-package"]}

        # Run the command:
        res = client.api_call(command=command, payload=parameters)

        if command.split("-")[0] in ["add", "delete", "set"] and res.success and not module.check_mode:
            was_changed = True

        if not res.success:
            error("Command '{} {}' failed{}. All changes are discarded and the session is invalidated."
                  .format(command, parameters,
                          " with error message: " + str(res.error_message) if hasattr(res, "error_message") else ""),
                  client=client)

        resp = res.data
    module.exit_json(response=resp, changed=was_changed)