Saturday, September 27, 2008

Collecting Remote Volatile Data with PowerShell

This post is really about a script (Get-Volatile) I have been working on in PowerShell that will collect volatile data from a remote host using WMI. The aim of my script is to easily and quickly grab a bunch of useful information that may change from a host that I have an interest in for whatever reason. My script does assume thst you have permission and administrative access to the host that you are pulling information from.

Currently I use a bunch of batch files and Perl scripts written by Harlan Carvey and these are great because they help me keep an idea of what I want to achieve with my script.


The information I want to gather from a remote host with the script is the following:

  • System Time
  • Running Processes
  • Services
  • Shares
  • Sessions
  • Drivers
  • Logged on Users
  • Command History
  • Clipboard Contents
  • Hotfix/Patch Status
  • Start-up Information
  • Local Accounts & Groups
  • Networking Details & Open Ports
  • Network Connections

As my script is first run it will ask you for target and then for a name and location where you want to save the results. The results are simply a text file that can be used for further examination.

As the script is run it will have a friendly display to show where it is up to. I may well modify this to either state "1 of 2 tasks complete" or to display a progress bar.



The script is still evolving and as I have more code to add in I will update this post.

The code so far:

function Get-Volatile {

cls

$target = read-host "target?"
$Results = read-host "Results Location and Filename?"
write-host "Starting Get-Volatile V1.2 ........ Please Wait"
#
Write-Output "Current date on target as script starts" | Out-File -Width 255 $Results
Write-Output "" | Out-File -Width 255 -Append $Results
$Datenow = Get-Date
Write-Output $dateNow | Out-File -Width 255 -Append $Results
#
#OS Details
Write-Output "OS" | Out-File -Width 255 -Append $Results
Write-Output "" | Out-File -Width 255 -Append $Results
$OS = gwmi win32_operatingsystem -computername $target | Select CSName,Caption,CSDVersion,BuildNumber,RegisteredUser,Organization | Ft -AutoSize
Write-Output $OS | Out-File -Width 255 -Append $Results
#
write-host "Got OS........ Please Wait"
#
#
# Services & Processes
Write-Output "Running Services" | Out-File -Width 255 -Append $Results
Write-Output "" | Out-File -Width 255 -Append $Results
$services = gwmi win32_service -ComputerName $Target | select SystemName,ProcessID,Name,DisplayName,StartMode,State,PathName | sort StartMode | ft -AutoSize
Write-Output $Services | Out-File -Width 255 -Append $Results
#
write-host "Got Services........ Please Wait"
#
Write-Output "Running Processes" | Out-File -Width 255 -Append $Results
Write-Output "" | Out-File -Width 255 -Append $Results
$Processes = gwmi win32_process -ComputerName $Target | select CSName,ProcessID,ProcessName,WS,CommandLine | sort WS -Descending | ft -AutoSize
Write-Output $Processes | Out-File -Width 255 -Append $Results
#
write-host "Got Processes........ Please Wait"
#
#
# Local Users and Groups
Write-Output "Local Users & Groups" | Out-File -Width 255 -Append $Results
Write-Output "" | Out-File -Width 255 -Append $Results
$Users = gwmi Win32_UserAccount -filter "domain='$Target'" -ComputerName $Target | select name,Password*,LocalAccount,Lockout,SID | ft -AutoSize
Write-Output $Users | Out-File -Width 255 -Append $Results
#
write-host "Got Users ........ Please Wait"
#
#
$Groups = gwmi Win32_Group -filter "domain='$Target'" -ComputerName $Target | select Domain,Name,SID | ft -AutoSize
Write-Output $Groups | Out-File -Width 255 -Append $Results
#
write-host "Got Groups ........ Please Wait"
#
Write-Output "Profiles" | Out-File -Width 255 -Append $Results
Write-Output "" | Out-File -Width 255 -Append $Results
$Profiles = Get-ChildItem -path "\\$target\C$\Documents and Settings" | Sort-Object LastWriteTime -descending | select Name,LastWriteTime | ft -AutoSize
Write-Output $Profiles | Out-File -Width 255 -Append $Results
#
#
# Networking
Write-Output "Shares" | Out-File -Width 255 -Append $Results
Write-Output "" | Out-File -Width 255 -Append $Results
$Shares = gwmi win32_share -ComputerName $Target | ft -AutoSize
Write-Output $Shares | Out-File -Width 255 -Append $Results
#
write-host "Got Shares........ Please Wait"
#
Write-Output "Domain Details" | Out-File -Width 255 -Append $Results
Write-Output "" | Out-File -Width 255 -Append $Results
$Domain = gwmi Win32_NTDomain -ComputerName $Target | Select DomainName,DCSiteName,DomainControllerAddress,DomainControllerName | ft -AutoSize
Write-Output $Domain | Out-File -Width 255 -Append $Results
#
write-host "Got Domain........ Please Wait"
#
# Software
#
Write-Output "Hotfixes" | Out-File -Width 255 -Append $Results
Write-Output "" | Out-File -Width 255 -Append $Results
$Hotfixes = gwmi win32_quickfixengineering -ComputerName $Target | select CSName,HotfixID,ServicePackInEffect,Description,InstalledOn,InstalledBy | ft -AutoSize
Write-Output $Hotfixes | Out-File -Width 255 -Append $Results
#
write-host "Got Software and Hotfixes........ Please Wait"
#
Write-Output "Date and time as script finishes" | Out-File -Width 255 -Append $Results
Write-Output "" | Out-File -Width 255 -Append $Results
$Datenow = Get-Date
Write-Output "date is $dateNow" | Out-File -Width 255 -Append $Results
#
Write-Host "Finished!"
}

Get-Volatile


Any suggestions or comment are welcome as always.


Change Log.
  • 27/09/08 - First script posted - Includes Date, Services, Processes, Local Users & Groups, Shares & Hotfixes.
  • 29/09/08 - Added in command to get a list of local profiles and some section headings for the output.
  • 07/09/08 - Added codeto retreive OS details and Domain & Site Details.

Tuesday, September 16, 2008

Wardriving with the IPhone

I decided to see which apps were available for the IPhone to do a little Wardriving with and I was chuffed with what I found. Below are deteails on a few applications that I have found useful to do a little network exploration with.


Tools

The apps I'll discuss in this post are WiFiFoFum, WiFinder, Ping (Lite), Net Utility and Portscan. These tools are all available from the App Store and do not require you to jailbreak the IPhone. Which I thought was very nice.





First I used the IPhones native WiFi tool to see which networks I could see.




Currently I can just pick up the one access point. I can see that there is no padlock icon so I know it's not encrypted which is useful, but it doesn't tell me whether it's WPA or WEP which is quite useful to know. OK, lets see what I can discover with my fancy new apps.


WifiFoFum

I have used this app before on Windows Mobile and found the IPhone version to be very stable. I was quickly able to see that it had picked up another AP.

I really like the Radar as it allows me to easily see which points are nearest to me as I am moving around.




Using this WifiFoFum I was able to quickly able to see which AP's had encryption.



And then by clicking on the point i'm interested in I can see which type of encryption it is using.




OK, thats all very nice but If I want an easier way to see which AP's are using encryption as I am driving about I need something different.



WiFinder

Ok, so this app does similar stuff but it goes a little further.



As you can see from the screenshot above, open and closed networks are sorted in categories and the encryption type is listed. I found this is slightly better when driving. As you can see from the screenshot below it's pretty effective at detecting access points




Now what is happening here is when the application finds an open AP, it will connect through to a remote website and if it gets through you'll see a green check mark next the name.


After selecting an Access Point you are presented with some more details and given the option to connect.



You can of course opt to connect by selecting the Connect button as shown above and you will be on that wireless LAN.


Ping (Lite)

This is a free application that I find pretty useful. After bring the application up, you are presented with some pretty standard utilities.



The one I was interested in to start with was Ping Subnet. After running this I was presented with details of all hosts on the subnet that respond to ICMP requests.



It's pretty hard to see in the graphic above but responding hosts are colored green. Well this is great. So now I know who else is on the subnet, you know, on the safe & soft inside.

Oh, and a handy traceroute utility to maybe help get more details of the network infrastructure.



So, I want to take this one step further.


Net Utility

Now I have to change my focus to another site here but basically here I am able to use the port scan feature of Net Utility to see if the host has an open port. This will give you some idea of the role of the host and maybe the firewall rules or lack thereof.



and as we see it's open (obviously)



And then there is also the really handy whois utility too.




And another utility included with this tool is the IP Address Information. This will show you your IP address AND the wireless networks external IP address. Nice!


PortScan

I found this utility and i thought I would update the post with it. It does basicaly what it says onthe tin. It port scans a host.

It has a few otions where you can set the ports, select a range or let it scan well known ports. And the speed of the scan can be adjusted. It's pretty basic but its the best out there that I have found.



I have tested this on a couple of devices and it seems okay. The option to guess the OS is just that, a guess. But it's not bad and it's fun.




Most of the utilities do have additional functionality on top of what I have shown here.


Change Log:
10-10-08 updated post with details of Portscan.

Monday, September 15, 2008

Retrieving Remote Processes with PowerShell

Keeping in line with my current theme of retrieving useful information from a compromised PC, below is a simple one-line that will grab the running processes from a remote host.

Get-WmiObject win32_process -ComputerName . | Select-Object CSName,Description,Processid,WS,Path | Sort-Object WS -Descending | Format-Table * -AutoSize


This is the full cmdlets rather than the aliases or shortened version, but for anyone reading this who might be wondering, that command would be:

gwmi win32_process -Co . | Select CSName,Description,Processid,WS,Path | Sort WS -Desc | Ft * -Au


And the output would be something like this.




Again, this can be run on an remote host by substituting . after -ComputerName to a remote computer name. The output can be exported straight to CSV by removing the Format-Table command and using Export-CSV cmdlet.

Sunday, September 14, 2008

Retrieving Remote Services with PowerShell

In the few weeks that I have been using PowerShell I've been really keen to see how I could use it to help with the security parts of my job. In the past I have used scripts and tools from Harlan Carvey's book "Windows Forensics and Incident Recovery" when I have had to look at a PC that has been comprised. Now I'm beginning to grasp PowerShell I am keen to write my own scripts to investigate compromised PC's and retrieve volatile and non-volatile information.

In this post I will simply detail how to retrieve data about services from a remote PC using WMI and PowerShell.


Services

The information i'm interested in regarding Windows services is really what services are running, the state of them and the executable involved. Below is the command I would use to output that information to the screen.

gwmi win32_service -ComputerName . | sort StartMode | ft SystemName,DisplayName,StartMode,State,PathName




Unfortunately The whole output doesn't fit. So I would use this next Command to export the results to a CSV file for closer analysis.

gwmi win32_service -ComputerName . | sort StartMode | select SystemName,DisplayName,StartMode,State,PathName | export-csv -path d:\runningServices.csv

Now in the CSV i can see all of the output including the full path of the executable.



Obviously, in both examples the . after -ComputerName can be substituted fora remote computer that you have permission to query.

Saturday, September 13, 2008

Talking PowerShell Ping-Script

Tonight I wrote a short Powershell script to have PowerShell go through a list of servers and report back which are up.  Just for fun I thought I would add in a couple of lines to make PowerShell tell me which servers are down by using the voice functions available and by highlighting the down servers with a red background.

I know, it's not groundbreaking but I like it!



Here is the code.

cls
$Voice = new-object -com SAPI.SpVoice

function Ping-Host {
BEGIN {}
PROCESS {

$results = gwmi -query "SELECT * FROM Win32_PingStatus WHERE Address = '$computer'"

if ($results.StatusCode -eq 0) { 

Write-Host "$computer is Pingable"
} else {
$Voice.Speak( "Alert Alert Alert $computer is down", 1 )
Write-Host "$computer is not Pingable" -BackgroundColor red
}
}
END {}
}
$computers = Get-Content q:\servers.txt
foreach ($computer in $computers) {
if (Ping-Host $computer) {
}
}

The output looks like this:




All i'm doing is listing a bunch of servers in Q:\Servers, then piping each one through a ping and outputing on screen the servers that respond and the ones that don't go to the screen with a red background and to the voice thingy that talks like in war games.

Right now to me this is the coolest thing I have made in PowerShell.


Saturday, September 6, 2008

IPhone Port Scan

Just out of interest I thought I would port scan my IPhone.

After issuing just nmap ipaddress I had no response So I turned off the ping first option and tried again.

nmap 192.168.1.108 -P0



Okay so I found it. The MAC ties up with my phones MAC address.

Next I'll just try all TCP ports to see what I get.

nmap -P0 -p1-65535 192.168.1.108



So I found one TCP port open. I'lll use the -sV switch to get the version.

nmap -P0 -sV -p62087 192.168.1.108



Hmmm. Still nothing. Maybe an OS Scan would be interesting.

nmap -P0 -O 192.168.1.108



So it got the right OS

Okay. So I know there is still that open port. What if I send something to it and see what comes back.

So using TCPDump I throw on a filter for just the IPhone IP address.

tcpdump -i eth0 host 192.168.1.108



Thats a bit noisey. I want just my target port for now.

tcpdump -i eth0 host 192.168.1.108 && port 62078

now In a seperate window, I create a test file by echoing "test" to a file and thow that at the port using nc.



nc 192.168.1.108 62078 < face="georgia">Okay, so that went well. I'll repeat the process and capture the results to analyse in Wireshark using the -w switch with tcpdump:

tcpdump -i eth0 -w iphone-capture.pcap host 192.168.1.108 && port 62078

Okay. I'll be honest. The results were not good. I'm still clueless. Maybe i'll resort to good old Google.

2 Mins later................................

Okay, now i find that the leg work has already been done. It's a port used when synching with iTunes.




Oh well, i suppose it was one way to waste an hour.

P.S - If you do try port scanning the Iphone, you might find that it needs a hard reset before it will synch properly.

Friday, September 5, 2008

DNS Discovery With Fierce Domain Scan

This is just a quick post about some fun I had recently with Fierce Domain Scanner. I always find it amusing when I hear people say that they think naming a Server something other than www will afford them some protection. I always assume if it's out there then people know about it, no matter what you call it.

Using Fierce Domain Scanner from the Backtrack Distro I was able to point it at a domain and query DNS for available hosts. Using the command line below it turned up some interesting results:

perl fierce.pl -dns boots.com




When run, Fierce will contact my DNS server to get the targets name servers and then use them to first attempt to get the SOA records (which will likely fail these days) and then it will use the hosts.txt file to guess names. The reason it will switch to using the targets DNS is because it assumed that there is a chance that the internal DNS and the external DNS are on the same box, so here theres a chance of getting some internal names.

This scan uses the hosts.txt file in the same directory as the perl script to bruteforce DNS names and discover live hosts. The hosts.txt file can be updated manually or you can point Fierce to an alternative one.

Once a name is found it will scan up and down that range (5 address by default but this can be changed) looking for hosts with the same domain name. Now if this is a pentest and earlier reconnaissance has uncovered other associated domain that are in the scope of the test, Fierce can be told to look out for host with those domain names (use the -search option).

This tool is great to run against your own domain to see if there's anything there that shouldn't be.

Please remember, this is Fierce at it's most basic. More information can be found here at the creator, Rsnakes site.

PowerShell Script Repositoy

This post really has little to do with security or hacking but I'm throwing it up here because I'm really enjoying playing with powershell and learning loads of new ways of doing things.

This page is really going to be a bit of a repository for scripts and one-liners that I have found useful and I want a place to keep them for reference. If anyone else finds a use for them then thats great too. If anyone has any question or comments about them then please ask and i'll try to help.


Active Directory Admin

#To connect to an alternate DC:

Connect-QADService -service 'server.company.com'


#To export user details to track down stale accounts:

get-qaduser -sizelimit 0 -IncludedProperties altRecipient | select name,altRecipient,accountexpires,pass*,accountisdisabled,lastlog*,canonicalname | export-csv -path d:\logon-details.csv


# once user accounts are identified as stale and a list is made in a text file called:

$users = (c:\users.txt)

foreach ($user in $users) { Disable-QADUser "$user" }


# To move accounts to a new OU

foreach ($user in $Users) { Move-QADObject "$user" -NewParentContainer 'domainname.co.uk/leavers/disabled' }


# To remove group membership (all but domain users) from selected user:

foreach($user in (gc c:\users.txt)){
(Get-QADUser $user).memberOf | Get-QADGroup | where {$_.name -notmatch '^users|domain users}


# To validate selected accounts for properties rather than the whole of AD:

$users | foreach { get-qaduser $_ -IncludedProperties altRecipient | select name,altRecipient,accountexpires,pass*,accountisdisabled,lastlog*,canonicalname} | export-csv -path d:\Leaver-Validation.csv



#To set one user as hidden from the address book:

Set-QADUser "Test User" -oa @{'msExchHideFromAddressLists'=$True}



# To set many users to be hidden from the Address Book:

foreach ($user in $users) { Set-QADUser "$user" -oa @{'msExchHideFromAddressLists'=$True}}



# To validate selected accounts for properties rather than the whole of AD:

$users | foreach { get-qaduser $_ -IncludedProperties altRecipient | select name,altRecipient,accountexpires,pass*,accountisdisabled,lastlog*,canonicalname} | export-csv -path d:\Leaver-Validation.csv




Server Administration

### 3 Event log queries:

# Using WMI

Get-WmiObject Win32_NTLogEvent -ComputerName server01 | where {$_.logfile -eq "System" -AND $_.type -EQ "Error”} | Select TimeGenerated, Message | Format-Table –Auto


Get-WmiObject -query " Select Logfile, Eventcode, TimeGenerated, Message from Win32_NTLogEvent where LogFile='Application' AND EventCode='1054'" | Select TimeGenerated, Message | Format-List


# Using .Net

$server = "server01"
$log = New-Object Diagnostics.Eventlog "Application","$server"
$log.entries | where {$_.EventID -eq "1054"}



# Check diskspace on selected servers:

gwmi -query "SELECT SystemName,Caption,VolumeName,Size,Freespace FROM win32_logicaldisk WHERE DriveType=3" -computer (gc c:\servers.txt) | Select-Object SystemName,Caption,VolumeName,@{Name="Size(GB)"; Expression={"{0:N2}" -f ($_.Size/1GB)}},@{Name="Freespace(GB)"; Expression={"{0:N2}" -f ($_.Freespace/1GB)}}, @{n="% Free";e={"{0:P2}" -f ([long]$_.FreeSpace/[long]$_.Size)}} | sort "% Free" | export-csv c:\Disk-GB.csv


# To Find the who logged onto servers last.

$target=("server")
Get-ChildItem -path "\\$target\C$\Documents and Settings" | Sort-Object LastWriteTime -descending | select Name,LastWriteTime


# To restart a service on a list of computers

$service = Read-Host "enter service name"
$ServerList = gc (Read-Host "Enter server list file")
function StopService {
$ServerList | % { gwmi win32_service -ComputerName $_ -Filter "name='$Service'" | % { $_.stopservice() }}
}
Function StartService {
$ServerList | % { gwmi win32_service -ComputerName $_ -Filter "name='$Service'" | % { $_.startservice() }}
}
stopservice
startservice


#To locate services that are stopped but should be running on a list of servers.

gc (Read-Host "serverlist or servername") | 
% { gwmi win32_service -ComputerName $_ -Filter "startmode='auto'"} | 
where { $_.state -eq "stopped" } | 
select SystemName,Name,StartMode,State,Caption,PathName | 
ft -AutoSize -GroupBy SystemName



#To set a new password on a service

gc Q:\servers.txt | % { gwmi win32_service -ComputerName $_ -Filter "name='alerter'" | % { $_.change(,,,,,,"newpassword") }}


#To reboot a list of computers

gc q:\servers.txt | ForEach-Object { gwmi win32_operatingsystem -ComputerName $_  | ForEach-Object { $_.reboot() }}




Exchange 2003 Administration

# list remote Exchange classes

gwmi -namespace root\microsoftexchangev2 -list -comp server01


# get exchange mailboxes from a server and sort:

gwmi -namespace root\microsoftexchangev2 Exchange_Mailbox -comp server01 | select mailboxdisplayname,size | sort size -Descending


# logged on users to exchange, filtering out system accounts:

gwmi -namespace root\microsoftexchangev2 -class Exchange_logon -comp server01 | where { $_.LoggedonUserAccount -notmatch "NT AUTHORITY*" } | select ServerName,ClientIP,LoggedonUserAccount,MailboxDisplayName | ft -auto



Archived Files

# To retrieve archived files from directory and subdirectory

Get-ChildItem -recurse "*" | where { $_.attributes -match "offline" } | select-string "test" -simple


# To list archived files with file paths

Get-ChildItem | where { $_.attributes -match "offline" } | select fullname




Log Parser Fun

Recently I needed to interogate the event logs of about 80 servers for a particular event. Well Windows doesn't exactly make that sort of thing easy. Being a fan of the free tool Log Parser I was able to make pretty short work out of what could have been a very time consuming task.

First I set about getting the names of all my servers into a text file called servers.txt (each server on a new line).

Then I used a simple FOR loop with Log Parser to rip through the servers event logs and look for the particular event. Any instances it found I placed into a new log file. The FOR loop I used was simply:

FOR /f %i in (c:\servers.txt) do @LogParser.exe -i:EVT -o:CSV "SELECT computername,message FROM \\%i\System WHERE eventid= '531'" >>c:\event-capture.log

The script can be run direct from the commandline and all it does is loops the the servers looking for the event 531 in the System Event Log and outputs the computername and message fields in csv format to a text file called event-capture.log

And that's pretty much it on Log Parser for now.

I do recommend the Log Parser book from Syngress Publishing for some really funky uses of Log Parser and a nice post from George Starcher can be found here on integrating Log Parser with other tools for some real geeky fun!

Log Parser is a free tool and can be downloaded from here. Whilst googling around I came across another free tool that is like a GUI front end for Log Parser called Log Parser Lizard. It's well worth a look and can be found here.

Hacktop Refresh

Recently I gave my Asus eee hacktop a bit of a makeover. After a bit of googling I settled on eeebuntu. I'm a big Ubuntu fan and this seemed to be a nice looking custom distro for the eee.

After downloading the iso from the sight and whacking it on a USB using the utility on the site it was as simple as rebooting and going straight into the live CD (or USB in this case) to test.



Everything worked straight out of the box, the wireless, the camera, sound, ACPI, I mean everything.

The interface is well designed, looks polished and proffesional and makes using a small screen much more fun. I love gnome on the desktop but when your screen real estate is restricted this does the job.

I had no hestitations in opting to install permanently. After the install I was able to easily customise the interface to suit my needs and I had my favourite tools within minutes.




For more details visit eeebuntu here