Wednesday, September 23, 2009

Powershell Port Scan

Ed Skoudis used the for loop to create an ftp script for the ftp command in order to do a port scan. I did an modification to it so that it didn't require the script file and no files were written to the file system. You can find that posting here:

In my quest to port the Kung Fu of Mr. Skoudis in to powershell I came up with this command:

1..1024 | % { echo ((new-object Net.Sockets.TcpClient).Connect("",$_)) "$_ is open" } 2>out-null

If you have been following the previous entries there isn't anything fancy here, except one handy little trick that has to do with the output from the echo command. If you look closely you see that the command attempts to write the output of the connection as well as the string at the end. If the first portion throws an error, then the second part isn't output. Here is a simple example with the output.
PS C:\> echo (1+1) (2+2)

If we replace the (1+1) with (1/0) then nothing is displayed (other than the error). . If we discard the error with 2>Out-Null then there is no output.
PS C:\> echo (1/0) (2+2) 2>Out-Null(No Output)

We can use this to our advantage. If our connection fails, an error is raised and we don't output the "$_ is open" portion. If the connection works then the "$_ is open" is displayed.

Unfortunately, there is no easy way to change the connection timeout so this process is slow. We can do it with asynchronous calls, but that is a lot of work and is no longer a one liner. I'll put that in a future version.

No comments:

Post a Comment