Example #1
0
        public static ulong GetKernelBase()
        {
            ulong buffer;
            uint  bufferSize = 2048;

            buffer = (ulong)Marshal.AllocHGlobal((int)bufferSize);

            uint status = NT.NtQuerySystemInformation(11 /*SystemModuleInformation*/, buffer, (uint)bufferSize, out bufferSize);

            if (status == 0xC0000004L /*STATUS_INFO_LENGTH_MISMATCH*/)
            {
                Marshal.FreeHGlobal((IntPtr)buffer);
                buffer = (ulong)Marshal.AllocHGlobal((int)bufferSize);

                status = NT.NtQuerySystemInformation(11 /*SystemModuleInformation*/, buffer, (uint)bufferSize, out bufferSize);
            }

            if (status != 0)
            {
                throw new Exception("GetKernelBase Failed");
            }

            NT._RTL_PROCESS_MODULES *modulesPointer = (NT._RTL_PROCESS_MODULES *)buffer;

            return((ulong)modulesPointer->Modules.ImageBase);
        }
Example #2
0
            public rpn_inst(NT v)
            {
                m_cmd = rpn_cmd.PUSH_CONST;


                m_param.val = v;
            }
Example #3
0
        public async Task <IActionResult> Edit(int id, [Bind("Noticiasid,Topicosid")] NT nT)
        {
            if (id != nT.Topicosid)
            {
                return(RedirectToAction("Index"));
            }

            if (ModelState.IsValid)
            {
                try
                {
                    db.Update(nT);
                    await db.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!NTExists(nT.Topicosid))
                    {
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["Noticiasid"] = new SelectList(db.Noticias, "Id", "Id", nT.Noticiasid);
            ViewData["Topicosid"]  = new SelectList(db.Topicos, "Id", "Id", nT.Topicosid);
            return(View(nT));
        }
Example #4
0
 public AST_Logic(SourceLocation loc, NT operation, int memberCount, int count, AST_Node condition, AST_Node a, AST_Node b)
     : base(loc, operation, a, b, true)
 {
     this.memberCount = memberCount;
     this.condition   = condition;
     this.count       = count;
 }
Example #5
0
 public Enclosure(NT t, AST_Node n, SymbolTable s, int e)
 {
     scope = s;
     type  = t;
     node  = n;
     end   = e;
 }
Example #6
0
        public static ulong GetPebAddress(this Process process)
        {
            NT.PROCESS_BASIC_INFORMATION pbi = new NT.PROCESS_BASIC_INFORMATION();
            NT.NtQueryInformationProcess(process.Handle, 0, &pbi, pbi.Size, IntPtr.Zero);

            return(pbi.PebBaseAddress);
        }
Example #7
0
        public static NT.MEMORY_BASIC_INFORMATION VirtualQuery(this Process process, ulong memoryPointer)
        {
            var structSize = (uint)Marshal.SizeOf(typeof(NT.MEMORY_BASIC_INFORMATION));

            NT.VirtualQueryEx(process.Handle, memoryPointer, out NT.MEMORY_BASIC_INFORMATION mem, structSize);
            return(mem);
        }
Example #8
0
        private void IssueClientFrameProcessRequests(Socket inHandler)
        {
            while (true)
            {
                var nextFrameRange = GetNextFrameRange();

                // If there are no more frames to process, exit loop allow connections to be closed
                if (nextFrameRange.Length == 0)
                {
                    // Send frame indices to be processed
                    NT.SendInt(inHandler, 0);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Frames left to process: {nextFrameRange.Length}");
                    Console.ResetColor();
                    break;
                }
                NT.SendIntCollections(inHandler, nextFrameRange);

                // Receive processed frame data
                var processOutput = NT.ReceiveIntCollections(inHandler);

                // Save process output to database
                SaveFrameBlocks(processOutput.collections);
            }
        }
Example #9
0
 public AST_Operation(SourceLocation loc, NT operation, AST_Node a, AST_Node b, bool leftToRight)
     : base(loc, operation)
 {
     this.leftToRight = leftToRight;
     this.a           = a;
     this.b           = b;
 }
Example #10
0
        private void ReceiveFrameProcessRequests(Socket inHandler)
        {
            while (true)
            {
                var frameRangeToProcess = NT.ReceiveIntCollections(inHandler);
                if (frameRangeToProcess.receivedSuccessfully)
                {
                    foreach (var arr in frameRangeToProcess.collections)
                    {
                        _engine.IdentifyDifferences(arr);
                    }
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Frame range to process count: {frameRangeToProcess.collections.Count}");
                    Console.ResetColor();
                    break;
                }

                // Process data for frame range
                var processedData = _engine.GetDifferenceBlocks();

                // Send processed results back to server
                NT.SendIntCollections(inHandler, processedData);
            }
        }
Example #11
0
        public UInt32 MapImage(string imageName, byte[] rawImage)
        {
            Log.LogInfo($"Mapping {imageName}");

            // GET HEADERS
            Tools.GetImageHeaders(rawImage, out NT.IMAGE_DOS_HEADER dosHeader, out NT.IMAGE_FILE_HEADER fileHeader, out NT.IMAGE_OPTIONAL_HEADER64 optionalHeader);

            // CREATE A MEMORY SECTION IN TARGET PROCESS
            UInt32 sectionHandle = (UInt32)TargetProcess.CreateSection(NT.MemoryProtection.ExecuteReadWrite, optionalHeader.SizeOfImage);

            // MAP THE SECTION INTO BOTH OUR OWN AND THE TARGET PROCESS
            // THIS WILL RESULT IN A MIRRORED MEMORY SECTION, WHERE EVERY CHANGE
            // TO THE LOCAL SECTION WILL ALSO CHANGE IN THE TARGET PROCESS
            // AND VICE VERSA
            UInt32 remoteImage = (UInt32)TargetProcess.MapSection(sectionHandle, NT.MemoryProtection.ExecuteReadWrite);
            UInt32 localImage  = (UInt32)Process.GetCurrentProcess().MapSection(sectionHandle, NT.MemoryProtection.ExecuteReadWrite);

            // SAVE MAPPED EXECUTABLES IN A LIST
            // SO WE CAN RECURSIVELY MAP DEPENDENCIES, AND THEIR DEPENDENCIES
            // WITHOUT BEING STUCK IN A LOOP :)
            MappedModules[imageName]   = remoteImage;
            MappedRawImages[imageName] = rawImage;

            // ADD LOADER REFERENCE
            if (imageName == Options.LoaderImagePath)
            {
                if (Options.CreateLoaderReference)
                {
                    AddLoaderEntry(imageName, remoteImage);
                }
            }
            else // ALWAYS CREATE REFERENCE FOR DEPENDENCIES
            {
                AddLoaderEntry(imageName, remoteImage);
            }

            // COPY HEADERS TO SECTION
            Marshal.Copy(rawImage, 0, (IntPtr)localImage, (int)optionalHeader.SizeOfHeaders);

            // DO THE ACTUAL MANUALMAPPING
            this.WriteImageSections(rawImage, dosHeader, localImage, fileHeader.NumberOfSections);
            this.RelocateImageByDelta(localImage, remoteImage, optionalHeader);
            this.FixImportTable(localImage, optionalHeader);

            // NUKE HEADERS
            // TODO: DONT WRITE THEM IN THE FIRST PLACE
            if (Options.EraseHeaders)
            {
                byte[] headerBuffer = new byte[(int)optionalHeader.SizeOfHeaders];
                NTM.RandomEngine.NextBytes(headerBuffer);

                Marshal.Copy(headerBuffer, 0, (IntPtr)localImage, (int)optionalHeader.SizeOfHeaders);
            }

            NT.CloseHandle(sectionHandle);
            Process.GetCurrentProcess().UnmapSection(localImage);

            return(remoteImage);
        }
Example #12
0
        public static void UpdateDynamicData()
        {
            NT._OSVERSIONINFOEXW osvi = new NT._OSVERSIONINFOEXW()
            {
                dwOSVersionInfoSize = (uint)Marshal.SizeOf(typeof(NT._OSVERSIONINFOEXW))
            };
            NT.RtlGetVersion(&osvi);
            g_VersionLong = (osvi.dwMajorVersion << 16) | (osvi.dwMinorVersion << 8) | osvi.wServicePackMajor;

            switch (g_VersionLong)
            {
            case 0x060101 /*win 7*/:
                g_IsWindows7Machine    = true;
                g_OffsetDirectoryTable = 0x028;
                g_OffsetProcessId      = 0x180;
                g_OffsetProcessLinks   = 0x188;
                g_OffsetObjectTable    = 0x200;
                break;

            case 0x060200 /*win 8*/:
            case 0x060300 /*win 8.1*/:
                g_OffsetDirectoryTable = 0x028;
                g_OffsetProcessId      = 0x2e0;
                g_OffsetProcessLinks   = 0x2e8;
                g_OffsetObjectTable    = 0x408;
                break;

            case 0x0A0000 /*win 10*/:
            {
                switch (osvi.dwBuildNumber)
                {
                case 10240:
                case 10586:
                case 14393:
                    g_OffsetDirectoryTable = 0x028;
                    g_OffsetProcessId      = 0x2E8;
                    g_OffsetProcessLinks   = 0x2F0;
                    g_OffsetObjectTable    = 0x418;
                    break;

                case 15063:
                case 16299:
                    g_OffsetDirectoryTable = 0x028;
                    g_OffsetProcessId      = 0x2E0;
                    g_OffsetProcessLinks   = 0x2E8;
                    g_OffsetObjectTable    = 0x418;
                    break;

                default:
                    throw new Exception("Unsupported dwBuildNumber");
                }
                break;
            }

            default:
                throw new Exception("Unsupported version_long");
            }
        }
Example #13
0
 public static byte[] ReadRawMemory(this Process process, ulong memoryPointer, int size)
 {
     byte[] buffer = new byte[size];
     if (!NT.ReadProcessMemory(process.Handle, memoryPointer, buffer, buffer.Length, 0))
     {
         throw new Exception($"ReadRawMemory - ReadProcessMemory() failed - {Marshal.GetLastWin32Error().ToString("x2")}");
     }
     return(buffer);
 }
Example #14
0
        private static byte *FindKernelProcedure(string szName)
        {
            ulong ntoskrnlHandle = NT.LoadLibrary("ntoskrnl.exe");
            ulong kernelBase     = GetKernelBase();

            ulong functionPointer = NT.GetProcAddress(ntoskrnlHandle, szName);

            return((byte *)(functionPointer - ntoskrnlHandle + kernelBase));
        }
Example #15
0
        public static NT.MemoryProtection VirtualProtect(this Process process, ulong memoryPointer, int size, NT.MemoryProtection newProtect)
        {
            if (!NT.VirtualProtectEx(process.Handle, memoryPointer, size, newProtect, out NT.MemoryProtection oldProtect))
            {
                throw new Exception($"VirtualProtect - VirtualProtectEx() failed - {Marshal.GetLastWin32Error().ToString("x2")}");
            }

            return(oldProtect);
        }
Example #16
0
        /// <summary>
        /// Trigger a "Blue Screen Of Death" (BSOD)
        /// </summary>
        public static void TriggerBSOD()
        {
            bool bool_0;
            uint uint_0;

            // enable shutdown privilege
            _ = NT.RtlAdjustPrivilege(NT.PRIVILEGE_SE_SHUTDOWN_NAME, true, false, out bool_0);

            // trigger bsod
            _ = NT.NtRaiseHardError(NT.STATUS_ACCESS_DENIED, 0, 0, IntPtr.Zero, NT.HARDWARE_RESPONSE_OPTION_SHUTDOWN_SYSTEM, out uint_0);
        }
Example #17
0
 public Operator(byte precedence, byte valCount, bool leftToRight, NT operation, bool isSpecial = false, SourceLocation location = new SourceLocation())
 {
     this.canStillDefine = false;
     this.operatorIndex  = 0;
     this.leftToRight    = leftToRight;
     this.precedence     = precedence;
     this.operation      = operation;
     this.isSpecial      = isSpecial;
     this.location       = location;
     this.valCount       = valCount;
 }
Example #18
0
        public static void WriteRawMemory(this Process process, byte[] buffer, ulong memoryPointer)
        {
            //NT.MemoryProtection oldProtect = process.VirtualProtect(memoryPointer, buffer.Length, NT.MemoryProtection.ExecuteReadWrite);

            if (!NT.WriteProcessMemory(process.Handle, memoryPointer, buffer, (uint)buffer.Length, 0))
            {
                throw new Exception($"WriteBuffer - WriteProcessMemory() failed - {Marshal.GetLastWin32Error().ToString("x2")}");
            }

            //process.VirtualProtect(memoryPointer, buffer.Length, oldProtect);
        }
Example #19
0
        public static ulong MapSection(this Process process, ulong sectionHandle, NT.MemoryProtection memoryProtection)
        {
            ulong memoryPointer = 0;
            var   result        = NT.NtMapViewOfSection(sectionHandle, process.Handle, ref memoryPointer, 0, 0, 0, out uint viewSize, 2, 0, memoryProtection);

            if (result != 0)
            {
                throw new Exception($"MapSection - NtMapViewOfSection() failed - {result.ToString("x2")}");
            }

            return(memoryPointer);
        }
Example #20
0
        public async Task <IActionResult> Create([Bind("Noticiasid,Topicosid")] NT nT)
        {
            if (ModelState.IsValid)
            {
                db.Add(nT);
                await db.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["Noticiasid"] = new SelectList(db.Noticias, "Id", "Id", nT.Noticiasid);
            ViewData["Topicosid"]  = new SelectList(db.Topicos, "Id", "Id", nT.Topicosid);
            return(View(nT));
        }
Example #21
0
 public override string ToString()
 {
     return(NV.ToString()
            + NR.ToString()
            + NC.ToString()
            + NL.ToString()
            + N_BPT.ToString()
            + N_UPT.ToString()
            + NOA.ToString()
            + NT.ToString()
            + NIOA.ToString()
            + NTR.ToString());
 }
Example #22
0
        private void AdicionarNaoTerminalOnClick(object sender, RoutedEventArgs e)
        {
            if (!_gramatica.NaoTerminais.Any(t => t.Valor == textBoxNaoTerminal.Text))
            {
                var nt = new NT(textBoxNaoTerminal.Text);
                _gramatica.NaoTerminais.Add(nt);
                PrintarGramatica();
                _producoes.Add(nt);
            }

            labelProducoes.Visibility = Visibility.Visible;
            textBoxNaoTerminal.Clear();
        }
Example #23
0
        private (bool sucessfulInitiaition, double similarityThreshold, int miniBatchSize, string fileLocation) ServerInitiation(Socket inHandler)
        {
            string _fileLocation         = null;
            var    _initiationSuccessful = false;
            double _similarityThreshold  = 0.0;
            int    _miniBatchSize        = 0;

            // Handshake Loop - Abort if loop fails 10 times
            for (var i = 0; i < 10; i++)
            {
                // Receive filename from server
                var _fileName = NT.ReceiveString(inHandler);
                // Echo video filename to server
                NT.SendString(inHandler, _fileName);

                // Receive file location from server
                _fileLocation = NT.ReceiveString(inHandler);
                // Echo file location
                NT.SendString(inHandler, _fileLocation);

                // Receive similarity threshold from server
                _similarityThreshold = NT.ReceiveDouble(inHandler);
                // Echo similarity threshold
                NT.SendDouble(inHandler, _similarityThreshold);

                // Receive mini batch size from server
                _miniBatchSize = NT.ReceiveInt(inHandler);
                // Echo mini batch size
                NT.SendInt(inHandler, _miniBatchSize);

                // Send file checksum to ensure both machines are referring to same file
                NT.SendString(inHandler, "file checksum test");

                // Receive "file good" confirmation from server
                var response = NT.ReceiveString(inHandler);
                if (response == "OK")
                {
                    // Send machine name to server
                    NT.SendString(inHandler, "client_name");

                    _initiationSuccessful = true;
                    break;
                }
            }

            // Proceed to connection handler stage 2
            return(_initiationSuccessful, _similarityThreshold, _miniBatchSize, _fileLocation);
        }
Example #24
0
        public static ulong GetModuleByName(this Process process, string moduleName)
        {
            ulong[] moduleHandleArray = new ulong[1000];

            fixed(ulong *hMods = moduleHandleArray)
            {
                if (NT.EnumProcessModules(process.Handle, (ulong)hMods, (uint)(sizeof(ulong) * moduleHandleArray.Length), out uint cbNeeded) > 0)
                {
                    for (int moduleIndex = 0; moduleIndex < cbNeeded / sizeof(ulong); moduleIndex++)
                    {
                        string name = NTM.GetModuleBaseName(process.Handle, moduleHandleArray[moduleIndex]);

                        if (String.Equals(name, moduleName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            return(moduleHandleArray[moduleIndex]);
                        }
                    }
                }
            }

            return(0);
        }
Example #25
0
        public static Dictionary <string, ulong> GetModules(this Process process)
        {
            var result = new Dictionary <string, ulong>();

            ulong[] moduleHandleArray = new ulong[1000];

            fixed(ulong *hMods = moduleHandleArray)
            {
                if (NT.EnumProcessModules(process.Handle, (ulong)hMods, (uint)(sizeof(ulong) * moduleHandleArray.Length), out uint cbNeeded) > 0)
                {
                    for (int moduleIndex = 0; moduleIndex < cbNeeded / sizeof(ulong); moduleIndex++)
                    {
                        string name = NTM.GetModuleBaseName(process.Handle, moduleHandleArray[moduleIndex]);

                        result[name.ToLower()] = moduleHandleArray[moduleIndex];

                        //if (String.Equals(name, moduleName, StringComparison.InvariantCultureIgnoreCase))
                        //    return moduleHandleArray[moduleIndex];
                    }
                }
            }

            return(result);
        }
Example #26
0
 public static ulong AllocateMemory(this Process process, uint length, NT.AllocationType allocationType, NT.MemoryProtection memoryProtection) =>
 NT.VirtualAllocEx(process.Handle, 0, length, allocationType, memoryProtection);
        public override void ToJSON(JObject ParentObject)
        {
            //! the data should be stored this way in the DB and not transformed into it, but we can't do this in Magnolia because of design mode and field type shenanigans

            /*
             * data is coming from the server in two dictionaries: a mapping of value to string, and an array of held permissions
             *                          Options: {
             *                             'nt_1_Create': 'Role',
             *                             'nt_1_tab_1_View': 'Role, Role',
             *                             ...
             *                          }
             *                          Values: [
             *                            'nt_1_Create',
             *                            'nt_1_tab_5_Create',
             *                            ...
             *                         ]
             *
             * We need it in the format: Options: [
             *                            { name: 'Role',
             *                              Create: true,
             *                              Edit: true,
             *                              Delete: true,
             *                              View: true,
             *                              Children: [
             *                                 { name: 'Role Tab',
             *                                   Create: true,
             *                                   Edit: true,
             *                                   Delete: true,
             *                                   View: true,
             *                                   leaf: true
             *                                 }]
             *                             },
             *                             ...
             *                             ]
             *
             */

            ParentObject[_ValueSubField.ToXmlNodeName(true)] = Value.ToString();

            JObject OptionsArray = new JObject();

            ParentObject["options"] = OptionsArray;

            //first build the skeleton of the object we want to return
            foreach (CswNbtMetaDataNodeType NT in _CswNbtResources.MetaData.getNodeTypes())
            {
                JObject NewNT = new JObject();
                NewNT["itemname"] = NT.NodeTypeName;
                NewNT["create"]   = false;
                NewNT["edit"]     = false;
                NewNT["view"]     = false;
                NewNT["delete"]   = false;
                NewNT["itemid"]   = NT.NodeTypeId;
                JArray Children = new JArray();
                foreach (CswNbtMetaDataNodeTypeTab Tab in NT.getNodeTypeTabs())
                {
                    JObject NewTab = new JObject();
                    NewTab["itemname"] = Tab.TabName + " Tab";
                    NewTab["create"]   = false;
                    NewTab["edit"]     = false;
                    NewTab["view"]     = false;
                    NewTab["delete"]   = false;
                    NewTab["itemid"]   = Tab.TabId;
                    NewTab["leaf"]     = true;

                    Children.Add(NewTab);
                }
                NewNT["children"] = Children;
                OptionsArray[NT.NodeTypeId.ToString()] = NewNT;
            }

            //now iterate the values we've stored and assign them to the correct permissions in the skeleton:
            foreach (string Permission in Value)
            {
                string[] PermissionComponents = Permission.Split('_');
                bool     IsTab              = PermissionComponents.Length == 5;
                string   Nodetype           = PermissionComponents[1];
                string   PermissionCategory = PermissionComponents[PermissionComponents.Length - 1].ToLower();

                //our permissions data needs a good cleaning... there are invalid nodetypes in the Values dictionary
                if (ParentObject["options"][Nodetype] != null)
                {
                    if (false == IsTab)
                    {
                        //if we're not dealing with a tab, we can just set the proper permission
                        ParentObject["options"][Nodetype][PermissionCategory] = true;
                    }
                    else
                    {
                        string TabId = PermissionComponents[3];
                        //for tabs we have no choice but to iterate to find the correct tab, because of client-side restrictions
                        foreach (JObject Tab in ParentObject["options"][Nodetype]["children"])
                        {
                            if (Tab["itemid"].ToString() == TabId.ToString())
                            {
                                Tab[PermissionCategory] = true;
                            }
                        } //for each tab in the returned JObject
                    }     //else -- if the permission is a tab
                }         //if this nodetype exists
            }             //for each permission stored in the database
        }                 // ToJSON()
Example #28
0
 public static bool FreeMemory(this Process process, ulong memoryPointer) =>
 NT.VirtualFreeEx(process.Handle, memoryPointer, 0, NT.AllocationType.Release);
Example #29
0
        public void FixImportTable(UInt32 localImage, NT.IMAGE_OPTIONAL_HEADER64 optionalHeader)
        {
            NT.IMAGE_IMPORT_DESCRIPTOR *importDescriptor = (NT.IMAGE_IMPORT_DESCRIPTOR *)(localImage + optionalHeader.ImportTable.VirtualAddress);
            for (; importDescriptor->FirstThunk > 0; ++importDescriptor)
            {
                string libraryName = Marshal.PtrToStringAnsi((IntPtr)(localImage + importDescriptor->Name));

                // RECODE THIS, THIS IS STUPID & DANGEROUS
                // I AM ONLY DOING THIS BECAUSE OF API-SET DLLS
                // I COULDNT BE ARSED TO MAKE A PINVOKE FOR ApiSetResolveToHost
                ulong localLibraryHandle = NT.LoadLibrary(libraryName);
                libraryName = NTM.GetModuleBaseName(Process.GetCurrentProcess().Handle, localLibraryHandle).ToLower();

                // IF WE MAPPED DEPENDENCY EARLIER, WE SHOULD USE RVA
                // INSTEAD OF STATIC MEMORY ADDRESS
                bool mappedDependency = MappedModules.TryGetValue(libraryName, out ulong remoteLibraryHandle);
                bool linkedInProcess  = LinkedModules.TryGetValue(libraryName, out remoteLibraryHandle);

                if (!mappedDependency && !linkedInProcess) // DEPENDENCY NOT FOUND, MAP IT!
                {
                    string dependencyPath = Tools.FindDll(libraryName);

                    // SKIP IF DEPENDENCY COULDN'T BE FOUND
                    if (dependencyPath == null)
                    {
                        continue;
                    }

                    // [8:44 PM] markhc: i had something similar
                    // [8:44 PM] markhc: it was deep inside CRT initialization(edited)
                    // [8:45 PM] Ch40zz: how did you fix it?
                    // [8:46 PM] markhc: i didnt fix it
                    // [8:46 PM] markhc: i thought it was something wrong with my manual mapper code, but i couldnt figure out what was it
                    // [8:46 PM] markhc: so i threw it all away
                    if (libraryName == "msvcp140.dll")
                    {
                        var tempOptions = Options;
                        tempOptions.EraseHeaders = false;

                        new LoadLibraryInjection(TargetProcess, TypeOfExecution, tempOptions).InjectImage(dependencyPath);
                        --importDescriptor;
                        continue;
                    }

                    remoteLibraryHandle = MapImage(libraryName, File.ReadAllBytes(dependencyPath));
                    mappedDependency    = true;
                }

                UInt32 *functionAddress = (UInt32 *)(localImage + importDescriptor->FirstThunk);
                UInt32 *importEntry     = (UInt32 *)(localImage + importDescriptor->OriginalFirstThunk);

                do
                {
                    ulong procNamePointer = *importEntry < 0x8000000000000000 /*IMAGE_ORDINAL_FLAG64*/ ? // IS ORDINAL?
                                            localImage + *importEntry + sizeof(ushort) /*SKIP HINT*/ :   // FUNCTION BY NAME
                                            *importEntry & 0xFFFF;                                       // ORDINAL

                    var localFunctionPointer = NT.GetProcAddress(localLibraryHandle, procNamePointer);
                    var rva = localFunctionPointer - localLibraryHandle;

                    // SET NEW FUNCTION POINTER
                    *functionAddress = (UInt32)(mappedDependency ? remoteLibraryHandle + rva : localFunctionPointer);

                    // GET NEXT ENTRY
                    ++functionAddress;
                    ++importEntry;
                } while (*importEntry > 0);
            }
        }
Example #30
0
        public void CallEntrypoint(byte[] rawImage, UInt32 moduleHandle)
        {
            // GET HEADERS
            Tools.GetImageHeaders(rawImage, out NT.IMAGE_DOS_HEADER dosHeader, out NT.IMAGE_FILE_HEADER fileHeader, out NT.IMAGE_OPTIONAL_HEADER64 optionalHeader);

            // GET DLLMAIN
            UInt32 entrypoint = moduleHandle + optionalHeader.AddressOfEntryPoint;

            if (optionalHeader.AddressOfEntryPoint == 0)
            {
                Log.LogError($"Invalid Entrypoint - skipping {moduleHandle.ToString("x2")}");
                return;
            }

            Log.LogVariable("AddressOfEntryPoint", optionalHeader.AddressOfEntryPoint.ToString("x2"));

            // GET PROPER SHELLCODE FOR EXECUTION TYPE
            byte[] shellcode = ShellcodeGenerator.CallDllMain(moduleHandle, entrypoint, TypeOfExecution == ExecutionType.HijackThread);

            // EXECUTE DLLMAIN
            switch (TypeOfExecution)
            {
                #region Create Thread
            case ExecutionType.CreateThread:
                // INJECT OUR SHELLCODE -> REMOTE PROCESS TO CALL DLLMAIN REMOTELY :)
                TargetProcess.InjectShellcode(shellcode);
                break;
                #endregion

                #region Hijack Thread
            case ExecutionType.HijackThread:
                // WRITE SHELLCODE TO TARGET MEMORY
                var remoteShellcodePointer = TargetProcess.AllocateAndWrite(shellcode, NT.AllocationType.Commit | NT.AllocationType.Reserve, NT.MemoryProtection.ExecuteReadWrite);

                // GET THREAD HANDLE WITH PROPER ACCESS RIGHTS
                // I FILTER THE THREADS LIKE THIS BECAUSE FROM
                // EXPERIENCE SOME THREADS WITH TimeCritical PRIORITY
                // ETC WILL CAUSE SOME WONKY CRASHES
                var usableThreads = TargetProcess.Threads.Cast <ProcessThread>().Where(
                    x => x.ThreadState == System.Diagnostics.ThreadState.Wait && x.WaitReason == ThreadWaitReason.UserRequest);
                ProcessThread targetThread = usableThreads.ElementAt(NTM.RandomEngine.Next(usableThreads.Count()));
                var           threadHandle = targetThread.GetNativeHandle((NT.ThreadAccess) 0x1FFFFF);

                // ELEVATE HANDLE VIA DRIVER EXPLOIT
                if (Options.ElevateHandle)
                {
                    ElevateHandle.Elevate(threadHandle, 0x1FFFFF);
                }

                Log.LogInfo($"Thread {targetThread.Id} - {targetThread.ThreadState} - {targetThread.PriorityLevel} - {targetThread.CurrentPriority}");

                // INITIALISE THREAD CONTEXT STRUCT
                NT.CONTEXT64 ctx = new NT.CONTEXT64()
                {
                    ContextFlags = NT.CONTEXT_FLAGS.CONTEXT_FULL
                };

                // SUSPEND THE THREAD SO WE CAN MODIFY REGISTERS
                if (NT.SuspendThread(threadHandle) == uint.MaxValue)
                {
                    Log.LogError($"Failed to suspend thread - {Marshal.GetLastWin32Error().ToString("x2")}");
                }

                // GET CONTEXT
                if (!NT.GetThreadContext(threadHandle, ref ctx))
                {
                    throw new Win32Exception("GetThreadContext");
                }

                // ALLOCATE 8 BYTES ON STACK
                ctx.Rsp -= sizeof(ulong);

                // 'RET' WILL CALL POP AND JUMP TO THAT VALUE
                // SO WE WRITE OLD INSTRUCTION POINTER TO THE STACK SO WE CAN RETURN
                // SO DONT F**K UP THE STACK
                // F*****G RETARD
                TargetProcess.WriteRawMemory(BitConverter.GetBytes(ctx.Rip), ctx.Rsp);

                Log.LogInfo($"{ctx.Rip.ToString("x2")} -> {remoteShellcodePointer.ToString("x2")}");

                // OVERWRITE INSTRUCTION POINTER
                ctx.Rip = remoteShellcodePointer;

                // SET THREAD CONTEXT TO APPLY CHANGES
                if (!NT.SetThreadContext(threadHandle, ref ctx))
                {
                    throw new Win32Exception("SetThreadContext");
                }

                // RESUME THREAD
                Log.LogVariable("Resumed?", NT.ResumeThread(threadHandle));
                //if ( == uint.MaxValue/*-1*/)
                //     Log.LogError($"Failed to resume thread - {Marshal.GetLastWin32Error().ToString("x2")}");

                // CLOSE THREAD HANDLE
                NT.CloseHandle(threadHandle);

                // WAIT FOR MODULE TO LOAD FULLY BEFORE FREEING SHELLCODE
                // GHETTO SLEEP
                Thread.Sleep(1000);

                // MEMORY LEAKS ARE BAD
                TargetProcess.FreeMemory(remoteShellcodePointer);
                break;
                #endregion
            }
        }