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.

Powershell NSLookup Brute Force

Stealing two other commands from Mr. Skoudis we can do an nslookup of each host in a range.

for /L %i in (1,1,255) do @echo 10.10.10.%i: & @nslookup 10.10.10.%i 2>nul | find "Name"

for /L %i in (1,1,255) do @nslookup 10.10.10.%i 2>nul | find "Name" && echo 10.10.10.%i

The first command shows each IP as it is looked up. The second only shows those that successfully resolve.
Here is the powershell version and it's output:

1..255 | % { [System.Net.Dns]::GetHostByAddress("10.10.10.$_") } 2> Out-Null | Format-List
HostName    :
Aliases     : {,,,}
AddressList : {}

You'll notice a big difference from the first output. The standard nslookup just returns one result, while the powershell version gets all the aliases. We may not have ever known about those other DNS entries otherwise.
Using the [System.Net.Dns]::GetHostByAddress() method gives us more power, plus we can send the objects we want down the pipeline for further actions. We use the 2> Out-Null so that the error messages for the unresolvable IP addresses aren't shown.

Powershell Ping Sweep

Ed Skoudis came up with some fantastic Command Line Kung Fu for Windows to do some basic scanning. Powershell is becoming more and more common so I decided to port these commands to powershell. I think Ed would agree that the standard windows commands can be rather painful and aren't easily extensible (blasted windows) and I hoped to make it slightly less agonizing. In order to make it easier to understand, I won't use the shortcuts in my examples for the foreach-object cmdlet (%) or where-object cmdlet (?).

The first CLKF I thought I would tackle was the ping sweep. You can check out the great write-up over at the Command Line Kung Fu Blog.

Taken from the blog, here is the Windows command to do ping sweep at the command line and its associated output:

C:\>for /L %i in (1,1,255) do @ping -n 1 10.10.10.%i | find "Reply"

Reply from bytes=32 time=4ms TTL=64
Reply from bytes=32 time=5ms TTL=64
Reply from bytes=32 time=4ms TTL=64

The above command uses a FOR loop to ping each device and looks for "Reply" in the output. If there is a "Reply" then the host is up (duh).
Here is the powershell version and its output:

PS C:\>1..255 | foreach-object { (new-object System.Net.Networkinformation.Ping).Send("10.10.10.$_") } | where-object {$_.Status -eq "success"} | select Address


At first glance the results are very similar and you would think, "Why all the extra typing? The second command is 2.5 times longer!" The big difference between the standard windows command line and powershell is that the latter uses objects, which gives a lot of our shell. Not let's see how it works...
In the above command the range operator (..) generates a list of the numbers 1 through 255. The cool thing is you don't have to use just a single range, you can string them together like this (1..5),7,(9..10) which would give you the numbers 1-10 skipping 6 and 8.

foreach-object { (new-object System.Net.Networkinformation.Ping).Send("10.10.10.$_") }

The foreach-object takes the numbers fed into the pipeline and operates on them one at a time. First, it creates a new ping object and then calls the send method. The parameter given to the send method is a string concatenation of 10.10.10. and the number from $_, which is the "current pipeline object." The $_ variable in our example will contain the numbers 1-255.
where-object {$_.Status -eq "success"}
The output of the send method is the PingReply object which contains a status. We can filter the results only successful pings reply objects will be sent further down the pipeline.
Select Address

Finally, all we care about is the address so that is the only piece we have displayed.

Now that we know how it works, let's pimp out our powershell version.

First, we don't have to just use a contiguous set of numbers. If we wanted to scan all ip address before, after and we could use this:

(1..99),(200..255),155 | foreach-object ....
We can use the results to feed into other commands. You can ping sweep an entire subnet and have it automatically do an nslookup, attempt to list the contents of the c$ share, and tell you that you are doing a good job (a little positive reinforcement never hurts).

PS C:\>1..255 | foreach-object { (new-object System.Net.Networkinformation.Ping).Send("10.10.10.$_") } | where-object {$_.Status -eq "success"} | foreach-object { nslookup $_; gci "\\$($_.Address)\c$"; echo "Good Job" }

The ping sweep can be sped up by setting a timeout value (in milliseconds). In the example below we set the timeout value to 100ms.
... (new-object System.Net.Networkinformation.Ping).Send("10.10.10.$_", 100) ...
Next time we'll look into using the powershell version of nslookup and the brute force reverse dns lookup.

Sunday, September 20, 2009

VMware Login via AD

I put this together in order to integrate the login from VMWare into AD.

To setup the ESX server for AD authentication the following steps need to be taken. NTP needs to be done first so the server has a time close to that of the domain controller. The ntp ports need to be opened via the gui and the deamon needs to be started as well.

Allow the ntp client access through the firewall
In the GUI under the Configuration tab click on Security Profile then click on Properties… on the top right. A Firewall Options window will open.  Click the checkbox next to NTP Client.

Edit the ntp configuration file located at /etc/ntp.conf

Under servers add the same servers the domain uses for ntp (i.e. and
restrict default kod nomodify notrap
fudge line
server #local clock
restrict default kod nomodify notrap

Edit the steptickers file located at /etc/ntp/step-tickers
add the same servers the domain uses for ntp on separate lines

restart the ntp service:
service ntpd restart
check to make sure the time update worked (from command line)
ntpdate -q
ntpdate -q

Active Directory Authentication
Paste these lines into the CLI. The first two lines can be added via the GUI. VIC -> Configuration -> Security Profile -> Properties -> Add activeDirectorKerberos [sic] (NOT Kerberos).
esxcfg-firewall --openPort 88,tcp,out,KerberosClient
esxcfg-firewall --openPort 464,tcp,out,KerberosPasswordChange
esxcfg-auth --enablead --addomain agstar.local --addc mydc.mycdomain.blah
esxcfg-auth --enablekrb5 --krb5realm=agstar.local --krb5kdc=

Edit the VMWare Authentication deamon config located at /etc/pam.d/vmware-authd and add this line to the top:
auth sufficient /lib/security/ shadow nullok

Prevent users’ password from expiring since that is taken care of in AD.
esxcfg-auth --passmaxdays=-1

Add users using the username found in AD
adduser jdoe
adduser ymomma
adduser bdover


Now don't forgot to add the users to the wheel groups so they can ssh to the box. Also, add them to the sudoers file so they don't have to use su.

Tuesday, September 1, 2009

Brute Force ESX Username/Password

This script will brute force the connection to ESX. You can either give it a single username or a username file. Similarly, you can either give it a single password or a password file. You also have the ability to define how many jobs will run in parallel.

#Description: Powershell Simple VMware ESX Login Brute Force Script
#Version: 1.0
#Author: Tim Medin
#Email: TimMedin A@T securitywhole D.O.T com
#Parameter Declaration
param (
string] $Server = $(Read-Host -prompt "Server"),
string] $User,
string] $Password,
string] $UsersFile,
string] $PasswordsFile,
int] $MaxJobs = 10

# Function to handle the jobs once they complete
# As the jobs finish (Completed, or Failed) they are handled by this routine
# Each Job has a child job that actually does the work, if that job
# does not have an error then we have found a successful user/pass combo
Function Handle-Jobs {
    Get-Job | Where-Object {
$_.State -ne "Running"} | ForEach-Object {
        $job = $_
        if (!$job.ChildJobs[0].Error) {
            # Found one!
            Receive-Job $job -Keep | Out-Null
            # Echo the user/pass combo stored the job name
            echo "Found $($job.Name)"
            #Clean up all the running jobs
            Get-Job | Stop-Job
            Get-Job | Remove-Job

# Make sure we have enough info passed in from the parameters
if (!$User -and !$UsersFile) {
    throw "User or UserFile required."
if (!$Password -and !$PasswordsFile) {
    throw "Password or PasswordFile required."

# If the UsersFile and a Username are provided then use the UsersFile
# Convert UsersFile or single User into an array so we can use a loop
if ($UsersFile)
    $Users = Get-Content $UsersFile
    $Users = @($User)

# If the PasswordsFile and aPassword is provided then use the PasswordsFile
# Convert PasswordsFile or single Password into an array so we can use a loop
if ($PasswordsFile)
    $Passwords = Get-Content $PasswordsFile
    $Passwords = @($Password)

$Passwords | ForEach-Object {
    $pass = $_
    $Users | ForEach-Object {
        $usr = $_
        # If too many jobs running then wait for some to complete
        while ((Get-Job).Count -ge $MaxJobs) {
            Start-Sleep -Seconds 5
        # Start the job to attempt the connection
        Start-Job -InitializationScript {Add-PSSnapin VMware.VimAutomation.Core} -ScriptBlock { param($Server, $usr, $pass) Connect-VIServer -Server $Server -Protocol https -User $usr -Password $pass } -Name "User:$usr Pass:$pass" -ArgumentList $Server,$usr,$pass

"Everything has been queued, waiting for jobs to complete"

# Wait for the jobs to complete
Do {
    Start-Sleep -Seconds 5
while (Get-Job)