import json
import time
import sys, traceback
import os
import yaml
import re
from random import shuffle


from dakd_vt import VirusTotalAPI



def initConf():
    """
        every plugin uses its own config file
    """
    return yaml.load(open(os.path.abspath('./dakd/plugins/dakd_cuckoo.conf'),'r'))

conf = initConf()

def vt_label(scan):

	report={'virustotal' :scan}
	try:
		#print("virustotal analysis ")
		#print(report['virustotal']['summary']['positives'])


		if int(report['virustotal']['summary'] ['positives'])>0:
			#somehow extract the first or the more recurrent classifications
			# or take a sole antivirus... Symantec, Kaspersky...

			detection = ""
			for av in conf["Antivirus"]:
				try:
					if report['virustotal']['scans'][av]['detected']==True:
						detection = report['virustotal']['scans'][av]['result'].lower()
						#print(av+" : "+detection)
						break
				except:
					pass
					   
			if detection=="":
				for av in report['virustotal']['scans'].keys():
					if report['virustotal']['scans'][av]['detected']==True:
						detection = report['virustotal']['scans'][av]['result'].lower()
						#print(av+" : "+detection)
						break				 

			# from more specificc category to more genèric category, look all acronyms for each
			for cat in conf["categories"]:
			    
				categories = []
				catname = ""
				for k,v in cat.items():
					categories=v
					catname=k

					acronyms = re.split('\.|:|/', detection)
					
					#print("detection acronyms:")
					#print(acronyms)
					#print("categories:")
					#print(catname)
					#print(categories)

					for acronym in acronyms:
						if acronym.lower() in categories:
					    		print("label: " + catname)
					    		return catname
					    	
						for cat in categories:
					    		if acronym.find(cat)>0:
					    			print("label:" +catname)
					    			return catname
					
		elif int(report['virustotal']['summary'] ['positives'])==0:
			print("label: safe" )
			return 'safe'
	
	except Exception as e:
		traceback.print_exc()

	return 'unknown'

data=[]
try:
	data = json.load(open('./lvl4/binaries_labelled.df'))
except:
	data = json.load(open('./lvl4/binaries.df'))

randindexes = [i for i in range(len(data))]
print(randindexes[:10])
shuffle(randindexes)
print(randindexes[:10])

key1="1bd81a4a9c818e2b7cb825444a5ca712bc646d98ce97defd34216e95477a7fbd"
key2="<KEY>"
thekey=key1

count=0
for i in randindexes:
	sample = data[i]
	
	if sample['label'] == "unknown":
		try:
			if count<4:
				thekey=key1
			else:
				thekey=key2
			count+=1
			print("searching vt for "+sample['hash']['md5'])
			scan =VirusTotalAPI(api=thekey,).file_report(sample['hash']['md5'])
		
			#parse
			label = vt_label(scan)

			# write back to data
			sample['label'] = label

			# write data to binaries_labelled.df
			with open('./lvl4/binaries_labelled.df','w+') as outfile:
				json.dump(data,outfile)

		except Exception as e:
			#traceback.print_exc()
			print(" ERROR with "+sample['hash']['md5'])
		time.sleep(10)
		




import json
import time
import sys, traceback
import os
import yaml
import re
from random import shuffle


from dakd_vt import VirusTotalAPI



def initConf():
    """
        every plugin uses its own config file
    """
    return yaml.load(open(os.path.abspath('./dakd/plugins/dakd_cuckoo.conf'),'r'))

conf = initConf()

def vt_label(scan):

	report={'virustotal' :scan}
	try:
		#print("virustotal analysis ")
		#print(report['virustotal']['summary']['positives'])


		if int(report['virustotal']['summary'] ['positives'])>0:
			#somehow extract the first or the more recurrent classifications
			# or take a sole antivirus... Symantec, Kaspersky...

			detection = ""
			for av in conf["Antivirus"]:
				try:
					if report['virustotal']['scans'][av]['detected']==True:
						detection = report['virustotal']['scans'][av]['result'].lower()
						#print(av+" : "+detection)
						break
				except:
					pass
					   
			if detection=="":
				for av in report['virustotal']['scans'].keys():
					if report['virustotal']['scans'][av]['detected']==True:
						detection = report['virustotal']['scans'][av]['result'].lower()
						#print(av+" : "+detection)
						break				 

			# from more specificc category to more genèric category, look all acronyms for each
			for cat in conf["categories"]:
			    
				categories = []
				catname = ""
				for k,v in cat.items():
					categories=v
					catname=k

					acronyms = re.split('\.|:|/', detection)
					
					#print("detection acronyms:")
					#print(acronyms)
					#print("categories:")
					#print(catname)
					#print(categories)

					for acronym in acronyms:
						if acronym.lower() in categories:
					    		print("label: " + catname)
					    		return catname
					    	
						for cat in categories:
					    		if acronym.find(cat)>0:
					    			print("label:" +catname)
					    			return catname
					
		elif int(report['virustotal']['summary'] ['positives'])==0:
			print("label: safe" )
			return 'safe'
	
	except Exception as e:
		traceback.print_exc()

	return 'unknown'

data=[]
try:
	data = json.load(open('./lvl4/binaries_labelled.df'))
except:
	data = json.load(open('./lvl4/binaries.df'))

randindexes = [i for i in range(len(data))]
print(randindexes[:10])
shuffle(randindexes)
print(randindexes[:10])

key1="1bd81a4a9c818e2b7cb825444a5ca712bc646d98ce97defd34216e95477a7fbd"
key2="<KEY>"
thekey=key1

count=0
for i in randindexes:
	sample = data[i]
	
	if sample['label'] == "unknown":
		try:
			if count<4:
				thekey=key1
			else:
				thekey=key2
			count+=1
			print("searching vt for "+sample['hash']['md5'])
			scan =VirusTotalAPI(api=thekey,).file_report(sample['hash']['md5'])
		
			#parse
			label = vt_label(scan)

			# write back to data
			sample['label'] = label

			# write data to binaries_labelled.df
			with open('./lvl4/binaries_labelled.df','w+') as outfile:
				json.dump(data,outfile)

		except Exception as e:
			#traceback.print_exc()
			print(" ERROR with "+sample['hash']['md5'])
		time.sleep(10)
		




every plugin uses its own config file #print("virustotal analysis ") #print(report['virustotal']['summary']['positives']) #somehow extract the first or the more recurrent classifications # or take a sole antivirus... Symantec, Kaspersky... #print(av+" : "+detection) #print(av+" : "+detection) # from more specificc category to more genèric category, look all acronyms for each #print("detection acronyms:") #print(acronyms) #print("categories:") #print(catname) #print(categories) #parse # write back to data # write data to binaries_labelled.df #traceback.print_exc()