Monday, February 10, 2014

Resolving Hostnames with PowerShell and the Pipeline

Thanks to Matt, PowerSploit has had a function to resolve hostnames to IP addresses for a while. The Invoke-ReverseDnsLookup utility is useful in mapping a domain from inside or out. Often, organizations use overly-descriptive names which can help an attacker narrow down their targets during initial recon and again once they have a foothold on the inside of a network. If you haven't used it, you should check it out.

Recently, we added support for two things to the function which I found helpful on a recent engagement. Both are simple enhancements that come with the PowerShell language that you may want to implement in your tools.

The first is the use of the Write-Verbose cmdlet which is a Common Parameter. That means it comes free when you declare your parameters with "[CmdletBinding()]" and then can be called by adding the "-verbose" switch when the function is called. Optionally, it can be enabled by changing $VerbosePreference, but by default it doesn't show anything. In the case of Invoke-ReverseDnsLookup, I added it to the function to be able to see what IP address it was currently trying to resolve. Since verbose statements are written to the console and not the output pipeline, you can use any of the "out-*" without it being cluttered with messages.


The next feature of PowerShell that we added is support for input from the pipeline. Pipeline input allows functions to be chained together and allows developers to focus on doing one thing. Where input is coming from and how the output is parsed or stored should be handled by the user. For example, I had a text file of several different network ranges and IP addresses that I wanted to be able to pass to Invoke-ReverseDnsLookup, but it didn't support it. Fortunately, it is simple to add support to your tools. The first thing you need to do is decide what logic (if any) only needs to happen once at the beginning or at the end of the script. In our case, Matt wrote a function to break out and validate CIDR ranges into individual addresses. We don't need to declare that function for every IP address, so we will create a BEGIN script block:


The only required script block is PROCESS. That is the part that will do the work on each object coming down the pipeline. You can see the PROCESS block above and how the current IP address in the pipeline is reference with the pipeline variable ($_). Once the PROCESS block is done, the optional END block does any post-processing for the function.



Certainly nothing ground-breaking here, but I thought I would share some neat features of PowerShell and how they can be applied to your tools. It may give you some insight into the "why" behind some of the functions in PowerSploit. Thank you for reading.

No comments:

Post a Comment