def judge(self, filepath):
        '''
            virustotal에 특정 파일 검사
            :param filepath: 검사 대상 path
            :param api_key: virustotal API_KEY
            :return: 결과 boolean True : Non-malware, False : malware
        '''
        # Normal Initialisation.
        vtotal = Virustotal(self.api_key)
        result = vtotal.file_scan(filepath)

        print('>> Virustotal Search report. <<')
        json_resp = result['json_resp']
        md5 = json_resp['md5'].strip()
        print('result link : ', json_resp['permalink'])

        url = 'https://www.virustotal.com/vtapi/v2/file/report'
        params = {'apikey': self.api_key, 'resource': md5}
        response = requests.get(url, params=params)

        total = response.json()['total']
        positives = response.json()['positives']
        print('Result : (' + str(total) + ' / ' + str(positives) + ')')

        if positives == 0:
            vtotal_judge = True
        else:
            vtotal_judge = False

        # 최종 검사 결과, 탐지 횟 수
        return vtotal_judge, positives, total, json_resp['permalink']
Example #2
0
def check_file(key, file):
    msg()                                                           # prints scanning message
    scanner = Virustotal(key)                                       # passing api key to Virustotal class
    scanner.file_scan(file)                                         # scans the file for virus
    with open(file, 'rb') as f:                                     # opens file in read binary mode
        read = f.read()                                             # reads opened file
        file_hash = hashlib.sha256(read).hexdigest()                # Get sha256 hash of file
    report = scanner.file_report([file_hash])    # passing hash value of file to file_report function and returns report
    try:
        print('\n\nREPORT:\nStatus code:', report['status_code'])   # Prints all the reports
        print('Scan date:', report['json_resp']['scan_date'])
        print('Verbose msg:', report['json_resp']['verbose_msg'])
        print('Antivirus Scanned:', report['json_resp']['total'])
        print('Positives:', report['json_resp']['positives'])
        print('sha256:', report['json_resp']['sha256'])
        print('md5:', report['json_resp']['md5'])
    except KeyError:
        print('\n""Maximum four scans per minute""')
Example #3
0
class StartModule():
    def __init__(self):
        self._main_gui_func_ = 'isBadFile'
        self.__gui_label__ = 'Virustotal Search'

    def help(self):
        Logger.printMessage(
            message=ht.getFunctionsNamesFromModule('ht_virustotal'),
            debug_module=True)

    def isBadFileHash(self, fileHash, virustotal_api=None, session_id=None):
        try:
            if not virustotal_api:
                virustotal_api = ht.Config.getAPIKey('virustotal_api',
                                                     session_id)
            self.vtotal = Virustotal(virustotal_api)
            resp = self.vtotal.file_report([fileHash])
            if resp["status_code"] in (200, 204):
                if resp["status_code"] == 204:
                    Logger.printMessage(
                        message="isBadFileHash",
                        description="Testing - {hash} - Waiting 2 seconds...".
                        format(hash=fileHash),
                        debug_module=True)
                    time.sleep(2)
                    return self.isBadFileHash(fileHash, virustotal_api)
                while resp["json_resp"]["response_code"] == -2:
                    Logger.printMessage(
                        message="isBadFileHash",
                        description="Testing - {hash} - Waiting 2 seconds...".
                        format(hash=fileHash),
                        debug_module=True)
                    time.sleep(2)
                    return self.isBadFileHash(fileHash, virustotal_api)
                no_detected_list = []
                detected_list = []
                detected_types = []
                for antivirus in resp["json_resp"]["scans"]:
                    if resp["json_resp"]["scans"][antivirus]["detected"]:
                        detected_list.append(
                            (antivirus,
                             resp["json_resp"]["scans"][antivirus]["version"]))
                        if not resp["json_resp"]["scans"][antivirus][
                                "result"] in detected_types:
                            detected_types.append(resp["json_resp"]["scans"]
                                                  [antivirus]["result"])
                    else:
                        no_detected_list.append(
                            (antivirus,
                             resp["json_resp"]["scans"][antivirus]["version"]))
                if detected_list:
                    data = {}
                    data["detected_list"] = detected_list
                    data["detected_types"] = detected_types
                    data["no_detected_list"] = no_detected_list
                    return json.dumps({"Detected": data},
                                      indent=4,
                                      sort_keys=True)
                return json.dumps({"No detected": no_detected_list},
                                  indent=4,
                                  sort_keys=True)
            return resp
        except Exception as e:
            Logger.printMessage(message="isBadFileHash",
                                description=str(e),
                                is_error=True)
            return str(e)

    def isBadFile(self, filename, virustotal_api=None):
        try:
            if not virustotal_api:
                virustotal_api = ht.Config.config['API']['virustotal']
            Logger.printMessage(message="isBadFile",
                                description=filename,
                                debug_module=True)
            self.vtotal = Virustotal(virustotal_api)
            response = self.vtotal.file_scan(filename)
            if response["status_code"] == 200:
                scan_id = str(response["json_resp"]["scan_id"])
                time.sleep(2)
                resp = self.isBadFileHash(scan_id, virustotal_api)
                return resp
        except Exception as e:
            Logger.printMessage(message="isBadFile",
                                description=str(e),
                                is_error=True)
            return str(e)
Example #4
0
async def vt(event):
    await event.edit(f"Analyzing Datas......")
    input_str = event.pattern_match.group(1)
    if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY):
        os.makedirs(TEMP_DOWNLOAD_DIRECTORY)
    if "|" in input_str:
        url, file_name = input_str.split("|")
        url = url.strip()      
        file_name = file_name.strip()
        head, tail = os.path.split(file_name)
        if head:
            if not os.path.isdir(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)):
                os.makedirs(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head))
                file_name = os.path.join(head, tail)
        downloaded_file_name = TEMP_DOWNLOAD_DIRECTORY + "" + file_name
        downloader = SmartDL(url, downloaded_file_name, progress_bar=False)
        downloader.start(blocking=False)
        c_time = time.time()
        display_message = None
        while not downloader.isFinished():
            status = downloader.get_status().capitalize()
            total_length = downloader.filesize if downloader.filesize else None
            downloaded = downloader.get_dl_size()
            now = time.time()
            diff = now - c_time
            percentage = downloader.get_progress() * 100
            speed = downloader.get_speed()
            elapsed_time = round(diff) * 1000
            progress_str = "[{0}{1}] {2}%".format(
                ''.join(["█" for i in range(math.floor(percentage / 10))]),
                ''.join(["░"
                         for i in range(10 - math.floor(percentage / 10))]),
                round(percentage, 2))
            estimated_total_time = downloader.get_eta(human=True)
            try:
                current_message = f"{status}..\
                \nURL: {url}\
                \nFile Name: {file_name}\
                \n{progress_str}\
                \n{humanbytes(downloaded)} of {humanbytes(total_length)}\
                \nETA: {estimated_total_time}"

                if round(diff %
                         10.00) == 0 and current_message != display_message:
                    await event.edit(current_message)
                    display_message = current_message
            except Exception as e:
                LOGS.info(str(e))
        if downloader.isSuccessful():
            await event.edit(f"{text} \n\nDownloaded  successfully !!")
        else:
            await event.edit("Incorrect URL\n{}".format(url))
    elif event.reply_to_msg_id:
        try:
            c_time = time.time()
            downloaded_file_name = await event.client.download_media(
                await event.get_reply_message(),
                TEMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop(
                ).create_task(
                    progress(d, t, event, c_time, f"{text} \n\nDownloading...")))
        except Exception as e:  # pylint:disable=C0103,W0703
            await event.edit(str(e))
        else:
            await event.edit(f"{text} \n\nDownloaded successfully !!")
    else:
        return await event.edit(f"Error\n`Reply to a file to scan.`")
    await event.edit(" `Scanning......`")
    vscan = downloaded_file_name
    if a ==2:
		      return await event.edit("`You need to Update wolfs to use this command.......`")
    if not vscan:
		     return await event.edit("`Unknown command type !help virus_scan for more info`")            
    try:
         vtotal = Virustotal(Vapi)
    except:
          return await event.edit("Failed to connect virus total , is api key added? type `!help virus_scan` for more info")
    try:
      vr = vtotal.file_scan(vscan)
    except:
      return await event.edit("`Unknown command type !help virus_scan for more info")            
    test = vr['json_resp'] ; link = test['permalink'] ; scan_id = test['scan_id'] ; response_code = test['response_code']
    return await event.edit(""                 
                    f"• **Virus Total Response Code:** `{response_code}`\n"                                 
                    f"• **Scan Results:** [ClickHere]({link}) ")
Example #5
0
def main():

    parser = argparse.ArgumentParser(
        description=
        "Scan a single file in VirusTotal and waits until report is complete")
    parser.add_argument('file', help='File to be scanned')

    args = parser.parse_args()

    if 'VT_API_KEY' not in os.environ:
        LOGGER.error('VT_API_KEY environment variable not set.')
        sys.exit(SCAN_ERROR)

    LOGGER.debug('Initialzing VirusTotal API')
    vt_api_key = os.environ['VT_API_KEY']
    vt = Virustotal(vt_api_key)

    # Hash file
    LOGGER.info('Checking if report already exists via file hash.')
    file_hash = sha256sum(args.file)
    try:
        response = vt.file_report([file_hash])
    except ConnectionError as e:
        err_str = str(e)
        LOGGER.error(f"Connection error to VT: {err_str}.")
        sys.exit(SCAN_ERROR)

    ret = parse_response(response)

    # If report is available, just exit with the appropriate RC
    if ret != SCAN_NOT_FOUND:
        ret_str = RET_STR_INFECTED if ret else RET_STR_CLEAN
        LOGGER.info(f"Report found. Status: {ret_str}.")
        sys.exit(ret)

    # Send file to VT for scanning
    try:
        LOGGER.info(
            'Report not found. Sending file to VirusTotal for scanning.')
        vt.file_scan(args.file)
    except ConnectionError as e:
        err_str = str(e)
        LOGGER.error(f"Connection error to VT: {err_str}")
        sys.exit(SCAN_ERROR)

    while ret == SCAN_NOT_FOUND:
        LOGGER.info(f"Scan still running, sleeping for {WAIT_TIME} seconds.")
        sleep(WAIT_TIME)
        # Try again
        try:
            response = vt.file_report([file_hash])
        except ConnectionError as e:
            err_str = str(e)
            LOGGER.error(
                f"Temporary connection error to VT: {err_str}... Retrying in {WAIT_TIME} seconds."
            )
            continue

        ret = parse_response(response)

    ret_str = RET_STR_INFECTED if ret else RET_STR_CLEAN
    LOGGER.info(f"Scan finished. Status: {ret_str}.")
    sys.exit(ret)
Example #6
0
async def vt(event):
    await event.edit(f"Analyzing Datas......")
    input_str = event.pattern_match.group(1)
    if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY):
        os.makedirs(TEMP_DOWNLOAD_DIRECTORY)
    if "|" in input_str:
        url, file_name = input_str.split("|")
        url = url.strip()
        file_name = file_name.strip()
        head, tail = os.path.split(file_name)
        if head:
            if not os.path.isdir(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)):
                os.makedirs(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head))
                file_name = os.path.join(head, tail)
        downloaded_file_name = TEMP_DOWNLOAD_DIRECTORY + "" + file_name
        downloader = SmartDL(url, downloaded_file_name, progress_bar=False)
        downloader.start(blocking=False)
        c_time = time.time()
        display_message = None
        while not downloader.isFinished():
            status = downloader.get_status().capitalize()
            total_length = downloader.filesize if downloader.filesize else None
            downloaded = downloader.get_dl_size()
            now = time.time()
            diff = now - c_time
            percentage = downloader.get_progress() * 100
            speed = downloader.get_speed()
            elapsed_time = round(diff) * 1000
            progress_str = "[{0}{1}] {2}%".format(
                ''.join(["█" for i in range(math.floor(percentage / 10))]),
                ''.join(["░"
                         for i in range(10 - math.floor(percentage / 10))]),
                round(percentage, 2))
            estimated_total_time = downloader.get_eta(human=True)
            try:
                current_message = f"{status}..\
                \nURL: {url}\
                \nFile Name: {file_name}\
                \n{progress_str}\
                \n{humanbytes(downloaded)} of {humanbytes(total_length)}\
                \nETA: {estimated_total_time}"

                if round(diff %
                         10.00) == 0 and current_message != display_message:
                    await event.edit(current_message)
                    display_message = current_message
            except Exception as e:
                LOGS.info(str(e))
        if downloader.isSuccessful():
            await event.edit(f"{text} \n\nDownloaded  successfully !!")
        else:
            await event.edit("Incorrect URL\n{}".format(url))
    elif event.reply_to_msg_id:
        try:
            c_time = time.time()
            downloaded_file_name = await event.client.download_media(
                await event.get_reply_message(),
                TEMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop(
                ).create_task(
                    progress(d, t, event, c_time, f"{text} \n\nDownloading...")
                ))
        except Exception as e:  # pylint:disable=C0103,W0703
            await event.edit(str(e))
        else:
            await event.edit(f"{text} \n\nDownloaded successfully !!")
    else:
        return await event.edit(f"Error\n`Reply to a file to scan.`")
    await event.edit(" `Scanning......`")
    vscan = downloaded_file_name

    if not vscan:
        return await event.edit("`downloaded_file missing`")
    try:
        vtotal = Virustotal(Vapi)
    except:
        return await event.edit(
            "Failed to connect virus total , is api key added? type `!help virus_scan` for more info"
        )
    try:
        vr = vtotal.file_scan(vscan)
        test = vr['json_resp']
        link = test['permalink']
        scan_id = test['scan_id']
        response_code = test['response_code']
        return await event.edit(
            ""
            f"• **Virus Total Response Code:** `{response_code}`\n"
            f"• **Scan Results:** [ClickHere]({link}) ")
    except:
        url = "https://www.virustotal.com/vtapi/v2/file/scan"

        params = {"apikey": Vapi}
        files = {
            "file": (downloaded_file_name, open(downloaded_file_name, "rb"))
        }
        response = requests.post(url, files=files, params=params)
        try:
            a = response.json()
            b = a["permalink"]
        except Exception as e:
            await event.edit(str(e))
        try:
            await event.edit(
                f"<b><u> File Scan Request Complete</u></b>\n\n<b>Link of the report:-</b>\n{b}\n\nNote:- Please open the link after 5-10 minutes.",
                parse_mode="HTML",
            )
        except Exception as e:
            await event.edit(str(e))
    else:
        await event.edit("Some Internal Issus")