Exemple #1
0
    def download_report(self, s, report_ID, target_IP):
        # downloading the reports
        ts = time.time()
        dt = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%dT%H%M%S')
        #file format: report folder, IP, date-time stamp
        filename = "qualys_scan_report_" + target_IP + "_" + dt + ".pdf"
        payload = {
            'action': 'fetch',
            'id': report_ID,
        }

        r = s.post('https://qualysapi.qualys.com/api/2.0/fo/report/',
                   data=payload,
                   stream=True)
        if r.status_code == 200:
            with open(filename, 'wb') as f:
                r.raw.decode_content = True
                shutil.copyfileobj(r.raw, f)
                Utilities.printLog("report downloaded")
        else:
            Utilities.printError(
                "report failed to download with status code: " +
                r1.status_code)

        #this is another way to save report
        #if the above method fails to save report correctly, use the below method
        '''
Exemple #2
0
 def addSite(self, access_req):
     # print("TestModule:SiteManagement")
     siteSaveRequest = Element('SiteSaveRequest', attrib={'session-id': self.session_id})
     # print(access_req['site_name'])
     # Site element have 'S' in caps !!--lost a day on this !!
     site_elem = SubElement(siteSaveRequest, 'Site', attrib={'name': access_req['site_name'], 'id': '-1'})
     host_elem = SubElement(site_elem, 'Hosts')
     for ip in access_req['ip'].split(','):
         range_elem = SubElement(host_elem, 'range', attrib={'from': ip, 'to': ''})
     scanConfig_elem = SubElement(site_elem, 'ScanConfig', attrib={'name': 'Full audit', 'templateID': 'full-audit'})
     xmlTree = ElementTree(siteSaveRequest)
     f = BytesIO()
     xmlTree.write(f, encoding='utf-8',
                   xml_declaration=True)  # required so that xml declarations will come up in generated XML
     saveSiteReqXML = f.getvalue().decode("utf-8")  # converts bytes to string
     # print(saveSiteReqXML)
     responseXML = self.makeRequest(self.reqURL, saveSiteReqXML, self.headers)
     tree = ElementTree(fromstring(responseXML))
     root = tree.getroot()
     addSiteResponse = root.get('success')
     if (addSiteResponse == "1"):
         self.site_id = root.get('site-id')
         Utilities.printSuccess("Created site with site-id: " + self.site_id)
         return True
     else:
         fa = root.find('Failure')
         ex = fa.find('Exception')
         msg = ex.find('message').text
         Utilities.printError("Site creation failed: " + msg)
         return False
Exemple #3
0
    def add_user(self, access_req):
        self.url = self.qualys_host + "/msp/user.php"

        usrLst = access_req['userList']
        for user in usrLst:
            userinfo = user.split(',')  # uname,name,email
            pswd = userinfo[0] + '!vul5c4p1'
            parms = {'action': 'add', 'user_role': 'scanner', 'business_unit': 'Unassigned',
                     'asset_groups': access_req['site_name'], 'first_name': userinfo[1].split(' ')[0],
                     'last_name': userinfo[1].split(' ')[1], 'title': 'Scanner User', 'phone': '0000000000',
                     'email': userinfo[2], 'address1': '3401 Hillview Ave', 'city': 'Palo Alto',
                     'country': 'United States of America', 'state': 'California', 'zip_code': '94304',
                     'send_email': '1'}
            response_user_add = self.makeRequest(parms)
            # print(response_user_add.content)
            responseXML = response_user_add.content
            tree = ElementTree(fromstring(responseXML))
            root = tree.getroot()
            asset_response = root.find('RETURN')
            user_add_status = asset_response.get('status')
            user_add_status_msg = asset_response.find('MESSAGE').text
            # print(user_add_status + user_add_status_msg)
            if user_add_status == "SUCCESS":
                Utilities.printSuccess( user_add_status_msg +" for " + userinfo[1])
                return True
            else:
                Utilities.printError("User addition Failure: " + user_add_status_msg)
                return False
Exemple #4
0
def access_request_handler():
    access_details = readAccessReq()  # Reading the Access Request
    try:
        tree = parse('scanner_details.xml')  # Reading the Scanner Details
        root = tree.getroot()

        # Access request handler for scanners
        # Read Nessus scanner details
        scanner = root.find('nessus')
        execute_nessus = scanner.get('enabled')
        if execute_nessus == '1':
            # print(scanner)

            if scanner.find('host').text is None or scanner.find('username').text is None or scanner.find('host').text is None:
                xml_error("Nessus data missing in scanner_details.xml")
            print("Nessus" + " host@:" + scanner.find('host').text)
            # print(scanner.find('username').text)
            usr_passwd = input("Please enter your password for " + " Nessus" + ": ")
            nessus_details = {'uname': scanner.find('username').text, 'passwd': usr_passwd, 'host': scanner.find('host').text}
            # Scanner task calls from here
            Utilities.printLog("Executing Nessus tasks")
            nessusObj = nes.Nessus(nessus_details)  # Create Nessus scanner class obj
            msg = nessusObj.handleAccessReq(access_details, nessus_details)  # Login | Add User | Logout

        # Read Nexpose scanner details
        scanner = root.find('nexpose')
        execute_nexpose = scanner.get('enabled')
        if execute_nexpose == '1':
            # print(scanner)
            if scanner.find('host').text is None or scanner.find('username').text is None or scanner.find('host').text is None:
                xml_error("Nexpose data missing in scanner_details.xml")
            print("Nexpose" + " host@:" + scanner.find('host').text)
            # print(scanner.find('username').text)
            usr_passwd = input("Please enter your password for " + " Nexpose" + ": ")
            nexpose_details = {'uname': scanner.find('username').text, 'passwd': usr_passwd, 'host': scanner.find('host').text}
            # Scanner task calls from here
            Utilities.printLog("Executing Nexpose tasks")
            nexposeObj = nex.Nexpose(nexpose_details)  # Create Nexpose scanner class obj
            msg += "\n"+nexposeObj.handleAccessReq(access_details, nexpose_details)  # Login | SaveSite | Add User | Logout

        # Read Qualys scanner details
        scanner = root.find('qualys')
        execute_qualys = scanner.get('enabled')
        if execute_qualys == '1':
            # print(scanner)
            if scanner.find('host').text is None or scanner.find('username').text is None or scanner.find('host').text is None:
                xml_error("Qualys data missing in scanner_details.xml")
            print("Qualys" + " host@:" + scanner.find('host').text)
            # print(scanner.find('username').text)
            usr_passwd = input("Please enter your password for " + " Qualys" + ": ")
            qualys_details = {'uname': scanner.find('username').text, 'passwd': usr_passwd, 'host': scanner.find('host').text}
            # Scanner task calls from here
            Utilities.printLog("Executing Qualys tasks")
            qualysObj = qua.Qualys(qualys_details)  # Create Qualys scanner class obj
            qualysObj.handleAccessReq(access_details, qualys_details)  # Login | Add Asset | Add Asset Grp | Add User
            msg +="\nQualys\nDetails send to email."

        Utilities.write_to_file(msg)
    except Exception as e:
                Utilities.printException("In fun access_request_handler():"+ str(e))
Exemple #5
0
    def add_asset(self, access_req):
        self.url = self.qualys_host + "/api/2.0/fo/asset/ip/"
        params = {'action': 'add', 'ips': access_req['ip'], 'enable_vm': '1'}
        max_login_try_limit = 2

        while True:  # Login check done here, if it fails here then rest all task is skipped
            if (self.login_try > 0) and (self.login_try < max_login_try_limit):
                self.uname = input("Please enter your username for " +
                                   " Qualys" + ": ")
                self.passwd = input("Please enter your password for " +
                                    " Qualys" + ": ")
            elif self.login_try >= max_login_try_limit:
                Utilities.printError(
                    "Qualys login attemts exceded maximum limit, skipping Qualys tasks.."
                )
                return False
            response_aasset_add = self.makeRequest(params)
            # print(response_aasset_add.content)
            responseXML = response_aasset_add.content
            tree = ElementTree(fromstring(responseXML))
            root = tree.getroot()
            asset_response = root.find('RESPONSE')
            asset_status = asset_response.find('TEXT').text
            if asset_status == "IPs successfully added to Vulnerability Management":
                Utilities.printSuccess("Asset added to Qualys Scanner")
                return True
            elif asset_status == "Bad Login/Password":
                Utilities.printError("Qualys login failed..")
                self.login_try += 1
            else:
                Utilities.printError("Asset adition Failure: " + asset_status)
                Utilities.printLog("Skipping remaning Qualys tasks..")
                return False
Exemple #6
0
    def login_nessus(self, scanner_info):
        sessionreqURL = self.nessus_host + "/session"
        max_login_try_limit = 2
        while True:
            if self.login_try == 0:
                payload = {'username': scanner_info['uname'], 'password': scanner_info['passwd']}
            elif self.login_try > 0 and self.login_try < max_login_try_limit:
                usr_name = input("Please enter your username for " + " Nessus" + ": ")
                usr_passwd = input("Please enter your password for " + " Nessus" + ": ")
                payload = {'username': usr_name, 'password': usr_passwd}
            else:
                Utilities.printError("Nessus login attemts exceded maximum limit, skipping Nessus tasks..")
                return False

            response = self.makeRequest(sessionreqURL, json.dumps(payload), self.headers)
            json_rep = json.loads(response.decode("utf-8"))  # convert to string then convert to json
            # print(json_rep)
            if self.status_code == 200:
                self.session_token = json_rep['token']
                self.headers.update({'X-Cookie': 'token=' + self.session_token})  # session token added to HTTP header
                # print(self.headers)
                Utilities.printSuccess("Logged in to Nessus Scanner")
                return True
            elif self.status_code == 400:
                Utilities.printError("Login Failure: username format is not valid")
                self.login_try += 1
            elif self.status_code == 401:
                Utilities.printError("Login Failure: username or password is invalid")
                self.login_try += 1
            elif self.status_code == 500:
                Utilities.printError("Login Failure:  too many users are connected")
                self.login_try += 1
Exemple #7
0
    def add_asset(self, access_req):
        self.url = self.qualys_host + "/api/2.0/fo/asset/ip/"
        params = {'action': 'add', 'ips': access_req['ip'], 'enable_vm': '1'}
        max_login_try_limit = 2

        while True:  # Login check done here, if it fails here then rest all task is skipped
            if (self.login_try > 0) and (self.login_try < max_login_try_limit):
                self.uname = input("Please enter your username for " + " Qualys" + ": ")
                self.passwd = input("Please enter your password for " + " Qualys" + ": ")
            elif self.login_try >= max_login_try_limit:
                Utilities.printError("Qualys login attemts exceded maximum limit, skipping Qualys tasks..")
                return False
            response_aasset_add = self.makeRequest(params)
            # print(response_aasset_add.content)
            responseXML = response_aasset_add.content
            tree = ElementTree(fromstring(responseXML))
            root = tree.getroot()
            asset_response = root.find('RESPONSE')
            asset_status = asset_response.find('TEXT').text
            if asset_status == "IPs successfully added to Vulnerability Management":
                Utilities.printSuccess("Asset added to Qualys Scanner")
                return True
            elif asset_status == "Bad Login/Password":
                Utilities.printError("Qualys login failed..")
                self.login_try += 1
            else:
                Utilities.printError("Asset adition Failure: " + asset_status)
                Utilities.printLog("Skipping remaning Qualys tasks..")
                return False
Exemple #8
0
 def addUser(self, access_req):
     # print("addUser Module")
     usrLst = access_req['userList']
     for user in usrLst:
         usrSaveRequest = Element('UserSaveRequest', attrib={'session-id': self.session_id})
         userinfo = user.split(',')  # uname,name,email
         pswd = Utilities.gen_code()
         usrConfig_elem = SubElement(usrSaveRequest, 'UserConfig',
                                     attrib={'id': '-1', 'role-name': 'user', 'authsrcid': '-1', 'enabled': '1',
                                             'name': userinfo[0], 'fullname': userinfo[1], 'email': userinfo[2],
                                             'password': pswd})
         sites_elem = SubElement(usrConfig_elem, 'UserSite')
         site_elem = SubElement(sites_elem, 'site', attrib={'id': self.site_id})
         site_elem.text = access_req['site_name']
         xmlTree = ElementTree(usrSaveRequest)
         f = BytesIO()
         xmlTree.write(f, encoding='utf-8',
                       xml_declaration=True)  # required so that xml declarations will come up in generated XML
         usrSaveReqXML = f.getvalue().decode("utf-8")  # converts bytes to string
         # print(usrSaveReqXML)
         responseXML = self.makeRequest(self.reqURL, usrSaveReqXML, self.headers)
         # print(responseXML)
         tree = ElementTree(fromstring(responseXML))
         root = tree.getroot()
         addUserReq = root.get('success')
         if (addUserReq == "1"):
             Utilities.printSuccess("Created user: "******"Nexpose\nUsername:"******"\nPassword:"******"User creation failed: " + msg)
             return False
Exemple #9
0
def readAccessReq():
    # read access request from XML
    try:
        ip = ""
        usrlst = []
        tree = parse('access_request.xml')
        root = tree.getroot()
        for child in root.findall('user'):
            uname = child.find('uname').text
            name = child.find('name').text
            email = child.find('email').text
            if uname is None or name is None or email is None:
                xml_error("Data missing in access_request.xml")
            usrlst.append(uname + ',' + name + ',' + email)
        asst_det = root.find('asset_details')
        site_det = root.find('site')
        site_name = site_det.get('name')
        site_desc = site_det.get('desc')
        for ipchild in asst_det.findall('ip'):
            if ipchild.text is None:
                xml_error("IP missing in access_request.xml")
            ip = ip + "," + ipchild.text

        # print(ip)
        ip = ip.strip(',')
        access_req = {
            'userList': usrlst,
            'ip': ip,
            'site_name': site_name,
            'site_desc': site_desc
        }
        # print(access_req)
        return access_req
    except Exception as e:
        Utilities.printException("Error with access_request.xml." + str(e))
Exemple #10
0
def readAccessReq():
    # read access request from XML
    try:
        ip = ""
        usrlst = []
        tree = parse('access_request.xml')
        root = tree.getroot()
        for child in root.findall('user'):
            uname = child.find('uname').text
            name = child.find('name').text
            email = child.find('email').text
            if uname is None or name is None or email is None:
                xml_error("Data missing in access_request.xml")
            usrlst.append(uname + ',' + name + ',' + email)
        asst_det = root.find('asset_details')
        site_det = root.find('site')
        site_name = site_det.get('name')
        site_desc = site_det.get('desc')
        for ipchild in asst_det.findall('ip'):
            if ipchild.text is None:
                xml_error("IP missing in access_request.xml")
            ip = ip + "," + ipchild.text

        # print(ip)
        ip = ip.strip(',')
        access_req = {'userList': usrlst, 'ip': ip, 'site_name': site_name, 'site_desc': site_desc}
        # print(access_req)
        return access_req
    except Exception as e:
            Utilities.printException("Error with access_request.xml."+ str(e))
Exemple #11
0
    def logout(self, s):
        payload = {'action': 'logout'}

        r = s.post('https://qualysapi.qualys.com/api/2.0/fo/session/',
                   data=payload)
        xmlreturn = ET.fromstring(r.text)
        for elem in xmlreturn.findall('.//TEXT'):
            Utilities.printLog(elem.text)
Exemple #12
0
 def __init__(self, scanner_info):
     try:
         # Login and get the session here
         self.nessus_host = scanner_info['host']
         self.headers = {'Content-Type': 'application/json'}
         self.login_try = 0
         self.message = ""
     except Exception as e:
         Utilities.printException(str(e))
Exemple #13
0
    def logout(self, s):
        payload = {
                 'action':'logout'
                }

        r = s.post('https://qualysapi.qualys.com/api/2.0/fo/session/', data=payload)
        xmlreturn = ET.fromstring(r.text)
        for elem in xmlreturn.findall('.//TEXT'):
            Utilities.printLog(elem.text)
Exemple #14
0
 def __init__(self, scanner_info):
     try:
         self.nexpose_host = scanner_info['host']
         self.reqURL = self.nexpose_host + "/api/1.1/xml"
         self.headers = {'Content-Type': 'text/xml'}
         self.login_try = 0
         self.msg = ""
     except Exception as e:
         Utilities.printException(str(e))
Exemple #15
0
 def __init__(self, scanner_info):
     try:
         # Login and get the session here
         self.nessus_host = scanner_info['host']
         self.headers = {'Content-Type': 'application/json'}
         self.login_try = 0
         self.message = ""
     except Exception as e:
         Utilities.printException(str(e))
Exemple #16
0
 def __init__(self, scanner_info):
     try:
         self.nexpose_host = scanner_info['host']
         self.reqURL = self.nexpose_host + "/api/1.1/xml"
         self.headers = {'Content-Type': 'text/xml'}
         self.login_try = 0
         self.msg = ""
     except Exception as e:
         Utilities.printException(str(e))
Exemple #17
0
 def handleAccessReq(self, access_req, scanner_info):
     try:
         asset_adittion_success = self.add_asset(access_req)
         if asset_adittion_success:
             asset_grp_add_status = self.add_asset_grp(access_req)
             if asset_grp_add_status:
                 create_user_status = self.add_user(access_req)
             # self.logout_user()
     except Exception as e:
         Utilities.printException(str(e))
Exemple #18
0
 def handleAccessReq(self, access_req, scanner_info):
     try:
         asset_adittion_success = self.add_asset(access_req)
         if asset_adittion_success:
             asset_grp_add_status = self.add_asset_grp(access_req)
             if asset_grp_add_status:
                 create_user_status = self.add_user(access_req)
             # self.logout_user()
     except Exception as e:
         Utilities.printException(str(e))
Exemple #19
0
 def handleAccessReq(self, access_req, scanner_info):
     try:
         if self.login_nessus(scanner_info):
             create_user_status = self.create_user(access_req)
             self.logout_user()
         if create_user_status:
             return self.message
         else:
             return "Nessus user creation failed"
     except Exception as e:
         Utilities.printException(str(e))
Exemple #20
0
 def handleAccessReq(self, access_req, scanner_info):
     try:
         if self.login_nessus(scanner_info):
             create_user_status = self.create_user(access_req)
             self.logout_user()
         if create_user_status:
             return self.message
         else:
             return "Nessus user creation failed"
     except Exception as e:
         Utilities.printException(str(e))
    def __init__(self, colors=None):
        """Create a local debugger instance.

        :Parameters:

          - `colors` (None): a string containing the name of the color scheme to
        use, it must be one of IPython's valid color schemes.  If not given, the
        function will default to the current IPython scheme when running inside
        IPython, and to 'NoColor' otherwise.

        Usage example:

        from IPython.Debugger import Tracer; debug_here = Tracer()

        ... later in your code
        debug_here()  # -> will open up the debugger at that point.

        Once the debugger activates, you can use all of its regular commands to
        step through code, set breakpoints, etc.  See the pdb documentation
        from the Python standard library for usage details.
        """

        global __IPYTHON__
        try:
            __IPYTHON__
        except NameError:
            # Outside of ipython, we set our own exception hook manually
            __IPYTHON__ = ipapi.get(True, False)
            BdbQuit_excepthook.excepthook_ori = sys.excepthook
            sys.excepthook = BdbQuit_excepthook
            def_colors = 'NoColor'
            try:
                # Limited tab completion support
                import rlcompleter, readline
                readline.parse_and_bind('tab: complete')
            except ImportError:
                pass
        else:
            # In ipython, we use its custom exception handler mechanism
            ip = ipapi.get()
            def_colors = ip.options.colors
            ip.set_custom_exc((bdb.BdbQuit, ), BdbQuit_IPython_excepthook)

        if colors is None:
            colors = def_colors
        self.debugger = Pdb(colors)

        #additions for pydebug
        from util import Utilities
        self.util = Utilities(None)
        #save xid so that we can return to it after the pdb sesion
        self.xid = self.util.get_xid()
	def file_to_ngram(file_path, n):
		if n < 1:
			return None
		if Utilities.is_file(file_path) == False:
			return None
		fileContent = []
		file = Utilities.open_file(file_path);
		for line in file:
			fileContent += TextUtils.normalize_line(line)
			fileContent.append(' ')

		ng = ngrams(fileContent, n)
		return ng
    def file_to_ngram(file_path, n):
        if n < 1:
            return None
        if Utilities.is_file(file_path) == False:
            return None
        fileContent = []
        file = Utilities.open_file(file_path)
        for line in file:
            fileContent += TextUtils.normalize_line(line)
            fileContent.append(' ')

        ng = ngrams(fileContent, n)
        return ng
Exemple #24
0
    def login(self, s, username, password):
        payload = {
               'action':'login',
               'username':username,
               'password':password
              }

        r = s.post('https://qualysapi.qualys.com/api/2.0/fo/session/', data=payload)
        xmlreturn = ET.fromstring(r.text)
        for elem in xmlreturn.findall('.//TEXT'):
            Utilities.printLog(elem.text)

        Utilities.printLog("Cookie: QualysSession = " + r.cookies['QualysSession'])
Exemple #25
0
 def add_asset_grp(self, access_req):
     scanner_id = self.get_scanners()
     self.url = self.qualys_host + "/api/2.0/fo/asset/group/"
     if scanner_id is not None:
         params = {
             'action': 'add',
             'ips': access_req['ip'],
             'title': access_req['site_name'],
             'appliance_ids': scanner_id
         }
         # print(self.url)
         response_asset_grp_add = self.makeRequest(params)
         # print(response_asset_grp_add.content)
         responseXML = response_asset_grp_add.content
         tree = ElementTree(fromstring(responseXML))
         root = tree.getroot()
         asset_response = root.find('RESPONSE')
         asset_status = asset_response.find('TEXT').text
         if asset_status == "Asset Group successfully added.":
             Utilities.printSuccess("Asset group added to Qualys Scanner")
             return True
         else:
             Utilities.printError("Asset group addition Failure: " +
                                  asset_status)
             Utilities.printLog("Skipping remaning Qualys tasks..")
             return False
     else:
         Utilities.printError(
             "Asset Group adition Failure: Scanner id not found")
         return False
Exemple #26
0
 def addUser(self, access_req):
     # print("addUser Module")
     usrLst = access_req['userList']
     for user in usrLst:
         usrSaveRequest = Element('UserSaveRequest',
                                  attrib={'session-id': self.session_id})
         userinfo = user.split(',')  # uname,name,email
         pswd = Utilities.gen_code()
         usrConfig_elem = SubElement(usrSaveRequest,
                                     'UserConfig',
                                     attrib={
                                         'id': '-1',
                                         'role-name': 'user',
                                         'authsrcid': '-1',
                                         'enabled': '1',
                                         'name': userinfo[0],
                                         'fullname': userinfo[1],
                                         'email': userinfo[2],
                                         'password': pswd
                                     })
         sites_elem = SubElement(usrConfig_elem, 'UserSite')
         site_elem = SubElement(sites_elem,
                                'site',
                                attrib={'id': self.site_id})
         site_elem.text = access_req['site_name']
         xmlTree = ElementTree(usrSaveRequest)
         f = BytesIO()
         xmlTree.write(
             f, encoding='utf-8', xml_declaration=True
         )  # required so that xml declarations will come up in generated XML
         usrSaveReqXML = f.getvalue().decode(
             "utf-8")  # converts bytes to string
         # print(usrSaveReqXML)
         responseXML = self.makeRequest(self.reqURL, usrSaveReqXML,
                                        self.headers)
         # print(responseXML)
         tree = ElementTree(fromstring(responseXML))
         root = tree.getroot()
         addUserReq = root.get('success')
         if (addUserReq == "1"):
             Utilities.printSuccess("Created user: "******"Nexpose\nUsername:"******"\nPassword:"******"User creation failed: " + msg)
             return False
Exemple #27
0
 def addSite(self, access_req):
     # print("TestModule:SiteManagement")
     siteSaveRequest = Element('SiteSaveRequest',
                               attrib={'session-id': self.session_id})
     # print(access_req['site_name'])
     # Site element have 'S' in caps !!--lost a day on this !!
     site_elem = SubElement(siteSaveRequest,
                            'Site',
                            attrib={
                                'name': access_req['site_name'],
                                'id': '-1'
                            })
     host_elem = SubElement(site_elem, 'Hosts')
     for ip in access_req['ip'].split(','):
         range_elem = SubElement(host_elem,
                                 'range',
                                 attrib={
                                     'from': ip,
                                     'to': ''
                                 })
     scanConfig_elem = SubElement(site_elem,
                                  'ScanConfig',
                                  attrib={
                                      'name': 'Full audit',
                                      'templateID': 'full-audit'
                                  })
     xmlTree = ElementTree(siteSaveRequest)
     f = BytesIO()
     xmlTree.write(
         f, encoding='utf-8', xml_declaration=True
     )  # required so that xml declarations will come up in generated XML
     saveSiteReqXML = f.getvalue().decode(
         "utf-8")  # converts bytes to string
     # print(saveSiteReqXML)
     responseXML = self.makeRequest(self.reqURL, saveSiteReqXML,
                                    self.headers)
     tree = ElementTree(fromstring(responseXML))
     root = tree.getroot()
     addSiteResponse = root.get('success')
     if (addSiteResponse == "1"):
         self.site_id = root.get('site-id')
         Utilities.printSuccess("Created site with site-id: " +
                                self.site_id)
         return True
     else:
         fa = root.find('Failure')
         ex = fa.find('Exception')
         msg = ex.find('message').text
         Utilities.printError("Site creation failed: " + msg)
         return False
def textutils_normalize_line():
	expected_file = Utilities.open_file(TST_DIR + TXT_NORMAL_FILE_EXP)
	expected_output = []
	for line in expected_file:
		# need to strip new line characters
		expected_output += line.rstrip().split()

    # this constructs a list where each element is the normalized version
    # of the corresponding line in the file
	test_file = Utilities.open_file(TST_DIR + TXT_NORMAL_FILE)
	test_output = []
	for line in test_file:
		test_output += TextUtils.normalize_line(line)
	assert test_output == expected_output
Exemple #29
0
 def handleAccessReq(self, access_req, scanner_info):
     user_add_status = False
     # print("TestMofule")
     if self.login_nexpose(scanner_info):
         addSiteStatus = self.addSite(access_req)
         if addSiteStatus:
             user_add_status = self.addUser(access_req)
         else:
             Utilities.printError("Site creation failed, aborting user creation..")
         self.logoutOperation()
     if user_add_status:
         return self.msg
     else:
         return "Nexpose user creation failed"
Exemple #30
0
 def handleAccessReq(self, access_req, scanner_info):
     user_add_status = False
     # print("TestMofule")
     if self.login_nexpose(scanner_info):
         addSiteStatus = self.addSite(access_req)
         if addSiteStatus:
             user_add_status = self.addUser(access_req)
         else:
             Utilities.printError(
                 "Site creation failed, aborting user creation..")
         self.logoutOperation()
     if user_add_status:
         return self.msg
     else:
         return "Nexpose user creation failed"
Exemple #31
0
    def login(self, s, username, password):
        payload = {
            'action': 'login',
            'username': username,
            'password': password
        }

        r = s.post('https://qualysapi.qualys.com/api/2.0/fo/session/',
                   data=payload)
        xmlreturn = ET.fromstring(r.text)
        for elem in xmlreturn.findall('.//TEXT'):
            Utilities.printLog(elem.text)

        Utilities.printLog("Cookie: QualysSession = " +
                           r.cookies['QualysSession'])
Exemple #32
0
    def load_song_from_path(self, path):
        """
        Reads file at given path, if possible, and saves as an object.
        """
        bsy = wx.BusyInfo("Loading song from path: " + path)

        # cleanup everything
        self.current_notes.clear()
        self.next_notes.clear()
        self.is_playing = False
        self.should_play = False
        self.preset_loaded = False

        # parse file
        self.parser.parse_file(path)
        self.instrument_map = self.parser.instruments
        self.units.clear()
        self.tempo = self.parser.get_tempo()
        self.notes = util.get_viz_notes(self.parser.score)
        self.key = muse.analyze_key(self.parser.score)
        self.main_frame.statusbar.SetStatusText("Key: " + str(self.key), 4)

        # Print track instruments to debugger

        self.main_frame.statusbar.SetStatusText(
            "Tempo: " + str(self.tempo) + " bpm", 2)
        bsy = None
Exemple #33
0
    def add_IP(self, s, target_IP):
        #set up host authentication
        payload = {
                   'action':'add',
                   'ips':target_IP,
                   'enable_vm':1,
                   'enable_pc':0,
                   }

        r = s.post('https://qualysapi.qualys.com/api/2.0/fo/asset/ip/', data=payload)
        xmlreturn = ET.fromstring(r.text)
        for elem in xmlreturn.findall('.//TEXT'):
            if "action has invalid value" in elem.text:
                Utilities.printError("You do not have permissions do add IP(s)")
            else:
                Utilities.printSuccess(elem.text)
Exemple #34
0
    def login_nessus(self, scanner_info):
        sessionreqURL = self.nessus_host + "/session"
        max_login_try_limit = 2
        while True:
            if self.login_try == 0:
                payload = {
                    'username': scanner_info['uname'],
                    'password': scanner_info['passwd']
                }
            elif self.login_try > 0 and self.login_try < max_login_try_limit:
                usr_name = input("Please enter your username for " +
                                 " Nessus" + ": ")
                usr_passwd = input("Please enter your password for " +
                                   " Nessus" + ": ")
                payload = {'username': usr_name, 'password': usr_passwd}
            else:
                Utilities.printError(
                    "Nessus login attemts exceded maximum limit, skipping Nessus tasks.."
                )
                return False

            response = self.makeRequest(sessionreqURL, json.dumps(payload),
                                        self.headers)
            json_rep = json.loads(response.decode(
                "utf-8"))  # convert to string then convert to json
            # print(json_rep)
            if self.status_code == 200:
                self.session_token = json_rep['token']
                self.headers.update({
                    'X-Cookie': 'token=' + self.session_token
                })  # session token added to HTTP header
                # print(self.headers)
                Utilities.printSuccess("Logged in to Nessus Scanner")
                return True
            elif self.status_code == 400:
                Utilities.printError(
                    "Login Failure: username format is not valid")
                self.login_try += 1
            elif self.status_code == 401:
                Utilities.printError(
                    "Login Failure: username or password is invalid")
                self.login_try += 1
            elif self.status_code == 500:
                Utilities.printError(
                    "Login Failure:  too many users are connected")
                self.login_try += 1
Exemple #35
0
    def load_preset(self):
        """
        Loads the currently selected preset. Calls its on_first_load function.
        """
        # clears all current units
        self.units.clear()
        self.screen.fill((0, 0, 0))

        bsy = wx.BusyInfo("Initial Loading...")
        self.preset.first_load(self.parser.score)
        bsy = None
        dbg = self.main_frame.debugger.textbox

        # part = self.parser.score.parts[0]   # Gets first track/part of song

        self.should_play = False
        self.next_notes = []

        # get the offset of the first note in the song
        # so we can put it in next_notes
        first_offset = self.notes[0].note.offset
        for n in self.notes:
            if n.note.offset == first_offset:
                ticks = pygame.time.get_ticks()
                new_next_note = [n]
                # new_next_note.append(ticks + util.offet_ms(n.offset, self.tempo))
                try:
                    mts = n.notes.midiTickStart
                except AttributeError:
                    mts = util.offet_ms(n.note.offset, self.tempo)
                try:
                    oq_error = n.note.editorial.offsetQuantizationError
                    mts += oq_error
                except AttributeError:
                    pass

                new_next_note.append(ticks + mts)
                self.next_notes.append(new_next_note)

            if n.note.offset > self.last_offset:
                self.last_offset = n.note.offset

        self.preset_loaded = True
        print("Preset Loaded")
        util.print_line_to_panel(dbg, "\nPreset Loaded\n\n")
Exemple #36
0
    def add_IP(self, s, target_IP):
        #set up host authentication
        payload = {
            'action': 'add',
            'ips': target_IP,
            'enable_vm': 1,
            'enable_pc': 0,
        }

        r = s.post('https://qualysapi.qualys.com/api/2.0/fo/asset/ip/',
                   data=payload)
        xmlreturn = ET.fromstring(r.text)
        for elem in xmlreturn.findall('.//TEXT'):
            if "action has invalid value" in elem.text:
                Utilities.printError(
                    "You do not have permissions do add IP(s)")
            else:
                Utilities.printSuccess(elem.text)
Exemple #37
0
def selenium_browser_setdriver(context):
    # -- SETUP-FIXTURE PART:
    logger = Logger.getlogger()
    browser_name = context.config.userdata.get('BrowserName')
    Utilities.killbrowserdriver(browser_name)
    if browser_name == "Chrome":
        logger.info(browser_name + " Browser option is selected")
        context.driver = webdriver.Chrome(
            executable_path=ChromeDriverManager().install(),
            options=OptionsManager.getchromeoptions())
    elif browser_name == "Firefox":
        logger.info(browser_name + " Browser option is selected")
        context.driver = webdriver.Firefox(
            executable_path=GeckoDriverManager().install(),
            options=OptionsManager.getfirefoxoptions())
    else:
        logger.info("Entered Wrong Browser name")

    yield context.driver
def setdriver(browser_name):
    try:
        global driver
        Utilities.killbrowserdriver(browser_name)
        if browser_name == "Chrome":
            print(browser_name + " Browser option is selected")
            driver = webdriver.Chrome(
                executable_path=ChromeDriverManager().install(),
                options=OptionsManager.getchromeoptions())
        elif browser_name == "Firefox":
            print(browser_name + " Browser option is selected")
            driver = webdriver.Firefox(
                executable_path=GeckoDriverManager().install(),
                options=OptionsManager.getfirefoxoptions())
        else:
            print("Entered Wrong Browser name")

    except Exception as e:
        print("Exception Occurred")
def load_word_gen(filename):
    if Utilities.is_file(filename) == False:
        sys.exit("Fatal Error: no word hash found for file '%s'. Please \
            re-train the model and try again" % filename)
    try:
        file = open(filename, 'rb')
    except:
        sys.exit("Fatal Error: cannot open word hash '%s' for \
            reading" % filename)
    return pickle.load(file)
def load_word_gen(filename):
    if Utilities.is_file(filename) == False:
        sys.exit("Fatal Error: no word hash found for file '%s'. Please \
            re-train the model and try again" % filename)
    try:
        file = open(filename, 'rb')
    except:
        sys.exit("Fatal Error: cannot open word hash '%s' for \
            reading" % filename)
    return pickle.load(file)
Exemple #41
0
    def launch_report(self, s, scan_ref, report_type, target_IP, report_template_id):
        # launching report
        report_ID = ""
        payload = {
                   'action':'launch',
                   'report_type':'Scan',
                   'template_id':report_template_id,#'991466',
                   'output_format':report_type,
                   'report_refs':scan_ref,
                   'report_title':target_IP,
                   }

        r = s.post('https://qualysapi.qualys.com/api/2.0/fo/report/', data=payload)
        xmlreturn = ET.fromstring(r.text)
        for elem in xmlreturn.findall('.//ITEM'):
            if (elem[0].text == 'ID'):
                report_ID = elem[1].text

        Utilities.printLog("Report ID: " + report_ID)
        return report_ID
Exemple #42
0
    def get_scanners(self):

        self.url = self.qualys_host + "/api/2.0/fo/appliance/"
        parms = {'action': 'list'}
        response_get_scanners = self.makeRequest(parms)
        # print(response_get_scanners.content)
        responseXML = response_get_scanners.content
        tree = ElementTree(fromstring(responseXML))
        root = tree.getroot()
        if root.find('RESPONSE') is not None:
            response = root.find('RESPONSE')
        if response.find('APPLIANCE_LIST') is not None:
            appliance_list = response.find('APPLIANCE_LIST')
            appliance = appliance_list.findall('APPLIANCE')  # we take only the first appliance, coz no multiple appliance nw.
            appliance_id = appliance[0].find('ID').text
        if response.find('TEXT') is not None: # Error condition
            Utilities.printError("Failure to get the scanner list: "+ response.find('TEXT').text)
            appliance_id = None
        # print(appliance_id)
        return appliance_id
Exemple #43
0
    def setup_auth(self, s, target_IP, username, password, title):
        #set up host authentication
        status = "Success"
        payload = {
            'action': 'create',
            'title': title + '_' + target_IP,
            'ips': target_IP,
            'username': username,
            'password': password,
        }

        r = s.post('https://qualysapi.qualys.com/api/2.0/fo/auth/unix/',
                   data=payload)
        xmlreturn = ET.fromstring(r.text)
        for elem in xmlreturn.findall('.//TEXT'):
            if "action has invalid value" in elem.text:
                Utilities.printError(
                    "You do not have permissions do add authentication records"
                )
            else:
                Utilities.printSuccess("Authentication Record " + elem.text)

            if "existing scan auth record has the specified title" in elem.text:
                #delete the auth record
                payload = {'action': 'list', 'title': target_IP}
                r = s.post(
                    'https://qualysapi.qualys.com/api/2.0/fo/auth/unix/',
                    data=payload)
                xmlreturn = ET.fromstring(r.text)
                for elem in xmlreturn.findall('.//AUTH_UNIX'):
                    title_id = elem[0].text

                payload = {
                    'action': 'delete',
                    'ids': title_id,
                }
                r = s.post(
                    'https://qualysapi.qualys.com/api/2.0/fo/auth/unix/',
                    data=payload)
                xmlreturn = ET.fromstring(r.text)
                for elem in xmlreturn.findall('.//TEXT'):
                    status = elem.text
                    Utilities.printLog("Authentication Record " + status)
                    self.setup_auth(s, target_IP, username, password, title)
            elif "one or more of the specified IPs" in elem.text:
                #delete the auth record
                status = "Failure"
                Utilities.printError(
                    "---\nPlease note:\nIP exists in another authentication record\nQualys doesn't support multiple authentication record of same type for any IP\nPlease delete the existing authentication record manually to proceed.\n---"
                )
        return status
Exemple #44
0
    def add_user(self, access_req):
        self.url = self.qualys_host + "/msp/user.php"

        usrLst = access_req['userList']
        for user in usrLst:
            userinfo = user.split(',')  # uname,name,email
            pswd = userinfo[0] + '!vul5c4p1'
            parms = {
                'action': 'add',
                'user_role': 'scanner',
                'business_unit': 'Unassigned',
                'asset_groups': access_req['site_name'],
                'first_name': userinfo[1].split(' ')[0],
                'last_name': userinfo[1].split(' ')[1],
                'title': 'Scanner User',
                'phone': '0000000000',
                'email': userinfo[2],
                'address1': '3401 Hillview Ave',
                'city': 'Palo Alto',
                'country': 'United States of America',
                'state': 'California',
                'zip_code': '94304',
                'send_email': '1'
            }
            response_user_add = self.makeRequest(parms)
            # print(response_user_add.content)
            responseXML = response_user_add.content
            tree = ElementTree(fromstring(responseXML))
            root = tree.getroot()
            asset_response = root.find('RETURN')
            user_add_status = asset_response.get('status')
            user_add_status_msg = asset_response.find('MESSAGE').text
            # print(user_add_status + user_add_status_msg)
            if user_add_status == "SUCCESS":
                Utilities.printSuccess(user_add_status_msg + " for " +
                                       userinfo[1])
                return True
            else:
                Utilities.printError("User addition Failure: " +
                                     user_add_status_msg)
                return False
Exemple #45
0
    def logoutOperation(self):
        xmlReq = Element('LogoutRequest', attrib={'session-id': self.session_id})
        xmlTree = ElementTree(xmlReq)
        f = BytesIO()
        xmlTree.write(f, encoding='utf-8',
                      xml_declaration=True)  # required so that xml declarations will come up in generated XML
        logoutReqXML = f.getvalue().decode("utf-8")  # converts bytes to string
        # print(logoutReqXML)
        responseXML = self.makeRequest(self.reqURL, logoutReqXML, self.headers)

        tree = ElementTree(fromstring(responseXML))
        root = tree.getroot()
        logoutResponse = root.get('success')
        if (logoutResponse == "1"):
            self.session_id = root.get('session-id')
            Utilities.printSuccess("Logged out of Nexpose Scanner")
        else:
            fa = root.find('Failure')
            ex = fa.find('Exception')
            msg = ex.find('message').text
            Utilities.printError("Logout Failure: " + msg)
Exemple #46
0
    def launch_scan(self, s, target_IP, scan_option_id):
        # launching the scan
        scan_ref = ""
        payload = {
                   'action':'launch',
                   'ip':target_IP,
                   'iscanner_name':'is_vmwar_as',
                   'option_id':scan_option_id, #'797901',
                   'scan_title':target_IP,
                   }

        r = s.post('https://qualysapi.qualys.com/api/2.0/fo/scan/', data=payload)
        xmlreturn = ET.fromstring(r.text)
        for elem in xmlreturn.findall('.//ITEM'):
            if (elem[0].text == 'REFERENCE'):
                scan_ref = elem[1].text

        for elem in xmlreturn.findall('.//TEXT'):
            if "none of the specified IPs are eligible" in elem.text:
                Utilities.printError("You do not have permissions to run scans on IP " + target_IP)
            else:
                Utilities.printLog(elem.text)

        if "scan" in scan_ref:
            Utilities.printLog("Scan Reference Number: " + scan_ref)
        else:
            scan_ref = "SCAN_NOT_STARTED"
        return scan_ref
Exemple #47
0
    def login_nexpose(self, scanner_info):
        # API v1.1 Login and get the session here
        max_login_try_limit = 2

        while True:
            if self.login_try == 0:
                xmlReq = Element('LoginRequest', attrib={'user-id': scanner_info['uname'], 'password': scanner_info['passwd']})
            elif self.login_try > 0 and self.login_try < max_login_try_limit:
                usr_name = input("Please enter your username for " + " Nexpose" + ": ")
                usr_passwd = input("Please enter your password for " + " Nexpose" + ": ")
                xmlReq = Element('LoginRequest', attrib={'user-id': usr_name, 'password': usr_passwd})
            else:
                Utilities.printError("Nexpose login attemts exceded maximum limit, skipping Nexpose tasks..")
                return False

            xmlReq = Element('LoginRequest', attrib={'user-id': scanner_info['uname'], 'password': scanner_info['passwd']})
            xmlTree = ElementTree(xmlReq)
            f = BytesIO()
            xmlTree.write(f, encoding='utf-8', xml_declaration=True)  # required so that xml declarations will come up in generated XML
            loginReqXML = f.getvalue().decode("utf-8")  # converts bytes to string
            # print(self.loginReqXML)
            responseXML = self.makeRequest(self.reqURL, loginReqXML, self.headers)
            tree = ElementTree(fromstring(responseXML))
            root = tree.getroot()
            loginResponse = root.get('success')
            if (loginResponse == "1"):
                self.session_id = root.get('session-id')
                Utilities.printSuccess("Logged in to Nexpose Scanner")
                return True
            else:
                fa = root.find('Failure')
                ex = fa.find('Exception')
                msg = ex.find('message').text
                Utilities.printError("Login Failure: " + msg)
                self.login_try += 1
Exemple #48
0
    def launch_scan(self, s, target_IP, scan_option_id):
        # launching the scan
        scan_ref = ""
        payload = {
            'action': 'launch',
            'ip': target_IP,
            'iscanner_name': 'is_vmwar_as',
            'option_id': scan_option_id,  #'797901',
            'scan_title': target_IP,
        }

        r = s.post('https://qualysapi.qualys.com/api/2.0/fo/scan/',
                   data=payload)
        xmlreturn = ET.fromstring(r.text)
        for elem in xmlreturn.findall('.//ITEM'):
            if (elem[0].text == 'REFERENCE'):
                scan_ref = elem[1].text

        for elem in xmlreturn.findall('.//TEXT'):
            if "none of the specified IPs are eligible" in elem.text:
                Utilities.printError(
                    "You do not have permissions to run scans on IP " +
                    target_IP)
            else:
                Utilities.printLog(elem.text)

        if "scan" in scan_ref:
            Utilities.printLog("Scan Reference Number: " + scan_ref)
        else:
            scan_ref = "SCAN_NOT_STARTED"
        return scan_ref
Exemple #49
0
    def launch_report(self, s, scan_ref, report_type, target_IP,
                      report_template_id):
        # launching report
        report_ID = ""
        payload = {
            'action': 'launch',
            'report_type': 'Scan',
            'template_id': report_template_id,  #'991466',
            'output_format': report_type,
            'report_refs': scan_ref,
            'report_title': target_IP,
        }

        r = s.post('https://qualysapi.qualys.com/api/2.0/fo/report/',
                   data=payload)
        xmlreturn = ET.fromstring(r.text)
        for elem in xmlreturn.findall('.//ITEM'):
            if (elem[0].text == 'ID'):
                report_ID = elem[1].text

        Utilities.printLog("Report ID: " + report_ID)
        return report_ID
Exemple #50
0
    def quick_scan(self, s, target_IP, username, password, title,
                   scan_option_id, report_template_id):
        Utilities.printLog("Quick Scan: " + target_IP)
        #add IPs
        self.add_IP(s, target_IP)

        #add authentication record
        status = self.setup_auth(s, target_IP, username, password,
                                 title).lower()
        if status == "failure":
            return

        #start the scan
        scan_ref = self.launch_scan(s, target_IP, scan_option_id)
        if scan_ref == "SCAN_NOT_STARTED":
            Utilities.printError("Scan has not started for IP: " + target_IP)
            return

        #check the scan status after every 100 seconds
        #add a new if statement for various check_scan return value that is discovered
        while 1:
            #waiting for 5 mins = 300
            time.sleep(300)
            status = self.check_scan(s, scan_ref).lower()
            if status == "finished":
                break
            elif status == "queued" or status == "loading" or status == "running":
                continue
            else:
                return

        #generate report after scan has completed
        report_type = 'pdf'
        report_ID = self.launch_report(s, scan_ref, report_type, target_IP,
                                       report_template_id)

        #waiting for report generation; then download report
        time.sleep(25)
        self.download_report(s, report_ID, target_IP)
Exemple #51
0
    def check_scan(self, s, scan_ref):
        # checks the status of the scan
        state = "Default"
        payload = {
                   'action':'list',
                   'scan_ref':scan_ref,
                   }
        r = s.post('https://qualysapi.qualys.com/api/2.0/fo/scan/', data=payload)
        xmlreturn = ET.fromstring(r.text)
        code = xmlreturn.find('.//CODE')
        status = xmlreturn.find('.//STATUS')
        text = xmlreturn.find('.//TEXT')

        if status != None:
            state = status[0].text

        if code != None:
            if text != None:
                Utilities.printError("Error Text: " + text.text)

        Utilities.printLog("Scan status: " + state)
        return state
Exemple #52
0
    def check_scan(self, s, scan_ref):
        # checks the status of the scan
        state = "Default"
        payload = {
            'action': 'list',
            'scan_ref': scan_ref,
        }
        r = s.post('https://qualysapi.qualys.com/api/2.0/fo/scan/',
                   data=payload)
        xmlreturn = ET.fromstring(r.text)
        code = xmlreturn.find('.//CODE')
        status = xmlreturn.find('.//STATUS')
        text = xmlreturn.find('.//TEXT')

        if status != None:
            state = status[0].text

        if code != None:
            if text != None:
                Utilities.printError("Error Text: " + text.text)

        Utilities.printLog("Scan status: " + state)
        return state
Exemple #53
0
    def get_scanners(self):

        self.url = self.qualys_host + "/api/2.0/fo/appliance/"
        parms = {'action': 'list'}
        response_get_scanners = self.makeRequest(parms)
        # print(response_get_scanners.content)
        responseXML = response_get_scanners.content
        tree = ElementTree(fromstring(responseXML))
        root = tree.getroot()
        if root.find('RESPONSE') is not None:
            response = root.find('RESPONSE')
        if response.find('APPLIANCE_LIST') is not None:
            appliance_list = response.find('APPLIANCE_LIST')
            appliance = appliance_list.findall(
                'APPLIANCE'
            )  # we take only the first appliance, coz no multiple appliance nw.
            appliance_id = appliance[0].find('ID').text
        if response.find('TEXT') is not None:  # Error condition
            Utilities.printError("Failure to get the scanner list: " +
                                 response.find('TEXT').text)
            appliance_id = None
        # print(appliance_id)
        return appliance_id
Exemple #54
0
    def scan(self):
        try:
            #read data from config file
            tree = ET.parse('host_details.xml')
            root = tree.getroot()
            username = root[0][0].text
            password = root[0][1].text

            #setup connection
            s = requests.Session()
            s.headers.update({'X-Requested-With':'Qualys Vuln Api Scan'})
            self.login(s, username, password)

        #scan each host
            for host in root.iter('host'):
                self.quick_scan(s, host[0].text, host[1].text, host[2].text, host[3].text, host[4].text, host[5].text)
        except:
            Utilities.printException("Unexpected error: " + sys.exc_info()[0])
            Utilities.printException("sys.exc_info(): " + sys.exc_info())
        finally:
            #always log out and close the session
            self.logout(s)
            s.close()
Exemple #55
0
    def download_report(self, s, report_ID, target_IP):
        # downloading the reports
        ts = time.time()
        dt = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%dT%H%M%S')
        #file format: report folder, IP, date-time stamp
        filename = "qualys_scan_report_"+target_IP+"_"+dt+".pdf"
        payload = {
                   'action':'fetch',
                   'id':report_ID,
                   }

        r = s.post('https://qualysapi.qualys.com/api/2.0/fo/report/', data=payload, stream=True)
        if r.status_code == 200:
            with open(filename, 'wb') as f:
                r.raw.decode_content = True
                shutil.copyfileobj(r.raw, f)
                Utilities.printLog("report downloaded")
        else:
            Utilities.printError("report failed to download with status code: " + r1.status_code)

        #this is another way to save report
        #if the above method fails to save report correctly, use the below method
        '''
Exemple #56
0
    def quick_scan(self, s, target_IP, username, password, title, scan_option_id, report_template_id):
        Utilities.printLog("Quick Scan: " + target_IP)
        #add IPs
        self.add_IP(s, target_IP)

        #add authentication record
        status = self.setup_auth(s, target_IP, username, password, title).lower()
        if status == "failure":
            return

        #start the scan
        scan_ref = self.launch_scan(s, target_IP, scan_option_id)
        if scan_ref == "SCAN_NOT_STARTED":
            Utilities.printError("Scan has not started for IP: " + target_IP)
            return

        #check the scan status after every 100 seconds
        #add a new if statement for various check_scan return value that is discovered
        while 1:
            #waiting for 5 mins = 300
            time.sleep(300)
            status = self.check_scan(s, scan_ref).lower()
            if status == "finished":
                break
            elif status == "queued" or status == "loading" or status == "running":
                continue
            else:
                return

        #generate report after scan has completed
        report_type = 'pdf'
        report_ID = self.launch_report(s, scan_ref, report_type, target_IP, report_template_id)

        #waiting for report generation; then download report
        time.sleep(25)
        self.download_report(s, report_ID, target_IP)
Exemple #57
0
    def setup_auth(self, s, target_IP, username, password, title):
        #set up host authentication
        status = "Success"
        payload = {
                   'action':'create',
                   'title':title+'_'+target_IP,
                   'ips':target_IP,
                   'username':username,
                   'password':password,
                   }

        r = s.post('https://qualysapi.qualys.com/api/2.0/fo/auth/unix/', data=payload)
        xmlreturn = ET.fromstring(r.text)
        for elem in xmlreturn.findall('.//TEXT'):
            if "action has invalid value" in elem.text:
                Utilities.printError("You do not have permissions do add authentication records")
            else:
                Utilities.printSuccess("Authentication Record " + elem.text)

            if "existing scan auth record has the specified title" in elem.text:
                #delete the auth record
                payload = {
                           'action':'list',
                           'title':target_IP
                           }
                r = s.post('https://qualysapi.qualys.com/api/2.0/fo/auth/unix/', data=payload)
                xmlreturn = ET.fromstring(r.text)
                for elem in xmlreturn.findall('.//AUTH_UNIX'):
                    title_id = elem[0].text

                payload = {
                           'action':'delete',
                           'ids':title_id,
                           }
                r = s.post('https://qualysapi.qualys.com/api/2.0/fo/auth/unix/', data=payload)
                xmlreturn = ET.fromstring(r.text)
                for elem in xmlreturn.findall('.//TEXT'):
                    status = elem.text
                    Utilities.printLog("Authentication Record " + status)
                    self.setup_auth(s, target_IP, username, password, title)
            elif "one or more of the specified IPs" in elem.text:
                #delete the auth record
                status = "Failure"
                Utilities.printError("---\nPlease note:\nIP exists in another authentication record\nQualys doesn't support multiple authentication record of same type for any IP\nPlease delete the existing authentication record manually to proceed.\n---")
        return status
Exemple #58
0
 def logout_user(self):
     try:
         # destroy the user session
         logoutURL = self.nessus_host + "/session"
         response = self.makeRequest(logoutURL, {}, self.headers, "DELETE")
         if self.status_code == 200:
             Utilities.printSuccess("Logged out of Nessus Scanner")
         if self.status_code == 401:
             Utilities.printSuccess("Logged out failure: No session exists")
     except Exception as e:
         Utilities.printException(str(e))
Exemple #59
0
 def add_asset_grp(self, access_req):
     scanner_id = self.get_scanners()
     self.url = self.qualys_host + "/api/2.0/fo/asset/group/"
     if scanner_id is not None:
         params = {'action': 'add', 'ips': access_req['ip'], 'title': access_req['site_name'], 'appliance_ids':scanner_id}
         # print(self.url)
         response_asset_grp_add = self.makeRequest(params)
         # print(response_asset_grp_add.content)
         responseXML = response_asset_grp_add.content
         tree = ElementTree(fromstring(responseXML))
         root = tree.getroot()
         asset_response = root.find('RESPONSE')
         asset_status = asset_response.find('TEXT').text
         if asset_status == "Asset Group successfully added.":
             Utilities.printSuccess("Asset group added to Qualys Scanner")
             return True
         else:
             Utilities.printError("Asset group addition Failure: " + asset_status)
             Utilities.printLog("Skipping remaning Qualys tasks..")
             return False
     else:
         Utilities.printError("Asset Group adition Failure: Scanner id not found")
         return False
Exemple #60
0
    def create_user(self, access_req):
        try:
            # Create User
            create_user_URL = self.nessus_host + "/users"
            usrLst = access_req['userList']
            for user in usrLst:
                userinfo = user.split(',')  # uname,name,email
                pswd = Utilities.gen_code()
                payload = {'username': userinfo[0], 'password': pswd, 'permissions': '32',
                           'name': userinfo[1], 'email': userinfo[2], 'type': 'local'}
                response = self.makeRequest(create_user_URL, json.dumps(payload), self.headers)
                json_rep = json.loads(response.decode("utf-8"))
                # print(json_rep)
                if self.status_code == 200:
                    Utilities.printSuccess("Created user: "******"Nessus\nUsername:"******"\nPassword:"******"User creation Failure: Invalid field request")
                    return False
                if self.status_code == 403:
                    Utilities.printError("User creation Failure: No permission to create a user")
                    return False
                if self.status_code == 409:
                    Utilities.printError("User creation Failure: Duplicate username")
                    return False

        except Exception as e:
            Utilities.printException(str(e))