├── .gitignore
├── KernelBypassSharp
├── KernelBypassSharp.csproj
├── KernelBypassSharp.sln
├── KernelSharp
│ ├── Runtime
│ │ ├── CompilerHelpers.cs
│ │ ├── CompilerServices.cs
│ │ ├── InteropServices.cs
│ │ ├── Runtime.cs
│ │ └── System.cs
│ └── WDK.cs
├── NTImage.cs
├── Program.cs
├── Util.cs
├── build.bat
└── nuget.config
├── LICENSE
├── README.md
└── UsermodeApp
├── App.config
├── MainForm.Designer.cs
├── MainForm.cs
├── MainForm.resx
├── Program.cs
├── Properties
├── AssemblyInfo.cs
├── Resources.Designer.cs
├── Resources.resx
├── Settings.Designer.cs
└── Settings.settings
└── UsermodeApp.csproj
/.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 | *.ilexe
13 | *.lnk
14 | *.map
15 | *.exe
16 | *.sys
17 |
18 | # User-specific files (MonoDevelop/Xamarin Studio)
19 | *.userprefs
20 |
21 | # Mono auto generated files
22 | mono_crash.*
23 |
24 | # Build results
25 | [Dd]ebug/
26 | [Dd]ebugPublic/
27 | [Rr]elease/
28 | [Rr]eleases/
29 | x64/
30 | x86/
31 | [Aa][Rr][Mm]/
32 | [Aa][Rr][Mm]64/
33 | bld/
34 | [Bb]in/
35 | [Oo]bj/
36 | [Ll]og/
37 | [Ll]ogs/
38 |
39 | # Visual Studio 2015/2017 cache/options directory
40 | .vs/
41 | # Uncomment if you have tasks that create the project's static files in wwwroot
42 | #wwwroot/
43 |
44 | # Visual Studio 2017 auto generated files
45 | Generated\ Files/
46 |
47 | # MSTest test Results
48 | [Tt]est[Rr]esult*/
49 | [Bb]uild[Ll]og.*
50 |
51 | # NUnit
52 | *.VisualState.xml
53 | TestResult.xml
54 | nunit-*.xml
55 |
56 | # Build Results of an ATL Project
57 | [Dd]ebugPS/
58 | [Rr]eleasePS/
59 | dlldata.c
60 |
61 | # Benchmark Results
62 | BenchmarkDotNet.Artifacts/
63 |
64 | # .NET Core
65 | project.lock.json
66 | project.fragment.lock.json
67 | artifacts/
68 |
69 | # StyleCop
70 | StyleCopReport.xml
71 |
72 | # Files built by Visual Studio
73 | *_i.c
74 | *_p.c
75 | *_h.h
76 | *.ilk
77 | *.meta
78 | *.obj
79 | *.iobj
80 | *.pch
81 | *.pdb
82 | *.ipdb
83 | *.pgc
84 | *.pgd
85 | *.rsp
86 | *.sbr
87 | *.tlb
88 | *.tli
89 | *.tlh
90 | *.tmp
91 | *.tmp_proj
92 | *_wpftmp.csproj
93 | *.log
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Visual Studio code coverage results
146 | *.coverage
147 | *.coveragexml
148 |
149 | # NCrunch
150 | _NCrunch_*
151 | .*crunch*.local.xml
152 | nCrunchTemp_*
153 |
154 | # MightyMoose
155 | *.mm.*
156 | AutoTest.Net/
157 |
158 | # Web workbench (sass)
159 | .sass-cache/
160 |
161 | # Installshield output folder
162 | [Ee]xpress/
163 |
164 | # DocProject is a documentation generator add-in
165 | DocProject/buildhelp/
166 | DocProject/Help/*.HxT
167 | DocProject/Help/*.HxC
168 | DocProject/Help/*.hhc
169 | DocProject/Help/*.hhk
170 | DocProject/Help/*.hhp
171 | DocProject/Help/Html2
172 | DocProject/Help/html
173 |
174 | # Click-Once directory
175 | publish/
176 |
177 | # Publish Web Output
178 | *.[Pp]ublish.xml
179 | *.azurePubxml
180 | # Note: Comment the next line if you want to checkin your web deploy settings,
181 | # but database connection strings (with potential passwords) will be unencrypted
182 | *.pubxml
183 | *.publishproj
184 |
185 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
186 | # checkin your Azure Web App publish settings, but sensitive information contained
187 | # in these scripts will be unencrypted
188 | PublishScripts/
189 |
190 | # NuGet Packages
191 | *.nupkg
192 | # NuGet Symbol Packages
193 | *.snupkg
194 | # The packages folder can be ignored because of Package Restore
195 | **/[Pp]ackages/*
196 | # except build/, which is used as an MSBuild target.
197 | !**/[Pp]ackages/build/
198 | # Uncomment if necessary however generally it will be regenerated when needed
199 | #!**/[Pp]ackages/repositories.config
200 | # NuGet v3's project.json files produces more ignorable files
201 | *.nuget.props
202 | *.nuget.targets
203 |
204 | # Microsoft Azure Build Output
205 | csx/
206 | *.build.csdef
207 |
208 | # Microsoft Azure Emulator
209 | ecf/
210 | rcf/
211 |
212 | # Windows Store app package directories and files
213 | AppPackages/
214 | BundleArtifacts/
215 | Package.StoreAssociation.xml
216 | _pkginfo.txt
217 | *.appx
218 | *.appxbundle
219 | *.appxupload
220 |
221 | # Visual Studio cache files
222 | # files ending in .cache can be ignored
223 | *.[Cc]ache
224 | # but keep track of directories ending in .cache
225 | !?*.[Cc]ache/
226 |
227 | # Others
228 | ClientBin/
229 | ~$*
230 | *~
231 | *.dbmdl
232 | *.dbproj.schemaview
233 | *.jfm
234 | *.pfx
235 | *.publishsettings
236 | orleans.codegen.cs
237 |
238 | # Including strong name files can present a security risk
239 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
240 | #*.snk
241 |
242 | # Since there are multiple workflows, uncomment next line to ignore bower_components
243 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
244 | #bower_components/
245 |
246 | # RIA/Silverlight projects
247 | Generated_Code/
248 |
249 | # Backup & report files from converting an old project file
250 | # to a newer Visual Studio version. Backup files are not needed,
251 | # because we have git ;-)
252 | _UpgradeReport_Files/
253 | Backup*/
254 | UpgradeLog*.XML
255 | UpgradeLog*.htm
256 | ServiceFabricBackup/
257 | *.rptproj.bak
258 |
259 | # SQL Server files
260 | *.mdf
261 | *.ldf
262 | *.ndf
263 |
264 | # Business Intelligence projects
265 | *.rdl.data
266 | *.bim.layout
267 | *.bim_*.settings
268 | *.rptproj.rsuser
269 | *- [Bb]ackup.rdl
270 | *- [Bb]ackup ([0-9]).rdl
271 | *- [Bb]ackup ([0-9][0-9]).rdl
272 |
273 | # Microsoft Fakes
274 | FakesAssemblies/
275 |
276 | # GhostDoc plugin setting file
277 | *.GhostDoc.xml
278 |
279 | # Node.js Tools for Visual Studio
280 | .ntvs_analysis.dat
281 | node_modules/
282 |
283 | # Visual Studio 6 build log
284 | *.plg
285 |
286 | # Visual Studio 6 workspace options file
287 | *.opt
288 |
289 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
290 | *.vbw
291 |
292 | # Visual Studio LightSwitch build output
293 | **/*.HTMLClient/GeneratedArtifacts
294 | **/*.DesktopClient/GeneratedArtifacts
295 | **/*.DesktopClient/ModelManifest.xml
296 | **/*.Server/GeneratedArtifacts
297 | **/*.Server/ModelManifest.xml
298 | _Pvt_Extensions
299 |
300 | # Paket dependency manager
301 | .paket/paket.exe
302 | paket-files/
303 |
304 | # FAKE - F# Make
305 | .fake/
306 |
307 | # CodeRush personal settings
308 | .cr/personal
309 |
310 | # Python Tools for Visual Studio (PTVS)
311 | __pycache__/
312 | *.pyc
313 |
314 | # Cake - Uncomment if you are using it
315 | # tools/**
316 | # !tools/packages.config
317 |
318 | # Tabs Studio
319 | *.tss
320 |
321 | # Telerik's JustMock configuration file
322 | *.jmconfig
323 |
324 | # BizTalk build output
325 | *.btp.cs
326 | *.btm.cs
327 | *.odx.cs
328 | *.xsd.cs
329 |
330 | # OpenCover UI analysis results
331 | OpenCover/
332 |
333 | # Azure Stream Analytics local run output
334 | ASALocalRun/
335 |
336 | # MSBuild Binary and Structured Log
337 | *.binlog
338 |
339 | # NVidia Nsight GPU debugger configuration file
340 | *.nvuser
341 |
342 | # MFractors (Xamarin productivity tool) working folder
343 | .mfractor/
344 |
345 | # Local History for Visual Studio
346 | .localhistory/
347 |
348 | # BeatPulse healthcheck temp database
349 | healthchecksdb
350 |
351 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
352 | MigrationBackup/
353 |
354 | # Ionide (cross platform F# VS Code tools) working folder
355 | .ionide/
356 |
--------------------------------------------------------------------------------
/KernelBypassSharp/KernelBypassSharp.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net5.0
6 | true
7 | 9.0
8 |
9 | true
10 | true
11 | v4.0.30319
12 | false
13 | false
14 | true
15 |
16 | KernelBypassSharp
17 |
18 |
19 |
20 |
21 |
22 | Release
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/KernelBypassSharp/KernelBypassSharp.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.31624.102
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KernelBypassSharp", "KernelBypassSharp.csproj", "{451BECAD-6E93-4030-AEA6-28788F325250}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UsermodeApp", "..\UsermodeApp\UsermodeApp.csproj", "{0A503FF8-C512-441C-B84B-25E7B8CF4520}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {451BECAD-6E93-4030-AEA6-28788F325250}.Debug|Any CPU.ActiveCfg = Release|Any CPU
17 | {451BECAD-6E93-4030-AEA6-28788F325250}.Debug|Any CPU.Build.0 = Release|Any CPU
18 | {451BECAD-6E93-4030-AEA6-28788F325250}.Release|Any CPU.ActiveCfg = Release|Any CPU
19 | {451BECAD-6E93-4030-AEA6-28788F325250}.Release|Any CPU.Build.0 = Release|Any CPU
20 | {0A503FF8-C512-441C-B84B-25E7B8CF4520}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {0A503FF8-C512-441C-B84B-25E7B8CF4520}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {0A503FF8-C512-441C-B84B-25E7B8CF4520}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {0A503FF8-C512-441C-B84B-25E7B8CF4520}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {D473578D-2C7D-4E96-B270-BD236469142D}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/KernelBypassSharp/KernelSharp/Runtime/CompilerHelpers.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime;
2 |
3 | namespace Internal.Runtime.CompilerHelpers
4 | {
5 |
6 |
7 | // A class that the compiler looks for that has helpers to initialize the
8 | // process. The compiler can gracefully handle the helpers not being present,
9 | // but the class itself being absent is unhandled. Let's add an empty class.
10 | class StartupCodeHelpers
11 | {
12 | //A couple symbols the generated code will need we park them in this class
13 | // for no particular reason.These aid in transitioning to/from managed code.
14 | //Since we don't have a GC, the transition is a no-op.
15 | [RuntimeExport("RhpReversePInvoke2")]
16 | static void RhpReversePInvoke2() { }
17 | [RuntimeExport("RhpFallbackFailFast")]
18 | static void RhpFallbackFailFast() { }
19 | [RuntimeExport("RhpReversePInvokeReturn2")]
20 | static void RhpReversePInvokeReturn2() { }
21 | [RuntimeExport("RhpReversePInvoke")]
22 | static void RhpReversePInvoke() { }
23 | [RuntimeExport("RhpReversePInvokeReturn")]
24 | static void RhpReversePInvokeReturn() { }
25 | [System.Runtime.RuntimeExport("__fail_fast")]
26 | static void FailFast() { while (true) ; }
27 | [System.Runtime.RuntimeExport("RhpPInvoke")]
28 | static void RphPinvoke() { }
29 | [System.Runtime.RuntimeExport("RhpPInvokeReturn")]
30 | static void RphPinvokeReturn() { }
31 | }
32 |
33 | public class ThrowHelpers
34 | {
35 | //The function bodies can be left empty, they are only here to satisfy the compiler
36 |
37 | public enum ExceptionStringID
38 | {
39 | // TypeLoadException
40 | ClassLoadGeneral,
41 | ClassLoadExplicitGeneric,
42 | ClassLoadBadFormat,
43 | ClassLoadExplicitLayout,
44 | ClassLoadValueClassTooLarge,
45 | ClassLoadRankTooLarge,
46 |
47 | // MissingMethodException
48 | MissingMethod,
49 |
50 | // MissingFieldException
51 | MissingField,
52 |
53 | // FileNotFoundException
54 | FileLoadErrorGeneric,
55 |
56 | // InvalidProgramException
57 | InvalidProgramDefault,
58 | InvalidProgramSpecific,
59 | InvalidProgramVararg,
60 | InvalidProgramCallVirtFinalize,
61 | InvalidProgramUnmanagedCallersOnly,
62 | InvalidProgramCallAbstractMethod,
63 | InvalidProgramCallVirtStatic,
64 | InvalidProgramNonStaticMethod,
65 | InvalidProgramGenericMethod,
66 | InvalidProgramNonBlittableTypes,
67 |
68 | // BadImageFormatException
69 | BadImageFormatGeneric,
70 | }
71 |
72 | public static void ThrowInvalidProgramExceptionWithArgument(ExceptionStringID id, string methodName) { }
73 | public static void ThrowArgumentException() { }
74 | public static void ThrowOverflowException() { }
75 | public static void ThrowInvalidProgramException(ExceptionStringID id) { }
76 | }
77 | }
--------------------------------------------------------------------------------
/KernelBypassSharp/KernelSharp/Runtime/CompilerServices.cs:
--------------------------------------------------------------------------------
1 | namespace System.Runtime.CompilerServices
2 | {
3 | public class RuntimeHelpers
4 | {
5 | public static unsafe int OffsetToStringData => sizeof(IntPtr) + sizeof(int);
6 | }
7 |
8 | public sealed class ExtensionAttribute : Attribute { }
9 |
10 | public enum MethodImplOptions
11 | {
12 | Unmanaged = 0x0004,
13 | NoInlining = 0x0008,
14 | NoOptimization = 0x0040,
15 | AggressiveInlining = 0x0100,
16 | AggressiveOptimization = 0x200,
17 | InternalCall = 0x1000,
18 | }
19 |
20 | //Implementing the MethodImpl attribute for RuntimeExport to work
21 | public sealed class MethodImplAttribute : Attribute
22 | {
23 | public MethodImplAttribute(MethodImplOptions opt) { }
24 | }
25 | }
26 |
27 |
--------------------------------------------------------------------------------
/KernelBypassSharp/KernelSharp/Runtime/InteropServices.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace System.Runtime.InteropServices
4 | {
5 | public enum CallingConvention
6 | {
7 | Winapi = 1,
8 | Cdecl = 2,
9 | StdCall = 3,
10 | ThisCall = 4,
11 | FastCall = 5,
12 | }
13 |
14 | public class UnmanagedType { }
15 |
16 | #nullable enable
17 | [AttributeUsage(AttributeTargets.Method)]
18 | public sealed class UnmanagedCallersOnlyAttribute : Attribute
19 | {
20 | public UnmanagedCallersOnlyAttribute()
21 | {
22 | }
23 |
24 | ///
25 | /// Optional. If omitted, the runtime will use the default platform calling convention.
26 | ///
27 | public CallingConvention CallingConvention;
28 |
29 | ///
30 | /// Optional. If omitted, no named export is emitted during compilation.
31 | ///
32 | public string? EntryPoint;
33 | }
34 |
35 | #nullable disable
36 | [AttributeUsage(AttributeTargets.Field, Inherited = false)]
37 | public sealed class FieldOffsetAttribute : Attribute
38 | {
39 | public FieldOffsetAttribute(int offset)
40 | {
41 | Value = offset;
42 | }
43 |
44 | public int Value { get; }
45 | }
46 |
47 | sealed class StructLayoutAttribute : Attribute
48 | {
49 | public StructLayoutAttribute(LayoutKind layoutKind)
50 | {
51 | }
52 | }
53 |
54 | internal enum LayoutKind
55 | {
56 | Sequential = 0, // 0x00000008,
57 | Explicit = 2, // 0x00000010,
58 | Auto = 3, // 0x00000000,
59 | }
60 |
61 | internal enum CharSet
62 | {
63 | None = 1, // User didn't specify how to marshal strings.
64 | Ansi = 2, // Strings should be marshalled as ANSI 1 byte chars.
65 | Unicode = 3, // Strings should be marshalled as Unicode 2 byte chars.
66 | Auto = 4, // Marshal Strings in the right way for the target system.
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/KernelBypassSharp/KernelSharp/Runtime/Runtime.cs:
--------------------------------------------------------------------------------
1 | namespace System
2 | {
3 | namespace Runtime
4 | {
5 | internal sealed class RuntimeExportAttribute : Attribute
6 | {
7 | public RuntimeExportAttribute(string entry) { }
8 | }
9 |
10 | internal sealed class RuntimeImportAttribute : Attribute
11 | {
12 | public string DllName { get; }
13 | public string EntryPoint { get; }
14 |
15 | public RuntimeImportAttribute(string entry)
16 | {
17 | EntryPoint = entry;
18 | }
19 |
20 | public RuntimeImportAttribute(string dllName, string entry)
21 | {
22 | EntryPoint = entry;
23 | DllName = dllName;
24 | }
25 | }
26 | }
27 |
28 | class Array : Array { }
29 | }
--------------------------------------------------------------------------------
/KernelBypassSharp/KernelSharp/Runtime/System.cs:
--------------------------------------------------------------------------------
1 | namespace System
2 | {
3 | public class Object
4 | {
5 | #pragma warning disable 169
6 | // The layout of object is a contract with the compiler.
7 | private IntPtr m_pMethodTable;
8 | #pragma warning restore 169
9 | }
10 | public struct Void { }
11 |
12 | // The layout of primitive types is special cased because it would be recursive.
13 | // These really don't need any fields to work.
14 | public struct Boolean { }
15 | public struct Char { }
16 | public struct SByte { }
17 | public struct Byte { }
18 | public struct Int16 { }
19 | public struct UInt16 { }
20 | public struct Int32 { }
21 | public struct UInt32 { }
22 | public struct Int64 { }
23 | public struct UInt64 { }
24 | public struct IntPtr { }
25 | public struct UIntPtr { }
26 | public struct Single { }
27 | public struct Double { }
28 | public struct Type { }
29 |
30 | public abstract class ValueType { }
31 | public abstract class Enum : ValueType { }
32 |
33 | public struct Nullable where T : struct { }
34 |
35 | public sealed class String { public readonly int Length; }
36 | public abstract class Array { }
37 | public abstract class Delegate { }
38 | public abstract class MulticastDelegate : Delegate { }
39 |
40 | public struct RuntimeTypeHandle { }
41 | public struct RuntimeMethodHandle { }
42 | public struct RuntimeFieldHandle { }
43 |
44 | public class Attribute { }
45 |
46 | [AttributeUsage(AttributeTargets.Class, Inherited = true)]
47 | public sealed class AttributeUsageAttribute : Attribute
48 | {
49 | private readonly AttributeTargets _attributeTarget;
50 | private bool _allowMultiple;
51 | private bool _inherited;
52 |
53 | internal static readonly AttributeUsageAttribute Default = new AttributeUsageAttribute(AttributeTargets.All);
54 |
55 | public AttributeUsageAttribute(AttributeTargets validOn)
56 | {
57 | _attributeTarget = validOn;
58 | _inherited = true;
59 | }
60 |
61 | internal AttributeUsageAttribute(AttributeTargets validOn, bool allowMultiple, bool inherited)
62 | {
63 | _attributeTarget = validOn;
64 | _allowMultiple = allowMultiple;
65 | _inherited = inherited;
66 | }
67 |
68 | public AttributeTargets ValidOn => _attributeTarget;
69 |
70 | public bool AllowMultiple
71 | {
72 | get => _allowMultiple;
73 | set => _allowMultiple = value;
74 | }
75 |
76 | public bool Inherited
77 | {
78 | get => _inherited;
79 | set => _inherited = value;
80 | }
81 | }
82 |
83 | [AttributeUsage(AttributeTargets.Enum, Inherited = false)]
84 | public class FlagsAttribute : Attribute
85 | {
86 | public FlagsAttribute()
87 | {
88 | }
89 | }
90 |
91 | [Flags]
92 | public enum AttributeTargets
93 | {
94 | Assembly = 0x0001,
95 | Module = 0x0002,
96 | Class = 0x0004,
97 | Struct = 0x0008,
98 | Enum = 0x0010,
99 | Constructor = 0x0020,
100 | Method = 0x0040,
101 | Property = 0x0080,
102 | Field = 0x0100,
103 | Event = 0x0200,
104 | Interface = 0x0400,
105 | Parameter = 0x0800,
106 | Delegate = 0x1000,
107 | ReturnValue = 0x2000,
108 | GenericParameter = 0x4000,
109 |
110 | All = Assembly | Module | Class | Struct | Enum | Constructor |
111 | Method | Property | Field | Event | Interface | Parameter |
112 | Delegate | ReturnValue | GenericParameter
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/KernelBypassSharp/KernelSharp/WDK.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | namespace KernelSharp
6 | {
7 | public static unsafe class WDK
8 | {
9 | #region Struct Definitions
10 |
11 | public struct PEPROCESS
12 | {
13 | private void* _Value;
14 |
15 | public static implicit operator PEPROCESS(void* value)
16 | {
17 | return new PEPROCESS { _Value = value };
18 | }
19 |
20 | public static implicit operator PEPROCESS(ulong value)
21 | {
22 | return new PEPROCESS { _Value = (void*)value };
23 | }
24 |
25 | public static implicit operator void*(PEPROCESS value)
26 | {
27 | return value._Value;
28 | }
29 |
30 | public static implicit operator ulong(PEPROCESS value)
31 | {
32 | return (ulong)value._Value;
33 | }
34 | }
35 |
36 | public struct PVOID
37 | {
38 | private void* _Value;
39 |
40 | public static implicit operator PVOID(void* value)
41 | {
42 | return new PVOID { _Value = value };
43 | }
44 |
45 | public static implicit operator PVOID(ulong value)
46 | {
47 | return new PVOID { _Value = (void*)value };
48 | }
49 |
50 | public static implicit operator void*(PVOID value)
51 | {
52 | return value._Value;
53 | }
54 |
55 | public static implicit operator ulong(PVOID value)
56 | {
57 | return (ulong)value._Value;
58 | }
59 | }
60 |
61 | #endregion
62 |
63 | #region Helper Methods
64 |
65 | public static bool NT_SUCCESS(NTSTATUS status)
66 | {
67 | return (((int)(status)) >= 0);
68 | }
69 |
70 | public static char* w_str(this string str)
71 | {
72 | fixed (char* wc = str)
73 | return wc;
74 | }
75 |
76 | ///
77 | /// Converts the Wide string into a Multibyte string. The pool has to be freed after usage.
78 | ///
79 | ///
80 | ///
81 | public static char* c_str(this string str)
82 | {
83 | fixed (void* wc = str)
84 | {
85 | //Allocate pool for char* taking the null terminator into consideration
86 | var buf = ExAllocatePool(PoolType.NonPagedPool, (ulong)str.Length + 1);
87 |
88 | //convert wchar_t* to char*
89 | wcstombs((char*)buf, wc, (ulong)(str.Length * 2) + 2);
90 | return (char*)buf;
91 | }
92 | }
93 |
94 | public static ulong __readcr3()
95 | {
96 | void* buffer = stackalloc byte[0x5C0];
97 | var sat = KeSaveStateForHibernate(buffer);
98 | ulong cr3 = *(ulong*)((ulong)buffer + 0x10);
99 | return cr3;
100 | }
101 |
102 | public static ulong DbgPrintEx(uint ComponentId, uint level, string Format, PVOID vararg1)
103 | {
104 | fixed (void* wc = Format)
105 | {
106 | //Allocate memory on the stack for char* taking the null terminator into consideration
107 | var buf = stackalloc byte[Format.Length + 1];
108 |
109 | //convert wchar_t* to char*
110 | wcstombs((char*)buf, wc, (ulong)(Format.Length * 2) + 2);
111 | return _DbgPrintEx(ComponentId, level, (char*)buf, vararg1);
112 | }
113 | }
114 |
115 | #endregion
116 |
117 | #region NTAPI Imports
118 |
119 | [MethodImpl(MethodImplOptions.InternalCall)]
120 | [RuntimeImport("ntoskrnl.exe", "ExAllocatePool")]
121 | public static extern PVOID ExAllocatePool(PoolType poolType, ulong size);
122 |
123 | [MethodImpl(MethodImplOptions.InternalCall)]
124 | [RuntimeImport("ntoskrnl.exe", "ExFreePool")]
125 | public static extern void ExFreePool(PVOID pool);
126 |
127 | [MethodImpl(MethodImplOptions.InternalCall)]
128 | [RuntimeImport("ntoskrnl.exe", "KeSaveStateForHibernate")]
129 | public static extern NTSTATUS KeSaveStateForHibernate(void* state);
130 |
131 | [MethodImpl(MethodImplOptions.InternalCall)]
132 | [RuntimeImport("ntoskrnl.exe", "DbgPrintEx")]
133 | private static extern ulong _DbgPrintEx(uint ComponentId, uint level, char* Format, void* vararg1);
134 |
135 | [MethodImpl(MethodImplOptions.InternalCall)]
136 | [RuntimeImport("ntoskrnl.exe", "ExGetPreviousMode")]
137 | public static extern KProcessorMode ExGetPreviousMode();
138 |
139 | [MethodImpl(MethodImplOptions.InternalCall)]
140 | [RuntimeImport("ntoskrnl.exe", "IoGetCurrentProcess")]
141 | public static extern void* IoGetCurrentProcess();
142 |
143 | [MethodImpl(MethodImplOptions.InternalCall)]
144 | [RuntimeImport("ntoskrnl.exe", "PsLookupProcessByProcessId")]
145 | public static extern NTSTATUS PsLookupProcessByProcessId(uint ProcessId, PEPROCESS* process);
146 |
147 | [MethodImpl(MethodImplOptions.InternalCall)]
148 | [RuntimeImport("ntoskrnl.exe", "DbgBreakPoint")]
149 | public static extern void DbgBreakPoint();
150 |
151 | [MethodImpl(MethodImplOptions.InternalCall)]
152 | [RuntimeImport("ntoskrnl.exe", "wcstombs")]
153 | public static extern ulong wcstombs(char* mbstr, void* wcstr, ulong count);
154 |
155 | [MethodImpl(MethodImplOptions.InternalCall)]
156 | [RuntimeImport("ntoskrnl.exe", "strstr")]
157 | public static extern char* strstr(char* str, char* subStr);
158 |
159 | [MethodImpl(MethodImplOptions.InternalCall)]
160 | [RuntimeImport("ntoskrnl.exe", "strlen")]
161 | public static extern ulong strlen(char* str);
162 |
163 | [MethodImpl(MethodImplOptions.InternalCall)]
164 | [RuntimeImport("ntoskrnl.exe", "wcslen")]
165 | public static extern ulong wcslen(char* str);
166 |
167 | [MethodImpl(MethodImplOptions.InternalCall)]
168 | [RuntimeImport("ntoskrnl.exe", "memcmp")]
169 | public static extern int memcmp(void* buf1, void* buf2, ulong size);
170 |
171 |
172 |
173 | #endregion
174 |
175 | public static class Undocumented
176 | {
177 |
178 | [MethodImpl(MethodImplOptions.InternalCall)]
179 | [RuntimeImport("ntoskrnl.exe", "ZwQuerySystemInformation")]
180 | public static extern NTSTATUS ZwQuerySystemInformation(SystemInformationClass SystemInformationClass, void* systemInformation, uint systemInformationLength, uint* ReturnLength);
181 |
182 | [MethodImpl(MethodImplOptions.InternalCall)]
183 | [RuntimeImport("ntoskrnl.exe", "MmCopyVirtualMemory")]
184 | public static extern NTSTATUS MmCopyVirtualMemory(void* SourceProcess, void* SourceAddress, void* TargetProcess, void* TargetAddress, ulong BufferSize, KProcessorMode PreviousMode, ulong* ReturnSize);
185 |
186 | [MethodImpl(MethodImplOptions.InternalCall)]
187 | [RuntimeImport("ntoskrnl.exe", "PsGetProcessSectionBaseAddress")]
188 | public static extern PVOID PsGetProcessSectionBaseAddress(void* process);
189 |
190 | [StructLayout(LayoutKind.Sequential)]
191 | public struct RTL_PROCESS_MODULE_INFORMATION
192 | {
193 | public ulong Handle;
194 | public ulong MappedBase;
195 | public ulong ImageBase;
196 | public uint ImageSize;
197 | public uint Flags;
198 | public ushort LoadOrderIndex;
199 | public ushort InitOrderIndex;
200 | public ushort LoadCount;
201 | public ushort OffsetToFileName;
202 | public fixed byte FullPathName[256];
203 | }
204 |
205 | [StructLayout(LayoutKind.Sequential)]
206 | public struct RTL_PROCESS_MODULES
207 | {
208 | public uint NumberOfModules;
209 | public RTL_PROCESS_MODULE_INFORMATION Modules;
210 | }
211 | }
212 |
213 | #region Enums
214 |
215 | public enum KProcessorMode
216 | {
217 | KernelMode,
218 | UserMode,
219 | MaximumMode
220 | };
221 |
222 | public enum SystemInformationClass
223 | {
224 | SystemBasicInformation = 0x0,
225 | SystemProcessorInformation = 0x1,
226 | SystemPerformanceInformation = 0x2,
227 | SystemTimeOfDayInformation = 0x3,
228 | SystemPathInformation = 0x4,
229 | SystemProcessInformation = 0x5,
230 | SystemCallCountInformation = 0x6,
231 | SystemDeviceInformation = 0x7,
232 | SystemProcessorPerformanceInformation = 0x8,
233 | SystemFlagsInformation = 0x9,
234 | SystemCallTimeInformation = 0xa,
235 | SystemModuleInformation = 0xb,
236 | SystemLocksInformation = 0xc,
237 | SystemStackTraceInformation = 0xd,
238 | SystemPagedPoolInformation = 0xe,
239 | SystemNonPagedPoolInformation = 0xf,
240 | SystemHandleInformation = 0x10,
241 | SystemObjectInformation = 0x11,
242 | SystemPageFileInformation = 0x12,
243 | SystemVdmInstemulInformation = 0x13,
244 | SystemVdmBopInformation = 0x14,
245 | SystemFileCacheInformation = 0x15,
246 | SystemPoolTagInformation = 0x16,
247 | SystemInterruptInformation = 0x17,
248 | SystemDpcBehaviorInformation = 0x18,
249 | SystemFullMemoryInformation = 0x19,
250 | SystemLoadGdiDriverInformation = 0x1a,
251 | SystemUnloadGdiDriverInformation = 0x1b,
252 | SystemTimeAdjustmentInformation = 0x1c,
253 | SystemSummaryMemoryInformation = 0x1d,
254 | SystemMirrorMemoryInformation = 0x1e,
255 | SystemPerformanceTraceInformation = 0x1f,
256 | SystemObsolete0 = 0x20,
257 | SystemExceptionInformation = 0x21,
258 | SystemCrashDumpStateInformation = 0x22,
259 | SystemKernelDebuggerInformation = 0x23,
260 | SystemContextSwitchInformation = 0x24,
261 | SystemRegistryQuotaInformation = 0x25,
262 | SystemExtendServiceTableInformation = 0x26,
263 | SystemPrioritySeperation = 0x27,
264 | SystemVerifierAddDriverInformation = 0x28,
265 | SystemVerifierRemoveDriverInformation = 0x29,
266 | SystemProcessorIdleInformation = 0x2a,
267 | SystemLegacyDriverInformation = 0x2b,
268 | SystemCurrentTimeZoneInformation = 0x2c,
269 | SystemLookasideInformation = 0x2d,
270 | SystemTimeSlipNotification = 0x2e,
271 | SystemSessionCreate = 0x2f,
272 | SystemSessionDetach = 0x30,
273 | SystemSessionInformation = 0x31,
274 | SystemRangeStartInformation = 0x32,
275 | SystemVerifierInformation = 0x33,
276 | SystemVerifierThunkExtend = 0x34,
277 | SystemSessionProcessInformation = 0x35,
278 | SystemLoadGdiDriverInSystemSpace = 0x36,
279 | SystemNumaProcessorMap = 0x37,
280 | SystemPrefetcherInformation = 0x38,
281 | SystemExtendedProcessInformation = 0x39,
282 | SystemRecommendedSharedDataAlignment = 0x3a,
283 | SystemComPlusPackage = 0x3b,
284 | SystemNumaAvailableMemory = 0x3c,
285 | SystemProcessorPowerInformation = 0x3d,
286 | SystemEmulationBasicInformation = 0x3e,
287 | SystemEmulationProcessorInformation = 0x3f,
288 | SystemExtendedHandleInformation = 0x40,
289 | SystemLostDelayedWriteInformation = 0x41,
290 | SystemBigPoolInformation = 0x42,
291 | SystemSessionPoolTagInformation = 0x43,
292 | SystemSessionMappedViewInformation = 0x44,
293 | SystemHotpatchInformation = 0x45,
294 | SystemObjectSecurityMode = 0x46,
295 | SystemWatchdogTimerHandler = 0x47,
296 | SystemWatchdogTimerInformation = 0x48,
297 | SystemLogicalProcessorInformation = 0x49,
298 | SystemWow64SharedInformationObsolete = 0x4a,
299 | SystemRegisterFirmwareTableInformationHandler = 0x4b,
300 | SystemFirmwareTableInformation = 0x4c,
301 | SystemModuleInformationEx = 0x4d,
302 | SystemVerifierTriageInformation = 0x4e,
303 | SystemSuperfetchInformation = 0x4f,
304 | SystemMemoryListInformation = 0x50,
305 | SystemFileCacheInformationEx = 0x51,
306 | SystemThreadPriorityClientIdInformation = 0x52,
307 | SystemProcessorIdleCycleTimeInformation = 0x53,
308 | SystemVerifierCancellationInformation = 0x54,
309 | SystemProcessorPowerInformationEx = 0x55,
310 | SystemRefTraceInformation = 0x56,
311 | SystemSpecialPoolInformation = 0x57,
312 | SystemProcessIdInformation = 0x58,
313 | SystemErrorPortInformation = 0x59,
314 | SystemBootEnvironmentInformation = 0x5a,
315 | SystemHypervisorInformation = 0x5b,
316 | SystemVerifierInformationEx = 0x5c,
317 | SystemTimeZoneInformation = 0x5d,
318 | SystemImageFileExecutionOptionsInformation = 0x5e,
319 | SystemCoverageInformation = 0x5f,
320 | SystemPrefetchPatchInformation = 0x60,
321 | SystemVerifierFaultsInformation = 0x61,
322 | SystemSystemPartitionInformation = 0x62,
323 | SystemSystemDiskInformation = 0x63,
324 | SystemProcessorPerformanceDistribution = 0x64,
325 | SystemNumaProximityNodeInformation = 0x65,
326 | SystemDynamicTimeZoneInformation = 0x66,
327 | SystemCodeIntegrityInformation = 0x67,
328 | SystemProcessorMicrocodeUpdateInformation = 0x68,
329 | SystemProcessorBrandString = 0x69,
330 | SystemVirtualAddressInformation = 0x6a,
331 | SystemLogicalProcessorAndGroupInformation = 0x6b,
332 | SystemProcessorCycleTimeInformation = 0x6c,
333 | SystemStoreInformation = 0x6d,
334 | SystemRegistryAppendString = 0x6e,
335 | SystemAitSamplingValue = 0x6f,
336 | SystemVhdBootInformation = 0x70,
337 | SystemCpuQuotaInformation = 0x71,
338 | SystemNativeBasicInformation = 0x72,
339 | SystemErrorPortTimeouts = 0x73,
340 | SystemLowPriorityIoInformation = 0x74,
341 | SystemBootEntropyInformation = 0x75,
342 | SystemVerifierCountersInformation = 0x76,
343 | SystemPagedPoolInformationEx = 0x77,
344 | SystemSystemPtesInformationEx = 0x78,
345 | SystemNodeDistanceInformation = 0x79,
346 | SystemAcpiAuditInformation = 0x7a,
347 | SystemBasicPerformanceInformation = 0x7b,
348 | SystemQueryPerformanceCounterInformation = 0x7c,
349 | SystemSessionBigPoolInformation = 0x7d,
350 | SystemBootGraphicsInformation = 0x7e,
351 | SystemScrubPhysicalMemoryInformation = 0x7f,
352 | SystemBadPageInformation = 0x80,
353 | SystemProcessorProfileControlArea = 0x81,
354 | SystemCombinePhysicalMemoryInformation = 0x82,
355 | SystemEntropyInterruptTimingInformation = 0x83,
356 | SystemConsoleInformation = 0x84,
357 | SystemPlatformBinaryInformation = 0x85,
358 | SystemThrottleNotificationInformation = 0x86,
359 | SystemHypervisorProcessorCountInformation = 0x87,
360 | SystemDeviceDataInformation = 0x88,
361 | SystemDeviceDataEnumerationInformation = 0x89,
362 | SystemMemoryTopologyInformation = 0x8a,
363 | SystemMemoryChannelInformation = 0x8b,
364 | SystemBootLogoInformation = 0x8c,
365 | SystemProcessorPerformanceInformationEx = 0x8d,
366 | SystemSpare0 = 0x8e,
367 | SystemSecureBootPolicyInformation = 0x8f,
368 | SystemPageFileInformationEx = 0x90,
369 | SystemSecureBootInformation = 0x91,
370 | SystemEntropyInterruptTimingRawInformation = 0x92,
371 | SystemPortableWorkspaceEfiLauncherInformation = 0x93,
372 | SystemFullProcessInformation = 0x94,
373 | SystemKernelDebuggerInformationEx = 0x95,
374 | SystemBootMetadataInformation = 0x96,
375 | SystemSoftRebootInformation = 0x97,
376 | SystemElamCertificateInformation = 0x98,
377 | SystemOfflineDumpConfigInformation = 0x99,
378 | SystemProcessorFeaturesInformation = 0x9a,
379 | SystemRegistryReconciliationInformation = 0x9b,
380 | SystemSupportedProcessArchitectures = 0xb5,
381 | }
382 |
383 | public enum PoolType
384 | {
385 | NonPagedPool,
386 | NonPagedPoolExecute = NonPagedPool,
387 | PagedPool,
388 | NonPagedPoolMustSucceed = NonPagedPool + 2,
389 | DontUseThisType,
390 | NonPagedPoolCacheAligned = NonPagedPool + 4,
391 | PagedPoolCacheAligned,
392 | NonPagedPoolCacheAlignedMustS = NonPagedPool + 6,
393 | MaxPoolType,
394 | NonPagedPoolBase = 0,
395 | NonPagedPoolBaseMustSucceed = NonPagedPoolBase + 2,
396 | NonPagedPoolBaseCacheAligned = NonPagedPoolBase + 4,
397 | NonPagedPoolBaseCacheAlignedMustS = NonPagedPoolBase + 6,
398 | NonPagedPoolSession = 32,
399 | PagedPoolSession = NonPagedPoolSession + 1,
400 | NonPagedPoolMustSucceedSession = PagedPoolSession + 1,
401 | DontUseThisTypeSession = NonPagedPoolMustSucceedSession + 1,
402 | NonPagedPoolCacheAlignedSession = DontUseThisTypeSession + 1,
403 | PagedPoolCacheAlignedSession = NonPagedPoolCacheAlignedSession + 1,
404 | NonPagedPoolCacheAlignedMustSSession = PagedPoolCacheAlignedSession + 1,
405 | NonPagedPoolNx = 512,
406 | NonPagedPoolNxCacheAligned = NonPagedPoolNx + 4,
407 | NonPagedPoolSessionNx = NonPagedPoolNx + 32,
408 | }
409 |
410 | public enum NTSTATUS : uint
411 | {
412 | // Success
413 | Success = 0x00000000,
414 | Wait0 = 0x00000000,
415 | Wait1 = 0x00000001,
416 | Wait2 = 0x00000002,
417 | Wait3 = 0x00000003,
418 | Wait63 = 0x0000003f,
419 | Abandoned = 0x00000080,
420 | AbandonedWait0 = 0x00000080,
421 | AbandonedWait1 = 0x00000081,
422 | AbandonedWait2 = 0x00000082,
423 | AbandonedWait3 = 0x00000083,
424 | AbandonedWait63 = 0x000000bf,
425 | UserApc = 0x000000c0,
426 | KernelApc = 0x00000100,
427 | Alerted = 0x00000101,
428 | Timeout = 0x00000102,
429 | Pending = 0x00000103,
430 | Reparse = 0x00000104,
431 | MoreEntries = 0x00000105,
432 | NotAllAssigned = 0x00000106,
433 | SomeNotMapped = 0x00000107,
434 | OpLockBreakInProgress = 0x00000108,
435 | VolumeMounted = 0x00000109,
436 | RxActCommitted = 0x0000010a,
437 | NotifyCleanup = 0x0000010b,
438 | NotifyEnumDir = 0x0000010c,
439 | NoQuotasForAccount = 0x0000010d,
440 | PrimaryTransportConnectFailed = 0x0000010e,
441 | PageFaultTransition = 0x00000110,
442 | PageFaultDemandZero = 0x00000111,
443 | PageFaultCopyOnWrite = 0x00000112,
444 | PageFaultGuardPage = 0x00000113,
445 | PageFaultPagingFile = 0x00000114,
446 | CrashDump = 0x00000116,
447 | ReparseObject = 0x00000118,
448 | NothingToTerminate = 0x00000122,
449 | ProcessNotInJob = 0x00000123,
450 | ProcessInJob = 0x00000124,
451 | ProcessCloned = 0x00000129,
452 | FileLockedWithOnlyReaders = 0x0000012a,
453 | FileLockedWithWriters = 0x0000012b,
454 |
455 | // Informational
456 | Informational = 0x40000000,
457 | ObjectNameExists = 0x40000000,
458 | ThreadWasSuspended = 0x40000001,
459 | WorkingSetLimitRange = 0x40000002,
460 | ImageNotAtBase = 0x40000003,
461 | RegistryRecovered = 0x40000009,
462 |
463 | // Warning
464 | Warning = 0x80000000,
465 | GuardPageViolation = 0x80000001,
466 | DatatypeMisalignment = 0x80000002,
467 | Breakpoint = 0x80000003,
468 | SingleStep = 0x80000004,
469 | BufferOverflow = 0x80000005,
470 | NoMoreFiles = 0x80000006,
471 | HandlesClosed = 0x8000000a,
472 | PartialCopy = 0x8000000d,
473 | DeviceBusy = 0x80000011,
474 | InvalidEaName = 0x80000013,
475 | EaListInconsistent = 0x80000014,
476 | NoMoreEntries = 0x8000001a,
477 | LongJump = 0x80000026,
478 | DllMightBeInsecure = 0x8000002b,
479 |
480 | // Error
481 | Error = 0xc0000000,
482 | Unsuccessful = 0xc0000001,
483 | NotImplemented = 0xc0000002,
484 | InvalidInfoClass = 0xc0000003,
485 | InfoLengthMismatch = 0xc0000004,
486 | AccessViolation = 0xc0000005,
487 | InPageError = 0xc0000006,
488 | PagefileQuota = 0xc0000007,
489 | InvalidHandle = 0xc0000008,
490 | BadInitialStack = 0xc0000009,
491 | BadInitialPc = 0xc000000a,
492 | InvalidCid = 0xc000000b,
493 | TimerNotCanceled = 0xc000000c,
494 | InvalidParameter = 0xc000000d,
495 | NoSuchDevice = 0xc000000e,
496 | NoSuchFile = 0xc000000f,
497 | InvalidDeviceRequest = 0xc0000010,
498 | EndOfFile = 0xc0000011,
499 | WrongVolume = 0xc0000012,
500 | NoMediaInDevice = 0xc0000013,
501 | NoMemory = 0xc0000017,
502 | NotMappedView = 0xc0000019,
503 | UnableToFreeVm = 0xc000001a,
504 | UnableToDeleteSection = 0xc000001b,
505 | IllegalInstruction = 0xc000001d,
506 | AlreadyCommitted = 0xc0000021,
507 | AccessDenied = 0xc0000022,
508 | BufferTooSmall = 0xc0000023,
509 | ObjectTypeMismatch = 0xc0000024,
510 | NonContinuableException = 0xc0000025,
511 | BadStack = 0xc0000028,
512 | NotLocked = 0xc000002a,
513 | NotCommitted = 0xc000002d,
514 | InvalidParameterMix = 0xc0000030,
515 | ObjectNameInvalid = 0xc0000033,
516 | ObjectNameNotFound = 0xc0000034,
517 | ObjectNameCollision = 0xc0000035,
518 | ObjectPathInvalid = 0xc0000039,
519 | ObjectPathNotFound = 0xc000003a,
520 | ObjectPathSyntaxBad = 0xc000003b,
521 | DataOverrun = 0xc000003c,
522 | DataLate = 0xc000003d,
523 | DataError = 0xc000003e,
524 | CrcError = 0xc000003f,
525 | SectionTooBig = 0xc0000040,
526 | PortConnectionRefused = 0xc0000041,
527 | InvalidPortHandle = 0xc0000042,
528 | SharingViolation = 0xc0000043,
529 | QuotaExceeded = 0xc0000044,
530 | InvalidPageProtection = 0xc0000045,
531 | MutantNotOwned = 0xc0000046,
532 | SemaphoreLimitExceeded = 0xc0000047,
533 | PortAlreadySet = 0xc0000048,
534 | SectionNotImage = 0xc0000049,
535 | SuspendCountExceeded = 0xc000004a,
536 | ThreadIsTerminating = 0xc000004b,
537 | BadWorkingSetLimit = 0xc000004c,
538 | IncompatibleFileMap = 0xc000004d,
539 | SectionProtection = 0xc000004e,
540 | EasNotSupported = 0xc000004f,
541 | EaTooLarge = 0xc0000050,
542 | NonExistentEaEntry = 0xc0000051,
543 | NoEasOnFile = 0xc0000052,
544 | EaCorruptError = 0xc0000053,
545 | FileLockConflict = 0xc0000054,
546 | LockNotGranted = 0xc0000055,
547 | DeletePending = 0xc0000056,
548 | CtlFileNotSupported = 0xc0000057,
549 | UnknownRevision = 0xc0000058,
550 | RevisionMismatch = 0xc0000059,
551 | InvalidOwner = 0xc000005a,
552 | InvalidPrimaryGroup = 0xc000005b,
553 | NoImpersonationToken = 0xc000005c,
554 | CantDisableMandatory = 0xc000005d,
555 | NoLogonServers = 0xc000005e,
556 | NoSuchLogonSession = 0xc000005f,
557 | NoSuchPrivilege = 0xc0000060,
558 | PrivilegeNotHeld = 0xc0000061,
559 | InvalidAccountName = 0xc0000062,
560 | UserExists = 0xc0000063,
561 | NoSuchUser = 0xc0000064,
562 | GroupExists = 0xc0000065,
563 | NoSuchGroup = 0xc0000066,
564 | MemberInGroup = 0xc0000067,
565 | MemberNotInGroup = 0xc0000068,
566 | LastAdmin = 0xc0000069,
567 | WrongPassword = 0xc000006a,
568 | IllFormedPassword = 0xc000006b,
569 | PasswordRestriction = 0xc000006c,
570 | LogonFailure = 0xc000006d,
571 | AccountRestriction = 0xc000006e,
572 | InvalidLogonHours = 0xc000006f,
573 | InvalidWorkstation = 0xc0000070,
574 | PasswordExpired = 0xc0000071,
575 | AccountDisabled = 0xc0000072,
576 | NoneMapped = 0xc0000073,
577 | TooManyLuidsRequested = 0xc0000074,
578 | LuidsExhausted = 0xc0000075,
579 | InvalidSubAuthority = 0xc0000076,
580 | InvalidAcl = 0xc0000077,
581 | InvalidSid = 0xc0000078,
582 | InvalidSecurityDescr = 0xc0000079,
583 | ProcedureNotFound = 0xc000007a,
584 | InvalidImageFormat = 0xc000007b,
585 | NoToken = 0xc000007c,
586 | BadInheritanceAcl = 0xc000007d,
587 | RangeNotLocked = 0xc000007e,
588 | DiskFull = 0xc000007f,
589 | ServerDisabled = 0xc0000080,
590 | ServerNotDisabled = 0xc0000081,
591 | TooManyGuidsRequested = 0xc0000082,
592 | GuidsExhausted = 0xc0000083,
593 | InvalidIdAuthority = 0xc0000084,
594 | AgentsExhausted = 0xc0000085,
595 | InvalidVolumeLabel = 0xc0000086,
596 | SectionNotExtended = 0xc0000087,
597 | NotMappedData = 0xc0000088,
598 | ResourceDataNotFound = 0xc0000089,
599 | ResourceTypeNotFound = 0xc000008a,
600 | ResourceNameNotFound = 0xc000008b,
601 | ArrayBoundsExceeded = 0xc000008c,
602 | FloatDenormalOperand = 0xc000008d,
603 | FloatDivideByZero = 0xc000008e,
604 | FloatInexactResult = 0xc000008f,
605 | FloatInvalidOperation = 0xc0000090,
606 | FloatOverflow = 0xc0000091,
607 | FloatStackCheck = 0xc0000092,
608 | FloatUnderflow = 0xc0000093,
609 | IntegerDivideByZero = 0xc0000094,
610 | IntegerOverflow = 0xc0000095,
611 | PrivilegedInstruction = 0xc0000096,
612 | TooManyPagingFiles = 0xc0000097,
613 | FileInvalid = 0xc0000098,
614 | InstanceNotAvailable = 0xc00000ab,
615 | PipeNotAvailable = 0xc00000ac,
616 | InvalidPipeState = 0xc00000ad,
617 | PipeBusy = 0xc00000ae,
618 | IllegalFunction = 0xc00000af,
619 | PipeDisconnected = 0xc00000b0,
620 | PipeClosing = 0xc00000b1,
621 | PipeConnected = 0xc00000b2,
622 | PipeListening = 0xc00000b3,
623 | InvalidReadMode = 0xc00000b4,
624 | IoTimeout = 0xc00000b5,
625 | FileForcedClosed = 0xc00000b6,
626 | ProfilingNotStarted = 0xc00000b7,
627 | ProfilingNotStopped = 0xc00000b8,
628 | NotSameDevice = 0xc00000d4,
629 | FileRenamed = 0xc00000d5,
630 | CantWait = 0xc00000d8,
631 | PipeEmpty = 0xc00000d9,
632 | CantTerminateSelf = 0xc00000db,
633 | InternalError = 0xc00000e5,
634 | InvalidParameter1 = 0xc00000ef,
635 | InvalidParameter2 = 0xc00000f0,
636 | InvalidParameter3 = 0xc00000f1,
637 | InvalidParameter4 = 0xc00000f2,
638 | InvalidParameter5 = 0xc00000f3,
639 | InvalidParameter6 = 0xc00000f4,
640 | InvalidParameter7 = 0xc00000f5,
641 | InvalidParameter8 = 0xc00000f6,
642 | InvalidParameter9 = 0xc00000f7,
643 | InvalidParameter10 = 0xc00000f8,
644 | InvalidParameter11 = 0xc00000f9,
645 | InvalidParameter12 = 0xc00000fa,
646 | MappedFileSizeZero = 0xc000011e,
647 | TooManyOpenedFiles = 0xc000011f,
648 | Cancelled = 0xc0000120,
649 | CannotDelete = 0xc0000121,
650 | InvalidComputerName = 0xc0000122,
651 | FileDeleted = 0xc0000123,
652 | SpecialAccount = 0xc0000124,
653 | SpecialGroup = 0xc0000125,
654 | SpecialUser = 0xc0000126,
655 | MembersPrimaryGroup = 0xc0000127,
656 | FileClosed = 0xc0000128,
657 | TooManyThreads = 0xc0000129,
658 | ThreadNotInProcess = 0xc000012a,
659 | TokenAlreadyInUse = 0xc000012b,
660 | PagefileQuotaExceeded = 0xc000012c,
661 | CommitmentLimit = 0xc000012d,
662 | InvalidImageLeFormat = 0xc000012e,
663 | InvalidImageNotMz = 0xc000012f,
664 | InvalidImageProtect = 0xc0000130,
665 | InvalidImageWin16 = 0xc0000131,
666 | LogonServer = 0xc0000132,
667 | DifferenceAtDc = 0xc0000133,
668 | SynchronizationRequired = 0xc0000134,
669 | DllNotFound = 0xc0000135,
670 | IoPrivilegeFailed = 0xc0000137,
671 | OrdinalNotFound = 0xc0000138,
672 | EntryPointNotFound = 0xc0000139,
673 | ControlCExit = 0xc000013a,
674 | PortNotSet = 0xc0000353,
675 | DebuggerInactive = 0xc0000354,
676 | CallbackBypass = 0xc0000503,
677 | PortClosed = 0xc0000700,
678 | MessageLost = 0xc0000701,
679 | InvalidMessage = 0xc0000702,
680 | RequestCanceled = 0xc0000703,
681 | RecursiveDispatch = 0xc0000704,
682 | LpcReceiveBufferExpected = 0xc0000705,
683 | LpcInvalidConnectionUsage = 0xc0000706,
684 | LpcRequestsNotAllowed = 0xc0000707,
685 | ResourceInUse = 0xc0000708,
686 | ProcessIsProtected = 0xc0000712,
687 | VolumeDirty = 0xc0000806,
688 | FileCheckedOut = 0xc0000901,
689 | CheckOutRequired = 0xc0000902,
690 | BadFileType = 0xc0000903,
691 | FileTooLarge = 0xc0000904,
692 | FormsAuthRequired = 0xc0000905,
693 | VirusInfected = 0xc0000906,
694 | VirusDeleted = 0xc0000907,
695 | TransactionalConflict = 0xc0190001,
696 | InvalidTransaction = 0xc0190002,
697 | TransactionNotActive = 0xc0190003,
698 | TmInitializationFailed = 0xc0190004,
699 | RmNotActive = 0xc0190005,
700 | RmMetadataCorrupt = 0xc0190006,
701 | TransactionNotJoined = 0xc0190007,
702 | DirectoryNotRm = 0xc0190008,
703 | CouldNotResizeLog = 0xc0190009,
704 | TransactionsUnsupportedRemote = 0xc019000a,
705 | LogResizeInvalidSize = 0xc019000b,
706 | RemoteFileVersionMismatch = 0xc019000c,
707 | CrmProtocolAlreadyExists = 0xc019000f,
708 | TransactionPropagationFailed = 0xc0190010,
709 | CrmProtocolNotFound = 0xc0190011,
710 | TransactionSuperiorExists = 0xc0190012,
711 | TransactionRequestNotValid = 0xc0190013,
712 | TransactionNotRequested = 0xc0190014,
713 | TransactionAlreadyAborted = 0xc0190015,
714 | TransactionAlreadyCommitted = 0xc0190016,
715 | TransactionInvalidMarshallBuffer = 0xc0190017,
716 | CurrentTransactionNotValid = 0xc0190018,
717 | LogGrowthFailed = 0xc0190019,
718 | ObjectNoLongerExists = 0xc0190021,
719 | StreamMiniversionNotFound = 0xc0190022,
720 | StreamMiniversionNotValid = 0xc0190023,
721 | MiniversionInaccessibleFromSpecifiedTransaction = 0xc0190024,
722 | CantOpenMiniversionWithModifyIntent = 0xc0190025,
723 | CantCreateMoreStreamMiniversions = 0xc0190026,
724 | HandleNoLongerValid = 0xc0190028,
725 | NoTxfMetadata = 0xc0190029,
726 | LogCorruptionDetected = 0xc0190030,
727 | CantRecoverWithHandleOpen = 0xc0190031,
728 | RmDisconnected = 0xc0190032,
729 | EnlistmentNotSuperior = 0xc0190033,
730 | RecoveryNotNeeded = 0xc0190034,
731 | RmAlreadyStarted = 0xc0190035,
732 | FileIdentityNotPersistent = 0xc0190036,
733 | CantBreakTransactionalDependency = 0xc0190037,
734 | CantCrossRmBoundary = 0xc0190038,
735 | TxfDirNotEmpty = 0xc0190039,
736 | IndoubtTransactionsExist = 0xc019003a,
737 | TmVolatile = 0xc019003b,
738 | RollbackTimerExpired = 0xc019003c,
739 | TxfAttributeCorrupt = 0xc019003d,
740 | EfsNotAllowedInTransaction = 0xc019003e,
741 | TransactionalOpenNotAllowed = 0xc019003f,
742 | TransactedMappingUnsupportedRemote = 0xc0190040,
743 | TxfMetadataAlreadyPresent = 0xc0190041,
744 | TransactionScopeCallbacksNotSet = 0xc0190042,
745 | TransactionRequiredPromotion = 0xc0190043,
746 | CannotExecuteFileInTransaction = 0xc0190044,
747 | TransactionsNotFrozen = 0xc0190045,
748 |
749 | MaximumNtStatus = 0xffffffff
750 | }
751 | #endregion
752 | }
753 | }
754 |
755 |
--------------------------------------------------------------------------------
/KernelBypassSharp/NTImage.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 |
4 | namespace KernelSharp
5 | {
6 | public static class NTImage
7 | {
8 | [StructLayout(LayoutKind.Sequential)]
9 | public unsafe struct IMAGE_DOS_HEADER
10 | {
11 | public UInt16 e_magic;
12 | public UInt16 e_cblp; // Bytes on last page of file
13 | public UInt16 e_cp; // Pages in file
14 | public UInt16 e_crlc; // Relocations
15 | public UInt16 e_cparhdr; // Size of header in paragraphs
16 | public UInt16 e_minalloc; // Minimum extra paragraphs needed
17 | public UInt16 e_maxalloc; // Maximum extra paragraphs needed
18 | public UInt16 e_ss; // Initial (relative) SS value
19 | public UInt16 e_sp; // Initial SP value
20 | public UInt16 e_csum; // Checksum
21 | public UInt16 e_ip; // Initial IP value
22 | public UInt16 e_cs; // Initial (relative) CS value
23 | public UInt16 e_lfarlc; // File address of relocation table
24 | public UInt16 e_ovno; // Overlay number
25 | public fixed UInt16 e_res1[4]; // Reserved words
26 | public UInt16 e_oemid; // OEM identifier (for e_oeminfo)
27 | public UInt16 e_oeminfo; // OEM information; e_oemid specific
28 | public fixed UInt16 e_res2[10]; // Reserved words
29 | public Int32 e_lfanew; // File address of new exe header
30 | }
31 |
32 | [StructLayout(LayoutKind.Explicit)]
33 | public struct IMAGE_NT_HEADERS64
34 | {
35 | [FieldOffset(0)]
36 | public uint Signature;
37 |
38 | [FieldOffset(4)]
39 | public IMAGE_FILE_HEADER FileHeader;
40 |
41 | [FieldOffset(24)]
42 | public IMAGE_OPTIONAL_HEADER64 OptionalHeader;
43 | }
44 |
45 | [StructLayout(LayoutKind.Sequential)]
46 | public struct IMAGE_FILE_HEADER
47 | {
48 | public UInt16 Machine;
49 | public UInt16 NumberOfSections;
50 | public UInt32 TimeDateStamp;
51 | public UInt32 PointerToSymbolTable;
52 | public UInt32 NumberOfSymbols;
53 | public UInt16 SizeOfOptionalHeader;
54 | public UInt16 Characteristics;
55 | }
56 |
57 | [StructLayout(LayoutKind.Explicit)]
58 | public struct IMAGE_OPTIONAL_HEADER64
59 | {
60 | [FieldOffset(0)]
61 | public MagicType Magic;
62 |
63 | [FieldOffset(2)]
64 | public byte MajorLinkerVersion;
65 |
66 | [FieldOffset(3)]
67 | public byte MinorLinkerVersion;
68 |
69 | [FieldOffset(4)]
70 | public uint SizeOfCode;
71 |
72 | [FieldOffset(8)]
73 | public uint SizeOfInitializedData;
74 |
75 | [FieldOffset(12)]
76 | public uint SizeOfUninitializedData;
77 |
78 | [FieldOffset(16)]
79 | public uint AddressOfEntryPoint;
80 |
81 | [FieldOffset(20)]
82 | public uint BaseOfCode;
83 |
84 | [FieldOffset(24)]
85 | public ulong ImageBase;
86 |
87 | [FieldOffset(32)]
88 | public uint SectionAlignment;
89 |
90 | [FieldOffset(36)]
91 | public uint FileAlignment;
92 |
93 | [FieldOffset(40)]
94 | public ushort MajorOperatingSystemVersion;
95 |
96 | [FieldOffset(42)]
97 | public ushort MinorOperatingSystemVersion;
98 |
99 | [FieldOffset(44)]
100 | public ushort MajorImageVersion;
101 |
102 | [FieldOffset(46)]
103 | public ushort MinorImageVersion;
104 |
105 | [FieldOffset(48)]
106 | public ushort MajorSubsystemVersion;
107 |
108 | [FieldOffset(50)]
109 | public ushort MinorSubsystemVersion;
110 |
111 | [FieldOffset(52)]
112 | public uint Win32VersionValue;
113 |
114 | [FieldOffset(56)]
115 | public uint SizeOfImage;
116 |
117 | [FieldOffset(60)]
118 | public uint SizeOfHeaders;
119 |
120 | [FieldOffset(64)]
121 | public uint CheckSum;
122 |
123 | [FieldOffset(68)]
124 | public SubSystemType Subsystem;
125 |
126 | [FieldOffset(70)]
127 | public DllCharacteristicsType DllCharacteristics;
128 |
129 | [FieldOffset(72)]
130 | public ulong SizeOfStackReserve;
131 |
132 | [FieldOffset(80)]
133 | public ulong SizeOfStackCommit;
134 |
135 | [FieldOffset(88)]
136 | public ulong SizeOfHeapReserve;
137 |
138 | [FieldOffset(96)]
139 | public ulong SizeOfHeapCommit;
140 |
141 | [FieldOffset(104)]
142 | public uint LoaderFlags;
143 |
144 | [FieldOffset(108)]
145 | public uint NumberOfRvaAndSizes;
146 |
147 | [FieldOffset(112)]
148 | public IMAGE_DATA_DIRECTORY ExportTable;
149 |
150 | [FieldOffset(120)]
151 | public IMAGE_DATA_DIRECTORY ImportTable;
152 |
153 | [FieldOffset(128)]
154 | public IMAGE_DATA_DIRECTORY ResourceTable;
155 |
156 | [FieldOffset(136)]
157 | public IMAGE_DATA_DIRECTORY ExceptionTable;
158 |
159 | [FieldOffset(144)]
160 | public IMAGE_DATA_DIRECTORY CertificateTable;
161 |
162 | [FieldOffset(152)]
163 | public IMAGE_DATA_DIRECTORY BaseRelocationTable;
164 |
165 | [FieldOffset(160)]
166 | public IMAGE_DATA_DIRECTORY Debug;
167 |
168 | [FieldOffset(168)]
169 | public IMAGE_DATA_DIRECTORY Architecture;
170 |
171 | [FieldOffset(176)]
172 | public IMAGE_DATA_DIRECTORY GlobalPtr;
173 |
174 | [FieldOffset(184)]
175 | public IMAGE_DATA_DIRECTORY TLSTable;
176 |
177 | [FieldOffset(192)]
178 | public IMAGE_DATA_DIRECTORY LoadConfigTable;
179 |
180 | [FieldOffset(200)]
181 | public IMAGE_DATA_DIRECTORY BoundImport;
182 |
183 | [FieldOffset(208)]
184 | public IMAGE_DATA_DIRECTORY IAT;
185 |
186 | [FieldOffset(216)]
187 | public IMAGE_DATA_DIRECTORY DelayImportDescriptor;
188 |
189 | [FieldOffset(224)]
190 | public IMAGE_DATA_DIRECTORY CLRRuntimeHeader;
191 |
192 | [FieldOffset(232)]
193 | public IMAGE_DATA_DIRECTORY Reserved;
194 | }
195 |
196 | [StructLayout(LayoutKind.Sequential)]
197 | public struct IMAGE_DATA_DIRECTORY
198 | {
199 | public UInt32 VirtualAddress;
200 | public UInt32 Size;
201 | }
202 |
203 | [StructLayout(LayoutKind.Sequential)]
204 | public struct IMAGE_EXPORT_DIRECTORY
205 | {
206 | public UInt32 Characteristics;
207 | public UInt32 TimeDateStamp;
208 | public UInt16 MajorVersion;
209 | public UInt16 MinorVersion;
210 | public UInt32 Name;
211 | public UInt32 Base;
212 | public UInt32 NumberOfFunctions;
213 | public UInt32 NumberOfNames;
214 | public UInt32 AddressOfFunctions; // RVA from base of image
215 | public UInt32 AddressOfNames; // RVA from base of image
216 | public UInt32 AddressOfNameOrdinals; // RVA from base of image
217 | }
218 |
219 | [StructLayout(LayoutKind.Explicit)]
220 | public unsafe struct IMAGE_SECTION_HEADER
221 | {
222 | [FieldOffset(0)]
223 | public fixed byte Name[8];
224 |
225 | [FieldOffset(8)]
226 | public UInt32 VirtualSize;
227 |
228 | [FieldOffset(12)]
229 | public UInt32 VirtualAddress;
230 |
231 | [FieldOffset(16)]
232 | public UInt32 SizeOfRawData;
233 |
234 | [FieldOffset(20)]
235 | public UInt32 PointerToRawData;
236 |
237 | [FieldOffset(24)]
238 | public UInt32 PointerToRelocations;
239 |
240 | [FieldOffset(28)]
241 | public UInt32 PointerToLinenumbers;
242 |
243 | [FieldOffset(32)]
244 | public UInt16 NumberOfRelocations;
245 |
246 | [FieldOffset(34)]
247 | public UInt16 NumberOfLinenumbers;
248 |
249 | [FieldOffset(36)]
250 | public DataSectionFlags Characteristics;
251 |
252 | }
253 | [Flags]
254 | public enum DataSectionFlags : uint
255 | {
256 | ///
257 | /// Reserved for future use.
258 | ///
259 | TypeReg = 0x00000000,
260 | ///
261 | /// Reserved for future use.
262 | ///
263 | TypeDsect = 0x00000001,
264 | ///
265 | /// Reserved for future use.
266 | ///
267 | TypeNoLoad = 0x00000002,
268 | ///
269 | /// Reserved for future use.
270 | ///
271 | TypeGroup = 0x00000004,
272 | ///
273 | /// The section should not be padded to the next boundary. This flag is obsolete and is replaced by IMAGE_SCN_ALIGN_1BYTES. This is valid only for object files.
274 | ///
275 | TypeNoPadded = 0x00000008,
276 | ///
277 | /// Reserved for future use.
278 | ///
279 | TypeCopy = 0x00000010,
280 | ///
281 | /// The section contains executable code.
282 | ///
283 | ContentCode = 0x00000020,
284 | ///
285 | /// The section contains initialized data.
286 | ///
287 | ContentInitializedData = 0x00000040,
288 | ///
289 | /// The section contains uninitialized data.
290 | ///
291 | ContentUninitializedData = 0x00000080,
292 | ///
293 | /// Reserved for future use.
294 | ///
295 | LinkOther = 0x00000100,
296 | ///
297 | /// The section contains comments or other information. The .drectve section has this type. This is valid for object files only.
298 | ///
299 | LinkInfo = 0x00000200,
300 | ///
301 | /// Reserved for future use.
302 | ///
303 | TypeOver = 0x00000400,
304 | ///
305 | /// The section will not become part of the image. This is valid only for object files.
306 | ///
307 | LinkRemove = 0x00000800,
308 | ///
309 | /// The section contains COMDAT data. For more information, see section 5.5.6, COMDAT Sections (Object Only). This is valid only for object files.
310 | ///
311 | LinkComDat = 0x00001000,
312 | ///
313 | /// Reset speculative exceptions handling bits in the TLB entries for this section.
314 | ///
315 | NoDeferSpecExceptions = 0x00004000,
316 | ///
317 | /// The section contains data referenced through the global pointer (GP).
318 | ///
319 | RelativeGP = 0x00008000,
320 | ///
321 | /// Reserved for future use.
322 | ///
323 | MemPurgeable = 0x00020000,
324 | ///
325 | /// Reserved for future use.
326 | ///
327 | Memory16Bit = 0x00020000,
328 | ///
329 | /// Reserved for future use.
330 | ///
331 | MemoryLocked = 0x00040000,
332 | ///
333 | /// Reserved for future use.
334 | ///
335 | MemoryPreload = 0x00080000,
336 | ///
337 | /// Align data on a 1-byte boundary. Valid only for object files.
338 | ///
339 | Align1Bytes = 0x00100000,
340 | ///
341 | /// Align data on a 2-byte boundary. Valid only for object files.
342 | ///
343 | Align2Bytes = 0x00200000,
344 | ///
345 | /// Align data on a 4-byte boundary. Valid only for object files.
346 | ///
347 | Align4Bytes = 0x00300000,
348 | ///
349 | /// Align data on an 8-byte boundary. Valid only for object files.
350 | ///
351 | Align8Bytes = 0x00400000,
352 | ///
353 | /// Align data on a 16-byte boundary. Valid only for object files.
354 | ///
355 | Align16Bytes = 0x00500000,
356 | ///
357 | /// Align data on a 32-byte boundary. Valid only for object files.
358 | ///
359 | Align32Bytes = 0x00600000,
360 | ///
361 | /// Align data on a 64-byte boundary. Valid only for object files.
362 | ///
363 | Align64Bytes = 0x00700000,
364 | ///
365 | /// Align data on a 128-byte boundary. Valid only for object files.
366 | ///
367 | Align128Bytes = 0x00800000,
368 | ///
369 | /// Align data on a 256-byte boundary. Valid only for object files.
370 | ///
371 | Align256Bytes = 0x00900000,
372 | ///
373 | /// Align data on a 512-byte boundary. Valid only for object files.
374 | ///
375 | Align512Bytes = 0x00A00000,
376 | ///
377 | /// Align data on a 1024-byte boundary. Valid only for object files.
378 | ///
379 | Align1024Bytes = 0x00B00000,
380 | ///
381 | /// Align data on a 2048-byte boundary. Valid only for object files.
382 | ///
383 | Align2048Bytes = 0x00C00000,
384 | ///
385 | /// Align data on a 4096-byte boundary. Valid only for object files.
386 | ///
387 | Align4096Bytes = 0x00D00000,
388 | ///
389 | /// Align data on an 8192-byte boundary. Valid only for object files.
390 | ///
391 | Align8192Bytes = 0x00E00000,
392 | ///
393 | /// The section contains extended relocations.
394 | ///
395 | LinkExtendedRelocationOverflow = 0x01000000,
396 | ///
397 | /// The section can be discarded as needed.
398 | ///
399 | MemoryDiscardable = 0x02000000,
400 | ///
401 | /// The section cannot be cached.
402 | ///
403 | MemoryNotCached = 0x04000000,
404 | ///
405 | /// The section is not pageable.
406 | ///
407 | MemoryNotPaged = 0x08000000,
408 | ///
409 | /// The section can be shared in memory.
410 | ///
411 | MemoryShared = 0x10000000,
412 | ///
413 | /// The section can be executed as code.
414 | ///
415 | MemoryExecute = 0x20000000,
416 | ///
417 | /// The section can be read.
418 | ///
419 | MemoryRead = 0x40000000,
420 | ///
421 | /// The section can be written to.
422 | ///
423 | MemoryWrite = 0x80000000
424 | }
425 |
426 | public enum MachineType : ushort
427 | {
428 | Native = 0,
429 | I386 = 0x014c,
430 | Itanium = 0x0200,
431 | x64 = 0x8664
432 | }
433 | public enum MagicType : ushort
434 | {
435 | IMAGE_NT_OPTIONAL_HDR32_MAGIC = 0x10b,
436 | IMAGE_NT_OPTIONAL_HDR64_MAGIC = 0x20b
437 | }
438 | public enum SubSystemType : ushort
439 | {
440 | IMAGE_SUBSYSTEM_UNKNOWN = 0,
441 | IMAGE_SUBSYSTEM_NATIVE = 1,
442 | IMAGE_SUBSYSTEM_WINDOWS_GUI = 2,
443 | IMAGE_SUBSYSTEM_WINDOWS_CUI = 3,
444 | IMAGE_SUBSYSTEM_POSIX_CUI = 7,
445 | IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9,
446 | IMAGE_SUBSYSTEM_EFI_APPLICATION = 10,
447 | IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER = 11,
448 | IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER = 12,
449 | IMAGE_SUBSYSTEM_EFI_ROM = 13,
450 | IMAGE_SUBSYSTEM_XBOX = 14
451 |
452 | }
453 | public enum DllCharacteristicsType : ushort
454 | {
455 | RES_0 = 0x0001,
456 | RES_1 = 0x0002,
457 | RES_2 = 0x0004,
458 | RES_3 = 0x0008,
459 | IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE = 0x0040,
460 | IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY = 0x0080,
461 | IMAGE_DLL_CHARACTERISTICS_NX_COMPAT = 0x0100,
462 | IMAGE_DLLCHARACTERISTICS_NO_ISOLATION = 0x0200,
463 | IMAGE_DLLCHARACTERISTICS_NO_SEH = 0x0400,
464 | IMAGE_DLLCHARACTERISTICS_NO_BIND = 0x0800,
465 | RES_4 = 0x1000,
466 | IMAGE_DLLCHARACTERISTICS_WDM_DRIVER = 0x2000,
467 | IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE = 0x8000
468 | }
469 |
470 | public static unsafe IMAGE_SECTION_HEADER* IMAGE_FIRST_SECTION(IMAGE_NT_HEADERS64* nth)
471 | {
472 | return (IMAGE_SECTION_HEADER*)((ulong)nth + 24 + (ulong)nth->FileHeader.SizeOfOptionalHeader);
473 | }
474 |
475 | }
476 | }
477 |
--------------------------------------------------------------------------------
/KernelBypassSharp/Program.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime;
2 | using System.Runtime.InteropServices;
3 | using static KernelSharp.WDK;
4 | using static KernelSharp.WDK.Undocumented;
5 |
6 |
7 | namespace KernelBypassSharp
8 | {
9 | public unsafe class Program
10 | {
11 | static delegate* NtUserGetObjectInformationOriginal;
12 |
13 | //Dummy main method to satisfy the compiler
14 | static void Main() { }
15 |
16 |
17 | static void HookHandler(SyscallData data)
18 | {
19 | if (data.ProcessId == 0) return;
20 |
21 | PEPROCESS proc = 0;
22 | if (!NT_SUCCESS(PsLookupProcessByProcessId(data.ProcessId, &proc)))
23 | return;
24 |
25 | if (proc == 0) return;
26 |
27 | ulong outSize = 0;
28 | switch (data.Op)
29 | {
30 | case Operation.Read:
31 |
32 | //I could check NTSTATUS here, but this is up to you to implement
33 | MmCopyVirtualMemory(proc, data.SourceAddress, IoGetCurrentProcess(), data.TargetAddress, data.Size, KProcessorMode.UserMode, &outSize);
34 | break;
35 |
36 | case Operation.Write:
37 |
38 | MmCopyVirtualMemory(IoGetCurrentProcess(), data.SourceAddress, proc, data.TargetAddress, data.Size, KProcessorMode.UserMode, &outSize);
39 | break;
40 |
41 | case Operation.Base:
42 |
43 | PVOID processBase = PsGetProcessSectionBaseAddress(proc);
44 | *(PVOID*)data.TargetAddress = processBase;
45 |
46 | break;
47 | }
48 | }
49 |
50 |
51 | //hook handler based on https://github.com/btbd/access/blob/noseh/Driver/main.c
52 | static ulong NtUserGetObjectInformationHook(void* a1, void* a2, SyscallData* data, ulong* status, void* a5)
53 | {
54 | if (ExGetPreviousMode() != KProcessorMode.UserMode)
55 | return NtUserGetObjectInformationOriginal(a1, a2, data, status, a5);
56 |
57 | SyscallData safeData = new SyscallData();
58 |
59 | //Check for magic and memory validity
60 | if(!Util.ProbeUserAddress(data, (ulong)sizeof(SyscallData), sizeof(uint)) || !Util.SafeCopy(&safeData, data, (ulong)sizeof(SyscallData)) || safeData.Magic != 0x69420)
61 | return NtUserGetObjectInformationOriginal(a1, a2, data, status, a5);
62 |
63 | HookHandler(safeData);
64 |
65 | return NtUserGetObjectInformationOriginal(a1, a2, data, status, a5);
66 | }
67 |
68 |
69 |
70 | [RuntimeExport("DriverEntry")]
71 | static NTSTATUS DriverEntry()
72 | {
73 | var win32k = Util.GetKernelModuleByName("win32kbase.sys");
74 |
75 | if (win32k == 0) return NTSTATUS.DllNotFound;
76 |
77 | PVOID function = ((ulong)Util.FindPatternImage((byte*)win32k, "\x74\x20\x48\x8B\x44\x24\x00\x44", "xxxxxx?x")) - 0xA;
78 |
79 | if (function == 0) return NTSTATUS.ProcedureNotFound;
80 |
81 | PVOID dataPtr = (byte*)function + *(int*)((byte*)function + 3) + 7;
82 |
83 | NtUserGetObjectInformationOriginal = (delegate*)*(ulong*)dataPtr;
84 |
85 | delegate* hookFunc = &NtUserGetObjectInformationHook;
86 | *(ulong*)dataPtr = (ulong)hookFunc;
87 |
88 | return NTSTATUS.Success;
89 | }
90 |
91 | [StructLayout(LayoutKind.Sequential)]
92 | struct SyscallData
93 | {
94 | public uint Magic;
95 | public uint ProcessId;
96 | public Operation Op;
97 | public PVOID SourceAddress;
98 | public PVOID TargetAddress;
99 | public ulong Size;
100 | }
101 |
102 | enum Operation
103 | {
104 | Read,
105 | Write,
106 | Base
107 | }
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/KernelBypassSharp/Util.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using static KernelSharp.NTImage;
3 | using static KernelSharp.WDK;
4 | using static KernelSharp.WDK.Undocumented;
5 |
6 | namespace KernelBypassSharp
7 | {
8 | public static unsafe class Util
9 | {
10 | public static PVOID GetKernelModuleByName(string moduleName)
11 | {
12 | uint poolSize = 0;
13 |
14 | //get estimated size first
15 | NTSTATUS status = ZwQuerySystemInformation(SystemInformationClass.SystemModuleInformation, null, 0, &poolSize);
16 |
17 | if (status != NTSTATUS.InfoLengthMismatch)
18 | return null;
19 |
20 | var sysModInfo = (RTL_PROCESS_MODULES*)ExAllocatePool(PoolType.NonPagedPool, poolSize);
21 |
22 | if (sysModInfo == null) return null;
23 |
24 | status = ZwQuerySystemInformation(SystemInformationClass.SystemModuleInformation, sysModInfo, poolSize, null);
25 |
26 | PVOID address = 0;
27 | char* s_moduleName = moduleName.c_str();
28 | RTL_PROCESS_MODULE_INFORMATION* moduleInfo = (RTL_PROCESS_MODULE_INFORMATION*)((ulong)sysModInfo + 8);
29 |
30 | for (uint i = 0; i < sysModInfo->NumberOfModules; i++)
31 | {
32 | var moduleEntry = moduleInfo[i];
33 |
34 | if(strstr((char*)moduleEntry.FullPathName, s_moduleName) != null)
35 | {
36 | address = moduleEntry.ImageBase;
37 | }
38 | }
39 |
40 | ExFreePool(sysModInfo);
41 | ExFreePool(s_moduleName);
42 |
43 | return address;
44 | }
45 |
46 |
47 | //based on https://github.com/btbd/hwid/blob/master/Kernel/util.c
48 | private static bool CheckMask(byte* addr, byte* pattern, byte* mask)
49 | {
50 | while(*mask != 0)
51 | {
52 | if ('x' == *mask && *addr != *pattern)
53 | return false;
54 |
55 | mask += 2; //C# chars are Widechars, so they are 2 bytes long --> we skip 2 bytes here
56 | pattern += 2;
57 | ++addr;
58 | }
59 | return true;
60 | }
61 |
62 | //based on https://github.com/btbd/hwid/blob/master/Kernel/util.c
63 | public static PVOID FindPattern(byte* address, uint length, byte* pattern, byte* mask)
64 | {
65 | length -= (uint)wcslen((char*)mask);
66 | for(uint i = 0; i <= length; ++i)
67 | {
68 | byte* addr = &address[i];
69 | if (CheckMask(addr, pattern, mask))
70 | return addr;
71 | }
72 |
73 | return null;
74 | }
75 |
76 | //based on https://github.com/btbd/hwid/blob/master/Kernel/util.c
77 | public static PVOID FindPatternImage(byte* address, string pattern, string mask)
78 | {
79 | PVOID match = 0;
80 |
81 | IMAGE_NT_HEADERS64* headers = (IMAGE_NT_HEADERS64*)(address + ((IMAGE_DOS_HEADER*)address)->e_lfanew);
82 | IMAGE_SECTION_HEADER* sections = IMAGE_FIRST_SECTION(headers);
83 |
84 | var textSectName = ".text".c_str();
85 | var s_pattern = pattern.w_str();
86 | var s_mask = mask.w_str();
87 |
88 | for (uint i = 0; i < headers->FileHeader.NumberOfSections; ++i)
89 | {
90 | IMAGE_SECTION_HEADER* section = §ions[i];
91 |
92 | //PAGE
93 | if (0x45474150 == *(int*)section->Name || memcmp(section->Name, textSectName, 5) == 0)
94 | {
95 | match = FindPattern(address + section->VirtualAddress, section->VirtualSize, (byte*)s_pattern, (byte*)s_mask);
96 | if ((ulong)match != 0) break;
97 | }
98 | }
99 |
100 | ExFreePool(textSectName);
101 |
102 | return match;
103 | }
104 |
105 | //from https://github.com/btbd/access/blob/noseh/Driver/util.c
106 | public static bool ProbeUserAddress(PVOID addr, ulong size, uint alignment)
107 | {
108 | if (addr == 0) return false;
109 | if (size == 0)
110 | {
111 | return true;
112 | }
113 |
114 | ulong current = (ulong)addr;
115 | if (((ulong)addr & (alignment - 1)) != 0)
116 | {
117 | return false;
118 | }
119 |
120 | ulong last = current + size - 1;
121 | if ((last < current) || (last >= 0x7FFFFFFF0000))
122 | {
123 | return false;
124 | }
125 |
126 | return true;
127 | }
128 |
129 | //from https://github.com/btbd/access/blob/noseh/Driver/util.c
130 | public static bool SafeCopy(PVOID dest, PVOID src, ulong size)
131 | {
132 | ulong returnSize = 0;
133 | if (NT_SUCCESS(MmCopyVirtualMemory(IoGetCurrentProcess(), src, IoGetCurrentProcess(), dest, size, KProcessorMode.KernelMode, &returnSize)) && returnSize == size)
134 | return true;
135 |
136 | return false;
137 | }
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/KernelBypassSharp/build.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 |
3 | :: you have to set the path to whatever it is for you
4 | @set ILCPATH="E:\tools"
5 | @set NTOSKRNLLIBPATH="D:\Windows Kits\10\lib\10.0.19041.0\km\x64\ntoskrnl.lib"
6 |
7 | @if not exist %ILCPATH%\ilc.exe (
8 | echo The Il2Native compiler was not found.
9 | exit /B
10 | )
11 |
12 | @del Program.ilexe >nul 2>&1
13 | @del Program.obj >nul 2>&1
14 | @del Program.exe >nul 2>&1
15 | @del Program.map >nul 2>&1
16 | @del Program.pdb >nul 2>&1
17 |
18 | @if "%1" == "clean" exit /B
19 |
20 | csc.exe /nologo /debug:embedded /noconfig /nostdlib /runtimemetadataversion:v4.0.30319 Program.cs NTImage.cs Util.cs KernelSharp/WDK.cs KernelSharp/Runtime/InteropServices.cs KernelSharp/Runtime/CompilerHelpers.cs KernelSharp/Runtime/CompilerServices.cs KernelSharp/Runtime/System.cs KernelSharp/Runtime/Runtime.cs /out:Program.ilexe /langversion:latest /unsafe || goto Error
21 | %ILCPATH%\ilc Program.ilexe -o Program.obj --systemmodule Program --map Program.map -O || goto Error
22 |
23 | :: Also set this path to your path
24 | link.exe %NTOSKRNLLIBPATH% /nologo /subsystem:native /DRIVER:WDM Program.obj /entry:DriverEntry /incremental:no /out:Driver.sys || goto Error
25 | @goto :EOF
26 |
27 | :Error
28 | @echo Tool failed.
29 | exit /B 1
30 |
--------------------------------------------------------------------------------
/KernelBypassSharp/nuget.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 VollRagm
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # KernelBypassSharp
2 | C# Kernel Mode Driver to read and write memory in protected processes.
3 | This project is based on my https://github.com/VollRagm/KernelSharp repository.
4 | The hooked function this example uses has been shared publicly, so Anticheat solutions might detect it.
5 |
6 | The most important part of the code is in [Program.cs](https://github.com/VollRagm/KernelBypassSharp/blob/main/KernelBypassSharp/Program.cs).
7 |
8 | # Compiling
9 | Clone this repository. Then run `nuget restore` to restore the required packages. Open the build.bat and fix the file paths.
10 | ILCPATH is located at something like `C:\Users\username\.nuget\packages\runtime.win-x64.microsoft.dotnet.ilcompiler\7.0.0-alpha.1.21430.2\tools`, ntoskrnl.lib is located in the WDK install path.
11 | Run `x64 Native Tools Command Prompt for VS 2019` from the Windows search, cd into the project directory and run build.bat.
12 | You can load the driver or map it with kdmapper.
13 |
14 | # Usage
15 | After mapping or loading the driver, run the UsermodeApp to test it.
16 | If you want to build your own API, simply replicate the structs and logic in the UsermodeApp example.
17 |
--------------------------------------------------------------------------------
/UsermodeApp/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/UsermodeApp/MainForm.Designer.cs:
--------------------------------------------------------------------------------
1 |
2 | namespace UsermodeApp
3 | {
4 | partial class MainForm
5 | {
6 | ///
7 | /// Required designer variable.
8 | ///
9 | private System.ComponentModel.IContainer components = null;
10 |
11 | ///
12 | /// Clean up any resources being used.
13 | ///
14 | /// true if managed resources should be disposed; otherwise, false.
15 | protected override void Dispose(bool disposing)
16 | {
17 | if (disposing && (components != null))
18 | {
19 | components.Dispose();
20 | }
21 | base.Dispose(disposing);
22 | }
23 |
24 | #region Windows Form Designer generated code
25 |
26 | ///
27 | /// Required method for Designer support - do not modify
28 | /// the contents of this method with the code editor.
29 | ///
30 | private void InitializeComponent()
31 | {
32 | this.ModuleBaseBtn = new System.Windows.Forms.Button();
33 | this.procName = new System.Windows.Forms.TextBox();
34 | this.selectProcBtn = new System.Windows.Forms.Button();
35 | this.label1 = new System.Windows.Forms.Label();
36 | this.label2 = new System.Windows.Forms.Label();
37 | this.readAddrTb = new System.Windows.Forms.TextBox();
38 | this.readBtn = new System.Windows.Forms.Button();
39 | this.label3 = new System.Windows.Forms.Label();
40 | this.writeAddrTb = new System.Windows.Forms.TextBox();
41 | this.writeBtn = new System.Windows.Forms.Button();
42 | this.writeValTb = new System.Windows.Forms.TextBox();
43 | this.lbl = new System.Windows.Forms.Label();
44 | this.SuspendLayout();
45 | //
46 | // ModuleBaseBtn
47 | //
48 | this.ModuleBaseBtn.Location = new System.Drawing.Point(106, 51);
49 | this.ModuleBaseBtn.Name = "ModuleBaseBtn";
50 | this.ModuleBaseBtn.Size = new System.Drawing.Size(117, 23);
51 | this.ModuleBaseBtn.TabIndex = 0;
52 | this.ModuleBaseBtn.Text = "Get Base Address";
53 | this.ModuleBaseBtn.UseVisualStyleBackColor = true;
54 | this.ModuleBaseBtn.Click += new System.EventHandler(this.ModuleBaseBtn_Click);
55 | //
56 | // procName
57 | //
58 | this.procName.Location = new System.Drawing.Point(89, 13);
59 | this.procName.Name = "procName";
60 | this.procName.Size = new System.Drawing.Size(174, 20);
61 | this.procName.TabIndex = 1;
62 | //
63 | // selectProcBtn
64 | //
65 | this.selectProcBtn.Location = new System.Drawing.Point(269, 12);
66 | this.selectProcBtn.Name = "selectProcBtn";
67 | this.selectProcBtn.Size = new System.Drawing.Size(71, 23);
68 | this.selectProcBtn.TabIndex = 0;
69 | this.selectProcBtn.Text = "Select";
70 | this.selectProcBtn.UseVisualStyleBackColor = true;
71 | this.selectProcBtn.Click += new System.EventHandler(this.selectProcBtn_Click);
72 | //
73 | // label1
74 | //
75 | this.label1.AutoSize = true;
76 | this.label1.Location = new System.Drawing.Point(4, 17);
77 | this.label1.Name = "label1";
78 | this.label1.Size = new System.Drawing.Size(79, 13);
79 | this.label1.TabIndex = 2;
80 | this.label1.Text = "Process Name:";
81 | //
82 | // label2
83 | //
84 | this.label2.AutoSize = true;
85 | this.label2.Location = new System.Drawing.Point(12, 142);
86 | this.label2.Name = "label2";
87 | this.label2.Size = new System.Drawing.Size(48, 13);
88 | this.label2.TabIndex = 3;
89 | this.label2.Text = "Address:";
90 | //
91 | // readAddrTb
92 | //
93 | this.readAddrTb.Location = new System.Drawing.Point(66, 139);
94 | this.readAddrTb.Name = "readAddrTb";
95 | this.readAddrTb.Size = new System.Drawing.Size(174, 20);
96 | this.readAddrTb.TabIndex = 1;
97 | //
98 | // readBtn
99 | //
100 | this.readBtn.Location = new System.Drawing.Point(106, 165);
101 | this.readBtn.Name = "readBtn";
102 | this.readBtn.Size = new System.Drawing.Size(93, 23);
103 | this.readBtn.TabIndex = 0;
104 | this.readBtn.Text = "Read INT64";
105 | this.readBtn.UseVisualStyleBackColor = true;
106 | this.readBtn.Click += new System.EventHandler(this.readBtn_Click);
107 | //
108 | // label3
109 | //
110 | this.label3.AutoSize = true;
111 | this.label3.Location = new System.Drawing.Point(12, 255);
112 | this.label3.Name = "label3";
113 | this.label3.Size = new System.Drawing.Size(48, 13);
114 | this.label3.TabIndex = 6;
115 | this.label3.Text = "Address:";
116 | //
117 | // writeAddrTb
118 | //
119 | this.writeAddrTb.Location = new System.Drawing.Point(66, 252);
120 | this.writeAddrTb.Name = "writeAddrTb";
121 | this.writeAddrTb.Size = new System.Drawing.Size(174, 20);
122 | this.writeAddrTb.TabIndex = 5;
123 | //
124 | // writeBtn
125 | //
126 | this.writeBtn.Location = new System.Drawing.Point(106, 306);
127 | this.writeBtn.Name = "writeBtn";
128 | this.writeBtn.Size = new System.Drawing.Size(93, 23);
129 | this.writeBtn.TabIndex = 4;
130 | this.writeBtn.Text = "Write INT64";
131 | this.writeBtn.UseVisualStyleBackColor = true;
132 | this.writeBtn.Click += new System.EventHandler(this.writeBtn_Click);
133 | //
134 | // writeValTb
135 | //
136 | this.writeValTb.Location = new System.Drawing.Point(66, 278);
137 | this.writeValTb.Name = "writeValTb";
138 | this.writeValTb.Size = new System.Drawing.Size(174, 20);
139 | this.writeValTb.TabIndex = 5;
140 | //
141 | // lbl
142 | //
143 | this.lbl.AutoSize = true;
144 | this.lbl.Location = new System.Drawing.Point(12, 281);
145 | this.lbl.Name = "lbl";
146 | this.lbl.Size = new System.Drawing.Size(37, 13);
147 | this.lbl.TabIndex = 6;
148 | this.lbl.Text = "Value:";
149 | //
150 | // MainForm
151 | //
152 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
153 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
154 | this.ClientSize = new System.Drawing.Size(352, 440);
155 | this.Controls.Add(this.lbl);
156 | this.Controls.Add(this.label3);
157 | this.Controls.Add(this.writeValTb);
158 | this.Controls.Add(this.writeAddrTb);
159 | this.Controls.Add(this.writeBtn);
160 | this.Controls.Add(this.label2);
161 | this.Controls.Add(this.label1);
162 | this.Controls.Add(this.readAddrTb);
163 | this.Controls.Add(this.procName);
164 | this.Controls.Add(this.selectProcBtn);
165 | this.Controls.Add(this.readBtn);
166 | this.Controls.Add(this.ModuleBaseBtn);
167 | this.Name = "MainForm";
168 | this.Text = "Control";
169 | this.ResumeLayout(false);
170 | this.PerformLayout();
171 |
172 | }
173 |
174 | #endregion
175 |
176 | private System.Windows.Forms.Button ModuleBaseBtn;
177 | private System.Windows.Forms.TextBox procName;
178 | private System.Windows.Forms.Button selectProcBtn;
179 | private System.Windows.Forms.Label label1;
180 | private System.Windows.Forms.Label label2;
181 | private System.Windows.Forms.TextBox readAddrTb;
182 | private System.Windows.Forms.Button readBtn;
183 | private System.Windows.Forms.Label label3;
184 | private System.Windows.Forms.TextBox writeAddrTb;
185 | private System.Windows.Forms.Button writeBtn;
186 | private System.Windows.Forms.TextBox writeValTb;
187 | private System.Windows.Forms.Label lbl;
188 | }
189 | }
190 |
191 |
--------------------------------------------------------------------------------
/UsermodeApp/MainForm.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.ComponentModel;
4 | using System.Data;
5 | using System.Diagnostics;
6 | using System.Drawing;
7 | using System.Linq;
8 | using System.Runtime.InteropServices;
9 | using System.Text;
10 | using System.Threading.Tasks;
11 | using System.Windows.Forms;
12 |
13 | namespace UsermodeApp
14 | {
15 | public unsafe partial class MainForm : Form
16 | {
17 | Process TargetProcess;
18 |
19 | public MainForm()
20 | {
21 | InitializeComponent();
22 | }
23 |
24 | [DllImport("win32u.dll")]
25 | public static extern ulong NtUserGetObjectInformation(ulong a1, ulong a2, void* a3, ulong a4, ulong a5);
26 |
27 | private void ModuleBaseBtn_Click(object sender, EventArgs e)
28 | {
29 | ulong moduleBase = 0;
30 |
31 | SyscallData data = GetSyscallData(Operation.Base);
32 | data.TargetAddress = (ulong)&moduleBase;
33 |
34 | NtUserGetObjectInformation(0, 0, &data, 0, 0);
35 |
36 | MessageBox.Show($"Main Module Base -> {moduleBase:X8}");
37 | }
38 |
39 | private SyscallData GetSyscallData(Operation op)
40 | {
41 | return new SyscallData { Op = op, ProcessId = (uint)TargetProcess.Id, Magic = 0x69420 };
42 | }
43 |
44 | [StructLayout(LayoutKind.Sequential)]
45 | struct SyscallData
46 | {
47 | public uint Magic;
48 | public uint ProcessId;
49 | public Operation Op;
50 | public ulong SourceAddress;
51 | public ulong TargetAddress;
52 | public ulong Size;
53 | }
54 |
55 | enum Operation
56 | {
57 | Read,
58 | Write,
59 | Base
60 | }
61 |
62 | private void selectProcBtn_Click(object sender, EventArgs e)
63 | {
64 | try
65 | {
66 | TargetProcess = Process.GetProcessesByName(procName.Text)[0];
67 | }
68 | catch
69 | {
70 | MessageBox.Show("Could not select target process!");
71 | }
72 | }
73 |
74 | private void readBtn_Click(object sender, EventArgs e)
75 | {
76 | ulong result = 0;
77 | ulong sourceAddress = ulong.Parse(readAddrTb.Text, System.Globalization.NumberStyles.HexNumber);
78 |
79 | SyscallData data = GetSyscallData(Operation.Read);
80 | data.TargetAddress = (ulong)&result;
81 | data.SourceAddress = sourceAddress;
82 | data.Size = sizeof(ulong);
83 |
84 | NtUserGetObjectInformation(0, 0, &data, 0, 0);
85 |
86 | MessageBox.Show($"Read result -> {result}");
87 | }
88 |
89 | private void writeBtn_Click(object sender, EventArgs e)
90 | {
91 | long value = long.Parse(writeValTb.Text);
92 | ulong targetAddress = ulong.Parse(writeAddrTb.Text, System.Globalization.NumberStyles.HexNumber);
93 |
94 | SyscallData data = GetSyscallData(Operation.Write);
95 | data.SourceAddress = (ulong)&value;
96 | data.TargetAddress = targetAddress;
97 | data.Size = sizeof(ulong);
98 |
99 | NtUserGetObjectInformation(0, 0, &data, 0, 0);
100 | }
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/UsermodeApp/MainForm.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
--------------------------------------------------------------------------------
/UsermodeApp/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using System.Windows.Forms;
6 |
7 | namespace UsermodeApp
8 | {
9 | static class Program
10 | {
11 | ///
12 | /// The main entry point for the application.
13 | ///
14 | [STAThread]
15 | static void Main()
16 | {
17 | Application.EnableVisualStyles();
18 | Application.SetCompatibleTextRenderingDefault(false);
19 | Application.Run(new MainForm());
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/UsermodeApp/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("UsermodeApp")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("UsermodeApp")]
13 | [assembly: AssemblyCopyright("Copyright © 2021")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("0a503ff8-c512-441c-b84b-25e7b8cf4520")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/UsermodeApp/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 |
12 | namespace UsermodeApp.Properties
13 | {
14 | ///
15 | /// A strongly-typed resource class, for looking up localized strings, etc.
16 | ///
17 | // This class was auto-generated by the StronglyTypedResourceBuilder
18 | // class via a tool like ResGen or Visual Studio.
19 | // To add or remove a member, edit your .ResX file then rerun ResGen
20 | // with the /str option, or rebuild your VS project.
21 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
22 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
23 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
24 | internal class Resources
25 | {
26 |
27 | private static global::System.Resources.ResourceManager resourceMan;
28 |
29 | private static global::System.Globalization.CultureInfo resourceCulture;
30 |
31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
32 | internal Resources()
33 | {
34 | }
35 |
36 | ///
37 | /// Returns the cached ResourceManager instance used by this class.
38 | ///
39 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
40 | internal static global::System.Resources.ResourceManager ResourceManager
41 | {
42 | get
43 | {
44 | if ((resourceMan == null))
45 | {
46 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("UsermodeApp.Properties.Resources", typeof(Resources).Assembly);
47 | resourceMan = temp;
48 | }
49 | return resourceMan;
50 | }
51 | }
52 |
53 | ///
54 | /// Overrides the current thread's CurrentUICulture property for all
55 | /// resource lookups using this strongly typed resource class.
56 | ///
57 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
58 | internal static global::System.Globalization.CultureInfo Culture
59 | {
60 | get
61 | {
62 | return resourceCulture;
63 | }
64 | set
65 | {
66 | resourceCulture = value;
67 | }
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/UsermodeApp/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 | text/microsoft-resx
107 |
108 |
109 | 2.0
110 |
111 |
112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
113 |
114 |
115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
--------------------------------------------------------------------------------
/UsermodeApp/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 |
12 | namespace UsermodeApp.Properties
13 | {
14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
17 | {
18 |
19 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
20 |
21 | public static Settings Default
22 | {
23 | get
24 | {
25 | return defaultInstance;
26 | }
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/UsermodeApp/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/UsermodeApp/UsermodeApp.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {0A503FF8-C512-441C-B84B-25E7B8CF4520}
8 | WinExe
9 | UsermodeApp
10 | UsermodeApp
11 | v4.8
12 | 512
13 | true
14 | true
15 |
16 |
17 | AnyCPU
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 |
26 |
27 | x64
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 | false
35 | true
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 | Form
53 |
54 |
55 | MainForm.cs
56 |
57 |
58 |
59 |
60 | MainForm.cs
61 |
62 |
63 | ResXFileCodeGenerator
64 | Resources.Designer.cs
65 | Designer
66 |
67 |
68 | True
69 | Resources.resx
70 |
71 |
72 | SettingsSingleFileGenerator
73 | Settings.Designer.cs
74 |
75 |
76 | True
77 | Settings.settings
78 | True
79 |
80 |
81 |
82 |
83 |
84 |
85 |
--------------------------------------------------------------------------------