├── .gitattributes ├── .gitignore ├── Enums ├── LUID_ATTRIBUTES.cs ├── MEMORY_BASIC_INFO_ENUMS.cs ├── PRIVILEGE_CONSTANTS.cs ├── PROCESS_ACCESS.cs ├── SECURITY_LOGON_TYPES.cs ├── TOKEN_ACCESS_FLAGS.cs └── TOKEN_INFORMATION_CLASS.cs ├── GetInjectedThreads.cs ├── GetInjectedThreads.csproj ├── InjectedThread.cs ├── MigrationBackup └── 9bf7db1d │ └── GetInjectedThreads │ ├── GetInjectedThreads.csproj │ ├── NuGetUpgradeLog.html │ └── packages.config ├── Properties └── AssemblyInfo.cs ├── Structs ├── LSA_UNICODE_STRING.cs ├── MEMORY_BASIC_INFORMATION.cs ├── SECURITY_LOGON_SESSION_DATA.cs ├── SYSTEM_INFO.cs ├── THREAD_ACCESS.cs └── TOKEN_STRUCTS.cs └── app.config /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb -------------------------------------------------------------------------------- /Enums/LUID_ATTRIBUTES.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace GetInjectedThreads.Enums 4 | { 5 | public enum LUID_ATTRIBUTES : UInt32 6 | { 7 | DISABLED = 0x00000000, 8 | SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001, 9 | SE_PRIVILEGE_ENABLED = 0x00000002, 10 | SE_PRIVILEGE_REMOVED = 0x00000004, 11 | SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Enums/MEMORY_BASIC_INFO_ENUMS.cs: -------------------------------------------------------------------------------- 1 | namespace GetInjectedThreads.Enums 2 | { 3 | public enum MemoryBasicInformationState : uint 4 | { 5 | MEM_COMMIT = 0x1000, 6 | MEM_FREE = 0x10000, 7 | MEM_RESERVE = 0x2000 8 | } 9 | 10 | public enum MemoryBasicInformationType : uint 11 | { 12 | MEM_IMAGE = 0x1000000, 13 | MEM_MAPPED = 0x40000, 14 | MEM_PRIVATE = 0x20000 15 | } 16 | 17 | public enum MemoryBasicInformationProtection : uint 18 | { 19 | PAGE_EXECUTE = 0x10, 20 | PAGE_EXECUTE_READ = 0x20, 21 | PAGE_EXECUTE_READWRITE = 0x40, 22 | PAGE_EXECUTE_WRITECOPY = 0x80, 23 | PAGE_NOACCESS = 0x01, 24 | PAGE_READONLY = 0x02, 25 | PAGE_READWRITE = 0x04, 26 | PAGE_WRITECOPY = 0x08, 27 | PAGE_TARGETS_INVALID = 0x40000000, 28 | PAGE_TARGETS_NO_UPDATE = 0x40000000, 29 | PAGE_GUARD = 0x100, 30 | PAGE_NOCACHE = 0x200, 31 | PAGE_WRITECOMBINE = 0x400 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Enums/PRIVILEGE_CONSTANTS.cs: -------------------------------------------------------------------------------- 1 | namespace GetInjectedThreads.Enums 2 | { 3 | public enum PRIVILEGE_CONSTANT 4 | { 5 | SeCreateTokenPrivilege = 1, 6 | SeAssignPrimaryTokenPrivilege, 7 | SeLockMemoryPrivilege, 8 | SeIncreaseQuotaPrivilege, 9 | SeUnsolicitedInputPrivilege, 10 | SeMachineAccountPrivilege, 11 | SeTcbPrivilege, 12 | SeSecurityPrivilege, 13 | SeTakeOwnershipPrivilege, 14 | SeLoadDriverPrivilege, 15 | SeSystemProfilePrivilege, 16 | SeSystemtimePrivilege, 17 | SeProfileSingleProcessPrivilege, 18 | SeIncreaseBasePriorityPrivilege, 19 | SeCreatePagefilePrivilege, 20 | SeCreatePermanentPrivilege, 21 | SeBackupPrivilege, 22 | SeRestorePrivilege, 23 | SeShutdownPrivilege, 24 | SeDebugPrivilege, 25 | SeAuditPrivilege, 26 | SeSystemEnvironmentPrivilege, 27 | SeChangeNotifyPrivilege, 28 | SeRemoteShutdownPrivilege, 29 | SeUndockPrivilege, 30 | SeSyncAgentPrivilege, 31 | SeEnableDelegationPrivilege, 32 | SeManageVolumePrivilege, 33 | SeImpersonatePrivilege, 34 | SeCreateGlobalPrivilege, 35 | SeTrustedCredManAccessPrivilege, 36 | SeRelabelPrivilege, 37 | SeIncreaseWorkingSetPrivilege, 38 | SeTimeZonePrivilege, 39 | SeCreateSymbolicLinkPrivilege 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Enums/PROCESS_ACCESS.cs: -------------------------------------------------------------------------------- 1 | namespace GetInjectedThreads.Enums 2 | { 3 | public enum ProcessAccessFlags 4 | { 5 | All = 0x001F0FFF, 6 | Terminate = 0x00000001, 7 | CreateThread = 0x00000002, 8 | VirtualMemoryOperation = 0x00000008, 9 | VirtualMemoryRead = 0x00000010, 10 | VirtualMemoryWrite = 0x00000020, 11 | DuplicateHandle = 0x00000040, 12 | CreateProcess = 0x000000080, 13 | SetQuota = 0x00000100, 14 | SetInformation = 0x00000200, 15 | QueryInformation = 0x00000400, 16 | QueryLimitedInformation = 0x00001000, 17 | Synchronize = 0x00100000 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Enums/SECURITY_LOGON_TYPES.cs: -------------------------------------------------------------------------------- 1 | namespace GetInjectedThreads.Enums 2 | { 3 | // https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/ne-ntsecapi-security_logon_type 4 | public enum SECURITY_LOGON_TYPES 5 | { 6 | System, 7 | UndefinedLogonType, 8 | Interactive, 9 | Network, 10 | Batch, 11 | Service, 12 | Proxy, 13 | Unlock, 14 | NetworkCleartext, 15 | NewCredentials, 16 | RemoteInteractive, 17 | CachedInteractive, 18 | CachedRemoteInteractive, 19 | CachedUnlock 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Enums/TOKEN_ACCESS_FLAGS.cs: -------------------------------------------------------------------------------- 1 | namespace GetInjectedThreads.Enums 2 | { 3 | enum TokenAccessFlags : uint 4 | { 5 | STANDARD_RIGHTS_REQUIRED = 0x000F0000, 6 | STANDARD_RIGHTS_READ = 0x00020000, 7 | TOKEN_ASSIGN_PRIMARY = 0x0001, 8 | TOKEN_DUPLICATE = 0x0002, 9 | TOKEN_IMPERSONATE = 0x0004, 10 | TOKEN_QUERY = 0x0008, 11 | TOKEN_QUERY_SOURCE = 0x0010, 12 | TOKEN_ADJUST_PRIVILEGES = 0x0020, 13 | TOKEN_ADJUST_GROUPS = 0x0040, 14 | TOKEN_ADJUST_DEFAULT = 0x0080, 15 | TOKEN_ADJUST_SESSIONID = 0x0100, 16 | TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY), 17 | TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | 18 | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | 19 | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | 20 | TOKEN_ADJUST_SESSIONID) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Enums/TOKEN_INFORMATION_CLASS.cs: -------------------------------------------------------------------------------- 1 | namespace GetInjectedThreads.Enums 2 | { 3 | // https://docs.microsoft.com/en-us/windows/win32/api/winnt/ne-winnt-token_information_class 4 | enum TOKEN_INFORMATION_CLASS 5 | { 6 | TokenUser = 1, 7 | TokenGroups, 8 | TokenPrivileges, 9 | TokenOwner, 10 | TokenPrimaryGroup, 11 | TokenDefaultDacl, 12 | TokenSource, 13 | TokenType, 14 | TokenImpersonationLevel, 15 | TokenStatistics, 16 | TokenRestrictedSids, 17 | TokenSessionId, 18 | TokenGroupsAndPrivileges, 19 | TokenSessionReference, 20 | TokenSandBoxInert, 21 | TokenAuditPolicy, 22 | TokenOrigin, 23 | TokenElevationType, 24 | TokenLinkedToken, 25 | TokenElevation, 26 | TokenHasRestrictions, 27 | TokenAccessInformation, 28 | TokenVirtualizationAllowed, 29 | TokenVirtualizationEnabled, 30 | TokenIntegrityLevel, 31 | TokenUIAccess, 32 | TokenMandatoryPolicy, 33 | TokenLogonSid, 34 | TokenIsAppContainer, 35 | TokenCapabilities, 36 | TokenAppContainerSid, 37 | TokenAppContainerNumber, 38 | TokenUserClaimAttributes, 39 | TokenDeviceClaimAttributes, 40 | TokenRestrictedUserClaimAttributes, 41 | TokenRestrictedDeviceClaimAttributes, 42 | TokenDeviceGroups, 43 | TokenRestrictedDeviceGroups, 44 | TokenSecurityAttributes, 45 | TokenIsRestricted, 46 | TokenProcessTrustLevel, 47 | TokenPrivateNameSpace, 48 | TokenSingletonAttributes, 49 | TokenBnoIsolation, 50 | TokenChildProcessFlags, 51 | TokenIsLessPrivilegedAppContainer, 52 | TokenIsSandboxed, 53 | TokenOriginatingProcessTrustLevel, 54 | MaxTokenInfoClass 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /GetInjectedThreads.cs: -------------------------------------------------------------------------------- 1 | using GetInjectedThreads.Enums; 2 | using GetInjectedThreads.Structs; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Diagnostics; 6 | using System.IO; 7 | using System.Management; 8 | using System.Runtime.ExceptionServices; 9 | using System.Runtime.InteropServices; 10 | using System.Text; 11 | 12 | 13 | 14 | namespace GetInjectedThreads 15 | { 16 | public class GetInjectedThreads 17 | { 18 | // Required Interop functions 19 | [DllImport("Shell32.dll", SetLastError = true)] 20 | [return: MarshalAs(UnmanagedType.Bool)] 21 | static extern bool IsUserAnAdmin(); 22 | 23 | [DllImport("Kernel32.dll", SetLastError = true)] 24 | public static extern IntPtr OpenProcess(ProcessAccessFlags processAccess, bool bInheritHandle, int processId); 25 | 26 | [DllImport("Kernel32.dll")] 27 | public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesRead); 28 | 29 | [DllImport("Kernel32.dll", SetLastError = true)] 30 | static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out MEMORY_BASIC_INFORMATION64 lpBuffer, uint dwLength); 31 | 32 | [DllImport("Kernel32.dll")] 33 | static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, int dwThreadId); 34 | 35 | [DllImport("Kernel32.dll")] 36 | static extern bool QueryFullProcessImageName(IntPtr hProcess, UInt32 dwFlags, StringBuilder lpExeName, ref int lpdwSize); 37 | 38 | [DllImport("Kernel32.dll")] 39 | private static extern bool CloseHandle(IntPtr hHandle); 40 | 41 | [DllImport("kernel32.dll")] 42 | static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo); 43 | 44 | [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] 45 | static extern Boolean OpenThreadToken(IntPtr ThreadHandle, TokenAccessFlags DesiredAccess, bool OpenAsSelf, out IntPtr TokenHandle); 46 | 47 | [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] 48 | static extern Boolean OpenProcessToken(IntPtr ProcessHandle, TokenAccessFlags DesiredAccess, out IntPtr TokenHandle); 49 | 50 | [DllImport("Advapi32.dll")] 51 | static extern bool GetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, int TokenInformationLength, out int ReturnLength); 52 | 53 | [DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] 54 | static extern int ConvertSidToStringSid(IntPtr pSID, out IntPtr ptrSid); 55 | 56 | [DllImport("Ntdll.dll", SetLastError = true)] 57 | static extern int NtQueryInformationThread(IntPtr threadHandle, ThreadInfoClass threadInformationClass, IntPtr threadInformation, int threadInformationLength, IntPtr returnLengthPtr); 58 | 59 | [DllImport("Secur32.dll")] 60 | static extern uint LsaGetLogonSessionData(IntPtr pLUID, out IntPtr ppLogonSessionData); 61 | 62 | [DllImport("Secur32.dll")] 63 | private static extern uint LsaFreeReturnBuffer(IntPtr buffer); 64 | 65 | 66 | [HandleProcessCorruptedStateExceptions] 67 | public static List InjectedThreads() 68 | { 69 | // Check if running as administrator first? Or at least check if SeDebugPrivilege enabled? 70 | if(IsUserAnAdmin() == false) 71 | { 72 | Console.WriteLine("Program is not running as Administrator. Exiting..."); 73 | System.Environment.Exit(1); 74 | } 75 | 76 | List injectedThreads = new List(); 77 | 78 | // Create array of Process objects for each running process 79 | Process[] runningProcesses = Process.GetProcesses(); 80 | 81 | // Iterate over each process and get all threads by ID 82 | foreach (Process process in runningProcesses) 83 | { 84 | // PID 0 and PID 4 aren't valid targets for injection 85 | if (process.Id != 0 && process.Id != 4) 86 | { 87 | IntPtr hProcess; 88 | 89 | try 90 | { 91 | // Get handle to the process 92 | hProcess = OpenProcess(ProcessAccessFlags.All, false, process.Id); 93 | } 94 | catch (System.ComponentModel.Win32Exception) 95 | { 96 | Console.WriteLine($"Couldn't get handle to process: {process.Id} - System.ComponentModel.Win32Exception - Access Is Denied"); 97 | continue; 98 | } 99 | catch (System.InvalidOperationException) 100 | { 101 | Console.WriteLine($"Couldn't get handle to process {process.Id} - System.InvalidOperationException - Process has Exited"); 102 | continue; 103 | } 104 | 105 | // Get all threads under running process 106 | ProcessThreadCollection threadCollection = process.Threads; 107 | 108 | // Iterate over each thread under the process 109 | foreach (ProcessThread thread in threadCollection) 110 | { 111 | // Get handle to the thread 112 | IntPtr hThread = OpenThread(ThreadAccess.AllAccess, false, thread.Id); 113 | 114 | // Create buffer to store pointer to the thread's base address - NTQueryInformationThread writes to this buffer 115 | IntPtr buf = Marshal.AllocHGlobal(IntPtr.Size); 116 | 117 | // Retrieve thread's Win32StartAddress - Different to thread.StartAddress 118 | Int32 result = NtQueryInformationThread(hThread, ThreadInfoClass.ThreadQuerySetWin32StartAddress, buf, IntPtr.Size, IntPtr.Zero); 119 | 120 | if(result == 0) 121 | { 122 | // Need to Marshal Win32 type pointer from CLR type IntPtr to access the thread's base address via pointer 123 | IntPtr threadBaseAddress = Marshal.ReadIntPtr(buf); 124 | 125 | // Retrieve MEMORY_BASIC_INFORMATION struct for each thread - assumes 64bit processes, otherwise need to use MEMORY_BASIC_INFORMATION32 126 | MEMORY_BASIC_INFORMATION64 memBasicInfo = new MEMORY_BASIC_INFORMATION64(); 127 | VirtualQueryEx(hProcess, threadBaseAddress, out memBasicInfo, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION64))); 128 | 129 | // Check the State and Type fields for the thread's MEMORY_BASIC_INFORMATION 130 | // Resolve to false suggests code running from this thread does not have a corresponding image file on disk, likely code injection 131 | if (memBasicInfo.State == MemoryBasicInformationState.MEM_COMMIT && memBasicInfo.Type != MemoryBasicInformationType.MEM_IMAGE) 132 | { 133 | // Create new InjectedThread object and set initial variables 134 | InjectedThread injectedThread = new InjectedThread() 135 | { 136 | ProcessName = process.ProcessName, 137 | ProcessID = process.Id, 138 | ThreadId = thread.Id, 139 | BaseAddress = threadBaseAddress, 140 | Path = process.MainModule.FileName, 141 | Size = (int)memBasicInfo.RegionSize, 142 | CommandLine = GetProcessCommandLine(process), 143 | MemoryState = Enum.GetName(typeof(MemoryBasicInformationState), memBasicInfo.State), 144 | MemoryType = Enum.GetName(typeof(MemoryBasicInformationType), memBasicInfo.Type), 145 | MemoryProtection = Enum.GetName(typeof(MemoryBasicInformationProtection), memBasicInfo.Protect), 146 | AllocatedMemoryProtection = Enum.GetName(typeof(MemoryBasicInformationProtection), memBasicInfo.AllocationProtect), 147 | BasePriority = thread.BasePriority, 148 | ThreadStartTime = thread.StartTime 149 | }; 150 | 151 | // Get handle to thread token. If Impersonation is not being used, thread will use Process access token 152 | // Try OpenThreadToken() - if it fails, use OpenProcessToken() 153 | if (OpenThreadToken(hThread, TokenAccessFlags.TOKEN_QUERY, false, out IntPtr hToken) == false) 154 | { 155 | // Thread doesn't have a unique token 156 | injectedThread.IsUniqueThreadToken = false; 157 | 158 | // Open process token instead 159 | if (OpenProcessToken(hProcess, TokenAccessFlags.TOKEN_QUERY, out hToken) == false) 160 | { 161 | Console.WriteLine($"Error opening thread and process token: {Marshal.GetLastWin32Error()}\nProcess ID {process.Id}"); 162 | } 163 | } 164 | else 165 | { 166 | injectedThread.IsUniqueThreadToken = true; 167 | } 168 | 169 | // Query process or thread token information 170 | injectedThread.SecurityIdentifier = QueryToken(hToken, TOKEN_INFORMATION_CLASS.TokenUser); 171 | injectedThread.Privileges = QueryToken(hToken, TOKEN_INFORMATION_CLASS.TokenPrivileges); 172 | injectedThread.Integrity = QueryToken(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel); 173 | injectedThread.LogonId = QueryToken(hToken, TOKEN_INFORMATION_CLASS.TokenOrigin); 174 | injectedThread.Username = GetProcessOwner(process.Id); 175 | 176 | // Get logon session information and add it to the InjectedThread object 177 | if (!string.IsNullOrEmpty(injectedThread.LogonId)) 178 | { 179 | GetLogonSessionData(hToken, injectedThread); 180 | } 181 | 182 | // Get thread's allocated memory via ReadProcessMemory 183 | injectedThread.ThreadBytes = GetThreadMemoryBytes(hProcess, threadBaseAddress, injectedThread.Size); 184 | 185 | // Read the full process memory ; 186 | injectedThread.ProcessBytes = GetProcessMemoryBytes(hProcess); 187 | 188 | // Read full name of executable image for the process 189 | int capacity = 1024; 190 | StringBuilder stringBuilder = new StringBuilder(capacity); 191 | QueryFullProcessImageName(hProcess, 0, stringBuilder, ref capacity); 192 | injectedThread.KernelPath = stringBuilder.ToString(0, capacity); 193 | 194 | // Check whether the kernel image path matches Process.MainModule.Filename 195 | if(injectedThread.Path.ToLower() != injectedThread.KernelPath.ToLower()) 196 | { 197 | injectedThread.PathMismatch = true; 198 | } 199 | 200 | injectedThreads.Add(injectedThread); 201 | CloseHandle(hToken); 202 | } 203 | 204 | CloseHandle(hThread); 205 | } 206 | } 207 | 208 | CloseHandle(hProcess); 209 | } 210 | } 211 | 212 | return injectedThreads; 213 | } 214 | 215 | 216 | // Get commandline for a process using WMI. Catch exceptions where either "Access Denied" or process has exited 217 | static string GetProcessCommandLine(Process process) 218 | { 219 | string commandLine = null; 220 | 221 | try 222 | { 223 | // Requres reference to System.Management.dll assembly for WMI class 224 | using (var searcher = new ManagementObjectSearcher($"SELECT CommandLine FROM Win32_Process WHERE ProcessId = {process.Id}")) 225 | { 226 | using (var matchEnum = searcher.Get().GetEnumerator()) 227 | { 228 | if (matchEnum.MoveNext()) 229 | { 230 | commandLine = matchEnum.Current["CommandLine"]?.ToString(); 231 | } 232 | } 233 | } 234 | } 235 | // Catch process exited exception 236 | catch(InvalidOperationException) 237 | { 238 | Console.WriteLine($"Couldn't get CommandLine for PID {process.Id} - Process has exited"); 239 | } 240 | 241 | return commandLine; 242 | } 243 | 244 | 245 | /// 246 | /// Extracts Token information from a thread's memory by wrapping GetTokenInformation(). Returns token information specified by the tokenInformationClass param 247 | /// 248 | /// 249 | /// 250 | /// String containing the requested token information 251 | static string QueryToken(IntPtr hToken, TOKEN_INFORMATION_CLASS tokenInformationClass) 252 | { 253 | int tokenInformationLength = 0; 254 | 255 | // First need to get the length of TokenInformation - won't return true 256 | bool result = GetTokenInformation(hToken, tokenInformationClass, IntPtr.Zero, tokenInformationLength, out tokenInformationLength); 257 | // Buffer for the struct 258 | IntPtr tokenInformation = Marshal.AllocHGlobal(tokenInformationLength); 259 | 260 | // Make call to GetTokenInformation() and get particular Struct 261 | switch (tokenInformationClass) 262 | { 263 | case TOKEN_INFORMATION_CLASS.TokenUser: 264 | 265 | // Store the requested token information in the buffer 266 | result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenUser, tokenInformation, tokenInformationLength, out tokenInformationLength); 267 | 268 | if (result) 269 | { 270 | // Marshal the buffer to TOKEN_USER Struct 271 | TOKEN_USER tokenUser = (TOKEN_USER)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_USER)); 272 | 273 | // Extract SID from the TOKEN_USER struct 274 | IntPtr pSID = IntPtr.Zero; 275 | ConvertSidToStringSid(tokenUser.User.Sid, out pSID); 276 | string SID = Marshal.PtrToStringAuto(pSID); 277 | 278 | return SID; 279 | } 280 | else { return null; } 281 | 282 | case TOKEN_INFORMATION_CLASS.TokenPrivileges: 283 | 284 | result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenPrivileges, tokenInformation, tokenInformationLength, out tokenInformationLength); 285 | 286 | if (result) 287 | { 288 | TOKEN_PRIVILEGES tokenPrivileges = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_PRIVILEGES)); 289 | 290 | StringBuilder stringBuilder = new StringBuilder(); 291 | 292 | for (int i = 0; i < tokenPrivileges.PrivilegeCount; i++) 293 | { 294 | // Bitwise AND comparison to check that each token privilege attribute for SE_PRIVILEGE_ENABLED 295 | if (((LUID_ATTRIBUTES)tokenPrivileges.Privileges[i].Attributes & LUID_ATTRIBUTES.SE_PRIVILEGE_ENABLED) == LUID_ATTRIBUTES.SE_PRIVILEGE_ENABLED) 296 | { 297 | // Append the privilege to the stringBuilder 298 | stringBuilder.Append($", {tokenPrivileges.Privileges[i].Luid.LowPart.ToString()}"); 299 | } 300 | } 301 | 302 | return stringBuilder.ToString().Remove(0, 2); 303 | } 304 | else { return null; } 305 | 306 | case TOKEN_INFORMATION_CLASS.TokenIntegrityLevel: 307 | 308 | // Mandatory Level SIDs for QueryToken() 309 | // https://support.microsoft.com/en-au/help/243330/well-known-security-identifiers-in-windows-operating-systems#allsids 310 | Dictionary tokenIntegritySIDs = new Dictionary 311 | { 312 | {"S-1-16-0", "Untrusted Mandatory Level"}, 313 | {"S-1-16-4096", "Low Mandatory Level"}, 314 | {"S-1-16-8192", "Medium Mandatory Level"}, 315 | {"S-1-16-8448", "Medium Plus Mandatory Level"}, 316 | {"S-1-16-12288", "High Mandatory Level"}, 317 | {"S-1-16-16384", "System Mandatory Level"}, 318 | {"S-1-16-20480", "Protected Process Mandatory Level"}, 319 | {"S-1-16-28672", "Secure Process Mandatory Level"} 320 | }; 321 | 322 | result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, tokenInformation, tokenInformationLength, out tokenInformationLength); 323 | 324 | if(result) 325 | { 326 | TOKEN_MANDATORY_LABEL tokenMandatoryLabel = (TOKEN_MANDATORY_LABEL)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_MANDATORY_LABEL)); 327 | 328 | // Extract SID string from TOKEN_MANDATORY_LABEL 329 | IntPtr pSID = IntPtr.Zero; 330 | ConvertSidToStringSid(tokenMandatoryLabel.label.Sid, out pSID); 331 | string SID = Marshal.PtrToStringAuto(pSID); 332 | 333 | if (tokenIntegritySIDs.ContainsKey(SID)) 334 | { 335 | return tokenIntegritySIDs[SID]; 336 | } 337 | else { return null; } 338 | } 339 | else { return null; } 340 | 341 | case TOKEN_INFORMATION_CLASS.TokenOrigin: 342 | 343 | result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenOrigin, tokenInformation, tokenInformationLength, out tokenInformationLength); 344 | 345 | if(result) 346 | { 347 | TOKEN_ORIGIN tokenOrigin = (TOKEN_ORIGIN)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_ORIGIN)); 348 | string logonId = tokenOrigin.OriginatingLogonSession.LowPart.ToString(); 349 | return logonId; 350 | } 351 | else { return null; } 352 | } 353 | return null; 354 | } 355 | 356 | /// 357 | /// Get SECURITY_LOGON_SESSION_DATA for a process or thread via a handle to its token and populate an InjectedThread object's Logon Session values 358 | /// 359 | /// 360 | /// 361 | static void GetLogonSessionData(IntPtr hToken, InjectedThread injectedThread) 362 | { 363 | int tokenInformationLength = 0; 364 | bool result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenOrigin, IntPtr.Zero, tokenInformationLength, out tokenInformationLength); 365 | IntPtr tokenInformation = Marshal.AllocHGlobal(tokenInformationLength); 366 | 367 | result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenOrigin, tokenInformation, tokenInformationLength, out tokenInformationLength); 368 | 369 | if(result) 370 | { 371 | // GetTokenInformation to retreive LUID struct 372 | TOKEN_ORIGIN tokenOrigin = (TOKEN_ORIGIN)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_ORIGIN)); 373 | IntPtr pLUID = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LUID))); 374 | 375 | // Get pointer to LUID struct for LsaGetLogonSessionData 376 | Marshal.StructureToPtr(tokenOrigin.OriginatingLogonSession, pLUID, false); 377 | 378 | IntPtr pLogonSessionData = IntPtr.Zero; 379 | LsaGetLogonSessionData(pLUID, out pLogonSessionData); 380 | 381 | SECURITY_LOGON_SESSION_DATA logonSessionData = (SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(pLogonSessionData, typeof(SECURITY_LOGON_SESSION_DATA)); 382 | 383 | // Check for a valid logon 384 | if(logonSessionData.PSiD != IntPtr.Zero) 385 | { 386 | if(injectedThread.Username.Equals("NO OWNER")) 387 | { 388 | string domain = Marshal.PtrToStringUni(logonSessionData.LoginDomain.buffer).Trim(); 389 | string username = Marshal.PtrToStringUni(logonSessionData.Username.buffer).Trim(); 390 | injectedThread.Username = $"{domain}\\{username}"; 391 | } 392 | 393 | // Add logon session information to InjectedThread object 394 | injectedThread.LogonSessionStartTime = DateTime.FromFileTime(logonSessionData.LoginTime); 395 | injectedThread.LogonType = Enum.GetName(typeof(SECURITY_LOGON_TYPES), logonSessionData.LogonType); 396 | injectedThread.AuthenticationPackage = Marshal.PtrToStringAuto(logonSessionData.AuthenticationPackage.buffer); 397 | } 398 | 399 | LsaFreeReturnBuffer(pLogonSessionData); 400 | } 401 | } 402 | 403 | /// 404 | /// Gets Domain\Username Owner of a process via its process ID. Uses WMI - requires System.Management.dll 405 | /// 406 | /// 407 | /// 408 | static string GetProcessOwner(int processId) 409 | { 410 | ManagementObjectSearcher searcher = new ManagementObjectSearcher($"Select * From Win32_Process Where ProcessID = {processId}"); 411 | ManagementObjectCollection processList = searcher.Get(); 412 | 413 | foreach(ManagementObject obj in processList) 414 | { 415 | string[] argList = new string[] { string.Empty, string.Empty }; 416 | int result = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList)); 417 | 418 | if(result == 0) 419 | { 420 | return $"{argList[1]}\\{argList[0]}"; 421 | } 422 | } 423 | return "NO OWNER"; 424 | } 425 | 426 | /// 427 | /// Read all bytes of a thread's allocated memory address via ReadProcessMemory() 428 | /// 429 | /// 430 | /// 431 | /// 432 | /// A byte[] containing all bytes of a thread's memory 433 | static byte[] GetThreadMemoryBytes(IntPtr hProcess, IntPtr threadBaseAddress, int threadSize) 434 | { 435 | // Read memory from the thread's address space into a byte array 436 | byte[] buffer = new byte[threadSize]; 437 | int numberOfBytesRead = 0; 438 | ReadProcessMemory(hProcess, threadBaseAddress, buffer, threadSize, ref numberOfBytesRead); 439 | 440 | return buffer; 441 | } 442 | 443 | /// 444 | /// Search the system's memory space for memory allocated to a target process and retrieve its sections via ReadProcessMemory 445 | /// 446 | /// 447 | /// A byte[] containing process's accessible memory 448 | public static byte[] GetProcessMemoryBytes(IntPtr hProcess) 449 | { 450 | // Get lowest and highest addresses where memory can be allocated for user-mode applications 451 | SYSTEM_INFO systemInfo; 452 | GetSystemInfo(out systemInfo); 453 | 454 | IntPtr minimumAddress = systemInfo.minimumApplicationAddress; 455 | IntPtr maximumAddress = systemInfo.maximumApplicationAddress; 456 | 457 | MEMORY_BASIC_INFORMATION64 memBasicInfo = new MEMORY_BASIC_INFORMATION64(); 458 | int bytesRead = 0; 459 | 460 | // Initialise MemoryStream to store all found chunks of memory 461 | MemoryStream processMemory = new MemoryStream(); 462 | 463 | // Iterate over all addressable memory searching for memory blocks belonging to the target process 464 | while (minimumAddress.ToInt64() < maximumAddress.ToInt64()) 465 | { 466 | // Check for memory belonging to target process 467 | VirtualQueryEx(hProcess, minimumAddress, out memBasicInfo, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION64))); 468 | 469 | /* Check for sections of memory that are RWX or RW. Remove protection checks to dump all committed pages. 470 | * Shouldn't have access issues if running as admin and handle to process was obtained using ProcessAccessFlags.All. 471 | * Removing protection checks will significantly increase size of memory stream. 472 | */ 473 | if ((memBasicInfo.Protect == MemoryBasicInformationProtection.PAGE_READWRITE || memBasicInfo.Protect == MemoryBasicInformationProtection.PAGE_EXECUTE_READWRITE) && 474 | memBasicInfo.State == MemoryBasicInformationState.MEM_COMMIT) 475 | { 476 | // Write chunk of memory to buffer 477 | byte[] buffer = new byte[(int)memBasicInfo.RegionSize]; 478 | ReadProcessMemory(hProcess, (IntPtr)memBasicInfo.BaseAddress, buffer, (int)memBasicInfo.RegionSize, ref bytesRead); 479 | 480 | // Append chunk of memory to MemoryStream 481 | processMemory.Write(buffer, 0, buffer.Length); 482 | } 483 | 484 | // Move to the next section of memory 485 | try 486 | { 487 | minimumAddress = new IntPtr(minimumAddress.ToInt64() + (Int64)memBasicInfo.RegionSize); 488 | } 489 | catch (OverflowException) 490 | { 491 | break; 492 | } 493 | } 494 | 495 | return processMemory.ToArray(); 496 | } 497 | } 498 | } 499 | -------------------------------------------------------------------------------- /GetInjectedThreads.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {B8A0CAB9-6BCC-4814-8664-BAA6462B7DE1} 8 | Library 9 | GetInjectedThreads 10 | GetInjectedThreads 11 | v4.6 12 | 512 13 | true 14 | 15 | 16 | 17 | 18 | 19 | AnyCPU 20 | true 21 | full 22 | false 23 | bin\Debug\ 24 | DEBUG;TRACE 25 | prompt 26 | 4 27 | false 28 | 29 | 30 | AnyCPU 31 | pdbonly 32 | true 33 | bin\Release\ 34 | TRACE 35 | prompt 36 | 4 37 | false 38 | 39 | 40 | true 41 | bin\x86\Debug\ 42 | DEBUG;TRACE 43 | full 44 | x86 45 | 7.3 46 | prompt 47 | MinimumRecommendedRules.ruleset 48 | false 49 | 50 | 51 | bin\x86\Release\ 52 | TRACE 53 | true 54 | pdbonly 55 | x86 56 | 7.3 57 | prompt 58 | MinimumRecommendedRules.ruleset 59 | false 60 | 61 | 62 | true 63 | bin\x64\Debug\ 64 | DEBUG;TRACE 65 | full 66 | x64 67 | 7.3 68 | prompt 69 | MinimumRecommendedRules.ruleset 70 | false 71 | 72 | 73 | bin\x64\Release\ 74 | TRACE 75 | true 76 | pdbonly 77 | x64 78 | 7.3 79 | prompt 80 | MinimumRecommendedRules.ruleset 81 | false 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /InjectedThread.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Text; 5 | 6 | namespace GetInjectedThreads 7 | { 8 | public class InjectedThread 9 | { 10 | public string ProcessName { get; set; } 11 | public int ProcessID { get; set; } 12 | public string Path { get; set; } 13 | public string KernelPath { get; set; } 14 | public string CommandLine { get; set; } 15 | public bool PathMismatch { get; set; } 16 | public int ThreadId { get; set; } 17 | public string AllocatedMemoryProtection { get; set; } 18 | public string MemoryProtection { get; set; } 19 | public string MemoryState { get; set; } 20 | public string MemoryType { get; set; } 21 | public int BasePriority { get; set; } 22 | public bool IsUniqueThreadToken { get; set; } 23 | public string Integrity { get; set; } 24 | public string Privileges { get; set; } 25 | public string LogonId { get; set; } 26 | public string SecurityIdentifier { get; set; } 27 | public string Username { get; set; } 28 | public DateTime LogonSessionStartTime { get; set; } 29 | public string LogonType { get; set; } 30 | public string AuthenticationPackage { get; set; } 31 | public IntPtr BaseAddress { get; set; } 32 | public int Size { get; set; } 33 | public byte[] ProcessBytes { get; set; } 34 | public byte[] ThreadBytes { get; set; } 35 | public DateTime ThreadStartTime { get; set; } 36 | 37 | public void OutputToConsole() 38 | { 39 | const string format = "{0,-32} : {1}"; 40 | Console.WriteLine(); 41 | Console.WriteLine(format, "ProcessName", ProcessName); 42 | Console.WriteLine(format, "ProcessId", ProcessID); 43 | Console.WriteLine(format, "Path", Path); 44 | Console.WriteLine(format, "KernelPath", KernelPath); 45 | Console.WriteLine(format, "CommandLine", CommandLine); 46 | Console.WriteLine(format, "PathMismatch", PathMismatch); 47 | Console.WriteLine(format, "ThreadId", ThreadId); 48 | Console.WriteLine(format, "AllocatedMemoryProtection", AllocatedMemoryProtection); 49 | Console.WriteLine(format, "MemoryProtection", MemoryProtection); 50 | Console.WriteLine(format, "MemoryState", MemoryState); 51 | Console.WriteLine(format, "MemoryType", MemoryType); 52 | Console.WriteLine(format, "BasePriority", BasePriority); 53 | Console.WriteLine(format, "IsUniqueThreadToken", IsUniqueThreadToken); 54 | Console.WriteLine(format, "Integrity", Integrity); 55 | Console.WriteLine(format, "Privileges", Privileges); 56 | Console.WriteLine(format, "LogonId", LogonId); 57 | Console.WriteLine(format, "SecurityIdentifier", SecurityIdentifier); 58 | Console.WriteLine(format, "Username", Username); 59 | Console.WriteLine(format, "LogonSessionStartTime", LogonSessionStartTime); 60 | Console.WriteLine(format, "LogonType", LogonType); 61 | Console.WriteLine(format, "AuthenticationPackage", AuthenticationPackage); 62 | Console.WriteLine(format, "BaseAddress", BaseAddress); 63 | Console.WriteLine(format, "Size", Size); 64 | Console.WriteLine(format, "Bytes", ByteArrayToString(ThreadBytes)); 65 | Console.WriteLine(); 66 | } 67 | 68 | /// 69 | /// Returns first 10 bytes of byte array as a its string representation for nicer output to console 70 | /// 71 | /// 72 | /// 73 | private string ByteArrayToString(byte[] bytes) 74 | { 75 | var stringBuilder = new StringBuilder("{ "); 76 | for(int i = 0; i < 10; i++) 77 | { 78 | stringBuilder.Append(bytes[i] + ", "); 79 | } 80 | stringBuilder.Append("... }"); 81 | return stringBuilder.ToString(); 82 | } 83 | 84 | /// 85 | /// Write thread's bytes to file in the current working directory. File name includes time of write to file, process id and thread id 86 | /// 87 | public void WriteBytesToFile() 88 | { 89 | string writeTime = DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss"); 90 | string threadDumpFileName = $"{writeTime}-proc{this.ProcessID}-thread{ThreadId}.dmp"; 91 | string procDumpFileName = $"{writeTime}-proc{this.ProcessID}.dmp"; 92 | 93 | if (this.ThreadBytes != null) 94 | { 95 | Console.WriteLine($"Writing injected thread bytes to file: {threadDumpFileName}"); 96 | File.WriteAllBytes(threadDumpFileName, this.ThreadBytes); 97 | } 98 | 99 | if (this.ProcessBytes != null) 100 | { 101 | Console.WriteLine($"Writing process bytes to file: {procDumpFileName}"); 102 | File.WriteAllBytes(procDumpFileName, this.ProcessBytes); 103 | } 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /MigrationBackup/9bf7db1d/GetInjectedThreads/GetInjectedThreads.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | Debug 7 | AnyCPU 8 | {B8A0CAB9-6BCC-4814-8664-BAA6462B7DE1} 9 | Exe 10 | GetInjectedThreads 11 | GetInjectedThreads 12 | v4.6 13 | 512 14 | true 15 | 16 | 17 | 18 | 19 | 20 | AnyCPU 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | false 29 | 30 | 31 | AnyCPU 32 | pdbonly 33 | true 34 | bin\Release\ 35 | TRACE 36 | prompt 37 | 4 38 | false 39 | 40 | 41 | true 42 | bin\x86\Debug\ 43 | DEBUG;TRACE 44 | full 45 | x86 46 | 7.3 47 | prompt 48 | MinimumRecommendedRules.ruleset 49 | false 50 | 51 | 52 | bin\x86\Release\ 53 | TRACE 54 | true 55 | pdbonly 56 | x86 57 | 7.3 58 | prompt 59 | MinimumRecommendedRules.ruleset 60 | false 61 | 62 | 63 | true 64 | bin\x64\Debug\ 65 | DEBUG;TRACE 66 | full 67 | x64 68 | 7.3 69 | prompt 70 | MinimumRecommendedRules.ruleset 71 | false 72 | 73 | 74 | bin\x64\Release\ 75 | TRACE 76 | true 77 | pdbonly 78 | x64 79 | 7.3 80 | prompt 81 | MinimumRecommendedRules.ruleset 82 | false 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 122 | 123 | 124 | 125 | -------------------------------------------------------------------------------- /MigrationBackup/9bf7db1d/GetInjectedThreads/NuGetUpgradeLog.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | NuGetMigrationLog 6 |

153 | NuGet Migration Report - GetInjectedThreads

Overview

Migration to PackageReference was completed successfully. Please build and run your solution to verify that all packages are available.
154 | If you run into any problems, have feedback, questions, or concerns, please 155 | file an issue on the NuGet GitHub repository.
156 | Changed files and this report have been backed up here: 157 | C:\Users\Michaelsoft\Desktop\GetInjectedThreads\MigrationBackup\9bf7db1d\GetInjectedThreads

Packages processed

Top-level dependencies:

Package IdVersion
Microsoft.O365.Security.Native.libyara.NET 158 | v4.0.2

Transitive dependencies:

Package IdVersion
159 | No transitive dependencies found. 160 |

Package compatibility issues

Description
161 | No issues were found. 162 |
-------------------------------------------------------------------------------- /MigrationBackup/9bf7db1d/GetInjectedThreads/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("GetInjectedThreads")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("GetInjectedThreads")] 13 | [assembly: AssemblyCopyright("")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("b8a0cab9-6bcc-4814-8664-baa6462b7de1")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Structs/LSA_UNICODE_STRING.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace GetInjectedThreads.Structs 4 | { 5 | // https://docs.microsoft.com/en-us/windows/win32/api/lsalookup/ns-lsalookup-lsa_unicode_string 6 | public struct LSA_UNICODE_STRING 7 | { 8 | public UInt16 Length; 9 | public UInt16 MaximumLength; 10 | public IntPtr buffer; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Structs/MEMORY_BASIC_INFORMATION.cs: -------------------------------------------------------------------------------- 1 | using GetInjectedThreads.Enums; 2 | using System; 3 | 4 | 5 | namespace GetInjectedThreads.Structs 6 | { 7 | // MEMORY_BASIC_INFORMATION struct required for VirtualQueryEx - to read state and type fields 8 | // https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-memory_basic_information 9 | 10 | public struct MEMORY_BASIC_INFORMATION64 11 | { 12 | public ulong BaseAddress; 13 | public ulong AllocationBase; 14 | public MemoryBasicInformationProtection AllocationProtect; 15 | public int __alignment1; 16 | public UIntPtr RegionSize; 17 | public MemoryBasicInformationState State; 18 | public MemoryBasicInformationProtection Protect; 19 | public MemoryBasicInformationType Type; 20 | public int __alignment2; 21 | } 22 | 23 | public struct MEMORY_BASIC_INFORMATION32 24 | { 25 | public IntPtr BaseAddress; 26 | public IntPtr AllocationBase; 27 | public MemoryBasicInformationProtection AllocationProtect; 28 | public IntPtr RegionSize; 29 | public MemoryBasicInformationState State; 30 | public MemoryBasicInformationProtection Protect; 31 | public MemoryBasicInformationType Type; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Structs/SECURITY_LOGON_SESSION_DATA.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace GetInjectedThreads.Structs 4 | { 5 | // https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/ns-ntsecapi-security_logon_session_data 6 | public struct SECURITY_LOGON_SESSION_DATA 7 | { 8 | public UInt32 Size; 9 | public LUID LoginID; 10 | public LSA_UNICODE_STRING Username; 11 | public LSA_UNICODE_STRING LoginDomain; 12 | public LSA_UNICODE_STRING AuthenticationPackage; 13 | public UInt32 LogonType; 14 | public UInt32 Session; 15 | public IntPtr PSiD; 16 | public Int64 LoginTime; 17 | public LSA_UNICODE_STRING LogonServer; 18 | public LSA_UNICODE_STRING DnsDomainName; 19 | public LSA_UNICODE_STRING Upn; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Structs/SYSTEM_INFO.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace GetInjectedThreads.Structs 7 | { 8 | // https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info 9 | public struct SYSTEM_INFO 10 | { 11 | public ushort processorArchitecture; 12 | ushort reserved; 13 | public uint pageSize; 14 | public IntPtr minimumApplicationAddress; // minimum address 15 | public IntPtr maximumApplicationAddress; // maximum address 16 | public IntPtr activeProcessorMask; 17 | public uint numberOfProcessors; 18 | public uint processorType; 19 | public uint allocationGranularity; 20 | public ushort processorLevel; 21 | public ushort processorRevision; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Structs/THREAD_ACCESS.cs: -------------------------------------------------------------------------------- 1 | namespace GetInjectedThreads 2 | { 3 | public enum ThreadAccess : int 4 | { 5 | Terminate = 0x0001, 6 | SuspendResume = 0x0002, 7 | GetContext = 0x0008, 8 | SetContext = 0x0010, 9 | SetInformation = 0x0020, 10 | QueryInformation = 0x0040, 11 | SetThreadToken = 0x0080, 12 | Impersonate = 0x0100, 13 | DirectImpersonation = 0x0200, 14 | AllAccess = 0x001f0ffb 15 | } 16 | 17 | public enum ThreadInfoClass : int 18 | { 19 | ThreadQuerySetWin32StartAddress = 9 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Structs/TOKEN_STRUCTS.cs: -------------------------------------------------------------------------------- 1 | using GetInjectedThreads.Enums; 2 | using System; 3 | using System.Runtime.InteropServices; 4 | 5 | 6 | namespace GetInjectedThreads.Structs 7 | { 8 | // Token Structs reference 9 | // https://docs.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-gettokeninformation 10 | 11 | 12 | [StructLayout(LayoutKind.Sequential)] 13 | struct TOKEN_USER 14 | { 15 | public SID_AND_ATTRIBUTES User; 16 | } 17 | 18 | [StructLayout(LayoutKind.Sequential)] 19 | public struct SID_AND_ATTRIBUTES 20 | { 21 | public IntPtr Sid; 22 | public int Attributes; 23 | } 24 | 25 | [StructLayout(LayoutKind.Sequential)] 26 | public struct TOKEN_PRIVILEGES 27 | { 28 | public Int32 PrivilegeCount; 29 | 30 | // https://docs.microsoft.com/en-us/dotnet/standard/native-interop/customize-struct-marshaling 31 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)] 32 | public LUID_AND_ATTRIBUTES[] Privileges; 33 | } 34 | 35 | [StructLayout(LayoutKind.Sequential)] 36 | public struct LUID 37 | { 38 | public PRIVILEGE_CONSTANT LowPart; 39 | public Int32 HighPart; 40 | } 41 | 42 | [StructLayout(LayoutKind.Sequential)] 43 | public struct LUID_AND_ATTRIBUTES 44 | { 45 | public LUID Luid; 46 | public UInt32 Attributes; 47 | } 48 | 49 | [StructLayout(LayoutKind.Sequential)] 50 | public struct TOKEN_MANDATORY_LABEL 51 | { 52 | public SID_AND_ATTRIBUTES label; 53 | } 54 | 55 | [StructLayout(LayoutKind.Sequential)] 56 | // https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-token_origin 57 | public struct TOKEN_ORIGIN 58 | { 59 | public LUID OriginatingLogonSession; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | --------------------------------------------------------------------------------