Advertisement
dberube4

PyInject - Final

Aug 20th, 2012
437
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 29.16 KB | None | 0 0
  1. from ctypes import *
  2. from PyQt4 import QtCore,QtGui
  3. import sys,time,pickle
  4.  
  5. #Shortening names
  6. button = QtGui.QPushButton
  7. label = QtGui.QLabel
  8. textbox = QtGui.QLineEdit
  9. checkbox = QtGui.QCheckBox
  10. listbox = QtGui.QListWidget
  11. combobox = QtGui.QComboBox
  12.  
  13. #This function roughly equals "process.GetProcessesByName(name)" (in vb) translated into python. It return the procees handle and the procees pid (handle,PID).
  14. #It only work for 32 bits process!
  15. #For more informations see : http://msdn.microsoft.com/en-us/library/windows/desktop/ms684320%28v=vs.85%29.aspx
  16. def openByName(access,handle,name):
  17.         kernel32 = windll.kernel32
  18.         psapi = windll.psapi
  19.         arr = c_ulong * 256
  20.         lpidProcess = arr()
  21.         cbNeeded = c_ulong()
  22.         hModule = c_ulong()
  23.         count =  c_ulong()
  24.         modname = c_buffer(30)
  25.        
  26.         psapi.EnumProcesses(byref(lpidProcess),sizeof(lpidProcess),byref(cbNeeded))
  27.        
  28.         for pid in lpidProcess:
  29.             hProcess = kernel32.OpenProcess(0x0400|0x0010,False, pid)
  30.            
  31.             if hProcess:
  32.                 psapi.EnumProcessModules(hProcess, byref(hModule), sizeof(hModule), byref(count))
  33.                 psapi.GetModuleBaseNameA(hProcess, hModule.value, modname, sizeof(modname))
  34.                 a = ''
  35.                 for i in modname:
  36.                     if i != b'\x00':
  37.                         a += str(i)
  38.                        
  39.                 if a != name:
  40.                     for i in range(modname._length_):
  41.                         modname[i]=b'\x00'
  42.                     kernel32.CloseHandle(hProcess)
  43.                 else:
  44.                     kernel32.CloseHandle(hProcess)
  45.                     handle = kernel32.OpenProcess(access,handle,pid)
  46.                     return handle,pid
  47.                    
  48.         return 0,0
  49.  
  50. #This is the same function as above but edited to return a list of process
  51. def listProcess():
  52.         processList = []
  53.         kernel32 = windll.kernel32
  54.         psapi = windll.psapi
  55.         arr = c_ulong * 256
  56.         lpidProcess = arr()
  57.         cbNeeded = c_ulong()
  58.         hModule = c_ulong()
  59.         count =  c_ulong()
  60.         modname = c_buffer(30)
  61.        
  62.         psapi.EnumProcesses(byref(lpidProcess),sizeof(lpidProcess),byref(cbNeeded))
  63.        
  64.         for pid in lpidProcess:
  65.             hProcess = kernel32.OpenProcess(0x0400|0x0010,False, pid)
  66.            
  67.             if hProcess:
  68.                 psapi.EnumProcessModules(hProcess, byref(hModule), sizeof(hModule), byref(count))
  69.                 psapi.GetModuleBaseNameA(hProcess, hModule.value, modname, sizeof(modname))
  70.                 a = ''
  71.                
  72.                 for i in modname:
  73.                     if i != b'\x00' and i != b'\xd1':
  74.                         a += str(i)
  75.                        
  76.                 processList.append(a)
  77.                
  78.                 for i in range(modname._length_):
  79.                     modname[i]=b'\x00'
  80.                
  81.                 kernel32.CloseHandle(hProcess)
  82.        
  83.         #last check, 2 loop because 1 is not enough:
  84.         for i in range (10):
  85.             for i in processList:
  86.                 if not '.exe' in i:
  87.                     processList.remove(i)
  88.         return processList
  89.  
  90. class injectorCore(QtCore.QThread):# !!! ACTUAL INJECTOR CODE IS IN HERE !!!
  91.        
  92.         def __init__(self,name,Dict):
  93.                 super(injectorCore,self).__init__()
  94.                 self.name = name
  95.                 self.Dict = Dict
  96.         def run(self):
  97.                 self.inject()
  98.         def inject(self):
  99.                 self.errorlog = ''
  100.                
  101.                 for path,calls in self.Dict.items():
  102.                         #Check is dll path is valid
  103.                         try:
  104.                             open(path,'rb')
  105.                             valid = True
  106.                         except:
  107.                             self.errorlog += "ERROR : Could not inject {0}, Reason: The file does not exist/ Can't access file.\n".format(path)
  108.                             valid = False
  109.                        
  110.                         if valid == True:
  111.                                 #Try to open a process
  112.                                 hprocess,pid = openByName(0x0400|0x0010|0x0020|0x0008|0x0002,0,self.name)
  113.                                 if hprocess == 0 and gui.injectAtStartup == 0:
  114.                                     gui.statusBar().showMessage('Could not find process, aborting.')
  115.                                     gui.injectBtn.setText('Inject!')
  116.                                     self.terminate()
  117.                                     return 0
  118.                                 elif hprocess == 0 and gui.injectAtStartup == 2:
  119.                                     while hprocess == 0:
  120.                                         gui.statusBar().showMessage('Waiting for {0}'.format(self.name))
  121.                                         hprocess,pid = openByName(0x0400|0x0010|0x0020|0x0008|0x0002,0,self.name)
  122.                                         time.sleep(0.1) #Not to overload cpu
  123.                                
  124.                                 kernel32 = windll.Kernel32 #Kernel 32 dll
  125.                                 kernel32 = windll.LoadLibrary('C:\Windows\System32\kernel32.dll')
  126.                                 null = c_int(0) #A c null
  127.                                 LEN_DLL = len(path)+1 # Get the length of the DLL PATH
  128.                                
  129.                                 #Get the address of loadlibrary function
  130.                                 module = kernel32.GetModuleHandleA("kernel32.dll")
  131.                                 lib_addr = kernel32.GetProcAddress( module,"LoadLibraryA")
  132.                                
  133.                                 # get some read/writable mem in target proc so target can read some data we give it
  134.                                 str_addr = kernel32.VirtualAllocEx ( hprocess,null,c_long(LEN_DLL),0x00001000|0x00002000,4 )
  135.                        
  136.                                 # write the dllname we want to run to the remote memory
  137.                                 kernel32.WriteProcessMemory (hprocess , str_addr ,path , c_long(LEN_DLL) , null)
  138.                                
  139.                                 #Creating Remote Thread to load our DLL
  140.                                 thread = kernel32.CreateRemoteThread ( hprocess ,null,null ,
  141.                                                                        c_long( lib_addr ) ,c_long( str_addr) , null,null)
  142.                                
  143.                                 time.sleep(0.1) #To ensure that everything is correct
  144.                                
  145.                                 if thread == 0:
  146.                                     self.errorlog += "ERROR : Could not inject {0}, Reason: UNKNOW (64 bit process?).\n".format(path)
  147.                                 else:
  148.                                     self.errorlog += "SUCCESS : {0} Injected\n".format(path)
  149.                                    
  150.                                     for a,b in calls.items():  #Function calling
  151.                                         #{'DLL NAME':{'FuncCall1':['NAME','Parameter','Iteration','Type']},'FuncCall2':['NAME','Parameter','Iteration','Type'],etc}
  152.                                         self.callFunction(hprocess,thread,b[0],b[1],b[2],b[3],path)            
  153.                                        
  154.                                
  155.                 open('info.log','w').write(self.errorlog)
  156.                 if 'ERROR' in open('info.log','r').read() and gui.closeAfterInject != 2:
  157.                         gui.statusBar().showMessage('Some error occurred while injecting, see info.log.')
  158.                 elif not 'ERROR' in open('info.log','r').read() and gui.closeAfterInject != 2:
  159.                         gui.statusBar().showMessage('Injection successfull.')
  160.                
  161.                 gui.injectBtn.setText('Inject!')
  162.                
  163.                 #Close the injector if needed.
  164.                 if gui.closeAfterInject == 2:
  165.                     gui.processListWindow.hide() #The user might be an idiot and still have this window open...
  166.                     gui.funcWindow.hide() #Again...
  167.                     gui.close()
  168.                     self.close()
  169.                    
  170.         def callFunction(self,hprocess,thread,name,arg,it,Type,path): # !!! HERE IS THE CODE USED TO CALL A FUNCTION IN THE DLL !!!
  171.                
  172.                 it = int(it)
  173.                 name = str(name)
  174.                
  175.                 #Value converting
  176.                 try:
  177.                         if Type == 'None':
  178.                             arg = None
  179.                         elif Type == 'String':
  180.                             arg = c_char_p(str(arg))
  181.                         elif Type == 'Integer':
  182.                             arg = c_int( int(arg) )
  183.                         elif Type == 'Float':
  184.                             arg = c_float( float(arg) )
  185.                         elif Type == 'Double':
  186.                             arg = c_double( float(arg) )
  187.                         elif Type == 'Boolean':
  188.                             arg = c_bool(bool(arg))
  189.                 except :
  190.                         self.errorlog += "     ERROR : Could not call {0} using {1} as {2}, Reason: Value could not be converted.\n".format(name,arg,Type)
  191.                         return 0
  192.                
  193.                 kernel32 = windll.Kernel32 #Kernel 32 dll
  194.                 null = c_int(0) #A c null
  195.                 exitcode = c_int()
  196.                
  197.                 a = kernel32.GetExitCodeThread( thread,byref(exitcode))
  198.                 findoff =  kernel32.LoadLibraryA(path)
  199.                 modfunc = kernel32.GetProcAddress ( findoff, name  )
  200.                 if modfunc == 0:
  201.                         self.errorlog += "    ERROR : Could not call {0} using {1} as {2}, Reason: This function do not exist.\n".format(name,arg,Type)
  202.                         return 0
  203.                
  204.                 offset = modfunc - findoff
  205.                 exitcode = exitcode.value + offset
  206.        
  207.                 for i in range(it):
  208.                         try:
  209.                              if arg != None:
  210.                                 thread2 = kernel32.CreateRemoteThread ( hprocess ,null,null , # proc , sa, stacksize,
  211.                                                                         c_long( exitcode ) ,arg,null ,null) # start_addr, args, flags,out[ID]
  212.                                 if thread2 == 0:
  213.                                         self.errorlog += "    ERROR : Could not call {0} using {1} as {2}, Reason: Wrong argument.\n".format(name,arg,Type)
  214.                              else:
  215.                                 thread2 = kernel32.CreateRemoteThread ( hprocess ,null,null , # proc , sa, stacksize,
  216.                                                                         c_long( exitcode ) ,null,null ,null) # start_addr, args, flags,out[ID]
  217.                                 if thread2 == 0:
  218.                                         self.errorlog += "    ERROR : Could not call {0} using {1} as {2}, Reason: Wrong argument.\n".format(name,arg,Type)
  219.                         except:
  220.                              self.errorlog += "    ERROR : Could not call {0} using {1} as {2}, Reason: UNKNOW.\n".format(name,arg,Type)
  221.  
  222.  
  223. class InjectorGUI(QtGui.QMainWindow):
  224.    
  225.     def __init__(self):
  226.         super(InjectorGUI,self).__init__() #This line roughly make "self" = QtGui.QMainWindow
  227.        
  228.         #Global variables of the program are inited here
  229.         self.dllPath = {}  #{'DLL NAME':{'FuncCall1':['NAME','Parameter','Iteration','Type']},'FuncCall2':['NAME','Parameter','Iteration','Type'],etc}
  230.         self.processName = ''
  231.         self.injectAtStartup = 0
  232.         self.closeAfterInject = 0
  233.         self.itemSelected = None
  234.        
  235.         #This start the function who init the main window and other windows.
  236.         self.initMain()
  237.         self.initProcessList()
  238.         self.initFuncList()
  239.         self.initDllList()
  240.        
  241.     def initMain(self): #Main window is inited here
  242.        
  243.         def actions(*argv): #Main window actions are handled here (*argv will hold extra data sent by the widget)
  244.             sender = self.sender() #This get the last widget who activated this functions.
  245.                
  246.             if sender == self.getProcessBtn:
  247.                 self.processListWindow.show() # See "def initProcessList(self)"
  248.                
  249.             if sender == self.getDllBtn:
  250.                 self.dllWindow.show()
  251.                
  252.             if sender == self.injectAtStartupCB:
  253.                 self.injectAtStartup = argv[0] #Note: argv[0] is the current Qt.CheckState of the checkbox (0 if unchecked,2 if checked).
  254.                
  255.             if sender == self.closeAfterInjectCB:
  256.                         self.closeAfterInject = argv[0] #Note: argv[0] is the current Qt.CheckState of the checkbox (0 if unchecked,2 if checked).
  257.                
  258.             if sender == self.injectBtn:
  259.                 if sender.text() == 'Inject!':
  260.                         if not '0 dll loaded...' in self.dllTxtBox.text():
  261.                                 sender.setText('Cancel')
  262.                                 self.processName = str(self.processTxtBox.text())
  263.                                 self.core = injectorCore(self.processName,self.dllPath)
  264.                                 self.core.start()
  265.                         else:
  266.                                 resp = QtGui.QMessageBox.critical(self.funcWindow,'Python injector','I think you forgot to add a dll.',QtGui.QMessageBox.Ok)
  267.                 else:
  268.                         gui.statusBar().showMessage('Injection cancelled')
  269.                         sender.setText('Inject!')
  270.                         self.core.terminate()
  271.                         del self.core
  272.        
  273.             if sender == self.saveAction:
  274.                 saveFilename = 'config.dat'
  275.                 data = (self.dllPath,
  276.                         str(self.processTxtBox.text()),
  277.                         int(self.injectAtStartupCB.checkState()),
  278.                         int(self.closeAfterInjectCB.checkState()),
  279.                         str(self.dllTxtBox.text()))
  280.                
  281.                 f = open(saveFilename, 'wb')
  282.                 pickle.dump(data, f) # dump the object to a file
  283.                 f.close()
  284.                
  285.                 QtGui.QMessageBox.information(self.funcWindow,'Python injector','Configuration succesfully saved!',QtGui.QMessageBox.Ok)
  286.                
  287.             if sender == self.loadAction:
  288.                 self.dllListBox.clear()
  289.                 openFilename = 'config.dat'
  290.                 try:
  291.                     f = open(openFilename, 'rb')
  292.                 except:
  293.                     QtGui.QMessageBox.warning(self.funcWindow,'Python injector','No saved configuration found!',QtGui.QMessageBox.Ok)
  294.                     return 0
  295.                 data = pickle.load(f)
  296.                
  297.                 self.processTxtBox.setText(data[1])
  298.                 self.injectAtStartupCB.setCheckState(data[2])
  299.                 self.closeAfterInjectCB.setCheckState(data[3])
  300.                 self.dllTxtBox.setText(data[4])
  301.                 self.dllPath = data[0]
  302.                
  303.                 for a,b in self.dllPath.items():
  304.                     item = QtGui.QListWidgetItem(a);item.content = b
  305.                     self.dllListBox.addItem(item)
  306.                    
  307.                 QtGui.QMessageBox.information(self.funcWindow,'Python injector','Configuration succesfully loaded!',QtGui.QMessageBox.Ok)
  308.        
  309.         def initWidgets(): #Main window widgets are inited here.
  310.                
  311.                 #Note: I only use "self." in the name of the widgets if I need to get their value outside this functions (ex: When executing actions()).
  312.                
  313.                 processLbl = label('Process:',self);processLbl.move(10,45)
  314.                 dllLbl = label('Dll:',self);dllLbl.move(10,85)
  315.                
  316.                 #Menu bar is inited here
  317.                 menubar = self.menuBar()
  318.                 self.saveAction = QtGui.QAction('&Save', self);self.saveAction.triggered.connect(actions)
  319.                 self.loadAction = QtGui.QAction('&Load', self);self.loadAction.triggered.connect(actions)
  320.                 fileMenu = menubar.addMenu('&Option');fileMenu.addAction(self.saveAction);fileMenu.addAction(self.loadAction)
  321.                        
  322.                 self.injectBtn = button('Inject!',self);self.injectBtn.setGeometry(190,135,150,60);self.injectBtn.clicked.connect(actions)
  323.                 self.getProcessBtn = button('...',self);self.getProcessBtn.setGeometry(310,55,30,20);self.getProcessBtn.clicked.connect(actions)
  324.                 self.getDllBtn = button('...',self);self.getDllBtn.setGeometry(310,95,30,20);self.getDllBtn.clicked.connect(actions)
  325.                 self.injectAtStartupCB = checkbox('Inject at startup',self);self.injectAtStartupCB.setGeometry(10,140,160,17);self.injectAtStartupCB.stateChanged.connect(actions)
  326.                 self.injectAtStartupCB.setToolTip('Check this if the process is not yet started')
  327.                 self.closeAfterInjectCB = checkbox('Close after inject',self);self.closeAfterInjectCB.setGeometry(10,170,160,17);self.closeAfterInjectCB.stateChanged.connect(actions)
  328.                 self.processTxtBox = textbox('Process.exe',self);self.processTxtBox.setGeometry(80,45,220,30)
  329.                 self.dllTxtBox = textbox('0 dll loaded...',self);self.dllTxtBox.setGeometry(80,85,220,30);self.dllTxtBox.setFont(self.smallFont)#Note : fonts are defined in style script.
  330.                 self.dllTxtBox.setEnabled(False)
  331.        
  332.         try:
  333.             exec(open('QNovaDark.py').read()) in locals(),globals() #This line execute a python file who set the palette (style) and the fonts of the application.
  334.         except:
  335.             QtGui.QMessageBox.warning(self,'Python injector','Cannot find style script... too bad for you.',QtGui.QMessageBox.Ok)
  336.             self.font = QtGui.QFont('MS Shell Dlg 2',pointSize = 13)
  337.             self.smallFont = QtGui.QFont('MS Shell Dlg 2',pointSize = 9)
  338.         #The main window properties are inited here
  339.         self.setFixedSize(350,225)
  340.         self.setFont(self.font) #Note font are defined in style script
  341.         self.setWindowTitle('PyInject - Python injector')
  342.         self.setWindowFlags(QtCore.Qt.CustomizeWindowHint|QtCore.Qt.WindowCloseButtonHint)
  343.         self.statusBar().showMessage('Ready')
  344.         initWidgets()
  345.         self.show()
  346.  
  347.     def initProcessList(self): #Another window
  348.        
  349.         def actions(*argv): #Main window actions are handled here (*argv will hold extra data sent by the widget)
  350.             sender = self.sender() #This get the last widget who activated this functions.
  351.            
  352.             if sender == self.chooseProcess:
  353.                 try: #Catch the error when the user click done but has selected nothing.
  354.                         self.processTxtBox.setText(self.processList.item(self.processList.currentRow()).text())
  355.                 except AttributeError:
  356.                         pass
  357.                 self.processListWindow.hide()
  358.                
  359.             if sender == self.refreshBtn:
  360.                 self.processList.clear()
  361.                 self.processList.addItems(listProcess())
  362.                
  363.         def initWidgets(wind):#Main window widgets are inited here.
  364.             self.processList = listbox(wind);self.processList.setGeometry(5,5,190,210);self.processList.setFont(self.smallFont) #Note : fonts are defined in style script.
  365.             self.chooseProcess = button('Done',wind);self.chooseProcess.setGeometry(5,217,90,30);self.chooseProcess.clicked.connect(actions)
  366.             self.refreshBtn = button('Refresh',wind);self.refreshBtn.setGeometry(105,217,90,30);self.refreshBtn.clicked.connect(actions)
  367.  
  368.  
  369.         #Adding a child window to the main window. THE NEW WIDGET MUST NOT BE PARENTED!!!!!
  370.         self.processListWindow = QtGui.QWidget()
  371.         self.processListWindow.setWindowTitle('Choose a process')
  372.         self.processListWindow.setFixedSize(200,250)
  373.         self.processListWindow.setWindowFlags(QtCore.Qt.CustomizeWindowHint|QtCore.Qt.WindowCloseButtonHint)
  374.         #self.processListWindow.show() is omitted because this window must be hidden when the program starts.
  375.         initWidgets(self.processListWindow)
  376.  
  377.     def initFuncList(self):#Another window
  378.        
  379.         def actions(*argv):
  380.             sender = self.sender()
  381.                
  382.             if sender == self.addBtn: #Add a call to the list
  383.                 def getID(less = False): #Create an ID for the next call
  384.                     num = 0;ID = 'func{0}'
  385.                     while self.funcCallList.findItems(ID.format(num),QtCore.Qt.MatchStartsWith) != []:
  386.                         num += 1
  387.                     return(ID.format(num))
  388.                 def check(a,b,c): #Simple check to see if the item is already here
  389.                     for i in range(self.funcCallList.count()):
  390.                         text = self.funcCallList.item(i).text().split('::')
  391.                         if text[1] == a and text[2] == b and text[4] == c:
  392.                                 return self.funcCallList.item(i),text[0],text[4]
  393.                     return False,False,False
  394.                
  395.                 ID = getID() #Get the last Id to protect against data overwrithing        
  396.                 if self.funcName.text() != '' and self.funcArg.text() != '':
  397.                     check,i,i2 = check(self.funcName.text(),self.funcArg.text(),self.argType.currentText())
  398.                     if check == False:
  399.                         self.funcCallList.addItem('{0}::{1}::{2}::1::{3}'.format(ID,self.funcName.text(),self.funcArg.text(),self.argType.currentText()))
  400.                         self.funcCallList.sortItems()
  401.                     else:
  402.                         num = int(str(check.text()).split('::')[3])+1
  403.                         check.setText('{0}::{1}::{2}::{3}::{4}'.format(i,self.funcName.text(),self.funcArg.text(),num,i2))
  404.                    
  405.                 else:
  406.                     QtGui.QMessageBox.warning(self.funcWindow,'Python injector','The function need a title and 1 argument.',QtGui.QMessageBox.Ok)
  407.                    
  408.             if sender == self.remBtn: #Remove a call from the list
  409.                 if self.funcCallList.currentRow() != -1:
  410.                     self.funcCallList.takeItem(self.funcCallList.currentRow())
  411.                 else:
  412.                     QtGui.QMessageBox.warning(self.funcWindow,'Python injector','Select a function first!',QtGui.QMessageBox.Ok)    
  413.            
  414.             if sender == self.clrBtn: #Clear all call from the list
  415.                 resp = QtGui.QMessageBox.warning(self.funcWindow,'Python injector','Do you really want to remove all items in the list?',QtGui.QMessageBox.Yes|QtGui.QMessageBox.No)
  416.                 if resp == QtGui.QMessageBox.Yes:
  417.                     self.funcCallList.clear()
  418.            
  419.             if sender == self.okBtn: #Save the calls to the item
  420.                 self.funcCall = {}
  421.                 for i in range(self.funcCallList.count()):
  422.                     text = self.funcCallList.item(i).text().split('::')
  423.                     self.itemSelected.content[str(text[0])] = [str(text[1]),str(text[2]),str(text[3]),str(text[4])]
  424.                 QtGui.QMessageBox.information(self.funcWindow,'Python injector','{0} functions call were added.'.format(self.funcCallList.count()),QtGui.QMessageBox.Ok)
  425.                 self.funcWindow.hide()
  426.        
  427.         def initWidgets(wind):
  428.                
  429.             self.funcName = textbox('Function name here',wind);self.funcName.setGeometry(10,10,200,25)
  430.             self.funcArg = textbox('Function argument',wind);self.funcArg.setGeometry(220,10,130,25)
  431.             self.argType = combobox(wind);self.argType.setGeometry(355,10,80,25);self.argType.addItems(['None','Integer','Boolean','Float','Double','String'])
  432.             self.addBtn = button('Add',wind);self.addBtn.setGeometry(345,160,100,25);self.addBtn.clicked.connect(actions)
  433.             self.remBtn = button('Remove',wind);self.remBtn.setGeometry(235,160,100,25);self.remBtn.clicked.connect(actions)
  434.             self.clrBtn = button('Clear',wind);self.clrBtn.setGeometry(125,160,100,25);self.clrBtn.clicked.connect(actions)
  435.             self.okBtn = button('OK',wind);self.okBtn.setGeometry(15,160,100,25);self.okBtn.clicked.connect(actions)
  436.             self.funcCallList = listbox(wind);self.funcCallList.setGeometry(10,45,430,108);self.funcCallList.setSortingEnabled(True)
  437.             self.funcCallList.setToolTip("Functions call are represented here\n ([ID]::[Function name]::[Argument]::[Time to call]:[Data Type]) .")
  438.  
  439.         #Adding a child window to the main window. THE NEW WIDGET MUST NOT BE PARENTED!!!!!
  440.         self.funcWindow = QtGui.QWidget()
  441.         self.funcWindow.setFont(self.smallFont)
  442.         self.funcWindow.setWindowTitle('Functions to call')
  443.         self.funcWindow.setFixedSize(450,190)
  444.         self.funcWindow.setWindowFlags(QtCore.Qt.CustomizeWindowHint|QtCore.Qt.WindowCloseButtonHint)
  445.         #self.funcWindow.show() is omitted because this window must be hidden when the program starts.
  446.         initWidgets(self.funcWindow)
  447.  
  448.     def initDllList(self): #Another window
  449.         def actions():
  450.             sender = self.sender()
  451.            
  452.             if sender == self.addDllBtn:#Add a new item and append "content" to it (to contain func call)
  453.                 response = QtGui.QFileDialog.getOpenFileName(self.dllWindow,'Choose a dll',filter = '*.dll')
  454.                 if response != '' and self.dllListBox.findItems(response,QtCore.Qt.MatchExactly) == [] :
  455.                         item = QtGui.QListWidgetItem(response);item.content = {}
  456.                         self.dllListBox.addItem(item)
  457.                 else:
  458.                     QtGui.QMessageBox.warning(self.dllWindow,'Python injector','This dll is already in the list!',QtGui.QMessageBox.Ok)
  459.            
  460.             if sender == self.remDllBtn: #Simply remove an item from the list
  461.                 selected = self.dllListBox.currentRow()
  462.                 if selected != -1:
  463.                      self.dllListBox.takeItem(selected)
  464.                 else:
  465.                      QtGui.QMessageBox.warning(self.dllWindow,'Python injector','No dll selected.',QtGui.QMessageBox.Ok)
  466.            
  467.             if sender == self.manageCallBtn: #Open the manage call window with the information contained in item.content
  468.                 selected = self.dllListBox.currentRow()
  469.                 if selected != -1:
  470.                     self.itemSelected = self.dllListBox.item(selected)
  471.                     self.funcCallList.clear()
  472.                     for i,c in self.itemSelected.content.items():
  473.                         self.funcCallList.addItem('{0}::{1}::{2}::{3}::{4}'.format(i,c[0],c[1],c[2],c[3]))
  474.                     self.funcWindow.show()
  475.                 else:
  476.                     QtGui.QMessageBox.warning(self.dllWindow,'Python injector','No dll selected.',QtGui.QMessageBox.Ok)  
  477.        
  478.             if sender == self.doneBtn: #Save dll informations into self.dllPath
  479.                 for i in range(self.dllListBox.count()):
  480.                     item = self.dllListBox.item(i)
  481.                     name,content = item.text(),item.content
  482.                     self.dllPath[str(name)] = content
  483.                     self.dllWindow.hide()
  484.                 self.dllTxtBox.setText('{0} dll loaded.'.format(self.dllListBox.count()))
  485.        
  486.         def initWidgets(wind):
  487.                
  488.                 self.dllListBox = listbox(wind);self.dllListBox.setGeometry(10,10,300,240)
  489.                 self.addDllBtn = button('Add dll',wind);self.addDllBtn.setGeometry(320,10,90,40);self.addDllBtn.clicked.connect(actions)
  490.                 self.remDllBtn = button('Remove dll',wind);self.remDllBtn.setGeometry(320,60,90,40);self.remDllBtn.clicked.connect(actions)
  491.                 self.manageCallBtn = button('Manage\nCalls',wind);self.manageCallBtn.setGeometry(320,110,90,40);self.manageCallBtn.clicked.connect(actions)
  492.                 self.doneBtn = button('Done',wind);self.doneBtn.setGeometry(320,210,90,40);self.doneBtn.clicked.connect(actions)
  493.        
  494.         self.dllWindow = QtGui.QWidget()
  495.         self.dllWindow.setFont(self.smallFont)
  496.         self.dllWindow.setWindowTitle('Dll List')
  497.         self.dllWindow.setFixedSize(420,260)
  498.         self.dllWindow.setWindowFlags(QtCore.Qt.CustomizeWindowHint|QtCore.Qt.WindowCloseButtonHint)
  499.         #self.funcWindow.show() is omitted because this window must be hidden when the program starts.
  500.         initWidgets(self.dllWindow)
  501.  
  502.     def displayMessageBox(self,title,text,Type):
  503.         if Type == 0:
  504.                 QtGui.QMessageBox.information(self,title,text,QtGui.QMessageBox.Ok)
  505.         elif Type == 1:
  506.                QtGui.QMessageBox.warning(self,title,text,QtGui.QMessageBox.Ok)
  507.         elif Type == 2:
  508.                QtGui.QMessageBox.critical(self,title,text,QtGui.QMessageBox.Ok)
  509.  
  510.     def closeEvent(self,event): #Script to execute when program is closing.
  511.         self.dllWindow.hide()
  512.         self.funcWindow.hide()
  513.         self.processListWindow.hide()
  514.  
  515. if __name__ == '__main__':
  516.     global app,gui
  517.     app = QtGui.QApplication(sys.argv)
  518.     gui = InjectorGUI()
  519.     sys.exit(app.exec_())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement