Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Hakin9 05 2010 EN

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

5/2010 (30)

PRACTICAL PROTECTION IT SECURITY MAGAZINE

team CONTENTS
Editor in Chief: Karolina Lesińska
karolina.lesinska@hakin9.org
Advisory Editor: Ewa Dudzic Dear readers,
ewa.dudzic@hakin9.org

Editorial Advisory Board: Matt Jonkman, Rebecca Wynn, This is the second time we meet digitally. This time I want to
Rishi Narang, Shyaam Sundhar, Terron Williams, Steve
Lape, Aditya K Sood, Donald Iverson, Flemming Laugaard, Nick thank you for your support and involvement in promoting
Baronian, Michael Munt our magazine. In the last months we noticed a great growth
DTP: Ireneusz Pogroszewski of Hakin9 readers and I am sure you actively take part in it:)
Art Director: Agnieszka Marchocka So, thank you!
agnieszka.marchocka@software.com.pl

Cover’s graphic: Łukasz Pabian In this issue we focus on several issues: Matt Jonkman gives
Proofreaders: James Broad, Ed Werzyn, Neil Smith, Steve us his thoughts on DDOS attacks, and in the expert section
Lape, Michael Munt, Monroe Dowling, Kevin Mcdonald you will find an article on botnets – dangers and protection
Contributing editor: James Broad against them. In the attack section you will read a great work
on jailbreaking and penetrating with the Iphone 3G & 3GS. In
Top Betatesters: Joshua Morin, Michele Orru, Shon Robinson, the defense section there is a beginner’s guide to cybercrime
Brandon Dixon, Stephen Argent, Jason Carpenter, Rishi Narang,
Graham Hili, Daniel Bright, Francisco Jesús Gómez Rodríguez, focusing on understanding attack methodologies and a more
Julián Estévez, Michael Sconzo, Laszlo Acs, Bob Folden, Cloud proactive approach to defense.
Strife, Marc-Andre Meloche, Robert White, Bob Monroe,

Special Thanks to the Beta testers and Proofreaders who


helped us with this issue. Without their assistance there would As I have mentioned last time, you will be receiving a
not be a Hakin9 magazine. newsletter with new issue at the end of each month, so keep
Senior Consultant/Publisher: Paweł Marciniak an eye on your emails! If you would like to help in creating
Hakin9 magazine, become an author, proofreader or
CEO: Ewa Łozowicka
ewa.lozowicka@software.com.pl betatester – don’t hesitate! Keep the mails coming in!
Production Director: Andrzej Kuca
andrzej.kuca@hakin9.org Enjoy your reading! And remember – go green, choose
Marketing Director: Karolina Lesińska
download!
karolina.lesinska@hakin9.org

Subscription: Iwona Brzezik


best regards
Email: iwona.brzezik@software.com.pl Karolina Lesinska
Publisher: Software Press Sp. z o.o. SK Editor-in-Chief
02-682 Warszawa, ul. Bokserska 1
Phone: 1 917 338 3631
www.hakin9.org/en

Whilst every effort has been made to ensure the high quality of
the magazine, the editors make no warranty, express or implied,
concerning the results of content usage.
All trade marks presented in the magazine were used only for
informative purposes.

All rights to trade marks presented in the magazine are


reserved by the companies which own them.
To create graphs and diagrams we used program
by

The editors use automatic DTP system


Mathematical formulas created by Design Science MathType™

DISCLAIMER!
The techniques described in our articles may only
be used in private, local networks. The editors
hold no responsibility for misuse of the presented
techniques or consequent data loss.

4 05/2010
CONTENTS

REGULARS
06 in Brief
Latest news from the IT security world
Armando Romeo
ID Theft Protect

10 Tools
NTFS Mechanic
Active@ Undelete
Michael Munt

39 Emerging Threats
Is DDOS Still a Threat?
Matt Jonkman

46 Expert Says...
Don’t let the zombies take you down!
Ian Kilpatrick

BASICS
12 Pulling Kernel Forensic with Python
Daniel Lohin

ATTACK
18 Jailbreaking and Penetrating with the Iphone 3G & 3GS
Wardell Motley

22 Flash Memory Forensic Tools - part two


Salvatore Fiorillo

DEFENSE
30 Securing Public Services Using Tariq
Ali Hussein

34 Beginner’s Guide to Cybercrime – Understanding Attack


Methodologies and a More Proactive Approach to Defense
Gary Miliefsky

40 More Secure PHP Server Side Source Encryption


Israel Torres

www.hakin9.org/en 5
IN BRIEF

for your friends, now host articles on


Beware the ID theft Khobe – malware bypassing how to handle your privacy concern.
protectors all Windows AV’s Even programmers, now prefer to
ID Theft is a true concern that is not The headlines of Matousec.com code online tools such as Openbook
going to stop. research sounded to Antivirus and Zesty.ca/facebook instead of
Incidents increased by 11% from vendors hype and terrifying at the pumping new facebook application
2008 to 2009 affecting over 11 same time: New malware bypasses into the funnel. These tools are now
million Americans in 2009. virtually all Windows AV’s. getting famous and very (mis)used
The most likely to fall victim are Researchers, in early May 2010, as Facebook privacy is getting laxer
young adult and small business said they were still able to have and laxer.
owners. all the most common Antivirus tool Facebook lack of privacy is
The first are not aware of the risks protections bypassed: the method basically creating another grey
related to privacy loss through social was known to Antivirus vendors market where your information is
networks. and indeed not new. The devised easily accessed and possibly sold.
The latters are subject to malware affects all the protection The latest Facebook privacy
complete a large number of financial mechanisms employing SSDT policy is 5830 words, 1287
transactions online and offline hooking on Windows. According words longer than United States
that necessarily require the use of to researchers most of security Contitution and it tends to be more
information such as SSN, Tax ID software vendors implemented and more permissive about what
and email addresses. their kernel hooks very poorly and you must to share.
When a market is growing so their applications were creating Doing something about it is now
much and TV starts to consider another holes into the operating creating another market niche. Now
this a real plague, it's not to wait system instead of protecting it. we have services that will fine tune
too long before someone comes up A new tool, named BsodHook, your account to avoid giving out too
with a solution. A fake solution in this has been devised to find this kind much information. Why? Because
case. of vulnerabilities automatically. according to PcWorld there are
Lifelock claims itself "leader in ID Vulnerable products includes a very over 50 settings and 170 options
theft protection". They try to avoid wide range of well known tools to adjust. And even that won’t
that your data falls into the wrong including McAfee, TrendMicro, AVG completely safeguard your info.
hands and even if it happens they and Symantec. The method used As long as having a Facebook
help you find out where your data by researchers has demonstrated account is felt as one of the
is. to be very reliable and with a high universal individual’s right, (a sort
The business model is similar to success rate on multi-processor of cyber freedom of speech?),
an insurance: you pay $10 to $15 systems. Zuckerberg and his multi-billion
every month and if you fall victim The disaffection of the community dollar new-con investors, will have
of an ID theft they will help you towards anti-malware vendors and the power and the arrogance to
keep up with the costs of solving the objective hype in the headline ask for forgiveness and never for
the issue up to 1 million dollar. made the research traverse Twitter permissions.
Everything sounds fantastic, until and all the security web sites, that
you find out that Lifelock own have all given massive coverage.
CEO has been fallen victim of ID Responses from the Antivirus
Do you trust Google?
theft at least 13 times in the last vendors, through their corporate United States is the only among
2 years. That New York times has blog, were limited to we are not western countries not having
uncovered, in a series of articles, vulnerable or it is unjustified hype. a federal law on Privacy. This
how the whole business is based doesn’t entitle Google, a US
on deceptive advertising and no corporation, to collect Europeans’
real value is brought to the user.
Now Facebook Privacy is data. This is the summarized
The Tempe company operations a concern statement given by German
still go on even after a 12$ After years of blindness, Facebook consumer protection ministry when
Million penalty and will probably users now realized their privacy is the shocking news was disclosed:
go on spending million dollar of at risk. Google searches for how Google has for years carried out
TV commercials and deceptive to remove facebook account is extensive wardriving collecting at
message to address a market and rising and all the printed and online least 600 gigabytes of illegal data
problem for which a real solution is magazines, after months of hype through the use of special wireless
not yet available. and tutorials on how to buy fake-gift equipment included in Google

6 5/2010
IN BRIEF

Street cars. Google admitted this framework supported by the open be owned by criminals just for
behavior in a blog post clarifying source community. this purpose. Usually criminals,
that the collected data regarded Metasploit Express features use iframe injection attacks to
solely photos, 3D building imagery a GUI for automatic scanning have a number of vulnerable and
and WiFi network information. At and exploitation configuration, unaware websites to link back to
first. administration and advanced their rogue page.
Among this information there reporting management. Google favors websites with
is SSID of networks and MAC It also emphasizes the importance a greater number of backlinks or
addresses, but not payload data of security auditing and exploitation backlinks with some reputation. Yahoo
according to big G. After this post, workflow, that is extremely important and other search engines do not
dated 27 April 2010, Alan Eustace, when testing the security of large base their ranking on the number of
Google senior vice president of enterprises. backlinks rather on the so called on-
research, gave a completely All these features and an page optimization, thus making it even
different and clarifying version: advertised ease of use, position more simple for a hacker to forge a well
It’s now clear that we have been this tool in the enterprise segment optimized web pages to show early in
mistakenly collecting samples for in-house security auditing and search results. However, Google is
of payload data from open WiFi for small-business security vendors the most targeted search engine since
networks stated. The payload were and consultants in the penetration it’s by far the most used.
collected by mistake. But it has testing field. When such an attack is launched
been collected. A piece of software Metasploit new release includes it takes just a few hours for results
coded by a former Google engineer massive improvements to to appear.
had been included in the firmware exploitation payloads, especially Criminals are now very smart at
of the devices shipped in Google meterpreter and new brute forcing picking the hottest topics: Miss USA
cars. This firmware was originally capabilities introduced in version Rima Fakih’s past photos appearing
meant to only store SSID’s and 3.4. on Google Images are the latest
MAC addresses. example.
This mistake will cause Google
a series of legal issues in Europe
Need SEO? Ask hackers Source: source: Armando Romeo
where Privacy is still something This is not to be confused with
serious. Blackhat SEO that has a completely
different meaning.
Destructive Malware
But the habit of exploiting SEO Identified
Metasploit techniques for malicious purposes A new computer virus that replaces
Express released is now consolidated among all files in the C: drive with copies of
Since the Metasploit project buyout criminals. It has been named as itself has been identified by a leading
by Rapid7, the Framework, led by HD SEO poisoning and we have had UK internet security company. The
Moore, has boosted its operations the most prominent example with malware, named W32/Scar-H, can
bringing an integration with Core the Chile earthquake: rogue pages, lead to a cascade effect where, in the
Impact and now a commercial containing malware and other end, it takes down the entire computer
version of the open source browser exploits, appeared on top of system. Oddly, there seems to be no
exploitation framework named the google ranking for hot searches, financial motive behind the virus
Metasploit Express. The project will in the hours of the tragedy. since its function is purely destructive.
now fork and both the open source Search terms like chile earthquake ID Theft Protect says that this type of
framework, now released in its 3.4 find relatives or Chile quake 2010 approach (hard drive destruction)
version, and the commercial version tsunami were heavily addressed is very unusual. Maybe someone
will be supported in parallel. with rogue blog posts appearing has a grudge against a particular
Metasploit Express has been among more reputable news organisation or person?
a great addition to the fast growing websites.
Rapid7 company: a penetration The technique is relatively simple.
tester has now the power of Everyone can get the list of the
Google Groups Delivering
Rapid7 vulnerability management hottest search keywords using free Malware
solutions, namely Nexpose, to use google tools. Then a number Cybercriminals are using Google
and the exploitation power, now of back-links pointing to the rogue Groups to distribute rogue anti-
even automated and extended page is required. A number of virus software and other malware,
of a commercial exploitation small websites are believed to according to leading security

www.hakin9.org/en 7
IN BRIEF

researchers. The attackers are operating system – Windows 7 and systems that use ONLY Yahoo
sending e-mails to Google Groups Windows Server 2008 RC2. The Instant Messenger.
members asking them to update security flaw could expose users The malware arrives via an
their e-mail settings by following to code execution and denial-of- instant message through Yahoo or
linked instructions. service (DDOS) attacks. The file Skype with any one of a number of
The links take users to a fake Google responsible for the flaw was found messages, including „Does my new
Groups page that infects visitors’ in the Canonical Display Driver hair style look good? bad? perfect?”
PCs with a Trojan that downloads (cdd.dll), which is used by desktop or My printer is about to be thrown
malicious software, including rogue composition to blend the Windows through a window if this pic won’t
anti-virus program Desktop Security Graphics Device Interface (GDI) come out right. You see anything
2010. The rogue software runs a fake and DirectX drawing. wrong with it?
PC scan, notifies the user that the PC Microsoft has stated that it is The message includes a link to a
has been infected and then prompts much more likely that an attacker web page that looks like it leads to
the user to buy software to remove who successfully exploited this a JPEG image file. When the link
the threat. The malware is designed vulnerability could cause the is clicked, the browser displays
to trick users into handing over their affected system to stop responding an interface that looks like the
credit card details and other personal and automatically restart. The RapidShare web hosting site and
information to purchase the bogus company has activated its security offers up a ZIP file for download.
software. response process and promises a The extracted file is actually
security patch to follow very shortly. an executable file with a .com
extension.
Software Piracy is on the
Increase Windows 7 Trojan Horse Source: ID Theft Protect
The overall rate of software piracy Threat
increased two percent compared Cyber criminals have disguised
to 2008, a spike that primarily can Trojan horse malware under the
Foxit Readers adds ‘Safe
be attributed to the rapid growth of guise of a Windows 7 compatibility Mode’
the consumer PC market in Brazil, checker. The malware comes as Foxit Corp (US) has added new
India and China, a leading report by a zip-based attachment to email security features to its alternative
IDC. Overall, the commercial value messages supposed offering help PDF reader software to help thwart
of global software theft exceeded on upgrading Windows boxes. But recent malware attacks that exploit
US$51 billion in 2009. this Windows 7 Upgrade Advisor the /launch feature. With Foxit PDF
In the study released earlier in Setup assistant offers only a Trojan, Reader Version 3.3, the company
May, IDC researchers analysed instead of the promised compatibility has added a Safe Mode that blocks
PC and software trends in 111 checking tool. external commands from being
countries. Researchers found that Windows users who open and run executed by the software. The Safe
some progress has been made the application end up with systems Mode is a key part of a new Trust
in the fight against piracy. During compromised with a backdoor Manager in the Foxit PDF Reader.
2009, unlicensed PC software use that allows hackers to insert other Earlier this month, Foxit Reader
decreased in 49 percent of the viruses and spyware. The hackers adopted a warning message before
nations studied. behind the attack get to pimp out running any executable command
The United States had a 20 percent these compromised systems to embedded in a PDF document. The
software piracy rate, the lowest out other miscreants, earning illicit changes follow the discovery by a
of all countries studied. In addition, affiliate income in the process. leading researcher, that dangerous
Japan and Luxembourg had piracy executables can be embedded into
rates of 21 percent. Countries with PDF files (and executed) without
the highest piracy rates included
Yahoo! Messenger Malware exploiting any vulnerabilities.
Georgia, Bangladesh, Zimbabwe Threat
and Moldova, each with a piracy A new worm has materialised via Source: ID Theft Protect/Foxit
rate above 90 percent. Yahoo Instant Messenger. It appears Corp (US)
that it is even more sophisticated in
social engineering and payload than
Windows 7 Aero Flaw Identified
previous worm attacks on Yahoo
In May, a serious vulnerability Instant Messenger. This new worm
was identified in Microsoft’s new installs via the backdoor of Windows

8 5/2010
TOOLS

NTFS Mechanic
Disk & Data Recovery for
NTFS Drives
Items Tested:
40GB External USB HDD that has had an extensive Pricing
Standard $99.95
amount of files written to it, and then randomly deleted,
Business $199.95
approximately 16GB in total and has intermittant Professional $299.95
connection issues to the point that the local machine Prices are in US Dollars
doesn’t actually register the drive is there.
Once I had the software installed it was time to see possible. It took just over an hour to scan through
how it performs. I plugged the external drive in and a 40GB hard drive. Once it was finished NTFS
then powered up the software. It saw my drive straight Mechanic provides all the data thats on the drive,
away, but it didnt actually state what disk format the deleted and non-deleted files. You can select in the
drive actually was. This might be due to the fact that the right hand menu to only see the recovered files,
operating system didn’t actually find the drive itself, so which makes it a lot easier to see what the program
it was a pleasant surprise that this program did indeed has actually found.
find it. If you look at the properties of the files and folders that
You are able to configure what types of files you have been listed as being recovered, you can actually
actually want the program to be searching for during the see the prognosis of each file if you decided to proceed
recovery process, for this test I just left everything as and recover the file completely.
default which means everything was selected. The process for recovery couldn’t be much easier,
I selected my external USB Drive and it scanned it’s simply a case of going through the folder list and
the partitions first to ensure that it can actually see selecting the files you want to recover and then just say
the drive correctly. Once this part of the process has where you want them to be stored.
been completed it then requests that you allow it The program performs really well and managed to
to scan the whole partition that you have selected, recover data from a disk that hasn’t been seen by
this appears to be a very cpu intensive program so any of my machines for a little while now which quite
I would suggest to just leave it running on its own if impressed me.
I noticed that there were a few area’s within the
program that could do with some QA work as there
were non english characters in use and some screens
weren’t actually needed in my opinion but they arent
detrimental to the product.

I would gladly have this tool in my toolbox.

http://recoverymechanic.com/ntfs_recovery/ntfs_
mechanic.php

Partition Recovery
Hard Drive Recovery
Recover deleted files

by Michael Munt

10 5/2010
Tools

Active@ LiveCD
Disk Suite Edition

Windows Based Product Details Personal Corporate


Active@ LiveCD provides a bootable CD that
Active@ Boot Disk (Win Edition) $79.95 $99.95
gives you a lightweight Windows (WinPE 2.0)
environment or a DOS based environment with a Active@ Boot Disk (DOS Edition) $69.95 $89.90
powerful suite of tools. You have the option to add Active@ Boot Disk Suite (Win + DOS) $109.95 $129.95
additional files, drivers and even scripts to aid you Active@ Boot Disk (DOS Edition) Enterprise not applicable $3499.00
at the time of disk creation.
Your able to create and restore images of Full hard disk performance monitoring and control is
the disks, explore the images and recover specific files also included, you can set the system to send out email
and folders from these images. Your also able to create notifications once certain criteria has been met. You can
a complete raw image which can be used for forensic create full detailed reports concerning the performance
purposes, finally you can completely clone a disk which of the hard drives in question, which is invaluable when
is useful for when creating a system image for rollouts of trying to track down errors on a intermittant faulty drive.
new equipment. The file recovery recognises file types There is a full suite of other applications included that
by their actual headers so even if the files have been will allow you to perform a multitude of tasks from taking
renamed by a virus etc, you can still recover them, the screenshots to editing the local registry. Full control of the
ability to rebuild RAID arrays and recover data from network settings and once online your able to connect to
them is an excellent feature and something that is FTP, Telnet and even surf the internet using the inbuilt
usually forgotten about by other recovery systems. browser (I found this browser to be a lot quicker than the
A full partition management system is included Internet Explorer of Firefox on my normal machine)
allowing you to have full control of the partitions on the
local machine (FAT12, FAT16, FAT32, NTFS, NTFS5 DOS Based
are supported). You are able to perform partition Even on the dos based side of the suite you are given
recovery on the fly with no reboot being required. You an excellent range of tools. Uneraser will allow you to
have the ability to create multiple partitions on USB/ undelete files from FAT16, FAT32 and NTFS partitions.
Flash drive devices, and also create partitions using the Supporting long filenames, creating disk images and even
FAT32 format upto 1TB in size. You can assign or even Master Boot Record backups. Using the disk viewer you
change partition settings on any drive that is connected can view any hard disk drive sectors no matter the version
to the system whilst using the LiveCD. of Windows OS installed. Killdisk (DOS version) is included
For secure deletion of data, KillDisk is provided and this as is a full partition recovery solution. The password
excellent tool securely overwrites and destroys all data changer performs exactly as the windows based one,
on the disk or selected partition. For the ultra paranoid giving you full control over all the local accounts on the
you can manually select upto 99 passes when erasing system. Finally the NTFS reader allows you read access
to ensure there is nothing left on there at all. Remember to the NTFS drive and you can preview all files (even
you can always double check this, by booting back up long filenames) and transfer them across to NTFS or FAT
with the disk and try to recover any data from the disk. volumes, even to network based drives.
Also included is a password manager that gives you Once again Active@ have produced an excellent
complete control over all accounts that are local to the piece of software and this one is also go straight into
machine you are using. It detects all known Microsoft my dvd case and will have a permanent home there. I
Security Databases (SAM). Your able to reset or can’t sing its praises highly enough.
change any of the flags that are currently set on any of
the accounts that you have identified. by Michael Munt

www.hakin9.org/en 11
BASICS

Pulling Kernel Forensic Data


with Python

How to proceed with gathering forensic information of


Linux machines when a user-level rootkit is suspected to
be installed by utilizing Python to automate the process of
pulling data.

What you will learn… What you should know…


• A basic understanding of /proc and how it can be used to col- • A basic understanding of Linux and Operating Systems
lect information about the Linux kernel • Experience with high level programming languages
• Using Python to collect information from /proc in an automa-
ted fashion

W
hen dealing with a machine that may be dependencies of the system itself. Another method is to
potentially compromised it is critical that an communicate with the /proc filesystem itself to pull this
incident analyst use as little tools as possible information. Linux and many other forms of UNIX contain
that are on the operating system itself. Many tools on a /proc psuedo-filesystem which contains what appears to
a Linux or Unix system like ps, netstat, arp, etc could have be a filesystem, but actually is a method of communicating
been compromised by the attacker to prevent the user with the underlying kernel. By opening many of these
from finding traces of the malicious actor in an incident. If files an analyst is able to get a lot of information about
an attacker is running a process on a box called virus it is processes the kernel is running, network connections,
a common technique to replace the ps command which open file handles and more. In addition, a root user can
normally lists running processes with a version that will not actually manipulate kernel variables on a live system.
display any executable with the name virus. This presents To view the contents of this filesystem simply list the
an analyst trying to perform live analysis a unique problem. contents of /proc as if it were a regular directory with the
This technique would be classified as a user level rootkit. command ls /proc (see Figure 1).
How do you get information about what is running on In this directory is a wealth of information. To view
the machine without trusting the machine itself. In many information about the current processor on the system list
instances an analyst will carry around many common the contents of the /proc/cpuinfo as if you were outputting
tools on a disk which are statically linked, or contain no a file with the command cat /proc/cpuinfo. It is possible
to get a lot of useful information about what is running in
the kernel by using this mechanism. This article looks at

Figure 1. Contents of /proc Figure 2. Contents of pid information in /proc

12 5/2010
Pulling Kernel Forensic Data with Python

how to get information from the proc psuedo-filesystem cwd: The current working directory of the process
for forensic purposes to get information directly from the exe: A symlink that points to the executable to the
kernel, which will bypass potentially compromised tools application running (useful if you expect that malicious
like ps, netstat, etc. software to make sure a process isn't running from
a strange location).
Process information fd: Currently open file descriptors, which will be
In the /proc directory should be a series of what appears discussed further.
to be random numbers. These are actually directories net: Information on the network connections which will
that correspond to each Process ID currently running be discussed further.
on the system (see Figure 2). In this directory we see maps: contains open shared libraries for information
several files that are of interest to us. There is an excellent Python Package which allows you
cmdline file: Displays the command that was run to to easily pull information from proc easily in a very python
execute the particular command. manner. http://pypi.python.org/pypi/enumprocess/0.1

Listing 1. Creating a simple Python script to pull open libraries by processes from /proc

#!/usr/bin/env python

import enumprocess
class processtest:
def processCheck(self):
"""This will get all the running processes running on the system"""
processinfo = {}
for i in enumprocess.getPidNames():
try:
processinfo = enumprocess.getPidDetails(i)
print "PID %d: %s" % (i,processinfo['name'])
except:
print("can't read the process %s, possible permissions issue? " % i)

def getLibs(self):
"""Print the process and all shared libraries that are currently open WARNING THIS WILL PRINT A LOT"""
#http://linux.die.net/man/5/proc
for i in enumprocess.getPidNames():
try:
processinfo = enumprocess.getPidDetails(i)
print("PID: %s NAME: %s" % (i,processinfo['name']))
path = "/proc/"+str(i)+"/maps"
maps = open(path)
maps.readline()
for i in maps:
print(" %s" % i)
except:
print("can't read the process %s, possible permissions issue?" % i)

process = processtest()

print("===========================Process Checks======================\n")
process.processCheck()
print("===========================Library Dump======================\n")
process.getLibs()

www.hakin9.org/en 13
BASICS

Listing 2. Pulling open �le handles of processes in /proc

#!/usr/bin/env python

import re
import os
import enumprocess

class fdFunctions:
def getPIDByFD(self,lookFor):
"""Put the fh to look for, and will suck out the process that currently has it open, you do not need the
whole thing, just a bit to find it"""
fileHandles = self.getOpenFDs()
for fd in fileHandles:
processNumber = fd[0]
fdNumber= fd[1]
match = re.match("/proc/[0-9]+/fd/([\s\w:\[\]\_\!\#\$\%\&\'\(\)\-\@\^\'\{\}\~\+\,\.\;\=\[\
]]+)",fileHandles[fd])
if match != None:
pass
if(match != None and match.group(1) == lookFor):
return processNumber

def getOpenFDs(self):
"""Finds a process and what open file handles they currently have, returns a multidimensional dictionary
of process number, the file descriptor number"""
contentsInProc = os.listdir("/proc")
processMap = {}
for i in contentsInProc:
process = re.match(r"(^[0-9]+)",i)
if process:
try:
fds = "/proc/"+process.group(0)+"/fd"
fileDescriptors = os.listdir(fds)
for j in fileDescriptors:
#real path gets me the path of the symlink
path = os.path.realpath(fds+"/"+j)
processMap[(i,j)] = path
except OSError:
print "Can't open, permission denied?"
return processMap

def printOpenFDs(self):
"""Finds a process and what open file handles they currently have, returns a multidimensional dictionary
of process number, the file descriptor number"""
contentsInProc = os.listdir("/proc")
for i in contentsInProc:
process = re.match(r"(^[0-9]+)",i)
if process:
try:
fds = "/proc/"+process.group(0)+"/fd"
fileDescriptors = os.listdir(fds)
for j in fileDescriptors:
#real path gets me the path of the symlink

14 5/2010
Pulling Kernel Forensic Data with Python

Listing 2. Pulling open �le handles of processes in /proc

path = os.path.realpath(fds+"/"+j)
print "PID: %s FD: %s Filename: %s" % (i,j,path)
except OSError:
print "Can't open, permission denied?"

def getFDsByPID(self,pidToLookFor):
"""Pass in the pid and it will return a list of all the file descriptors"""
fileHandles = self.getOpenFDs()
fdReturn = []
for fd in fileHandles:
processNumber = fd[0]
fdNumber= fd[1]
if processNumber == pidToLookFor:
#Create an array of fd Number
fdReturn.append(fileHandles[fd])
return fdReturn
fd = fdFunctions()
fd.printOpenFDs()

Enumprocess works on both Windows and Linux, but Place your following scripts that will be covered in
we will only be focusing on Linux for this process. If you this article in a seperate file in this ~pidenum directory.
look over the Enumprocess source code you will note This will allow you to use the library without installing
that enumprocess is basically pulling information from anything. When you want to run these scripts on
/proc to get process number and other information. We a customer's machine, just ensure you copy this folder
will be expanding on this by pulling network information, with your script.
file handles and shared libraries. Note that all of these scripts must be run as root.
It is possible to install the enumprocess library on your In many cases if you run these as a regular user, it
machine, but normally when you are working on a victim's will work, but you won't be able to see information on
machine they prefer that you do not install anything on their processes other than your own.
machine. If you download the .tar.gz file one this site you
can pull just the library itself. If you then place the directory First Python PID script
to the library in the same folder as your python script you For using Python we will write a simple Python object
will be able to use this library without installing the library that will use enumprocess to output all processes as well
on the machine, which is preferred. You are also trusting as print out the open shared libraries by all processes in
the libraries on the computer less which is preferred in the system. /proc/<pid>/maps is a simple file in /proc that
investigations. We will be putting all files in ~/pidenum (~ is shows all the shared libraries open by a process. You
a short cut for your home directory). To do this: can view this by simply running the command cat /proc
/<pid>/maps. All the scripts in this article have been tested
mkdir ~/pidenum on both Ubuntu and Fedora (see Listing 1).
tar xvzf enumprocess-0.1.tar.gz
cd enumprocess-0.1/src/
cp -rpf enumprocess ~/pidenum
cd ~/pidenum/

Figure 3. View open �lehandles in a process Figure 4. Viewing process network information

www.hakin9.org/en 15
BASICS

Listing 3. Accessing network information to view active connections of a process

#######Add the entire FDFunctions() class above this!######

class networkConnstest(object):
"""This will look at all established TCP connections as reported by /proc/net/tcp and report the information
as well as what process is using them"""
def getOpenPorts(self):
tcp = open("/proc/net/tcp")
#Throw away the header
tcp.readline()

ip = IPFunctions()
fh = fdFunctions()
#loop through each, pulling the necessary information
for i in tcp:
#nasty regex... match all of the information for the network connections.
info = re.match("\s+[0-9]+:\s+(\w+):(\w+)\s+(\w+):(\w+)\s+\w+\s+\w+:\w+\s\w+:\w+\s\w+\s+(\w+) \s+\
w+\s+(\w+)",i)
#All of the addresses are in HEX need to convert them.
localAddress = ip.convertHexIPtoString(info.group(1))
localPort = ip.convertHexToString(info.group(2))
remoteAddress = ip.convertHexIPtoString(info.group(3))
remotePort = ip.convertHexToString(info.group(4))
uid = info.group(5)
#Inode is the socket
inode = info.group(6)
#The socket the file descriptor
socket = "socket:["+inode+"]"
# a socket is just a file, so it can be retrieved the same a file descriptor
pid = fh.getPIDByFD(socket)
#We have all the necessary info for the ports open, now lets get the app
processDetails = enumprocess.getPidDetails(pid)
try:
print("Pid: %s Name: %s" % (pid, processDetails['name']))
print(" Pid for socket is %s, name is %s" % (pid,processDetails['name']))
print " local address, port: %s, %s" % (localAddress,localPort)
print " remote address, port: %s, %s" % (remoteAddress,remotePort)
except:
print "Can't open, permission denied?"

network = networkConnstest()

class IPFunctions(object):
"""This is needed because the IPs are all in hex and we want them to be easily readable"""
def convertHexIPtoString(self,ipHex):
"""Take an IP in Hex and make it look like a string with periods"""
count = 0
octet=""
ip = ""
for i in ipHex:
count += 1
#print "%s\n" %i
octet = octet+i

16 5/2010
Pulling Kernel Forensic Data with Python

Listing 3. Accessing network information to view active connections of a process

if count == 2:
count = 0
ipOct = str(int(octet,16))
ip = ipOct+"."+ip
octet = ""
ip = ip.rstrip(".")
return ip

def convertHexToString(self,hex):
"""Simple function that will be used in order to convert the HEX of port numbers"""
return str(int(hex,16))

print("===========================Network connections======================\n")
network = networkConnstest()
network.getOpenPorts()

File handle information Conclusion


Often in investigations, it is desired to understand what It needs to be understood that these python scripts do
files are currently open, and what network connections have some limitations, for one it relies on the integrity
are currently being made. /proc/<pid>/fd/<file descriptor of Python on the vicim's box. If the hacker was able to
number>. Each of these is a symlink to the file that is change the various userland binaries, then they may
opened by that particular process. have changed parts of Python. With that said, Python is
By running the ls –la command on each of these file usually not a high priority target to cover their tracks and
descriptors and you will be able to view. Because in Unix probably will be safe in these instances. These python
everything is a file, network connections or sockets will scripts also do not help with kernel level rootkits. A kernel
also show up in the file descriptors category, showing level rootkit will modify the system calls to the kernel and
a symlink to socket:[socket number] (see Figure 3). no user-land tool will be able to overcome this.
To pull this information I will build a Python class that By understanding the /proc filesystem it is possible
allows information to be easily pulled (see Listing 2). to view information about a computer system without
relying on user level tools like netstat, lsof and so forth.
Network Information This script is useful for quickly collecting information on
Information on individual network connections for a system when it is suspected of compromise. These
each process is stored in /proc/<pid>/net/tcp and scripts can be greatly expanded to pull a lot more
/proc/<pid>/net/tcp6 for all IPV6 connections. This is information out of a system with a little bit of work.
a file that you can simply run the cat command on to The enumprocess contains a lot more information.
dump the contents, but it is a little complicated to read. Understanding the /proc filesystem is useful for any
The local and remote address is written in hex along security professional that wants to further understand
with the port. Each two hex values correspond to one their linux based system and what functions it is
octet in an IP address. C09C0334:0050 corresponds currently performing at any given moment.
to 192.168.156.52 port 80. You can use the Windows
calculator to perform these calculation, but the To see the full script go to: http://dremspider.net/
Python script will automatically convert these for you scripts/hakin9.py
as well. This requires the fdFunctions class to work
which was included in the section above as we are
able to treat the network connections as files in Unix
(see Figure 4).
There are two classes contained here, the first class DANIEL LOHIN
is responsible for pulling the information out of the /proc Daniel Lohin currently works as a Information Security
/tcp/net file. Then we will use the getPIDbyFD function in the consultant at Booz Allen Hamilton. Daniel Lohin is focused on
fhFunctions class to pull the PID out for the open socket. incident detection as well as response. He is currently �nishing
The IPfunctions class is responsible for converting the up his Master’s in Information Security at George Mason
HEX address to standard IP address as well as the port University. When he is not studying, working or breaking his
number from HEX to base 10 (see Listing 3). computer he is bike riding with his girlfriend, Meagan.

www.hakin9.org/en 17
ATTACK

Jailbreaking and Penetrating


with the Iphone 3G & 3GS

Today Smart phones are getting smarter and smarter. They


are a far cry away from the Walkie-Talkie like devices from
the the early 90's.

What you will learn… What you should know…


• Jail Breaking Iphone 3G & 3GS • How to run command line tools like Nmap, Metasploit
• Penetrating Networks with the Iphone Platform • Basic Networking and Security

N
ow a smart phone in the hands of skilled attacker Step 0
can be used to help penetrate networks on the fly. Backup your IPHONE. Save all of your pictures and
No longer do you need to walk around with a bulky contacts and everything else. Take your IPhone and put
laptop to get the job done. By taking an IPHONE and into DFU Mode.
making a few software adjustments and installing the right
tools you can be well on your way to finding vulnerabilities Step 1
in your network before the rest of the world does. Open Itunes and connect the iPhone to your PC.

Setting up Step 2
Before we get started there are a few things that we Press and hold the Home button and the Sleep/Wake
will need to download beforehand to make things a bit button at the same time. After exactly 10 seconds
easier as we progress. First back up all files on your release the Sleep/Wake button (Figure 1).
IPHONE! Pictures, phones numbers and anything else Continue holding the home button until iTunes pops
that you deem valuable. Jailbreaking an IPHONE can up telling you that it has detected an iPhone in recovery
be a simple straight forward process, however, I have mode (Figure 2).
heard horror stories of people bricking there IPHONE's
after attempting a jailbreak the wrong way. Its better to Step 3
be safe than sorry so backup. Next I will need you to Next place your mouse over the restore button and hold
download the following software packages. down the shift key. Browse for the sn0wbreeze_iPhone 3G. ipsw
supplied. A snowflake will flash briefly and the proccess will
• Itunes 9.0 – This can be downloaded from oldapps.com, begin. It will take about 10 to 15 minutes to restore. After
• WinSCP – This can be downloaded from winscp.net. the process completes you should have your Jail Broken
device with Cydia installed and ready to go.
Iphone Jailbreaking
First off if you are running version OS 3.1.3 on your Iphone
then this should work for you (this has not been tested on
any later versions). First install Itunes 9.1 on your PC and
allow it to sync with your Iphone. Then close Itunes and
place your Iphone in DFU mode by doing the following. Figure 1. Placing the IPHONE into DFU Mode

18 5/2010
Jailbreaking and Penetrating with the Iphone 3G & 3GS

Figure 2. Restoring Custom IPSW

Iphone Software Installation


First we will start out by installing some basic utilities that Figure 3. Mobile Terminal Installation
will allow you to move around your IPHONE easier and up Cydia and do a search for OpenSSH. Once you
allow you access to information that you will find useful as have located it run the install and confirm. After the
we progress. Before you begin installing any software for installation it should make SSH avaliable immediately
your IPHONE I highly recommend connecting to a local on your Iphone (Figure 4).
wireless access point that’s close to you. If you try to Next we will install SBSsettings. The purpose of
download these installs over an Edge network like AT&T's SBSettings is to allow a quick view of your IP address
for example it will go painfully slow. The Installation is quite once you connect to a wireless AP. This will come in
simple let’s open up Cydia and do a search for it. You should handy later on. SBS also allows you to disable and
find Cydia by scrolling to the right of your screen. Tap the enable certain services on the fly instead of having to
Cydia icon and it should open up for you. You may receive resort to the command line or browsing through a ton
a refresh error just hit the okay button and continue. We of menus. Just as we did with Mobile Terminal above
will start out downloading MobileTerminal. This will allow reopen Cydia and do a search for SBSettings. Install
you access to the command line on the IPHONE. You and Corfirm the installation. It will install and it will then
will be able to use MobileTerminal to change the default restart springboard. After springboard comes back up
password on the iphone from alpine to something more give the SBSettings a try by placing your finger at the
secure and to your liking. Install Tap Mobile Terminal and top of your screen close to where your signal icon is
then select Install and Confirm (Figure 3). and slide your finger from left to right. It should bring
down a drop down menu that allows you see to quite
IPhone Password change and cont software Installation a bit of useful information. Here you have the ability of
After you have installed mobile terminal find the icon enabling and disabling your wifi or killing processes.
on springboard and tap it. It should bring up a terminal You will also notice that you now can view your IP
window where you will be able to log in as root and address if you are connected to a local wireless
change the password from the default. lan. The Wi-Fi Address is the address the Wireless
AP gives you while the Data IP address will be the
iPhone:~ mobile$ su
Password: alpine
iPhone:/var/mobile root# passw
Changing password for root.
New password:
Retype new password:
iPhone:/var/mobile root#

Next we will install OpenSSH. It will allow us to move


files back and forth from your PC to your Iphone. Open Figure 4. OPENSSH Installation

www.hakin9.org/en 19
ATTACK

Figure 5. SBSettings and Installation

IP given to you by your service provider. In order to


enable or disable a service simply tap its icon. As you
can see SSH and wifi are enabled and indicated by
the green icon color while Bluetooth has been disabled
and indicated by its red icon color (Figure 5).
Next let’s go out and grab Nmap and Metasploit. Just
as we have done with previous installations. After both
of those are installed some wireless reconaissance
software in this case Stumbler Plus for the IPHONE. Figure 7. Metasploit & Windows Command Shell
Stumbler plus will allow you to scan for wireless access
points that are close by and will you give you some IPhone Network Penetration
idea as to what type of encryption they are running Now that we have everything installed successfully lets
and some other useful information. After installing get to buisness open up Stumlerplus and do a search
Stumbler plus go to your desktop and install WinSCP for wireless AP's by tapping the Scan button. In this
that we downloaded earlier and download stumbler case we will connect to the New Caprica AP shown here
plus again from (http://www.iphone.mysticwall.com/ as it doesen’t have any encyption enabled. Next we will
download/stumblerplus-1.2rev1.tar.gz). Open nmap and see if there are any live hosts on our
You should now be able to access the OpenSSH AP and what if any ports are avaliable (Figure 6).
which we installed earlier on your Iphone. Login with the Next we will close down Stumbler Plus and Open
username root and the password that you chose earlier. Nmap and run a quick search for live hosts.
Unzip the files you downloaded and then use WinSCP
to browse for them. In WinSCP on your phone go to iPhone:~ mobile$ Nmap -vvv -P0 -sV 192.168.1.2-255.
the root then go into applications. You should see a list
of all your previoulsy installed Iphone apps. In WinSCP As you can see we have several ports open here
on your PC located the stumblerplus.app you extracted all are of the windows variety. Next we can open up
earlier and select all the files within that directory and Metasploit and try out a common exploit to see if we
copy and paste them into the stumblerplus.app on the can pop a shell on this host. Here we will use the
Iphone. A warning message will pop up telling you that ms08 _ 067 _ netapi with bind_tcp as our shell push back
you are overwriting files which is fine let it overwrite (Figure 7).
them all. Close WinSCP and you should now be able to
run Stumblerplus. Conclusion
As we have demonstrated today with a little skill and the
right tools a sophisticated attacker can take advantage
of the right tools on the Iphone platform. Although the
technology has not fully matured what we have looked
at today proves beyond the shadow of a doubt that
in the future attackers will be even more mobile and
inconspicous than your normal run of the meal hacker.

WARDELL MOTLEY JR.


Wardell Motley is a Systems Administrator for a Large clothing
Manufactures in Dallas Texas. He is a member of the ISSA and
Figure 6. Stumbler Plus & Nmap Scan in his spare time works as freelance IT security researcher.

20 5/2010
������������������

��������������� �����������
������������ ���� ������� ��������� ������ ���� ����������� ��������� ��������� ���� ��������
������������������������������������������� ����� �������� ��� ���� ������ �������� ���������� ���
���������������������������������������������� ���� ����������� �������� ��������� ��� ���
������������������������������������������������ ��� ����� ��� ���� ������������ ��������� �����
���������������������������������������������� ����� ������ ������ ��� ������ ������ �������� ���
���� �������� ������������ ������������ ������ ���������������������������������������������
������������������������������������������� �����������������������������������������
��������������������� ������������

���������������������� ��������������
�������������������������� ��������������������������

����������������� �������������
���������� ��� �� �������� ��������� ���������� �������������������������������������������
������������� ��� ������� ��������� ���� ��������� ����������������������������������������������
��������� ���������� ���� ��������� ������ ��� ��� ����������������������������������������������
���������������������������������������������� ��������������������������������������������
��������������������������������������������� ���������� ��������� ��� ���������� ����� ���� ��� ���
�������������������������������������������� ����������������������������������������������
������������������������������������������������� �����������������������������������������������
�������������������������������������������� ��������������������������������������������
��������������������������������������������
����������������� ������������������������
������������������������� ��������������������������

���������� �������
���������������������������������������������� ����������������������������������������������
���������������������������������������������� ������� �� ������������ ���������������� ����
���� ����� �������� ��� ��������� ���� ��������� ��� ������ ������ ���� ���������� �������� ����������
����� ��������� ���� ��������� ��������� ������ ������ ����������� ��� ���� ������� ������ ��� ���
��� �������� ������������������� ������������ ��� ���������������������������������������������
������ ������ ���������� �������� ������������ ��� ���������� ��� �������� ���� ���������� ����� ����
������� �������������� ������������� ���� �������� ��������������������������������
������������������������������

������������������������� ����������������������
��������������������������� ����������������������������

��������������������������������

�� ����������������������������
�� �����������������������������������������������
�� �����������������������

����������������������������
���������������������������
�������������������������������������������������������������������

������������������
ATTACK

Testing
Flash Memory Forensic Tools – part two

This second part is focused on advanced tests done on flash


memory embedded in a Nokia mobile phone. Tests presented
in this article are not for all as they require a well furbished
lab; even that what we try to demonstrate here is that – when
flash mobile forensic will leave its infancy – there are some
issues forensic officers should take in consideration.

What you will learn… What you should know…


• This article will present some underestimated issues on �ash • For this second part, too, a basic introduction to digital foren-
memories forensic. sic issues will be helpful (it is not a requirement).
• Reader will also understand how some techniques already se-
en with hard drive forensic can be reused with success to avo-
id detection in �ash memories too.

F
irst of all: is it possible to hide data in flash • E as the full set of evidences Existing on the device
memory using techniques as seen in hard disk • A as the set of evidences Acquired by forensic tools
forensic? Unfortunately the answer is yes and (i.e. dd)
for unexpected reasons, too. Outcomes presented in • O as the set of evidences Observed (found) by the
this article were updated in December 2009: we are analysts
working for a new and wider release of such tests and
results, when ready, will be presented to public using so that:
same channel.
At the end of this article there are references • Y is the ratio between Acquired evidences and
mentioned in first and second part of paper. Existing evidences [A/E=Y] and represents the
quality of forensic tools used (1=better, 0=worse);
Keywords • K is the ratio between Observed evidences and
Mobile forensic, OneNAND, NAND, NOR, bad blocks, Acquired evidences [O/A=K] and represents the
wear levelling, ECC, FTL analyst’s skill (1=better, 0=worse);
• Z is the ratio between Observed evidences and
A brief digression on evidence metrics Existing evidences [O/E=Z] and represents the
Considering a digital device as body of evidence, it is overall quality of analysis (1=better, 0=worse) see
possible to define some statements: Table 1.

Table 1. Quantitative relation between evidences, analyst’s skill, and quality of tools Thus, a good tool with a good analyst
gives an overall good analysis (case
Units of evidences Y K Z
1), a mediocre tool (case 2) or
Existing Acquired Observed (A/E) (O/A) (O/E)
(tool (analyst (overall quali- a mediocre analyst (case 3) will limit
(E) (A) (O) the overall value of examination. Of
quality) skill) ty of analysis)
course this is just a quantitative and
100 100 100 1 1 1
not qualitative measurement: the
100 80 80 0,8 1 0,8
importance of each evidence is set
100 80 60 0,8 0,75 0,6 aside see Figure 1.

22 5/2010
Testing flash memory forensic tools Part two

��������������������

����������������

������ ������ ������ ����������


����� �������� ��������
���������
��������������������� ��������������������� ���������������������

Figure 1. Quantitative relation between evidences, analyst’s skill, Figure 3. Hiding data in bad blocks (David, 2009)
and quality of tools
acquisition; it is also possible get data data via infrared
Logical vs Physical acquisition and Bluetooth interface using OBEX protocol, but this
Logical and physical acquisitions are already well is a method that poses some limitation and is generally
defined in the NIST Special Publication 800-101 less used (McCarthy, 2005). Some Nokia phones are
Guidelines on Cell Phone Forensics (Jansen and Ayers, now explored: registry addresses are blurred for
2007): confidentiality.
Forensic tools acquire data from a device in one of
two ways: physical acquisition or logical acquisition. Flash peculiarities in the acquisition process
Physical acquisition implies a bit-by-bit copy of an During this research it comes out the high level of
entire physical store (e.g., a memory chip), while confidentiality surrounding the flash technologies
logical acquisition implies a bit-by-bit copy of logical and market, so that nobody seems to be able to
storage objects (e.g., directories and files) that reside set a definitive point on how others can use or
on a logical store (e.g., a file system partition). The implement flash technologies: a problem reported
difference lies in the distinction between memory since the begin of mobile forensic (Willassen, 2003).
as seen by a process through the operating system In an attempt to understand better what really happen
facilities (i.e., a logical view), versus memory as seen in inside a flash there were several meetings with highly
raw form by the processor and other related hardware skilled people from the flash manufacturing field and
components (i.e., a physical view). the focus was set on how to preserve integrity of
Physical acquisition has advantages over logical evidence and grant completeness of acquisition. This
acquisition, since it allows deleted files and any data is what came out:
remnants present (e.g., in unallocated memory or file
system space) to be examined, which otherwise would Real effect of reclaim:
go unaccounted.
In the image below is given a representation of both • garbage collection is a known activity but not so
methods, in case of memory not physically extracted well documented for seized devices
from hosting device, that is, left on the phone and • garbage collection is a background activity, this
accessed with traditional means see Figure 2. means that when a mobile phone is powered
Proprietary cables with USB interface are used on, even in service mode, such activity could be
for both techniques, while JTAG or FBUS interfaces autonomously triggered with the effect of destroying
(where present) are mainly used for physical useful data in invalid blocks

����������������
��������� ����������
����������
�������
� � ���
� �
� � �� ������������
��������
� ��������� ��� �
� � �� �����
��������������

������ �������� ��������


� � �����
�� �����
� �
� ��
�����
��� ����������
������������������ �����
������������
���
���������������
��� ��������������
������������������ ���
�����������
Figure 2. Logical vs. Physical acquisition for �ash memory on the
hosting device (not extracted) Figure 4. Block Diagram on a multiplexed OneNAND™

www.hakin9.org/en 23
ATTACK

���������������� �������������������������������������

�������
����
�����
����
�����
��� ������
������
��� ����
��������
������������� ����� �����
�� �����

�������� ��
�� ��� ��������
��� ��������
�����

Figure 5. Worldwide Mobile Terminal Sales to End Users in 2Q09 Figure 6. 4Q08 NAND Flash brand sales break down
(Gartner, 2009) (DRAMeXchange, 2009)
Effective management of bad blocks: of data: a working OS could be as small as 50 MB
(www.damnsmalllinux.org) or much less with Embedian
• if the FTL is embedded in the flash memory (like distro (www.emdebian.org) see Figure 3.
in case of managed flash) then it will be difficult to
access and manage bad blocks because they will Misuse of Hidden Protected Area
be hided to the host file system; It could be possible for an hacker to store data even in
• if the FTL is supplied from the host (like in case of the Hidden Protected Area also referred as One Time
raw flash) then there are chances to manage bad Programming (Samsung, 2007a). The size of this area
blocks properly and have direct access to them. is generally equal to one block but variants are allowed
Analogous experiences are reported with modern (Samsung, 2005c, Micron, 2006c); it can be blocked,
hard disks managed with GNU ddrescue (There but usually this task is left under hosting manufacturer
is still an open debate on hard disk bad block care (ibid) see Figure 4.
management. Some interesting links are: http:// Computer analysts already know the issue related to
tech.groups.Yahoo.com/group/ForensicAnalysis/ Host Protected Areas (HPA) and Device Configuration
message/82, http://www.forensicfocus.com/index.p Overlays (DCO) in hard drives (Gupta et al., 2006,
hp?name=Forums&file=viewtopic&t=2557) (Carrier, Carrier, 2005): with flash memories we have similar
2005, Lyle and Wozar, 2007, Mukasey et al., 2008). issues. In future works we plan to test the possibility to
change (doubling) the dimension of such area and then
Security through obscurity to store and hide data in it.
Even knowing the memory specs, manufacturers can How the choice of the flash memory and mobile
apply autonomous decisions on how manage the phone was driven and the team was set
chip: it can happen that a managed flash will be used Simply, the choice of mobile phone and flash memory
with disabled features, or that a flash raw memory be to use was made by statistics. Nokia is the best seller in
customized as for manufacturer needs. Furthermore, the mobile phone market and Samsung is the leader in
due to high competition and Intellectual Property the NAND flash market see Figure 5 and 6.
protection, generally, there are not public information Then the choice to use an OneNAND was made for
on the chip used. At begin of the research some its advanced characteristics and the Nokia model was
manufacturers were contacted to get some info: it was chosen on the basis of a block of ten OneNAND available
even difficult to know the destination of some branded at moment. Numonyx has licensing agreement with
components. Samsung to produce OneNAND™, so it was decided
to call Numonyx for support and the folks there were
Bad management of good blocks happy to help. Then, was asked support to an advanced
A block is considered bad when there are multiple bit Nokia service repair centre that was willing to help, too:
errors that are not recoverable (Numonyx, 2008a). in few days a virtual team with high skilled people was
Like hard disks, NAND flash generally ships with a list s and ready to start. As this market is so hard-hitting,
of existing bad blocks set in a location defined by the a low profile participation has been adopted.
manufacturer. Additionally, to this list will be added all
future blocks will fail to operate during device lifecycle. How NOR and NAND are accessed on a Nokia
Forensic investigators are already aware of the possibility N70
to manipulate Bad Block List to hide information (David, The implementation layout of NOR and NAND
2009) this aspect should not be underestimated in flash chips in a Nokia mobile phone (N70 model), is
memories as they are able to store even larger quantity presented in the picture below (left). The combo

24 5/2010
Testing flash memory forensic tools Part two

memory (NAND+SDRAM) flash is managed by a TI a USB cable or a FBUS/JTAG interface, it is required


microcontroller unit (mcu) OMAP 1710. OMAP stands processor involvement (in this case it is a RapidoYawe
for Open Multimedia Application Platform and it is the (The chip with HSDPA logic (YAWE) stacked on the
application processor running with Symbian operating RAP3G processor unit (RAPIDO) forms the RapidoYawe
system (EPOC). The NOR flash is managed by CPU)). In the tables below are presented schematics
the microprocessor RAP3G (3G Radio Application of connections between two devices (memory and
Processor). Evidences on mobile phone are stored in processor). This phone will replace the Nokia 6650F in
NAND flash: whatever means are used, to access the our tests, as explained later: the layout is very similar.
NAND storage area it is required to move through the Larger images are available in appendices see Figure 9.
OMAP processor (right) see Figure 7.
Test Phase 1: preparing the phone
How OneNAND™ is accessed on a Nokia 6650F On a new flash memory (identical to the one on the
The Nokia 6650F phone has been introduced on the testing Nokia mobile phone) were stored some data
market on 2008. The application memory of the device in four good blocks; such blocks were then marked as
consists of NAND/DDR combo memory. The stacked bad, by opportunely manipulating the relative spare
DDR/NAND application memory has 512 Mbit of DDR area. Next, the original flash device embedded in the
memory and 1024 Mbit of flash memory (1024 Mb are phone was replaced with the one with four bad blocks
equal to 128 MB). This is the phone we have chosen to and the phone refurbished with original software: now,
be used for tests presented later: on the left the phone there is a working phone with data hided in bad blocks.
schematic, then two picture of the internal side (with The detailed procedure is in the appendices.
indication of the OneNAND™), the relation between
processor and flash memory and flash memory pins Test Phase 2. Feeding forensic tools with our
layout. Larger images are available in appendices see phones: results and feedbacks
Figure 8. At beginning, when decision on which type of phone
to use was made, it was considered an advantage to
How data on NAND are accessed via USB or use a Nokia phone, due to its popularity. Not too much
JTAG on a Nokia 6120c attention was paid on the specific model we were
To perform a memory dump of the flash memory via using: all in all there was an OneNAND™ inside and
physical acquisition on a Nokia 6120c, either with this was considered an advantage for the research. As

Figure 7. Layout of a Nokia N70 (left), and OMAP and NAND �ash relation on Nokia N70 (right)

www.hakin9.org/en 25
ATTACK

the testing memory was a raw NAND, we were optimist At this stage, was decided to speak directly with
forensic software would be able to acquire bad blocks technical support of these companies and tell them
because there were not embedded FTL layer could the problem we faced. An email was sent either to
interfere with the imaging process. companies aforementioned and to others that have
Then, we used some of the best forensic software to been tested their products with NIST (as reported in
test the acquisition of bad blocks from our phones, and the CFTT web page http://www.cftt.nist.gov/mobile_
this is what we got (in alphabetical order). devices.htm). The test of the emails is reported in
appendices. So far, these are the replies we got:
• CelleBrite UFED – This solution was not able to CelleBrite, Micro Systemation and Paraben confirmed
perform the physical acquisition. the inability of their solution to get physical acquisition
• Logicube CellDEK – We were not able to perform of our phone (even they can do with others); Guidance
any acquisition with CellDEK because the required Software, Logicube, and Susteen did not reply.
module, even already ordered, was not available at For what we tested and understood, with these
time of examination. solutions and the phone we used, if sensitive data
• Micro Systemation XACT – This solution was not are hided in bad blocks they will go undetected.
able to perform the physical acquisition. Furthermore, with this software, good blocks with wrong
• Paraben Device Seizure 3.1 – This solution was not ECC (i.e. due to power failure) could hide valid data to
able to perform the physical acquisition. forensic analyst.

Figure 8. From left to right (clockwise): Nokia 6650F layout; the internal hardware, stencil pointing at the OneNAND™ �ash; schematic
showing connections between CPU and OneNAND™, and generic OneNAND™ pins layout

26 5/2010
Testing flash memory forensic tools Part two

Figure 9. Adapted layout of access to NAND memory via USB (top) or JTAG (botom)

www.hakin9.org/en 27
ATTACK

Reporting to forensic metrics • Physical Acquisition is not an unreachable limit,


Our test take a lot of time to be set and only few minutes but some tools are designed only for logical
to be waived: we were a little disappointed. Going back acquisitions. The specification and test plan state
to evidences metrics seen before, we should say that that if the tool provides the functionality optional
any forensic tool not able to deal with bad blocks cases and assertions are tested as if they are core.
(completeness of evidence) should fall at least in the By following the CFTT formal testing methodology it
case number two. This without considering underground allows all tools that have the ability to acquire data
Reclaim activities, yet (the effect of Reclaim on integrity from mobile devices to receive a fair validation.
of evidence need further analysis).
The aim of this paper is not to argue with NIST, but
Physical acquisition as option: what says the NIST for what is written in the second sentence above,
Many companies are proud to say their products have test on tools designed either for logical and physical
been successfully tested with NIST, but what exactly acquisition, like Cellebrite UFED 1.1.05, should
say a NIST report on mobile physical acquisition and report physical acquisition in the core features: but
completeness of evidences acquired? by reading Test Results for Mobile Device Acquisition
A first answer can be found either in the version 1.1 Tool: Cellebrite UFED 1.1.05 it is possible to see that
(NIST, 2008) or 1.2 (NIST, 2009) of GSM Mobile Device physical acquisitions is reported in the CFT–IMO–05
and Associated Media Tool Specification and Test Plan, section, as an optional feature.
where is reported in the section CFT-IMO-05/06 and In the email sent to NIST, author suggests to shift
CFT-IMO-04, respectively, that physical acquisition is this feature from optional to core section, because
an optional feature. For analyst with hard disk forensic a document released from so regarded source, should
background, it could seem a little strange considering not allow a workaround of an important point like this.
physical acquisition an option.
Furthermore, the word completeness is reported in A confidential answer
the 2004 Digital Data Acquisition Tool Specification, in We asked to forensic software houses cited above,
the 2005 Digital Data Acquisition Tool Test Assertions why it is so difficult to perform a physical acquisition
and Test Plan Draft 1 for public comment Version 1.0, of non-volatile memory (We should not forget that on
in the 2008 GSM Mobile Device and Associated Media OneNAND we have both volatile memory (DDR) and
Tool Specification and Test Plan (ver 1.1) but not in non-volatile memory (NAND)) embedded in phones
the GSM Mobile Device and Associated Media Tool made by different manufacturers but using the same
3 Specification and Test Plan (ver 1.2): the question raw flash memory and the same I/O interface. This is the
is why completeness of evidences is then shifted answer got from a source asked not to be disclosed:
to be an optional feature. The NIST were contacted
either at institutional and authors’ addresses (email in • IP protection: many phone manufacturers need to
appendices). This is the synthesis of answers got – the protect their know-how, so they encrypt some area
source asked not to be cited, but to refer to CFTF site of the memory and use proprietary bootloading
solutions. This means that a forensic software
• Optional test cases are treated as Core test cases house should be able to decrypt, without altering,
IF the tool provides the capability defined by the the content of the evidence and also it need do this
test case. Unfortunately, all mobile forensic tools do for any mobile phone on the market: a very onerous
not have the ability to perform a physical acquisition task that in the lack of a collaboration between
at this time. The CFTT formal testing methodology chip manufacturer and software developers is too
validates that tools perform as they are designed uneconomical. When a flasher is used to change
not as one might wish them to. IMEI or unlock a phone it exactly circumvents this
protection (for this, the source states further that


in future mobile phones, JTAG interface will be
disabled to prevent illegal activities).
• Market alliance: for reasons seen above, forensic
solution providers could not have interest to release
something harmful for phone manufacturers
because otherwise the latter will not be anymore
������ ������
����� ��������
������ cooperative with them.
��������

��������������������� ��������������������� ���������������������


The ONFI project
Figure 10. Quantitative relation between existing evidences, The resolve the problem of disorder in the flash market,
quality of tools, and analyst’s skill some manufacturers decided to setup a consortium

28 5/2010
Testing flash memory forensic tools Part two

to define some standards: it is the Open NAND Flash Conclusion


Interface (ONFI) consortium. The ONFI is an industry In this paper has been attempted to offer a wide overview
Workgroup made up of more than 80 companies of forensic analysis of non-volatile flash memory. Starting
that build, design-in, or enable NAND Flash memory, from academic and industrial literature, we ended with
dedicated to simplifying NAND Flash integration into a practical and documented test in which some data were
consumer electronic products, computing platforms, hided in memory blocks (then marked as bad) to verify if it
and any other application that requires solid state was possible to foul the acquisition process of nowadays
mass storage. We define standardized component- forensic solutions. It was demonstrated that hiding data
level interface specifications as well as connector and in such blocks is achievable: none of the software tested
module form factor specifications for NAND Flash (http: was able to get a physical acquisition of the flash memory.
//onfi.org). Furthermore a suggestion to considerer physical acquisition
a core feature was sent to the NIST to make them more
Future works AND CALL FOR HELP aware of the problem of data hiding in flash memories and
We plan to do some feature works especially to test the need to grant the completeness of evidence.
the effect of reclaim in a controlled environment (like Author is available via email for any enquiry on the
a mobile phone left in standby), and capture (by sniffing) topic.
and analysis of data travelling on the bus to/from mcu
and NAND. As this tests will require financial as well SALVATORE FIORILLO
as technical support, everybody interested to support Author is a security consultant and researcher focused on
this research can express her/his availability via email weaknesses in the logic of physical and digital systems.
directly to me. He holds a Master of Computer Security accomplished in
Western Australia and the ISO 27001 certi�cation, and have
Credits trained hundreds of security officer either of public and private
Author wish thanks Numonyx Flash Group, Nokia Lab organizations. As consultant he works only for few, interesting
Southern Italy, Polizia Postale e delle Comunicazioni for and selected customers. s�orillo@theosecurity.com
their help and support.

A D V E R T I S E M E N T

www.hakin9.org/en 29
DEFENSE

Securing public
services using Tariq

When I first read about the port-knocking concept was


really amazed how such service can help us secure other
less secure services such as telnet, rsh, etc. But after a while
I realized that it was a great solution even to the ground
built up secure services such as SSH (Secure Shell)!

What you will learn… What you should know…


• What port-knocking is, and the bene�t of using it, • Howto con�gure a Linux iptables �rewall,
• Howto secure a public service such as SSH using Tariq. • Difference between iptables �rewalls policies.

Y
es, even the most secure services whom was about this technique, but the true answer for me is:
built from the scratch with security in mind fell to Port-knocking is a concealment in the same spirit as
its knees when a 0day vulnerability was exposed passwords and encryption keys [3].
CVE-2008-0166 [1][2], enabling attackers to conduct
brute force guessing attacks against cryptographic keys, What's new?
leading to a remote compromise. From here imagine What's new in the port-knocking arena, is Tariq :)
how much a port-knocking solution can be helpful to us.
I think after reading the intro, some are starting to ask Tariq Overview
questions: Tariq is a new hybrid port-knocking technique, that
uses Cryptography, Steganography, and Mutual
• What is this port-knocking?, Authentication to develop another security layer in
• Is port-knocking Security Through Obscurity?, front of any service that needs to be accessed from
• What's new?. different locations in the globe.
Tariq was developed using python and scapy by
What is this port-knocking? me to fulfil my Ph.D. Research. We had to use a new
Well first lets define the concept port-knocking. methodology that can communicate in an unseen
Simply, its a technique used to open port(s) on manner, making TCP Replay Attacks hard to be issued
a remote firewall by generating a connection attempt against Tariq. We also wanted the implementation to
on a pre-specified set of closed ports. Once the correct listen to no ports, or bind itself to no socket for packets
sequence of connection attempts is received, the exchange, so that Tariq won't be exposed himself to
firewall dynamically modifies its rules to allow the host a remote exploit.
which sent the connection attempts to connect over to
specific port(s). What does Tariq mean?
In English, it means knocking, hammering or coming at
Is port-knocking night :)
Security Through Obscurity?
Researchers are still arguing about the port-knocking How does Tariq Work?
technique and accuse that its “Security Through Tariq works by first running the python application
Obscurity”! This is a long going argue going out there TariqServer, the server shall be running in sniffing/packet

30 5/2010
Securing public services using Tariq

capturing mode, and the clients shall be using the hosts need to make services accessible to other hosts.
python application TariqClient to open ports or executes While some services need to be accessible to anyone
remote commands on those server(s). The whole from any location, others should only be accessed
scenario can be summerized as following: by a limited number of people, or from a limited set
of locations. The most obvious way to limit access is
• Servers run the python app TariqServer, and to require users to authenticate themselves before
clients open ports or executes remote commands granting them access. This is were Tariq comes in
on those servers by running the python app place. Tariq can be used to open ports on a firewall
TariqCleint, to authorized users, and blocking all other traffic
• TariqClient adds the action (open port/execute users. Tariq can also be used to execute a remotely
command) to a picture using Steganography, requested task, and finally for sure Tariq can close
• TariqClient uses the Steganography picture as the open ports that have been opened by a previous
a packet payload, TariqClient request.
• TariqClient adds the payload to TCP SYN packet(s) Tariq runs as a port authentication service on the
to be sent on pre-specified ports (configured on the iptables firewall, which validates the identity of remote
TariqServer), users and modifies firewall rules (plus other tasks)
• TariqServer captures the packets and makes sure it according to a mutual authentication process done
contains a picture, between TariqServer and a Tariq client. Tariq could be
• TariqServer extracts the commands from the used for a number of purposes, including:
Steganography picture. This is to make sure that
the packet really holds a clients request, • Making services invisible to port scans,
• TariqServer selects a random number and encryptes • Providing an extra layer of security that attackers
it using the client's GnuPG public key, must penetrate before accessing or breaking
• TariqServer uses the encrypted random number as anything important,
a packet payload, • Acting as a stop-gap security measure for services
• TariqServer crafts a packet holding the payload with known unpatched vulnerabilities,
and sends it to the client as if it is a reply to the • Providing a wrapper for a legacy or proprietary
clients SYN Packets. This is to complete the mutual services with insufficient integrated security.
authentication process,
• TariqClient receives the packet and extracts the Why Is Tariq Secure?
payload,
• TariqClient decrypts the payload using its GnuPG • Tariq Server's code is very simple, and is written
private key, completely using scapy (python),
• TariqClient uses the random number received • The code is concise enough to be easily audited,
as a packet payload to be sent to server after • Tariq needs root privileges to adjust iptables rules,
encrypting it using the TariqServer's GnuPG public and perform remote tasks,
key. This is to ensure that he is who he claims to • Tariq does not listen on any TCP/UDP port, which
be (completing the mutaul authentication process, means no sockets is used. Tariq uses scapy's
from the clients side), capabilities to sniff the incoming traffic and uses
• TariqServer receives the packet, extracts the Packet Crafting techniques to reply back to an
payload, and decrypts it to make sure that he legitimate client,
received the random number he sent to the • The communication protocol is a simple secure
client, encryption scheme that uses GnuPG keys with
• TariqServer after verifing that the client is ligitmate Steganography constructions. An observer
executes the commands extracted from the picture watching packets is not given any indication that the
sent in the first place. SYN packet transmitted by Tariq is a port knocking
request, but even if they knew, there would be
And thats how Tariq works, no listening, no sockets, no way for them to determine which port was
and no ports open, just pure packet crafting! requested to open, or what task was requested to
be done as all of that is inserted into a png picture
Why Is Tariq Needed? using Steganography and then encrypted using
Any host connected to the Internet needs to be GnuPG keys,
secured against unauthorized intrusion and other • Replaying the knock request later does them
attacks. Unfortunately, the only secure system is one no good, and in fact does not provide any
that is completely inaccessible, but, to be useful, many information that might be useful in determining

www.hakin9.org/en 31
DEFENSE

the contents of future request. The mechanism Preparing GnuPG


works using a single packet for the mutual You need to create a directory for gnupg using the
authentication. following commands:

Installation mkdir /etc/tariq/.server-gpg


Requirements: chmod 600 /etc/tariq/.server-gpg

• Python >= 2.6 You need to import and trust the client(s) public key(s):
• python-imaging – Python Imaging Library (PIL)
• GnuGP gpg --homedir /etc/tariq/.server-gpg --import <
• Scapy client.pub.txt
• A recent Linux kernel with iptables (eg. 2.6) gpg --homedir /etc/tariq/.server-gpg --edit-key
tariq@arabnix.com
Preparing the Client
Then select trust (5)
Preparing GnuPG
You need to create a directory for gnupg and generate Preparing iptables
a pair of keys using the following commands: Create an iptables chain to be used by tariq server:

mkdir /etc/tariq/.client-gpg iptables -P INPUT DROP


chmod 600 /etc/tariq/.client-gpg iptables -N tariq
gpg --homedir /etc/tariq/.client-gpg –gen-key iptables -A INPUT -j tariq
iptables -A INPUT -m state --state ESTABLISHED,RELATED
You need to export client's public key: -j ACCEPT

gpg --homedir /etc/tariq/.client-gpg -a --export Optional: you may specify a range of ports to be
tariq@arabnix.com > key.pub.txt filtered (dropped) in case you are running normal
services on the same box:
Configuring the client
Edit the client.conf file to specify the client gpg directory iptables -A INPUT -p tcp -m tcp --dport 1000,65535 -j
and the default gpg user: DROP
iptables -A INPUT -p udp -m udp --dport 1000,65535 -j
client_gpg_dir=/etc/tariq/.client-gpg DROP
user=tariq@arabnix.com iptables -A INPUT -p tcp -m tcp --dport 80 -m state --
state NEW -j ACCEPT
And specify the image directory used for
steganography, containing at least 1 reasonable png IMPORTANT NOTE: Do not use the REJECT target
image file, just like the one included as a sample with tariq.
sample.png:
Configuring the server
img_dir=/usr/share/TariqClient/img Edit server.conf and specify the correct sequence of
ports, by using the secret_ports variable. Example:
Now specify the default secret knock sequence to
match the sequence configured on the Tariq server. secret_ports=10000,7456,22022,12121,10001

secret_ports=10000,7456,22022,12121,10001 Now specify the server's gpg path:

Note: you may pass the gpg user and knock server_gpg_dir=/etc/tariq/.server-gpg
sequence as arguments to TariqClient (see howto use
section). Specify the iptables chain name you have created for
tariq:
Installing The Server
After installing the requirements, the first step is to iptables_chain=tariq
download, unpack, and install Tariq. Tariq can be
downloaded from: http://code.google.com/p/tariq/. Now please adjust the iptables chain name used to
Once this is done, we need to configure the server. open ports for a successful knock:

32 5/2010
Securing public services using Tariq

On the 'Net
• http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-0166 – Mitre's CVE dictionary CVE-2008-0166,
• http://www.debian.org/security/2008/dsa-1571 – DSA-1571-1 openssl – predictable random number generator,
• http://www.cipherdyne.org/fwknop/docs/SPA.html – Michael Rash, Developer of the SPA technique.
• http://code.google.com/p/tariq/ – Current Tariq project home page.

open_tcp_port=-A tariq -s {ip} -p tcp -m state -- ./TariqCleint -u tariq@arabnix.com example.com E service


state NEW -m tcp --dport {dport} -j httpd restart
ACCEPT
open_udp_port=-A tariq -s {ip} -p udp -m state --state Another example, here I'm sending an echo message
NEW -m udp --dport {dport} -j ACCEPT to the box:

Advanced Configuration ./TariqCleint -u tariq@arabnix.com example.com E echo


Sniffing Specific Ports Only – Sometimes you might “Hello, It's me tariq”
need to run Tariq on a box running different services
for example webserver (port 80). This can be done Finally to close the port you requested to open,
by adjusting the *sniff_range* variable in the servers all you need to do is either initiate a close port
configuration file*.* command or the TariqServer shall check after
This shall make Tariq sniff or capture packets a prespecified period of time if there is some activity
destianed to that port range only, without interfering or not on that port, if there is, Tariq shall leave the
with packets destined to our webserver (port 80), so no port open, if not Tariq shall request the close of that
packets shall be dropped. port. The command to close the port is as simple as
Random number (blob) Size – you can also adjust this:
the random number’s size sent by TariqServer to the
TariqClient as the challenge by the variable *min _ ./TariqCleint -u tariq@arabnix.com example.com C 22
random _ blob _ size* and *max _ random _ blob _ size*.
Working Threads – You can also increase the number As we saw, Tariq enabled us to create another layer
of working threads of the TariqServer in case you have a of security which needs to be penetrated in order to
wide number of users to serve and running on a heavy reach or penetrate any of the services we are using on
traffic box using the variable *threads_n*. Also found in our Linux box (for example: SSH server). This security
the server’s configuration file. layer that Tariq added shall make it very difficult for
attackers to gain remote access to our servers, and
Howto use tariq shall really make them think twice before spending
To start running tariq server, just run the following lots of time trying to figure out how shall they reach the
command using user root: box, because how can they discover a vulnerability in
something that isn't seen? :)
./TariqServer

Now that you have tariq server running, the firewall


rules configured on the server, and your profile
installed on the client, you're ready to run some
commands remotely or open some ports. Using user
root, to open, for instance, ssh (22) on the remote
server (example.com), all you simply need to do on the
client, is run: ALI HUSSEIN
The author has been working as a network security officer for
./TariqCleint -u tariq@arabnix.com example.com O 22 different large companies for more than �ve years. His day to
day activity is related to �rewall auditing, IDS/IPS, and policy
If you don't want to open a port but perform a remote enforcement. He is currently a Ph.D. student, holding an MS.c.
command for instance restarting the httpd service on degree in Computer Information Systems, and a BS.c. degree
the box, you don't need to login remotely and do it in Computer Science. Throughout his working career he
yourself and still working with the default drop firewall. managed to gain a couple of well known technical certi�cates
All you simply need to do on the client is run the such as: CNI, CLP10, CLA10, CLDA, IBM Certi�ed Specialist –
following command: System p Administration, Novell Linux Specialist, and RHCE.

www.hakin9.org/en 33
DEFENSE

Beginner’s Guide to Cybercrime


Understanding Attack Methodologies and a More Proactive
approach to Defense
If you are a regular reader of Hakin9 Magazine, you probably
already know a great deal about hacking. But do you know
the difference between traditional crime and cybercrime?
Do you know where are the cybercrime magnets?

What you will learn… What you should know…


• Types of Cybercrime Attacks • Basic „Hacking” Knowledge
• CyberCrime Magnets • Different Types of Crime
• The 4D’s and The Risk Formula • Finding Vulnerabilities
• Proactive Countermeasures • Testing Security Tools

H
ow about why nothing The Prevalence of New Malware
with an IP address is Most of the breaches happen because of new
secure and why traditional malware and more innovative malware. So let’s start
countermeasures such as firewalls, our journey with the basics of malware. What is it?
anti-virus and intrusion detection fail? Is it a virus, Trojan, worm, rootkit, botnet, zombie,
Would you like to learn new methods keylogger, adware or spyware? It is all of these
to proactively defend against things and some are combined into what is known as
attacks? If so, you’ve come to the blended threats.
right place. Is your computer infected with malware? It is
First, let’s start with a basic understanding of highly possible, as one study claims that 30,000
traditional crime vs. cybercrime. There are parallel computers are becoming infected every day with new
crime methodologies between crime in the real world malware, known as zero-day (this means the day it
and the digital paradigm enabled by the internet was released and before an anti-virus vendor has
protocols including the world wide web. a signature test for it), while still running firewalls and
Traditional criminal techniques involve burglary, anti-virus software.
deceptive callers, extortion, fraud, identity theft and Do you think some of the web sites you visit could be
child exploitation, to name a few. In Cybercrime we infected with malware? At least 1⁄2 of the Top 100 sites,
experience the same end results using from hacking, particularly social-networking sites such as Facebook
phishing, Internet extortion, Internet fraud, identity or YouTube, support user-generated content, which is
theft and child exploitation (sources: uscert.gov, becoming a significant way to disseminate malware
cybercrimes.gov and privacyrights.org see Figure 1) and conduct fraud. On Facebook and MySpace and
If you take a few moments to visit PrivacyRights.org other social-networking sites, there’s an explicit sense
and click on the Chronology of Data Breaches, you’ll of trust.
notice over 350 million personally identifiable information Do you pay your bills online? Criminals seized control
(PII) records have been lost, stolen and hacked. This of the CheckFree Web site and attempted to re-direct
information is about breaches in the United States of users to a Web site hosted in Ukraine that tried to install
America, alone. So do you still think you are secure or malware on victims’ computers. CheckFree has more
believe your anti-virus and firewall can truly secure your than 24 million customers and controls 70% to 80% of
network or personal computer? the online bill-payment market.

34 5/2010
Beginner’s Guide to Cybercrime

Figure 1. Traditional Crime vs Cybercrime

Much of the new malware is specifically designed just say the Cloud is also
to propogate across USB sticks. For example, the a cyber crime magnet. Why?
picture frame you just bought at Walmart using a USB Because cloud computing
connection might have come with zero-day malware has shifted the paradigm for
from China. In addition, they work their way onto file risk. The cloud offers low
servers using the Structured Message Block (SMB) overhead in return for powerful
protocol – that includes Linux and Windows file servers remote business functionality.
and network-attached storage devices. Some of this In return, you face the risk of
malware is so sophisticated, it finds data files such as data leakage, cloud attacks
.doc, .xls, .wav, .mp3, .pdf and other to infect so when and cloud infections. You most likely will not know if and
someone else opens them, they too become infected. when it happens because of the remote aspects and the
Don’t think you are safe at home, either. Cable pervasive nature of the Cloud.
networks are loaded with peer attackers. Most likely,
a trusted telecommuter is using an insecure, hacked Secure Wireless Networking – Easily Hacked
laptop with a key logger coming in securely into your Wired Equivalent Privacy (WEP) was the first commercial
network through an encrypted VPN tunnel. algorithm and attempt to secure wireless networks using
the IEEE 802.11 standard. Because wireless networks
Cloud Computing – A Malware Magnet broadcast messages using radio waves, they can more
My next article will delve more deeply into Cloud easily be eavesdropped than traditional wired local
computing and related security risks but for now, let’s area networks. It was released in 1997 as an attempt

www.hakin9.org/en 35
DEFENSE

to provide confidentiality that would be comparable to also easily susceptible to a man in the middle attack.
that of wired networks. However, in less than four years, A sample exploit known as Voice over Misconfigured
various weaknesses were uncovered in WEP and toay, IP Telephony (aka VOMIT) allows you to playback
it can be cracked in minutes. conversations that occurred earlier. Hackers simply
Then, just a few years later in 2003, along came use a TCP/IP ethertrace utility such as wireshark,
Wi-Fi Protected Access (WPA) and later updated to save a ‘dump’ file of network traffic and then run
WPA2 in 2004. Today, both WEP and WPA are widely the file through VOMIT to get a WAVE file of prior
deployed, yet with new tools such as BackTrack conversations.
v4.0, anyone can gain access to a secure wireless What about other wireless communication devices
network in a matter of minutes. In addition, most such as a Blackberry, an iPhone, an iTouch or an
wireless routers have critical flaws known as Common iPad? My first question is – do they really belong on
Vulnerabilities and Exposures (CVEs). Now, you can the ‘corporate’ network? If so, how do you know when
break into the admin interface of a wireless router by they come and go, along with other portable devices
sending malformed packets from your laptop without and laptops? How do you stop them from bringing
worrying about cracking the encryption. Just visit the malware into the network? How do you stop them from
National Vulnerability Database (NVD) located at http: being used to steal or leak confidential data? If you
//nvd.nist.gov and type in wireless to see where the can’t control, track and manage assets, how can you
holes are located. claim that your network and your data is secure? You
cannot. In fact, nothing with an IP address is secure.
Is VoIP More Secure than Wireless? No device is safe. All IP-based devices are exposed to
So if wireless networks are not secure, would Voice exploitation. Why? Because they are all targets – they
over IP (VoIP) be better off, as they are usually, can be spoofed, infected, remotely controlled and
physically wired? The answer is no. There are probably already are infected with some form of zero-
dozens of VoIP holes, also found under the NVD. day malware.
Some of these can be exploited by freely available
tools online. These tools will allow you to take over Traditional Countermeasures All Fail!
the administrative console of the VoIP server by Anti-virus utilities are usually one to seven days
exploiting just one CVE – remember, all it takes is BEHIND the current malware threat. With today’s
one hole and you can find many exploits. VoIP is malware, they are usually infected without knowing
it. Just try AVKILLER as one of 400,000 sample
pieces of zero-day malware to find out for yourself
how serious this problem has become. Firewalls are
easily circumvented or used as part of an exploit
because of their exploitable holes (CVEs). Finally,
Intrusion Detection System (IDS) detects odd or
mal-behaving traffic AFTER the infected system
or hacker system has breached the gates. To
understand why these security countermeasures
all fail, you need to understand the root cause of
exploitation. CVEs are holes and are exploited
daily. Let me give you a simple example: although
there might be 9,000,000 signatures in your
McAfee or Symantec Anti-virus scanner database
(and growing exponentially), there are only about
43,000 CVEs.
If you close just one CVE, for example, you can
block over 110,000 varients of W32 malware. If
you aren’t visiting http://nvd.nist.gov to see what
kind of exploitable holes you have in your network,
cybercriminals CERTAINLY are… because
everything with an IP address has a CVE, so, you
need to figure out which ones are critical holes
and how to patch, reconfigure and remove
them. This is also known as system hardening
and most folks seem too busy to find the
time to go after the root cause analysis

36 5/2010
Beginner’s Guide to Cybercrime

and stay in reactive mode…. cleaning old viruses, that are trusted but weak or infected need to be
patching one hole while opening another. You might quarantined in real-time or expect MALWARE
think you are defending your castle with traditional PROPOGATION.
countermeasures like bows, arrows and spears,
however, today’s cybercriminal is flying into your Proactive Defense
castle, behind the moat, using an apache helicopter, – Employee Awareness and Training
night goggles and a silencer. With these two formulas in place, you’ll still need to
account for the most important challenge to network
Proactive Defense security – untrained and easily exploited employees.
– Learn and use the secret formulas You’ll need to begin to invite employees to a quarterly
I’ve actually come up with a few simple formulas to 'lunch and learn' training session, give them 'bite-sized'
help you understand how to reduce risk, comply with nuggets of best practice information. Maybe even
regulations and harden your systems. The first formula consider giving them an award once per year to the
is based on US Military basic war tactics and is called best INFOSEC compliant employee who has shown an
the four D’s. They are: initiative to be proactive with your security policies, the
4Ds and the Risk Formula.
• Detect – awareness of a threat Remember, if you can keep them interested, they
• Deter – preempting exploitation will take some of the knowledge you are imparting
• Defend – fighting in real-time into their daily routines. That's the real goal. Launch
• Defeat – winning the battle! a 4D and Risk Formula educational campaign so all
employees in your organization to join your mission
The second formula is well known in the network to protect corporate information. Create your own
security circles and is called the Risk Formula, as 'security broadcast channel' via email or really-simple
follows: syndication (RSS) and get the message out to your
corporate work force. You can also give them 'security
R = T + V + A smart' tips or alert them to a new phishing scam or
(R)isk = (T)hreats + (V)ulnerabilities + (A)ssets that the corporate had to let go of an individual who
was attempting to steal corporate information. It’s
So, to fully understand your risks, you need to deal important to understand that keeping the entire team
with: in the loop will help bolster the corporate security
posture.
Threats = Cybercriminals, Malware, Malicious Insiders There are other tools available such as INFOSEC
Vulnerabilities = Weaknesses that Threats exploit awareness posters, which you can get from one of
Assets = People, Property, Your Network, Devices, etc. the security awareness training companies. If you are
creative and have the time, create post-cards with
Now, let’s put these two formulas together – the 4Ds do's and don'ts of best practices for the employees
and the Risk Formula to build a more proactive, next that they can pin-up in their offices as reminders. The
generation defense: bottom line: knowledge is power so start empowering
your fellow employees to gain a basic toehold in
4Ds x R = [4Ds x T] +[4Ds x V] + [4Ds x A] what they should and shouldn't do to help you in
your mission of more uptime and less compliance
You’ll never be 100% secure but you can dramatically headaches.
reduce your risk and proactively defend your There are also some great corporate security
organization by proactively containing and controlling policy tools available for free such as the powerful
threats, vulnerabilities and assets. Using the 4Ds with COBIT model at http://www.isaca.org, the e-tail/
the Risk Formula: retail oriented PCI model from the PCI Security
Standards Council found at https://www.pcisecurit
• Threats need to be detected, deterred, defended ystandards.org/ and the extremely comprehensive
against and defeated in real-time or expect DOWN- international model called ISO27001/17799 from
TIME. http://www.iso.org/. Any of these models will be
• Vulnerabilities need to be detected, deterred, a great starting point.
defended against and defeated (ie removed –
system hardening, reconfiguration, patching, etc.) Proactive Defense – Strong Encryption
as quickly as possible or expect to be EXPLOITED. There's an old saying loose lips sink ships. The
• Assets need to be controlled – which ones gain best practice is to look at all aspects of electronic
access to your network/infrastructure and those communication and data manipulation throughout

www.hakin9.org/en 37
DEFENSE

your enterprise. That should include all instant Proactive Defense


messaging, file transfer, chat, e-mail, online meetings – Host-based Intrusion Prevention System
and webinars plus all data creation, change, storage, Because so many Windows® systems are compromised
deletion and retrieval. For example, how are customer – especially laptops, you need to consider Host-based
records stored? How are electronic versions of other Intrusion Prevention Systems (HIPS). Simply put
confidential information protected? Backing up the data HIPS blocks malicious software from functioning. The
is not enough. evolution of anti-virus will always be a newer, faster
You should setup a VPN for external network signature testing engine (even if they try to add HIPS)
access. Make sure the systems that access your that’s one step behind the latest malware attack. Look
network through the encrypted tunnel are also not for a purely HIPS solution that blocks zero-day malware
the weakest links in your infrastructure so deploy without signature updates (heuristically). It should help
HIPS on endpoints. You can encrypt everything from mitigate malware propagation, quarantine malware in
your hard drives to your email sessions to your file real-time and not be a CPU or memory hog, making the
transfers. There are numerous free tools out there end-user PC unusable.
like http://www.truecrypt.org for hard drives and
http://www.openssl.org for web, email and instant Summary
messaging, plus the grand-daddy of free encryption Crime and Cybercrime are really the same concept,
at http://www.openpgp.org PGP (Pretty Good with the same end-results, only using different vehicles
Privacy). or mediums (ie physical vs logical). Web sites, e-mails,
You'll need policies in place for key storage and instant messaging, soft phones, and portable devices
password access so if ever the keys and passwords are all malware magnets. If you have an IP address,
are lost by the end-users, you'll have a way back in you are NOT secure and traditional countermeasures all
to decrypt the information, reset the keys or change fail! You can begin to take a more proactive approach to
the passwords. You might find out that some of the cyber defense by using and understanding the 4D’s and
servers and services you are running already offer the Risk Formula. You will never be 100% secure and
encryption if you simply check the box and turn this you can NEVER block or prevent all intrusions so focus
feature on. on INTRUSION DEFENSE and RISK MANAGEMENT–
in other words, expect it to happen – use the 4D’s and
Proactive Defense the Risk formula to contain the damage, if any. Don’t
– Physical Access Control forget to educate your fellow employees – the weakest
Piggybacking and tailgating are a major physical link and to document your security policies. Stay vigilant
security risk. Hence the need for more intelligence and proactive so you will get one step ahead of the next
Physical Access Control (PAC), so, you’ll need to threat.
make sure your PAC solution shares data over the
network to you and (potentially) to your NAC solution. Crime and Cybercrime are really the same.....Stay
You should make sure your PAC solution uses two vigilant and proactive so you will get one step ahead of
factor authentication and if your TCP/IP connections go the next threat.
down, the PAC system still functions mechanically with
accessible local logs.

Proactive Defense
– Network Access Control
Because so many exploits happen behind firewalls,
you need to consider deploying Network Access
Control (NAC). Simply put NAC determines who
belongs on your network and who does not, so
you should make sure your NAC solution doesn’t
telegraph to exploiters (ie welcome to NAC portal… GARY S. MILIEFSKY, FMDHS, CISSP®
please wait, installing XYZ corp trust agent v3.1). Gary S. Miliefsky is a 20+ year information security
Also, you’ll need to make sure it has a way to deal veteran and computer scientist. He is a member of ISC2.org
with non-Windows systems (hubs, switches, routers, and a CISSP®. Miliefsky is a Founding Member of the US
blackberries, iphones, etc…) – it needs to be holistic. Department of Homeland Security (DHS), serves on the
Try to find a non-inline or out of band appliance advisory board of MITRE on the CVE Program (CVE.mitre.org)
solution and avoid costly, hard to manage hacked and is a founding board member of the National Information
agents. Security Group (NAISG.org).

38 5/2010
EMERGING THREATS

Is DDOS Still a Threat?


I
s DDOS, or Distributed Denial of Service, still a if the attacker can disrupt enough critical services. I
credible threat? Do we lay awake at night scared of won’t rehash the details, but in summary if you make
when the next one might hit us? it impossible for people just to access their money
An obvious question perhaps, they are still a threat electronically society as we operate now breaks
to most online enterprises. But they’re not the top of down very quickly. Hoarding, looting, conflicts for
the news issues they once were. No one’s taken a shot basic resources. A week or two of mass hysteria and
at Google, or Yahoo, or the other major sites that’ll an attacking conventional force would easily be able
make the top of the mainstream news. Usually with a to waltz right in and plant their own flag. Most of the
headline like The Internet is Under Attack!!!! If only the society might not even notice!
mainstream media and public really understood what Where will this go next? If I were a militia, a terrorist
we all know is actually going on in the undercurrents of group, or even just a disgruntled teenager with a laptop,
the Internet, they’d be in a panic. I’d be thinking DoS. Why risk agents or sleeper cells,
The obvious reason there hasn’t really been a high finance them, sneak them into countries or secure areas
profile DoS of late is that most of the larger sites are now to blow themselves up and perhaps 20 or 30 people?
using services like Akami, distributing their content over High risk, highly expensive, and minimal impact. Rather
hundreds or thousands of nodes and geographically invest the money into training the same people to build
routing users to the closest node with the least load. and control large botnets. Build them out ,make some
This makes them arguably a near impossible DoS money spamming penis enlargement pills while you’ve
target. An attacker may slow down access in limited got it set up, and wait.
areas, but completely interrupting service is just not When the time is right, when your enemy does
feasible without crippling the backend of these sites, or something particularly offensive, of you just feel
interrupting the DNS used to route users. like making it a bad day for a lot of people, launch.
More importantly though, no one wants to be the target Hit the enemy in their weak spots. Disrupt banking,
of the investigation behind a high profile attack. The bad infrastructure controls (water, gas, oil distribution), and
guys realize (the smart ones at least) that there is so most importantly go after the supply chain for major
much crime, so many groups doing so many things, that food items. When a society suddenly can’t get tomatoes
as long as you stay under the radar your odds of being in the grocery store they’ll freak out. Seriously, it’s all
caught (or even investigated) are very VERY low. about the tomatoes.
We are still seeing DoS attacks, every day. It’s Well, and a few other staples. Milk, rice, flour, etc. Most
become a tool for groups to attack and extort money modern societies work with less than a week’s supply
from sites that can’t afford the infrastructure to globally in city to keep items fresh and minimize warehousing
distribute their content. Online gambling sites are a space in expensive retail locations. If you target the
particular target, and have been for some time. Many of major food providers (most regions of a country have
these sites aren’t legal in many countries so they can’t only two or three) and disrupt their ordering and
get much in the way of law enforcement. The bad guys dispatching capabilities things grind to a halt.
know this of course. So I’m not saying I hope a terrorist group gets a clue
The largest threat from DoS attacks is yet to be and figures out how to truly strike at an electronic world.
fully realized I believe. We’ve seen previews of it (hint, it’s not vest bombs) I hope we as the vulnerable
in Georgia and Estonia. Nation states using DoS societies wake the freak up and do a much better job
attacks as a disruption tactic in conjunction with a protecting our exposed underbellies.
conventional attack. In these two very high profile
attacks the effect was significant. All modern societies As always please send me your thoughts,
are very reliant on the Internet to conduct daily jonkman@emergingthreats.net.
business, communicate orders and supply needs,
manage public infrastructure, bank, and even track
where vehicles are in transit.
I’ve written other articles in this magazine on the
effects, that in a modern conflict an attacker can
rely on the society of their enemy to tear itself apart MATTHEW JONKMAN

www.hakin9.org/en 39
DEFENSE

More Secure
PHP Server Side Source Encryption

The Internet as we know it is full of mystery, intrigue and


obfuscation. One of my favorite curiosities is finding ways
to undo things that have been done then automating
the process programmatically and retooling the concept
entirely. Some may call this building a better mouse trap.

What you will learn… What you should know…


• You will learn various methods to obfuscate and encrypt sour- • HBasic HTML/PHP/Javascript and general programming know-
ce code. ledge

Scenario 1: being able to use the information; namely in a web


A common technique used today to obfuscate environment using PHP. I explained that most attempts
code to hide server-side PHP code were simple to decrypt
This scenario begins as follows: I recently had because they needed to be in a usable state at one
a conversation with a hacking buddy of mine (Kyle time or another. It is at this moment in time that it
Price) in regards to hiding information but still unravels and shows it’s true self. With such a blinding

Figure 1. Obfuscated code Figure 2. Eval function

40 5/2010
More Secure PHP Server Side Source Encryption

Figure 5. Full decloaking results


deter scanners and attackers from figuring out they
are using gzinflate. They have done this by using
a combination of zeros and upper case letter Os as
a variable name replacement. By simple replacing
Figure 3. Decoded second time $OO000OO000OO with gzinflate you’ve broken the first step
of the deobfuscation.
vulnerability hiding something from someone that Doing the replacement and running eval then
knows what to look for is just a game it will eventually decodes to another mystery. The code we decoded
lose. Kyle wasn’t exactly sure how it all worked so
I asked him to send me an obfuscated piece of code
and I would show him how to decode it. He searched
the ‘net and eventually sent me an email that looked
something like this (Figure 1).
It only took me a quick second to spot the infamous PHP
eval function call (Figure 2) eval ($OO000OO000OO(base64_
decode('. For those that don’t have experience with this
allow me to explain by breaking this down.
eval: eval evaluates a string as PHP code
($OO000OO000OO: this is a bogus function call but should
be gzinflate() to inflate deflated string (base64_decode('“:
this decodes data encoded with MIME base64.
Put all three functions together and you are running
a routine to unwrap a string that’s been deflated
and base64 encoded. To undo this you only need
to reverse the process and this is exactly what the
code in Figure 1 is doing already for you. The only
tricky part here is that the programmer is trying to

Figure 4. Decoded tenth time Figure 6. Full cloaking results

www.hakin9.org/en 41
DEFENSE

Figure 7. ITCloaker function calls

Figure 10. Setting up for decrypt function


code back to Kyle. He wasn’t as happy as I thought
he was going to be. I felt like I just told him Santa
Claus wasn’t real (and proved it). We then conversed
further and drew pictures on the white board about
a more secure form of obfuscation and I brought up
the notion of using something more complex and using
something more like a one-time-pad using XOR with
a keyed passphrase; then to using remote passphrase
keys via SSL to a remote server with more control,
port knocking, random key generation... I then went on
Figure 8. Encrypting using XORlib.php my way to create such a creature (ultimately named
itarmor).
almost looks identical to what we just decoded – but
shorter in length (Figure 3) and we are back to the Scenario 2:
$zero+O gzinflate variable label. In fact this process A more secure technique using XOR
is repeated for a total of 10 times before we finally encryption
get to the true encapsulated source (Figure 4) This next scenario involves developing a more secure
...congratulations indeed. technique I’ve named itarmor as it’s purpose it to
After running through the process manually I quickly armor the code from simple attacks as described in
built up a script that would programmatically decloak Scenario 1.
obfuscated code (Figure 5) created by the PHP I found a nice pre-fabricated free PHP xor snippet
obfuscator Kyle used as well as mimic the obfuscator authored by Jonas John created in 2007 and licensed
(Figure 6) itself by creating the same type of result with as public domain; the main function is XOREncryption()
arbitrary code and aptly named it itcloaker.php (as it with two complimentary helper functions XOREncrypt()
cloaks and decloaks) (source code: itcloaker.php) here and XORDecrypt(). I originally planned to roll my own
I’ve created a few functions that you can include and but this function fit perfectly for my needs in a very
call from your own PHP code (Figure 7). short amount of time. Saving time by not reinventing
Now this whole episode happened in a matter of the wheel is good! I saved the source and labeled it
minutes before I sent the resultant original source xorlib.php for all intents and purposes.

Figure 9. XORed and base64 encoded Figure 11. Decrypted using XORlib.php

42 5/2010
More Secure PHP Server Side Source Encryption

Figure 12. Abstracting the secret key Figure 13. PHP defensive methods to hide key
I created a very simple PHP test that prints to the
screen and does math with variables. In the first deployment tracking, to stop the average user from
test I call xorlib.php from another PHP file named copying your code and frankly the possibilities are
test1.php (Figure 8) using include "./xorlib.php"; Using limitless.
XOREncrypt() I get the resulting base64 encoding (Figure I wrote a new version of secret.php so that it just did
9) To run this in PHP I now use eval() and XORDecrypt() to not contain the variable and value but now had multiple
decode using the secret key random data. (Figure 10)
and when we execute it using PHP test2.php we get the
expected calculated results! (Figure 11) this is a step in
the right way but aside from xorlib.php being local the
$secretkey value is also right there in the code plain as
day.
For the third test (Figure 12) I removed $secretkey
to another file like xorlib.php using include() and
reformatted the code for a more uniform look and
received the expected successful results.

Scenario 3:
A more secure technique using XOR
encryption via remote https
This scenario evolves Scenario 2 by removing the
$secretkey from the local environment to a remote
environment using a few more barriers for someone
trying to reverse or backtrace what the secret key is.
The concept behind this remote secretkey is that
this secret key could be changing every few minutes
via a cron job or perhaps when a client doesn’t pay
the monthly invoice, or used as some type of license, Figure 14. Remote placement of secret key

www.hakin9.org/en 43
DEFENSE

Figure 15. Enable php.ini for remote access Figure 18. Attempt to get key using plain curl

Figure 16. Successful remote decoding result Figure 19. Bypassing User Agent using curl
barriers to thwart a common script kiddie from running I ran a browser test using Safari (Figure 17) and got
a simple attack. These barriers are as follows in this the expected result as the User-Agent for Safari is:
order (Figure 13)*: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3;
en-us) AppleWebKit/531.22.7 (KHTML, like Gecko)
• Barrier #1: Forcing SSL makes sniffing the Version/4.0.5 Safari/531.22.7 and in the secret.php
secretkey via wireshark more difficult. check I explicitly stated NO USER AGENT was
• Barrier #2: Checking the requestor’s IP address to permitted (you can change this to special strings; that’s
make sure it’s the correct server making the request. up to you to play with – as you’ll want to change it after
• Barrier #3 : Checking to see if the requestor is using seeing the next example).
a specific type of User Agent. I further tested it using curl (Figure 18) and because
the default curl request has a User Agent string of:
Once tested I replaced the local secret.php file with the curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7
remote secret.php in test4.php (Figure 14) with: include OpenSSL/0.9.8l zlib/1.2.3 this command also gets
"https://israeltorres.org/secret.php"; access denied. I was able to easily thwart this by using
On my mac I needed to create local php.ini (Figure the -A “” null parameter to get the secret key (Figure 19).
15) file with one line allow_url_include=1 to allow remote
include files and use the following syntax in terminal
(Figure 16): php -c php.ini test4.php and received the
expected decoded and calculated results.

Figure 17. Attempt to get key using web browser Figure 20. Advanced „randomness generator”

44 5/2010
More Secure PHP Server Side Source Encryption

Notes
all source code created and tested on my Apple Macbook
Pro running
Mac OS X 10.6.3
PHP 5.3.1 (cli) (built: Feb 11 2010 02:32:22)
GNU bash, version 3.2.48(1)-release (x86_64-apple-dar-
win10.0)

Special Thanks to Kyle Price

Web Links and References


• http://php.net/manual/en/function.eval.php
• http://php.net/manual/en/function.gzin�ate.php
• http://php.net/manual/en/function.base64-decode.php
• http://www.jonasjohn.de/snippets/php/xor-encryp-
tion.htm
• http://en.wikipedia.org/wiki/XOR_cipher
Figure 21. Larger and more random secret key
• http://php.net/manual/en/function.base64-encode.php
Again you can modify your User Agent and match
*various snippets the put together (ssl)secret.php
it with the remote secret.php to further confuse the
• http://www.commandlinefu.com/
attackers. • http://snipplr.com/
• http://www.google.com/
Scenario 4:
A more secure technique using XOR
encryption with more secret key randomness $secretkey (Figure 20) which significantly increases the
At this point my example ending with test4.php makes random characters in the secret key as well as gives it
it pretty obscure for an attacker to successfully reverse an extremely large and generous key space for a great
without the protected secret key over PHP, SSL, IP, and one-time pad using XOR (Figure 21).
User Agent strings. Note: For better security be sure not to use images
I went further on using base64 file encoder/decoder from google without some further modification as
to encode a random image and then use that as the someone that is really skilled may be able to find the
right image you used to create the secret key (highly
unlikely, but not impossible) (Figure 22).

Conclusion
In my PHP code examples and scenarios above I’ve
taken quite a few steps to further armor remote code
protection from common basic obfuscation techniques
that use eval() and can easily be decoded locally
using simple scripts and also provided methods to
do so easily (i.e. itcloaker). Some may require more
modification but the basic process is there. Also note
that this armoring technique didn’t require any special
server modifications or additional software modules
installed that third party obfuscators/ encryptors may
use. In the security universe nothing is entirely fool-
proof but it certainly changes the game in the world of
building a better mouse trap.

ISRAEL TORRES
Hacker at large with interests in the hacking realm.
hakin9@israeltorres.org
hakin9 crypto challenge
Figure 22. Sample mod�ied Google image http://hakin9.israeltorres.org/

www.hakin9.org/en 45
EXPERT SAYS..

Don’t let the zombies


take you down
Ian Kilpatrick, chairman of Wick Hill Group, specialists in
secure infrastructure solutions
Over the last year, the incidence of botnet (or zombie)
attacks has been growing rapidly. Some service providers
around the world have already begun to take action against
botnets [1] and there is increased interest from other service
providers, and from companies, in dealing with this serious
security threat.

B
otnets are most closely associated with Micro [3], which gives some idea of the scale of the
computers being taken over and used to send problem and the difficulties of disinfection, found
out spam emails. However the threat is much that the industry underestimated the length of time
wider than that. At the other end of the scale, there PCs were infected with botnets. The company found
are criminals renting out botnets to harvest personal that, in 100 million compromised machines, the
banking and security information, mount serious average infection was 300 days, not the estimated
commercial attacks, steal money or commit fraud. six weeks.
Both individuals and businesses are being The scale of individual botherds can also be very high.
targeted. Web sites are being infected (so called Recently a botnet of over 2 million pcs was discovered
drive-by infections) so that they deliver malicious in the UK and US [4]. And a Dutch botnet had over 1.4
code to the sites’ visitors. Botnets are also being million in the herd [5].
used to mount DDoS attacks on businesses, which
can have serious consequences. Twitter was How are you infected?
recently the victim of a DDoS attack and temporarily Botnets are multiple software robots (bots)
closed down [2]. that can run autonomously. They can
These are not trivial threats. There is a significant be malign or benign, but we are
amount of money to be made in harvesting banking just looking at the malign
information, launching blackmailing DDoS attacks, here. Bots are typically
or in just renting out the Zombie army for someone delivered by e-mail
else to use. So there is continual recruitment and or from a web
development of these armies, as well as investment site.
in the command and control infrastructures by bot
herders, the individuals or organisations which control
a group of botnets.
Botnets can be hugely sophisticated and very
resilient, with their own forms of disaster
recovery built in, so they can continue to
function even when attacked.
Recent research by Trend

46 5/2010
Don’t let the zombies take you down

Users are now well aware of email-based threats with, botnets will continue their explosive growth on the
and many have protected themselves in this area, so public internet [6].
web-based delivery of bots is increasing. This can be The best way to prevent botnets, though, is by having
through going onto what appears to be an innocent web proper security solutions in place to begin with.
site and picking up a malicious download. This kind of For companies, the place to start is at the gateway.
threat can also evade traditional list-based web content However gateway security will not be enough when
security systems, mobile users and visitors are connecting inside the
which rely on prepared lists of good and bad sites. gateway. Proper access control and strong two factor
Typically, infected good sites will not be identified on authentication will help here.
these lists. If staff are using USBs, laptops, iPods, etc. inside
Some phishing emails will take you to web sites where the gateway, there is the risk that they are bypassing
you may inadvertently download a bot. Your users could gateway security controls and infecting network
bring them in on laptops or USBs potentially infecting connected devices – so your security policy should
your whole network. You can even catch bots by taking cover the safe use of mobile equipment.
part in MMORPGs (massive multiplayer online role Other high risk areas inside the network include
playing games). infections picked up from staff visiting malicious web
Trojans and worms are common methods of joining sites. A classic security method here is to deploy multi-
botherds. Conficker, which recently cost Manchester layer protection. Alongside your gateway protection,
City Council over £1.5 million, is a sophisticated, self- you should also be installing protection on your PCs.
replicating worm managed by a central command and This should ideally be from a different manufacturer
control structure. than that used for your gateway protection.
You are also a target if you fail to use the right anti- There are many endpoint (PC/Laptop) solutions
virus and fail to rapidly update vulnerability patches. available that will provide protection. Solutions from
companies such as Check Point and Kaspersky Lab
Dangers will scan all incoming and outgoing data traffic on PCs
Once you’re part of a zombie army, you may not notice for malicious content and give them protection against
anything and be totally unaware that your machine is being hijacked for botnet activity.
infected. But the bot is now secretly installed on your Endpoint security solutions, such as those mentioned
computer and can use it to send out large volumes above, will protect against malicious code downloading
of spam in the background, or harvest keystroke from infected web sites, as well as Trojans from e-mail
information, passwords, online banking details, log-on or mobile devices, including USBs.
details, etc. At the gateway, companies such as M86 and Finjan
In the case of botnets being used to launch DDoS provide web gateway protection that can identify and
attacks, forensic tracking has led authorities to defend against malicious code loaded on rogue and
investigate innocent botnet members. It’s also possible infected, genuine web sites.
that you could find your company blacklisted as an
organisation sending out spam.
Bots can penetrate the corporate network so they can
potentially monitor everything going on, compromising
your security by potentially passing on information on
passwords or online banking.
And, once installed, significant spam activity, caused
by the bot, might slow down your network, leaving
your system sluggish, but leaving you unaware of the
cause.

Protecting against bots


There are many things you can do to protect your
organisation from becoming part of a botherd. Applying
security patches to key applications, as soon as is
practicable, is a major help. These vulnerabilities are
high risk until patched.
In a cyber security report by Lumension, released in
2009, security and forensic analyst Paul Henry said:
Until the underlying patch management issue is dealt

www.hakin9.org/en 47
EXPERT SAYS..

Ends
• Australian Internet Industry Association (government advisory) drafts code of conduct for �ghting botnets – http://
www.itnews.com.au/News/155673,isps-asked-to-cut-off-malware-infected-pcs.aspx [1]
• http://www.it-director.com/technology/news_release.php?rel=12725 [2]
• http://www.infosecurity-magazine.com/view/4016/compromised-machines-stay-compromised-trend-micro/ [3]
• http://www.itnews.com.au/News/143123,massive-uk-and-us-botnet-uncovered.aspx [4]
• http://www.infopackets.com/news/technology/word_of_the_day/2009/20090519_botnet.htm [5]
• http://www.lumensionsecurity.com/nwr_pressReleasesDetails.jsp;jsessionid=12892CA71D631B12F401988967085B11?i-
d=152123&metadataId=152123 [6]
• Dutch ISPs sign agreement for �ghting botnets – http://www.computerweekly.com/blogs/when-it-meets-politics/2009/09/
learning-from-the-dutch---isps.html [7]
• Messaging Anti-Abuse Working Group publishes best practices for �ghting botnets – http://�nance.yahoo.com/news/
MAAWG-Tackles-Bots-with-New-prnews-1561387349.html?x=0&.v=1 [8]
• ETF draft standard for �ghting botnets – http://www.scmagazineus.com/Standard-offers-best-practices-for-ISPs-to-�ght-
botnets/article/149162/ [9]
• http://blogs.zdnet.com/security/?p=4404 [10]

If you want to protect your own web site from This is not a customer-friendly approach and is
being infected and delivering malicious code to your short sighted because there are solutions available for
customers, companies such as Check Point and service providers, such as ServiceProtector from Allot,
Barracuda Networks have web application firewall which can effectively neutralise botnets and stop spam
capabilities to protect against this increasingly prevalent being sent out from subscribers’ computers, as well as
threat. preventing spam being received by them.
Other solutions, such as Barracuda Networks’ anti- It will also, importantly, protect service providers
spam, virus and spyware firewall, can help protect and enterprises from DDoS attacks, leaving them little
traffic going in and out of your network. This would excuse to carry on doing nothing about this serious
include attempts to send spam or return spyware security threat.
data. A number of other initiatives are taking place, though,
You can also detect bots by using traffic management in the fight against botnets. The Messaging Anti-Abuse
solutions, such as those from Allot. They are able to Working Group recently published best practises for
identify traffic patterns, even masked traffic patterns, fighting botnets [8] The IETF (Internet Engineering Task
which could be bot activity. Force) has also published some best practises [9]. And
Network intelligence systems, such as those from many large organisations are becoming increasingly
Loglogic or ArcSight, can also help. They can bring vocal in their requirements for botnets to be dealt with
together and let you analyse, all log information on your – witness Google’s recent comments [10].
network, down to a granular/PC level, highlighting any With pressure increasing, it is likely that there will be
unusual behaviour. some significant moves against the botnet threat over
Web sites such as Spamhaus.org explain how you the next few years.
can identify and remove botnets if you’re worried you
may have one. At a corporate level, some of the above
solutions will also disinfect your existing estate. At
a personal level, companies such as Kaspersky Lab
and Webroot provide low cost protection. IAN KILPATRICK
Ian Kilpatrick is chairman of value added distributor Wick
Need for action Hill Group plc, specialists in secure infrastructure solutions.
There are many ways for the unsuspecting or Kilpatrick has been involved with the Group for more than
unprotected to be infected and some of this should be 30 years. Wick Hill is an international organisation supplying
dealt with by service providers. Some ISPs are making SMEs and most of the Times Top 1000 companies through
strong efforts to manage the problem. For example, a value-added network of accredited resellers.
earlier this year Dutch ISPs banded together to deal Kilpatrick has an in-depth experience of computing with
with the threat [7]. a strong vision of the future in IT. He looks at computing
However, they are the exception. Many service from a business point-of-view and his approach re�ects his
providers don’t respond unless they find themselves philosophy that business bene�ts and ease-of-use are the
blacklisted for sending out spam or they become victims key factors in IT, rather than just technology. He has authored
of a DDoS attack themselves. numerous articles and publications, as well as being a regular
speaker at conferences, exhibitions and seminars.

48 5/2010
���������������������������������
��������������������������������������������������������

����������������������
��������������������������������
�������������������

���������������������� �������������������������� �����������������


������������������������������������������ ������������������������������������������� ��������������������������������������
������������������������� ��������������������������������������

���������������������������������������������������������

You might also like