def test_get(self):
     sg = self.site.get_server_group(self.ServerGroupName)
     self.assertEqual(sg, None)
     self.site.create_server_group(self.ServerGroupName)
     self.mx.logout()
     self.mx = imperva_sdk.MxConnection(Host=self.host,
                                        Username=self.user,
                                        Password=self.password)
     sg = self.mx.get_server_group(Name=self.ServerGroupName,
                                   Site=self.SiteName)
     self.assertTrue(self.ServerGroupName == sg.Name)
 def test_update(self):
     sg = self.site.create_server_group(self.ServerGroupName)
     self.assertTrue(sg.OperationMode == 'simulation')
     sg.OperationMode = 'active'
     sg.Name = '%s - 2' % self.ServerGroupName
     self.mx.logout()
     self.mx = imperva_sdk.MxConnection(Host=self.host,
                                        Username=self.user,
                                        Password=self.password)
     sg = self.mx.get_server_group(Name='%s - 2' % self.ServerGroupName,
                                   Site=self.SiteName)
     self.assertTrue(sg.OperationMode == 'active')
Exemple #3
0
    def setUp(self):
        if 'MX_HOST' in os.environ: self.host = os.environ['MX_HOST']
        if 'MX_USER' in os.environ: self.user = os.environ['MX_USER']
        if 'MX_PASSWORD' in os.environ:
            self.password = os.environ['MX_PASSWORD']
        if 'MX_PORT' in os.environ: self.port = int(os.environ['MX_PORT'])
        if not self.host:
            raise Exception("No MX specified (MX_HOST environment variable)")

        self.mx = imperva_sdk.MxConnection(Host=self.host,
                                           Username=self.user,
                                           Password=self.password,
                                           Port=self.port)
 def test_delete(self):
     try:
         self.site.delete_server_group(self.ServerGroupName)
         self.assertFalse(True)
     except:
         pass
     self.site.create_server_group(self.ServerGroupName)
     self.mx.logout()
     self.mx = imperva_sdk.MxConnection(Host=self.host,
                                        Username=self.user,
                                        Password=self.password)
     ret = self.mx.delete_server_group(Name=self.ServerGroupName,
                                       Site=self.SiteName)
     self.assertTrue(ret)
 def test_sdk_license(self):
     # Try to upload a license if it is provided
     if self.license:
         mx = imperva_sdk.MxConnection(Host=self.host,
                                       Username=self.user,
                                       Password=self.password,
                                       Port=self.port,
                                       FirstTime=True)
         try:
             mx.upload_license(LicenseFile=self.license)
         except imperva_sdk.MxException as e:
             if 'IMP-12107' in e.args[0]:
                 pass
             else:
                 raise e
         mx.logout
 def test_export_import(self):
     sg = self.site.create_server_group(self.ServerGroupName)
     export = self.mx.export_to_json(Discard=['policies'])
     export_dict = json.loads(export)
     # Remove from export sites that aren't part of the test
     test_site = []
     for site in export_dict['sites']:
         if site['Name'] == self.SiteName:
             test_site.append(site)
     export_dict['sites'] = test_site
     export_dict['sites'][0]['server_groups'][0][
         'OperationMode'] = 'disabled'
     self.site.delete_server_group(self.ServerGroupName)
     self.mx.logout()
     self.mx = imperva_sdk.MxConnection(Host=self.host,
                                        Username=self.user,
                                        Password=self.password)
     log = self.mx.import_from_json(json.dumps(export_dict))
     sg = self.mx.get_server_group(Name=self.ServerGroupName,
                                   Site=self.SiteName)
     self.assertTrue(sg.OperationMode == 'disabled')
    def test_sdk_sanity(self):

        # Try to upload a license if it is provided
        if self.license:
            mx = imperva_sdk.MxConnection(Host=self.host,
                                          Username=self.user,
                                          Password=self.password,
                                          Port=self.port,
                                          FirstTime=True)
            try:
                mx.upload_license(LicenseFile=self.license)
            except imperva_sdk.MxException as e:
                if 'IMP-12107' in e.args[0]:
                    pass
                else:
                    raise e
            mx.logout

        # Delete test resources if they exist from previous runs
        mx = imperva_sdk.MxConnection(Host=self.host,
                                      Username=self.user,
                                      Password=self.password,
                                      Port=self.port)
        if mx.get_site(self.Site["Name"]): mx.delete_site(self.Site["Name"])
        if mx.get_http_protocol_signatures_policy(
                self.HttpProtocolSignaturesPolicy["Name"]):
            mx.delete_http_protocol_signatures_policy(
                self.HttpProtocolSignaturesPolicy["Name"])
        if mx.get_parameter_type_global_object(
                self.ParameterTypeGlobalObject["Name"]):
            mx.delete_parameter_type_global_object(
                self.ParameterTypeGlobalObject["Name"])
        if mx.get_web_service_custom_policy(
                self.WebServiceCustomPolicy["Name"]):
            mx.delete_web_service_custom_policy(
                self.WebServiceCustomPolicy["Name"])
        if mx.get_action_set(self.ActionSet["Name"]):
            mx.delete_action_set(self.ActionSet["Name"])
        if mx.get_web_profile_policy(self.WebProfilePolicy['Name']):
            mx.delete_web_profile_policy(self.WebProfilePolicy['Name'])
        mx.logout()

        # Create test resources
        mx = imperva_sdk.MxConnection(Host=self.host,
                                      Username=self.user,
                                      Password=self.password,
                                      Port=self.port)
        mx.create_site(**self.Site)
        mx.create_server_group(**self.ServerGroup)
        mx.create_web_service(**self.WebService)
        app = mx.create_web_application(**self.WebApplication)
        try:
            mx.create_action_set(**self.ActionSet)
            mx.create_action(ActionSet=self.ActionSet["Name"], **self.Action)
        except imperva_sdk.MxExceptionNotFound:
            self.test_action_set = False
            self.WebServiceCustomPolicy["FollowedAction"] = "Long IP Block"
            self.HttpProtocolSignaturesPolicy["Rules"][0][
                "followedAction"] = "Long IP Block"
        try:
            mx.create_http_protocol_signatures_policy(
                **self.HttpProtocolSignaturesPolicy)
        except imperva_sdk.MxExceptionNotFound:
            self.test_http_protocol_signatures_policy = False
        try:
            mx.create_parameter_type_global_object(
                **self.ParameterTypeGlobalObject)
        except imperva_sdk.MxExceptionNotFound:
            self.test_parameter_type_global_object = False
        try:
            app.update_profile(SwaggerJson=self.Swagger)
        except imperva_sdk.MxExceptionNotFound:
            self.test_profile = False
        mx.create_web_service_custom_policy(**self.WebServiceCustomPolicy)
        try:
            mx.create_web_profile_policy(**self.WebProfilePolicy)
        except imperva_sdk.MxExceptionNotFound:
            self.test_web_profile_policy = False
        mx.logout()

        # Export to JSON
        mx = imperva_sdk.MxConnection(Host=self.host,
                                      Username=self.user,
                                      Password=self.password,
                                      Port=self.port)
        export = mx.export_to_json()
        mx.logout()

        # Delete test resources
        mx = imperva_sdk.MxConnection(Host=self.host,
                                      Username=self.user,
                                      Password=self.password,
                                      Port=self.port)
        mx.delete_web_application(self.WebApplication["Name"],
                                  WebService=self.WebService["Name"],
                                  ServerGroup=self.ServerGroup["Name"],
                                  Site=self.Site["Name"])
        mx.delete_web_service(**self.WebService)
        mx.delete_server_group(self.ServerGroup["Name"],
                               Site=self.Site["Name"])
        if self.test_http_protocol_signatures_policy:
            mx.delete_http_protocol_signatures_policy(
                self.HttpProtocolSignaturesPolicy["Name"])
        if self.test_parameter_type_global_object:
            mx.delete_parameter_type_global_object(
                self.ParameterTypeGlobalObject["Name"])
        mx.delete_web_service_custom_policy(
            self.WebServiceCustomPolicy["Name"])
        if self.test_web_profile_policy:
            mx.delete_web_profile_policy(self.WebProfilePolicy['Name'])
        mx.delete_site(**self.Site)
        if self.test_action_set:
            mx.delete_action(ActionSet=self.ActionSet["Name"],
                             Name=self.Action["Name"])
            mx.delete_action_set(self.ActionSet["Name"])
        mx.logout()

        # Import from JSON
        mx = imperva_sdk.MxConnection(Host=self.host,
                                      Username=self.user,
                                      Password=self.password,
                                      Port=self.port)
        log = mx.import_from_json(export)
        for entry in log:
            if entry["Result"] != "SUCCESS":
                raise Exception("import_from_json failure - %s" % str(entry))
        mx.logout()

        # Get test resources
        mx = imperva_sdk.MxConnection(Host=self.host,
                                      Username=self.user,
                                      Password=self.password,
                                      Port=self.port)
        site = mx.get_site(**self.Site)
        if not site: raise Exception("Failed getting site")
        server_group = mx.get_server_group(self.ServerGroup["Name"],
                                           Site=self.Site["Name"])
        if server_group.OperationMode != self.ServerGroup["OperationMode"]:
            raise Exception("Failed getting server group properties")
        web_service = mx.get_web_service(**self.WebService)
        if not web_service: raise Exception("Failed getting web service")
        web_application = mx.get_web_application(
            self.WebApplication["Name"],
            WebService=self.WebService["Name"],
            ServerGroup=self.ServerGroup["Name"],
            Site=self.Site["Name"])
        if not web_application.Mappings[0]["host"] == self.WebApplication[
                "Mappings"][0]["host"]:
            raise Exception("Failed getting web application properties")
        if self.test_action_set:
            action = mx.get_action(self.Action["Name"],
                                   ActionSet=self.ActionSet["Name"])
            if not action.ActionInterface == self.Action["ActionInterface"]:
                raise Exception("Failed getting action properties")
        if self.test_http_protocol_signatures_policy:
            pol = mx.get_http_protocol_signatures_policy(
                self.HttpProtocolSignaturesPolicy["Name"])
            if pol.Rules[0]["action"] != self.HttpProtocolSignaturesPolicy[
                    "Rules"][0]["action"]:
                raise Exception(
                    "Failed getting http protocol signatures policy properties"
                )
        if self.test_parameter_type_global_object:
            obj = mx.get_parameter_type_global_object(
                self.ParameterTypeGlobalObject["Name"])
            if obj.Regex != self.ParameterTypeGlobalObject["Regex"]:
                raise Exception(
                    "Failed getting parameter type configuration global object"
                )
        if self.test_profile:
            profile = web_application.get_profile()
            if len(profile["webProfileUrls"]) != len(self.Swagger["paths"]):
                raise Exception("Failed getting profile")
        pol = mx.get_web_service_custom_policy(
            self.WebServiceCustomPolicy["Name"])
        if pol.FollowedAction != self.WebServiceCustomPolicy["FollowedAction"]:
            raise Exception("Failed getting web service custom policy")
        if self.test_web_profile_policy:
            policy = mx.get_web_profile_policy(self.WebProfilePolicy['Name'])
            if not policy:
                raise Exception("Failed getting WebProfilePolicy %s" %
                                self.WebProfilePolicy['Name'])
        mx.logout()
Exemple #8
0
def main():

    # read commandline arguments, first
    fullCmdArguments = sys.argv
    # - further arguments
    argumentList = fullCmdArguments[1:]

    unixOptions = "ho:s:u:p:a:"
    gnuOptions = ["help", "output", "server", "username", "password", "agents"]

    try:
        arguments, values = getopt.getopt(argumentList, unixOptions,
                                          gnuOptions)
    except getopt.error as err:
        # output error, and return with an error code
        print(str(err))
        sys.exit(2)

    agentsOnly = False
    # evaluate given options
    for currentArgument, currentValue in arguments:
        if currentArgument in ("-s", "--server"):
            server = currentValue
        elif currentArgument in ("-u", "--username"):
            username = currentValue
        elif currentArgument in ("-p", "--password"):
            password = currentValue
        elif currentArgument in ("-h", "--help"):
            print(
                "Please use the following syntax: Export.py -o <output file> -s <source mx IP> -u <username> -p <password>"
            )
        elif currentArgument in ("-o", "--output"):
            outputFile = currentValue
        elif currentArgument in ("-a", "--agents"):
            agentsOnly = True

    try:
        source_mx = imperva_sdk.MxConnection(Host=server,
                                             Username=username,
                                             Password=password)
        if agentsOnly:
            print(
                ("About to export Agents configuration from (%s)") % (server))
            source_export = source_mx.export_agent_configurations()
        else:  #default - export all
            print(("About to export Full configuration from (%s)") % (server))
            source_export = source_mx.export_to_json(Discard=[
                'web_application_custom', 'web_service_custom',
                'http_protocol_signatures', 'web_profile'
            ])

    except RuntimeError as err:
        print(("Error exporting from (%s)") % (server))
        print(err)
        sys.exit(2)

    try:
        # json.dump() return ASCII-only by default so no encoding is needed
        with open(outputFile, 'w') as f:
            f.write(source_export)
            f.close()
        print(("Export was successfully written to output file (%s)") %
              (outputFile))
    except Exception as e:
        print(("Error writing export to output file (%s)") % (outputFile))

    source_mx.logout()
Exemple #9
0
    def test_dam_das_sdk_sanity(self):

        # Delete test resources if they exist from previous runs
        mx = imperva_sdk.MxConnection(Host=self.host,
                                      Username=self.user,
                                      Password=self.password,
                                      Port=self.port)
        if mx.get_site(self.Site["Name"]):
            mx.delete_site(self.Site["Name"])
        if mx.get_assessment_scan(self.AssessmentScan["Name"]):
            mx.delete_assessment_scan(self.AssessmentScan["Name"])
        if mx.get_classification_scan(self.ClassificationScan["Name"]):
            mx.delete_classification_scan(self.ClassificationScan["Name"])
        if mx.get_classification_profile(self.ClassificationProfile["Name"]):
            mx.delete_classification_profile(
                self.ClassificationProfile["Name"])
        if mx.get_db_audit_policy(self.DbAuditPolicy["policy-name"]):
            mx.delete_db_audit_policy(self.DbAuditPolicy["policy-name"])
        #if mx.get_db_audit_report(self.DbAuditReport["display-name"]):
        # delete_db_audit_report is not implemented
        #if mx.get_db_connection(self.Site["Name"], self.ServerGroup["Name"], self.DbService["Name"], selfDbConnection["ConnectionName]):
        # delete_db_connection is not implemented correctly
        mx.logout()

        # Create test resources
        mx = imperva_sdk.MxConnection(Host=self.host,
                                      Username=self.user,
                                      Password=self.password,
                                      Port=self.port)
        mx.create_site(**self.Site)
        mx.create_server_group(**self.ServerGroup)
        mx.create_db_service(**self.DbService)
        try:
            mx.create_db_connection(**self.DbConnection)
        except imperva_sdk.MxExceptionNotFound:
            self.test_db_connection = False
        try:
            mx.create_assessment_scan_das_object(**self.AssessmentScan)
        except imperva_sdk.MxExceptionNotFound:
            self.test_assessment_scan = False
        try:
            mx.create_classification_profile(**self.ClassificationProfile)
            mx.create_classification_scan_das_object(**self.ClassificationScan)
        except imperva_sdk.MxExceptionNotFound:
            self.test_classification_scan = False
        try:
            mx.create_db_audit_dam_policy(
                Name=self.DbAuditPolicy["policy-name"],
                Parameters=self.DbAuditPolicy)
        except imperva_sdk.MxExceptionNotFound:
            self.test_db_audit_policy = False
        # try:
        #   mx.create_db_audit_dam_report(Name=self.DbAuditReport["Name"], ReportFormat=self.DbAuditReport["ReportFormat"], Columns=self.DbAuditReport["Columns"],
        #                                 Filters=self.DbAuditReport["Filters"], Policies=self.DbAuditReport["Policies"], Sorting=self.DbAuditReport["Sorting"],
        #                                 TimeFrame=self.DbAuditReport["TimeFrame"], Scheduling=self.DbAuditReport["Scheduling"])
        # except imperva_sdk.MxExceptionNotFound:
        #   self.test_db_audit_Report = False
        mx.logout()

        # Export to JSON
        mx = imperva_sdk.MxConnection(Host=self.host,
                                      Username=self.user,
                                      Password=self.password,
                                      Port=self.port)
        export = mx.export_to_json()
        mx.logout()

        # Delete test resources
        mx = imperva_sdk.MxConnection(Host=self.host,
                                      Username=self.user,
                                      Password=self.password,
                                      Port=self.port)
        if mx.get_site(self.Site["Name"]):
            mx.delete_site(self.Site["Name"])
        if mx.get_assessment_scan(self.AssessmentScan["Name"]):
            mx.delete_assessment_scan(self.AssessmentScan["Name"])
        if mx.get_classification_scan(self.ClassificationScan["Name"]):
            mx.delete_classification_scan(self.ClassificationScan["Name"])
        if mx.get_classification_profile(self.ClassificationProfile["Name"]):
            mx.delete_classification_profile(
                self.ClassificationProfile["Name"])
        if mx.get_db_audit_policy(self.DbAuditPolicy["policy-name"]):
            mx.delete_db_audit_policy(self.DbAuditPolicy["policy-name"])
        #if mx.get_db_audit_report(self.DbAuditReport["display-name"]):
        # delete_db_audit_report is not implemented
        #if mx.get_db_connection(self.Site["Name"], self.ServerGroup["Name"], self.DbService["Name"], selfDbConnection["ConnectionName]):
        # delete_db_connection is not implemented correctly
        mx.logout()

        # Import from JSON
        mx = imperva_sdk.MxConnection(Host=self.host,
                                      Username=self.user,
                                      Password=self.password,
                                      Port=self.port)
        log = mx.import_from_json(export)
        for entry in log:
            if entry["Result"] != "SUCCESS":
                raise Exception("import_from_json failure - %s" % str(entry))
        mx.logout()

        # Get test resources
        mx = imperva_sdk.MxConnection(Host=self.host,
                                      Username=self.user,
                                      Password=self.password,
                                      Port=self.port)
        site = mx.get_site(**self.Site)
        if not site: raise Exception("Failed getting site")
        server_group = mx.get_server_group(self.ServerGroup["Name"],
                                           Site=self.Site["Name"])
        if server_group.OperationMode != self.ServerGroup["OperationMode"]:
            raise Exception("Failed getting server group properties")
        db_service = mx.get_db_service(
            Name=self.DbService["Name"],
            Site=self.DbService["Site"],
            ServerGroup=self.DbService["ServerGroup"])
        if not db_service: raise Exception("Failed getting web service")
        if self.test_assessment_scan:
            assess_scan = mx.get_assessment_scan(
                Name=self.AssessmentScan["Name"])
            if assess_scan.Type != self.AssessmentScan["Type"]:
                raise Exception(
                    "imported assessment scan is different from the exported scan"
                )
        if self.test_classification_scan:
            classification_scan = mx.get_classification_scan(
                Name=self.ClassificationScan["Name"])
            classification_profile = mx.get_classification_profile(
                classification_scan.ProfileName)
            if str(classification_profile.Name) != str(
                    self.ClassificationProfile["Name"]):
                raise Exception(
                    "imported classification profile is different from the exported profile"
                )
def main():

    # read commandline arguments, first
    fullCmdArguments = sys.argv
    # - further arguments
    argumentList = fullCmdArguments[1:]

    unixOptions = "hi:l:s:u:p:v:a:"
    gnuOptions = [
        "help", "input", "logfile", "server", "username", "password",
        "verbose", "agents"
    ]

    try:
        arguments, values = getopt.getopt(argumentList, unixOptions,
                                          gnuOptions)
    except getopt.error as err:
        # output error, and return with an error code
        print(str(err))
        sys.exit(2)

    # default verbose will output only the errors that occure during import
    verbose = VERBOSITY_LEVEL.ERRORS_ONLY
    agentsOnly = False

    # evaluate given options
    for currentArgument, currentValue in arguments:
        if currentArgument in ("-s", "--server"):
            server = currentValue
        elif currentArgument in ("-u", "--username"):
            username = currentValue
        elif currentArgument in ("-p", "--password"):
            password = currentValue
        elif currentArgument in ("-h", "--help"):
            print(
                "Please use the following syntax: Import.py -i <input file> -l <log file> -s <target mx IP> -u <username> -p <password> -v <verbose>"
            )
        elif currentArgument in ("-i", "--input"):
            inputFile = currentValue
        elif currentArgument in ("-l", "--logfile"):
            logFile = currentValue
        elif currentArgument in ("-v", "--verbose"):
            verbose = VERBOSITY_LEVEL.ALL if currentValue == '1' else VERBOSITY_LEVEL.ERRORS_ONLY
        elif currentArgument in ("-a", "--agents"):
            agentsOnly = True
    try:
        target_mx = imperva_sdk.MxConnection(Host=server,
                                             Username=username,
                                             Password=password)
    except Exception as e:
        print(("Error opening connection to (%s): %s") % (server, e))
        sys.exit(2)

    try:
        # json.dump() return ASCII-only by default so no encoding is needed
        with open(inputFile, 'r') as f:
            loaded_data = json.load(f)
            loaded_data_2 = dict_discard(loaded_data,
                                         ['ProtectedIps', 'ApplyToAgent'])
            json_string = json.dumps(loaded_data_2,
                                     indent=4,
                                     sort_keys=True,
                                     separators=(',', ': '))

    except RuntimeError as err:
        print("Error loading from file {0}: {1}", inputFile, err)

    try:
        if agentsOnly:
            print(("About to import Agents configuration to (%s)") % (server))
            log = target_mx.import_agent_configurations(Json=json_string)
        else:  # default - export all
            print(("About to import Full configuration to (%s)") % (server))
            log = target_mx.import_from_json(Json=json_string)

    except RuntimeError as err:
        print("Error in import: {0}", err)

    if verbose == VERBOSITY_LEVEL.ERRORS_ONLY:
        log = [
            line for line in log if line['Result'] == 'ERROR'
            and 'already exists' not in line['Error Message']
        ]

    for log_entry in log:
        print(log_entry)

    # json.dump() return ASCII-only by default so no encoding is needed
    with open(logFile, 'w') as logf:
        logs = json.dumps(log, indent=4, separators=(',', ': '))
        logf.write(logs)
        if verbose == VERBOSITY_LEVEL.ERRORS_ONLY:
            logf.write('\n\nTotal Errors: %s' % str(len(log)))
        logf.close()

    target_mx.logout()