Thursday, September 29, 2016

Working With Sockets in PowerShell


A couple weeks ago, I decided to start working on a new project that would allow me to learn more about working with TCP sockets.  Attending @blu3gl0w13's OffensivePython lunch and learn had peaked my interest in working with raw streams. After doing my own lunch and learn on PowerShell, I determined I needed a way to show how to use PowerShell as a testing utility, not just how it could be exposed in incorrect configurations.  Enter socket streams and porting ShellShock scripts over to PowerShell. 

The first thing I needed to do was get a better understanding of how to send data over a raw port in .NET.  Once I could do this, porting over to PowerShell would become a much simpler process.  MSDN documentation on the System.Net.Sockets class gave a nice example of how to go about working with sockets in .NET.  Since doing the work in PowerShell, I wanted to break apart pieces and portions of this into their own reusable functions.  This way I could utilize them in other ways later on while doing assessments and other tests.

The first thing I needed to do was initialize the TCP Socket Stream.  Enter New-TCPSocketStream. 

 
This just creates a new socket and if the test is successful by being able to connect, it returns the connected socket.  If it cannot connect, it will return a null value, which can be validated before actually trying to send and receive data over the connection.

Once that was created, I needed to write out the function to send and receive stream over the connected socket.  So enter Get-SendReceiveData.



This allowed me to send and receive raw streams over the connected socket passed as part of the input parameters. 

Having ported the connections over was the first part of my learning process in getting socket data over.  The last piece was creating a test to send the data over.  This is where @blu3gl0w13's help came in and the final piece.   



I created the test by porting the Shellshock payload from the Offensive Python training over to PowerShell.  This gave me something to send over the socket and see how it behaved.  There’s been plenty published on Shellshock and how that works now, to where I’m not going to rehash that here. 

From there, I was able to send and receive commands over the socket connection.  To test, I spun up the vulnerable machine used in the Offensive Python training, and after loading the functions into my shell, sent a Shellshock request:

 

Success.

All in all, this worked as a great learning experience for porting between languages to PowerShell, and show some of the adaptability of the language.  One of the other great things about PowerShell is the multiple ways of going about performing a task.  With that, I leave you with the same thing but using Invoke-WebRequest instead…