def send_file(md5): host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", get_vt_key())] dir_path = "" if vt_submissions == "manual": dir_path = MAN_DOWNLOAD_DIR else: dir_path = LIVE_DOWNLOAD_DIR # just a patch to old code... # we only submit the first file that matches # it is anyway highly unlikely that more than one would match file_name = None file_path = None for ext in vt_submissions_ext: for e in [ext.lower(), ext.upper()]: fn = md5 + "." + e fp = os.path.join(dir_path, fn) if os.path.isfile(fp): file_name = fn file_path = fp break if file_path and os.path.isfile(file_path): print "VT file submission:", file_path file_to_send = open(file_path, "rb").read() files = [("file", file_name, file_to_send)] json = postfile.post_multipart(host, selector, fields, files) return json
def run(self): self.logger.logger('FileSender Started') while True: tmp = self.sfQueue.get(1) items = tmp.split(',', 1) hashValue = items[0] fileName = items[1] fields = [('apikey', self.apiKey)] fileData = open(fileName, 'rb').read() files = [('file', 'sample.apk', fileData)] self.logger.logger('Sending File %s to Scan' % fileName) response = postfile.post_multipart(self.host, self.url, fields, files) result = json.loads(response) if result['response_code'] == 0 or result['response_code'] == -1: print response self.logger.logger('Operation ERROR') self.sfLock.acquire() self.sfQueue.put(tmp, 1) self.sfLock.release() if result['response_code'] == 1: self.logger.logger('Operation OK') self.fsLock.acquire() self.fsQueue.put(tmp, 1) self.fsLock.release() time.sleep(self.interval)
def ScanFilesOutput2textfile(path): try: host = "www.virustotal.com" fields = [("apikey", apikey)] selector = "https://www.virustotal.com/vtapi/v2/file/scan" filename = datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S_UploadedToVirusTotal")+".txt" foutput = open(filename,'a') filelist = getAllFilesFromDir(path) for fname in filelist: file_to_send = open(fname, "rb").read() files = [("file", fname, file_to_send)] r = postfile.post_multipart(host, selector, fields, files) jsondict = json.loads(r) foutput.write(os.path.abspath(fname)+","+jsondict['md5']+","+jsondict['permalink']+"\n") print os.path.abspath(fname) + "," + jsondict['verbose_msg'] print "\n\n[+] Detailes has been saved to " + filename except Exception, e: if "204" in str(e): print "[-] Exceed the public API request rate limit.\n" return else: print "[-] " + str(e) + "\n" return
def get_report(resource, filename, dl_url='unknown', protocol=None, origin=None): apikey = config().get('virustotal', 'apikey') url = "https://www.virustotal.com/vtapi/v2/file/report" parameters = {"resource": resource, "apikey": apikey } data = urllib.urlencode(parameters) req = urllib2.Request(url, data) response = urllib2.urlopen(req) json = response.read() j = simplejson.loads(json) if j['response_code'] == 1: # file known cfg = config() args = {'shasum': resource, 'url': dl_url, 'permalink': j['permalink']} # we don't use dispatcher, so this check is needed if cfg.has_section('database_mysql'): mysql_logger = cowrie.dblog.mysql.DBLogger(cfg) mysql_logger.handleVirustotal(args) args_scan = {'shasum': resource, 'json': json} mysql_logger.handleVirustotalScan(args_scan) if origin == 'db': # we don't use dispatcher, so this check is needed if cfg.has_section('database_textlog'): text_logger = cowrie.dblog.textlog.DBLogger(cfg) text_logger.handleVirustotalLog('log_from database', args) else: msg = 'Virustotal report of %s [%s] at %s' % \ (resource, dl_url, j['permalink']) # we need to print msg, because logs from SFTP are dispatched this way print msg if protocol: protocol.logDispatch(msg) elif j['response_code'] == 0: # file not known if origin == 'db': return j['response_code'] msg = 'Virustotal not known, response code: %s' % (j['response_code']) print msg host = "www.virustotal.com" url = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", apikey)] filepath = "dl/%s" % resource file_to_send = open(filepath, "rb").read() files = [("file", filename, file_to_send)] json = postfile.post_multipart(host, url, fields, files) print json msg = 'insert to Virustotal backlog %s [%s]' % \ (resource, dl_url) print msg virustotal_backlogs.insert(resource, dl_url) else: msg = 'Virustotal not known, response code: %s' % (j['response_code']) print msg return j['response_code']
def check_virustotal(md5, file_to_send, filename): parameters = {"resource": md5, "key": config_map("virustotal")['apikey']} data = urllib.urlencode(parameters) req = urllib2.Request(config_map("virustotal")['geturl'], data) response = urllib2.urlopen(req) json = response.read() datastructure = simplejson.loads(json) if datastructure.get("result") == 1: virus_count = 0 av_count = 0 results = '' for av, virus in datastructure.get("report")[1].iteritems(): av_count += 1 if virus: virus_count += 1 else: virus = '--' results += av + ': ' + virus + '\n' avscore = 'Score: ' + str(virus_count) + '/' + str(av_count) +' \n' message = str(avscore) + str(results) elif datastructure.get("result") == 0: fields = [("key", config_map("virustotal")['apikey'])] files = [("file", filename, file_to_send)] json = postfile.post_multipart(config_map("virustotal")['host'], config_map("virustotal")['sendurl'], fields, files) datastructure = simplejson.loads(json) scanid = str(datastructure.get("scan_id")) message = ''' There is no history of a virus scan for this MD5.\n One has been submitted to virustotal.com with Scan ID: %s''' % (scanid) else: message = "There was an issue with interfacting with virustotal.com. Error Code:" + str(datastructure.get("result")) return message
def virusTotalFile(input): for file in input: #Request File Scan api_key = "3e60acbae95913aa8b36c40c74e2e909150366465cce9e886fcd448d85a72a17" host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", api_key)] file_to_send = open(file, "rb").read() files = [("file", file, file_to_send)] json_request = postfile.post_multipart(host, selector, fields, files) json_loads = json.loads(json_request) scan_id = json_loads['scan_id'] #Recieve File Scan url = "https://www.virustotal.com/vtapi/v2/file/report" parameters = {"resource": scan_id, "apikey": api_key} data = urllib.urlencode(parameters) req = urllib2.Request(url, data) response = urllib2.urlopen(req) json_response = response.read() parsed_json = json.loads(json_response) print file print "Positives:", parsed_json['positives'] print "Total:", parsed_json['total'] for scan in parsed_json['scans']: print "Name:",scan, "Detected:", parsed_json['scans'][scan]["detected"], \ "Version:", parsed_json['scans'][scan]["version"], "Result:", \ parsed_json['scans'][scan]["result"] print "Source: VirusTotal" print"--------------------------------------------"
def vt_send_file(path) : host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", "5ab1d6314e4a07c42ca3662ca9f90afd1e0f7a53584bf4e1b28545fb1bfdff7d")] file_to_send = open(path, "rb").read() files = [("file", "test.txt", file_to_send)] json = postfile.post_multipart(host, selector, fields, files) return json
def submit(f): host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", APIKEY)] file_to_send = open(f, "rb").read() files = [("file", f, file_to_send)] jsond = postfile.post_multipart(host, selector, fields, files) return jsond
def rscScan(self,scanfile): """ Virustotal API module """ base = self.basescan + 'file/scan' file_to_send = open(scanfile , "rb").read() files = [("file", scanfile , file_to_send)] print 'sending...' json = postfile.post_multipart(self.host, base, self.apikeyscan, files) return json
def file_scan(self, filename): selector = self.header + "file/scan" fields = [("apikey", self.api_key)] file_to_send = open(filename, "rb").read() #files = [("file", "test.txt", file_to_send)] files = [(filename, filename, file_to_send)] #first arg is a common name, second is the filename, third is the file data json = postfile.post_multipart(host, selector, fields, files) return json
def scan_file(): host = "x.threatbook.cn" selector = "https://x.threatbook.cn/api/v1/file/scan" fields = [("apikey", Public_ApiKey)] file_content = open("sess201708090954.csv", "rb").read() files = [("file", "sess201708090954.csv", file_content)] json = postfile.post_multipart(host, selector, fields, files) print json return json
def scan(self, filename, fast=False): selector = "/api/upload" if fast: selector = "/api/upload_fast" file_buf = open(filename, "rb").read() files = [("file_upload", os.path.basename(filename), file_buf)] json_txt = postfile.post_multipart(self.host, selector, [], files) d = json.loads(json_txt) return d
def checkvirustotalDB(file): host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", "61ee5459e495525126a8b8297f24fd6768ca4f38a0cbbc3435c96926c47fa14d")] # my api key at virustotal file_to_send = open("mytext.txt", "rb").read() files = [("file", "mytext.txt", file_to_send)] json_ = postfile.post_multipart(host, selector, fields, files) j = json.loads(json_) return retrievefromvirustotal(j['scan_id']) # we are sending the scan_id parameter so we can get the correct response later
def grabFile(raw, sort): #Regex to parse out URLs x = re.compile(r"http://(\w*[.])*(\w*/)*(\w*[-]\w*)*[?]\w*(\w*[-]\w*)*") url = x.search(raw).group() print "URL found\n" #print url #Open URL and grab filename print "Searching URL for filename\n" zfile = urllib2.urlopen(url) _,params = cgi.parse_header(zfile.headers.get('Content-Disposition', '')) filename = params['filename'] print "Filename found\n" #Download the file print "Beginning File Download\n" data = zfile.read() print type(data) with open(filename, "wb") as code: code.write(data) print "Download Complete\n" #Unzip the file print "Unzipping file\n" with zipfile.ZipFile(filename, "r") as z: z.extractall() print "Unzip Complete\n" #Upload the file to vxcage # UNTESTED CODE CORRECT IN THEORY pathname = '/malware/'+sort+'/'+md5(fopen(filename)) scpquery = 'scp ' + filename + ' [email protected]:' + pathname os.system(scpquery) #Upload the file to virus total print "Uploading to virus total\n" host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", "")] file_to_send = open(filename, "rb").read() files = [("file", filename, file_to_send)] json = postfile.post_multipart(host, selector, fields, files) print "Upload successful\n" #Upload the file to totalhash print "Beginning FTP uplaod to totalhash" ftpserver = '198.100.146.47' #totalhash.com session = ftplib.FTP(ftpserver,'upload','totalhash') f = open(filename,'rb') # file to send session.storbinary(filename, f) # send the file f.close() # close file and FTP session.quit() print "Upload complete"
def postToVT(file): global my_api_key host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", my_api_key)] filename = path.basename(file) file_to_send = open(file, "rb").read() files = [("file", filename, file_to_send)] json = postfile.post_multipart(host, selector, fields, files) return simplejson.loads(json)
def vt_sendscan(file_to_send, APIKEY): host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", APIKEY)] fpath = open(file_to_send, "rb").read() md5sum = hashlib.md5(fpath).hexdigest() files = [("file", md5sum, fpath)] response= postfile.post_multipart(host, selector, fields, files) return response
def send_file(md5): host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", get_vt_key())] if vt_submissions == "manual": file_to_send = open("%s/%s.exe" % (MAN_DOWNLOAD_DIR, md5), "rb").read() else: file_to_send = open("parsed/pe_files/%s.exe" % (md5,), "rb").read() files = [("file", "%s.exe" % (md5,), file_to_send)] json = postfile.post_multipart(host, selector, fields, files) return json
def send_file(md5): host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", get_vt_key())] if vt_submissions == "manual": file_to_send = open("%s/%s.exe" % (MAN_DOWNLOAD_DIR, md5), "rb").read() else: file_to_send = open("parsed/pe_files/%s.exe" % (md5, ), "rb").read() files = [("file", "%s.exe" % (md5, ), file_to_send)] json = postfile.post_multipart(host, selector, fields, files) return json
def file_submit(self, f): host = 'www.virustotal.com' selector = self.api + 'file/scan' fields = [('apikey', self.key)] file_to_send = open(f, 'rb').read() files = [('file', f, file_to_send)] json_data = postfile.post_multipart(host, selector, fields, files) jsons = json.loads(json_data) print(jsons['verbose_msg']) print(jsons['permalink'])
def fileScan(fname): print('+++++++++++++++++++++++++++++++++++++++++++++++++++++++++') print("+\t\tSCANNING FILES +") print('+++++++++++++++++++++++++++++++++++++++++++++++++++++++++') #sending files VirusTotal #apikey='0c940f8ea73da597250d22c1a5bac45a20d3413a38862f0cf60166aea9b8a3c7' host = "www.virustotal.com"#host of the file scan provider "http://virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", "0c940f8ea73da597250d22c1a5bac45a20d3413a38862f0cf60166aea9b8a3c7")] file_to_send = open(fname, "rb").read() files = [("file", fname, file_to_send)] resp = postfile.post_multipart(host, selector, fields, files)#send files and other parameters as a POST request resp_json=(json.loads(resp))#Parse the json response using json module resource=(resp_json['resource']) #Retreiving file reports VirusTotal url = "https://www.virustotal.com/vtapi/v2/file/report"#retrieve the information from the url parameters = {"resource": resource, "apikey": "0c940f8ea73da597250d22c1a5bac45a20d3413a38862f0cf60166aea9b8a3c7"} data = urllib.urlencode(parameters) req = urllib2.Request(url, data) response = urllib2.urlopen(req) reports_json=json.loads(response.read())#load it into json module to extract response #print the reports print("If your file is infected, the below reports would indicate:") print("Report from nProtect: %s" %(reports_json.get("scans", {}).get("nProtect", {}).get("result"))) print("Report from CMC: %s" %(reports_json.get("scans", {}).get("CMC", {}).get("result"))) print("Report from CAT-QuickHeal: %s" %(reports_json.get("scans", {}).get("CAT-QuickHeal", {}).get("result"))) print("Report from AlYac: %s" %(reports_json.get("scans", {}).get("ALYac", {}).get("result"))) print("Report from Malwarebytes: %s"%(reports_json.get("scans", {}).get("Malwarebytes", {}).get("result"))) print("Report from K7AntiVirus: %s" %(reports_json.get("scans", {}).get("K7AntiVirus", {}).get("result"))) print("Report from Alibaba: %s" %(reports_json.get("scans", {}).get("Alibaba", {}).get("result"))) print("Report from Symantec: %s" %(reports_json.get("scans", {}).get("Symantec", {}).get("result"))) print("Report from Avast: %s"%(reports_json.get("scans", {}).get("Avast", {}).get("result"))) #Add a file to scan Malwr.com print('\n') print('sending file to scan malwr.com...') payload = {'api_key': 'dbb36411f71d4497ba521b8211cbecc5', 'shared': 'yes', 'file': fname}#populate the playload with the necessary information r = requests.post("https://malwr.com/api/analysis/add/", data=payload) print(r.text)#load it into a readable format print('\n')
def get_resource(file_name): host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey",apikey)] file_to_send = open(file_name, "rb").read() files = [("file", file_name, file_to_send)] json = postfile.post_multipart(host, selector, fields, files) l = json.split() re = l[5] re = re.strip("\"") re = re.strip(",") re = re.strip("\"") return re
def upload(): global md5sum global next try: file_to_send = open(file4Upload, "rb").read() except: print "file not found!" sys.exit(1) files = [("file", file4Upload, file_to_send)] output = postfile.post_multipart(host, selector, fields, files) joutput = json.loads(output) next = joutput['md5'] getReport(next)
def submit_md5(self, file_path): import postfile #submit the file FILE_NAME = os.path.basename(file_path) host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", APIKEY)] file_to_send = open(file_path, "rb").read() files = [("file", FILE_NAME, file_to_send)] json = postfile.post_multipart(host, selector, fields, files) print json pass
def _send_file(self, file_path): fields = [("apikey", self._key)] target_file = File(file_path) content = target_file.read() del target_file files = [("file", os.path.basename(file_path), content)] json_str = postfile.post_multipart(self._host, self._url_scan, fields, files) if json_str == '': return False data = json.loads(json_str) if data['response_code'] == 1: return True else: return False
def scanFile(self, file): ''' Sends the given parameter file to VT for scanning Files sent for scanning have lowest priority, could take up to several hours to be scanned POST to https://www.virustotal.com/vtapi/v2/file/scan ''' fields = [("apikey", self.api)] file_to_send = open(file, "rb").read() files = [("file", file, file_to_send)] url = self.base + "file/scan" json = postfile.post_multipart(self.base[:-10], url, fields, files) if json['response_code'] == 1: print "\n\tVirus Total File Scan Requested for --" + json['md5'] else: print "\n\tScan Request Failed"
def send_apk_to_vt(apkFilePath): """ send an apk file to the VirusTotal service to be placed on the analysis queue and write the JSON results on a file, note that each JSON object contains scan_id attribute which will be used later to pull the analysis result PARAMS: apkPath: full path to the apk """ # return '{"scan_id": "scn_id-1495910015", "sha1": "sha1_11", "resource": "d690e4c35df8b12b2853665ad58e7b024bfdaa1dc300e7486ca7a1cdd74b762e", "response_code": 1, "sha256": "d690e4c35df8b12b2853665ad58e7b024bfdaa1dc300e7486ca7a1cdd74b762e", "permalink": "https://www.virustotal.com/file/d690e4c35df8b12b2853665ad58e7b024bfdaa1dc300e7486ca7a1cdd74b762e/analysis/1495910015/", "md5": "6d03ce83166a96ced3fc6b9667737f2e", "verbose_msg": "Scan request successfully queued, come back later for the report"}' host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", key)] file_to_send = open(apkFilePath, "rb").read() files = [("file", apkFilePath, file_to_send)] jsondata = postfile.post_multipart(host, selector, fields, files) return jsondata
def scan(file_path, md5): if read_res(md5): return True file_size = os.path.getsize(file_path) if file_size > SIZE*1024*1024: logger.error("File too large.") return False file_to_send = open(file_path, "rb").read() files = [("file", "test", file_to_send)] res = postfile.post_multipart(HOST, SELECTOR, FIELDS, files) logger.info(res) try: res = json.loads(res) except Exception, e: logger.error(e) return False
def mal_sender(sfile): """send specified file to VirusTotal's server""" global myapi myapi = "ENTER YOUR VIRUS TOTAL\'s API" host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", "%s" % myapi)] file_to_send = open(sfile, "rb").read() files = [("file", sfile, file_to_send)] json = postfile.post_multipart(host, selector, fields, files) sha1_hash = ((json[json.find('sha1'):json.find('sha1') + \ 49]).lstrip('sha1\": \"')).rstrip('\"') print 'UPLOADED: %s : %s' % (sfile, time.ctime(time.time())) print 'SCANNING: %s : %s' % (sfile, time.ctime(time.time())) mal_recv_report(sfile, sha1_hash) global cnt cnt += 1
def submit_file(self): host = "www.virustotal.com" selector = "http://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", self.api_key)] file_to_send = open(self.path, "rb").read() files = [("file", self.path, file_to_send)] json_out = postfile.post_multipart(host, selector, fields, files) json_out = json.loads(json_out) response = json_out["response_code"] msg = json_out["verbose_msg"] if(response != 1): return_json = {"code":0,"val":msg} return return_json elif(response == 1): return_json = {"code":1,"val":msg,"scan_id":json_out["scan_id"]} return return_json
def sendto_virustotal(filepath, configuration): """Send file to Virustotal.""" host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", configuration.get('virustotal', 'apikey'))] if ARGS.verbose: print_time_message("Sending to virustotal:" + filepath) file_to_send = open(filepath, "rb").read() files = [("file", filepath, file_to_send)] tries = 0 error_message = str("") while tries < 10: tries += 1 try: reply = postfile.post_multipart(host, selector, fields, files) return reply except Exception as error: # pylint: disable=broad-except sleep(random.random()*100) error_message = str(error) raise SendtoVirustotal("Failed to send file to Virustotal.\n" + \ "reply:\n" + reply + "\n\n" + \ "Last exception:\n" + error_message)
def ScanFile(fname): try: host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", apikey)] file_to_send = open(fname, "rb").read() files = [("file", fname, file_to_send)] r = postfile.post_multipart(host, selector, fields, files) jsondict = json.loads(r) print "-----------------------INFO------------------------------------" print "File: " + os.path.abspath(fname) print "md5: " + jsondict['md5'] print "Link: " + jsondict['permalink'] print "Status: " + jsondict['verbose_msg'] except Exception, e: if "204" in str(e): print "[-] Exceed the public API request rate limit.\n" return else: print "[-] " + str(e) + "\n" return
def send(self, filePath): self.clean() fileSize = os.path.getsize(filePath) if fileSize > self.fileSize: return self.ADSE_ERR_TOOBIG fields = [('apikey', self.apiKey)] fileData = open(filePath, 'rb').read() sendData = [('file', 'sample.apk', fileData)] sendResponse = postfile.post_multipart( self.host, self.url, fields, sendData) sendResult = json.loads(sendResponse) responseCode = sendResult['response_code'] if responseCode <= 0: return self.ADSE_ERR_API elif responseCode == 1: self.report = sendResult return self.ADSE_OK return self.ADSE_ERR_UNKNOWN
class virustotal(object): def __init__(self, username='******'): self._key = base64.b64decode(APIKEY).split('+')[0] self._username = base64.b64decode(APIKEY).split('+')[-1] self._host = "www.virustotal.com" self._fields = [("apikey", self._key)] if self._username != username: raise Exception("Wrong Username") def _upload_check_file(self, _file): _file = os.path.basename(_file) try: __file = open(_file, 'rb').read() except Exception, reason: print "上传文件错误" return None _file_struct = [("file", _file, __file)] try: _json = postfile.post_multipart( self._host, "https://www.virustotal.com/vtapi/v2/file/scan", self._fields, _file_struct) except Exception, reason: print "获取文件报告错误" return None
selector = "https://www.virusbook.cn/api/v1/file/scan" fields = [("apikey", "填写自己的apikey")] with open('samples-malware.txt', 'r') as f: list1 = [i.strip() for i in f.readlines()] with open('samples-normal.txt', 'r') as f: list2 = [i.strip() for i in f.readlines()] myfile = open('out.txt', 'w') for i in list1: filename = 'samples-malware\\' + i file_content = open(filename, "rb").read() files = [("file", filename, file_content)] json_string = postfile.post_multipart(host, selector, fields, files) mydict = json.loads(json_string) myfile.write(mydict["permalink"]) myfile.write(' ' + i) myfile.write('\n') time.sleep(13) for i in list2: filename = 'samples-normal\\' + i file_content = open(filename, "rb").read() files = [("file", filename, file_content)] json_string = postfile.post_multipart(host, selector, fields, files) mydict = json.loads(json_string) myfile.write(mydict["permalink"]) myfile.write(' ' + i) myfile.write('\n')
import simplejson import postfile file = "/home/brandon/Desktop/pascoe.pdf" fields = [("key", "123456")] host = "127.0.0.1" url = "http://127.0.0.1/mop_rest/api/submit" file_to_send = open(file,"rb").read() files = [("file",file,file_to_send)] json = postfile.post_multipart(host,url,fields,files) print json
def searchvirustotal(dirname): filenames = os.listdir(dirname) workbook = xlwt.Workbook() ##엑셀파일 생성 t = 1 for filename in filenames: t = t + 1 full_filename = os.path.join(dirname, filename) k = unicode(full_filename) filepath = k file_to_send = open(filepath.encode('cp949'), 'rb').read() ##파일 보내는부분 files = [('file', filepath.encode('cp949'), file_to_send)] q = filepath.find("\\") ##파일 이름 print full_filename data = postfile.post_multipart(HOST, SCAN_URL, fields, files) data = ast.literal_eval(data) resource = data['resource'] params = {'apikey': VT_KEY, 'resource': resource} headers = { "Accept-Encoding": "gzip, deflate", "User-Agent": "gzip, My Python requests library example client or username" } response = requests.get( 'https://www.virustotal.com/vtapi/v2/file/report', ##받는부분 params=params, headers=headers) json_response = response.json() time.sleep(15) workbook.default_style.font.heignt = 20 * 11 xlwt.add_palette_colour("lightgray", 0x21) workbook.set_colour_RGB(0x21, 216, 216, 216) xlwt.add_palette_colour("lightgreen", 0x22) workbook.set_colour_RGB(0x22, 216, 228, 188) worksheet = workbook.add_sheet(filepath[q + 1:]) col_width_1 = 256 * 30 col_width_2 = 256 * 21 col_width_3 = 256 * 13 worksheet.col(0).width = col_width_3 worksheet.col(1).width = col_width_2 worksheet.col(2).width = col_width_2 worksheet.col(3).width = col_width_1 list_style = "font:height 180,bold on; pattern: pattern solid, fore_color lightgray; align: wrap on, vert centre, horiz center" worksheet.write_merge(0, 0, 0, 3, full_filename, xlwt.easyxf(list_style)) worksheet.write(1, 0, "sha256", xlwt.easyxf(list_style)) worksheet.write_merge(1, 1, 1, 3, json_response['sha256']) worksheet.write(2, 0, "Vaccine", xlwt.easyxf(list_style)) worksheet.write(2, 1, "Version", xlwt.easyxf(list_style)) worksheet.write(2, 2, "Update", xlwt.easyxf(list_style)) worksheet.write(2, 3, "Detect", xlwt.easyxf(list_style)) i = 3 ##시트 넘버를위한 변수 for h in json_response['scans']: ##시트에 입력하는 부분 type = str(h) worksheet.write(i, 0, h) worksheet.write(i, 1, json_response['scans'][str(type)]['version']) worksheet.write(i, 2, json_response['scans'][str(type)]['update']) if str(json_response['scans'][str(type)]['detected']) == 'True': worksheet.write(i, 3, json_response['scans'][str(type)]['result']) else: worksheet.write(i, 3, json_response['scans'][str(type)]['detected']) i = i + 1 workbook.save(str(strftime("%y-%m-%d_%H(h)_%M(m)_%S(s).xls", localtime()))) ##저장
def scan(file_path, md5): try: file_to_send = open(file_path, "rb").read() except Exception, e: logger.error(str(e)) return False files = [("file", "test", file_to_send)] retry_time = 3 count = 0 step = 5 while count < retry_time: count += 1 try: res = postfile.post_multipart(HOST, SELECTOR, FIELDS, files) logger.info("scan response: {0} --> {1}".format(md5, res)) return res except Exception, e: logger.error("upload fail: {0}".format(file_path)) logger.error(str(e)) logger.info("would retry after {0}s ...".format(count*step)) time.sleep(count*step) continue return False def set_file_scan_status(md5, status): db = mongodb.connect_readwrite() if not db: logger.critical("DB error, exit.")
#선언부 path_dir = ss file_list = os.listdir(path_dir) arr = file_list #파일 경로 설정 workbook = xlwt.Workbook(encoding='utf-8') for i in range (len(arr)): filename = arr[i] print filename + u"파일을 검사합니다" File_to_send = open(arr[i],'rb').read() files = [("file", arr[i], File_to_send)] file_send = postfile.post_multipart(host, selector, fields, files) dict_data = simplejson.loads(file_send) resource = dict_data.get("resource", {}) parameters = {"resource": resource, "apikey": "5ad70c8065f80b022e92e73f6643778b94b80edc9bcfab019d1a3dcd83590177"} data = urllib.urlencode(parameters) req = urllib2.Request(url, data) response = urllib2.urlopen(req) resource_data = response.read() result = simplejson.loads(resource_data) spray = result['scans'] #데이터 처리 ############################### 엑셀 처리 부분 ####################################
def get_report(resource, filename, dl_url='unknown', protocol=None, origin=None): apikey = config().get('virustotal', 'apikey') url = "https://www.virustotal.com/vtapi/v2/file/report" parameters = {"resource": resource, "apikey": apikey} data = urllib.urlencode(parameters) req = urllib2.Request(url, data) response = urllib2.urlopen(req) json = response.read() j = simplejson.loads(json) if j['response_code'] == 1: # file known cfg = config() args = {'shasum': resource, 'url': dl_url, 'permalink': j['permalink']} # we don't use dispatcher, so this check is needed if cfg.has_section('database_mysql'): mysql_logger = cowrie.dblog.mysql.DBLogger(cfg) mysql_logger.handleVirustotal(args) args_scan = {'shasum': resource, 'json': json} mysql_logger.handleVirustotalScan(args_scan) if origin == 'db': # we don't use dispatcher, so this check is needed if cfg.has_section('database_textlog'): text_logger = cowrie.dblog.textlog.DBLogger(cfg) text_logger.handleVirustotalLog('log_from database', args) else: msg = 'Virustotal report of %s [%s] at %s' % \ (resource, dl_url, j['permalink']) # we need to print msg, because logs from SFTP are dispatched this way print msg if protocol: protocol.logDispatch(msg) elif j['response_code'] == 0: # file not known if origin == 'db': return j['response_code'] msg = 'Virustotal not known, response code: %s' % (j['response_code']) print msg host = "www.virustotal.com" url = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey", apikey)] filepath = "dl/%s" % resource file_to_send = open(filepath, "rb").read() files = [("file", filename, file_to_send)] json = postfile.post_multipart(host, url, fields, files) print json msg = 'insert to Virustotal backlog %s [%s]' % \ (resource, dl_url) print msg virustotal_backlogs.insert(resource, dl_url) else: msg = 'Virustotal not known, response code: %s' % (j['response_code']) print msg return j['response_code']
#generate file path day be day now=datetime.now(); day=str(now.day-1); if (len(day)==1): day='0'+day; mon=str(now.month); if (len(mon)==1): mon='0'+mon; dirName=str(now.year)+"-"+mon+"-"+day MAL_DIR = '/root/JS_repository/'+dirName APIKEY="659fd24c11e839f866f32b0dfa37887e91d6713439505e717541595252d3c47f" dirs=os.listdir(MAL_DIR) #send malicious html found by MALTRIEVE to VIRUSTOTAL to scan for f in dirs: myFile = MAL_DIR+"/"+f host = "www.virustotal.com" selector = "https://www.virustotal.com/vtapi/v2/file/scan" fields = [("apikey",APIKEY)] # file_to_send=open('test.txt','rb').read() file_to_send = open(myFile,'rb').read() files = [("file",f,file_to_send)] #print file_to_send json = postfile.post_multipart(host,selector,fields,files) #print json
import urllib import urllib2 import json VT_KEY = 'cc9bd463018a4de98c4652c7c433a04b0fa91a8196057db03b0009a515046de7' HOST = 'www.virustotal.com' SCAN_URL = 'https://www.virustotal.com/vtapi/v2/file/scan' REPORT_URL = 'https://www.virustotal.com/vtapi/v2/file/report' ## 파일 검사 FILE_PATH = 'D:/Cyphers/CyphersLauncher.exe' fields = [('apikey', VT_KEY)] file_to_send = open(FILE_PATH, 'rb').read() files = [('file', FILE_PATH, file_to_send)] data = postfile.post_multipart(HOST, SCAN_URL, fields, files) # 문자열을 해당 데이터 타입으로 변경 (여기에서는 딕셔너리로 변경') data = ast.literal_eval(data) resource = data['resource'] ## 결과 출력 parameters = {'resource': resource, 'apikey': VT_KEY} data = urllib.urlencode(parameters) req = urllib2.Request(REPORT_URL, data) response = urllib2.urlopen(req) data = response.read() data = json.loads(data) scan = data.get('scans', {})
def submit_file(self,file): fields = [("apikey", self.api_key)] file2send = open(file, "rb").read() files = [("file", file, file2send)] json = postfile.post_multipart(self.url_vt, self.url_scanfile, fields, files) return json