import subprocess
import pefile
import hashlib


class InformationExtractor:

    def get_api_sequence_num(self,file):
       log_file = open(file,'r') 
       hook_functions = open('hookedfunction.csv','r')
       funIDs =dict()
       api_seq = list()
       for line in hook_functions:
        fun,mod,ids=line.split(',')
        ids=ids.replace("\n","")
        funIDs[fun]=int(ids)
       for line in log_file:
        lista = line.split(",")
        func=lista[0].split("!")
        if(len(func)>1):
         if(funIDs.get(func[1])!=None):
          api_seq.append(funIDs[func[1]])      
       return api_seq 
                       
        
    def exe_version(self,path):
     pe = pefile.PE(path)
     if(pe.OPTIONAL_HEADER.Magic == 267):
        resualt= 32
     else:
        resualt= 64
     return resualt

    def md5_hashing(self,path):
     file = open(path,'rb')   
     data = file.read()
     file.close()
     return hashlib.md5(data).hexdigest()


    def Get_file_sections(self,path):
     fin=[]
     pe = pefile.PE(path)   
     for section in pe.sections:
      sect = str(section.Name,'utf8')
      tem=[]
      tem.append(sect.rstrip('\x00')) 
      tem.append(section.Misc_VirtualSize)
      tem.append(section.SizeOfRawData)
      tem.append(section.get_hash_md5())
      fin.append(tem)
     return fin 

    

    def CreateProcessAndSuspend(self,spymanager,path):
       process,continueEvent = spymanager.CreateProcess(path, True)
       return process,continueEvent     
       
 
      
    def HookProcess(self,spymanager,path):
       process,con_event = self.CreateProcessAndSuspend(spymanager,path)
       db=spymanager.DbFunctions(32)
       collection= spymanager.CreateHooksCollection()
       hook_functions = open("hookedfunction.csv",'r') 
       for i in hook_functions :
           fun,mod,ids=i.split(',')
           fun= fun.replace(' ',"")
           mod =mod.replace(' ',"")
           check = db.GetByName(fun)
           if(check != None):
               hook=spymanager.CreateHook(mod+"!"+fun,True) 
               collection.Add(hook)

       print("list of hooked function constructed ..")        
       hook_functions.close()  
       collection.Attach(process.Id, True)
       print("attaching finished ..")
       collection.Hook(True)
       print("start logging ... ")       
       spymanager.ResumeProcess(process,con_event)
       return process  
